### Install Dependencies from requirements.txt Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Installs all necessary Python packages listed in the requirements.txt file. Ensure the virtual environment is activated. ```bash /opt/hyperguard/venv/bin/pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Clone the repository and install project dependencies using pip. Remember to set up environment variables by copying and editing the .env.example file. ```bash # Clone the repository git clone https://github.com/yourusername/hyperguard.git cd hyperguard # Install dependencies pip install -r requirements.txt # Set up environment variables cp .env.example .env # Edit .env with your credentials ``` -------------------------------- ### Docker Compose Quick Start Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Steps to build and run the HyperGuard application using Docker Compose, including configuring environment variables, starting the service, viewing logs, and stopping the container. ```bash # 1. Configure environment cp .env.example .env # Edit .env with your credentials # 2. Build and run (demo mode) docker compose up --build # 3. Run in background docker compose up -d # 4. View logs docker compose logs -f hyperguard # 5. Stop docker compose down ``` -------------------------------- ### Run Example Script for On-Chain Validation Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Execute the comprehensive example script `example_onchain_validation.py` to demonstrate all HyperGuard features in action, including connection, validation, policy checks, and limit testing. ```bash python example_onchain_validation.py ``` -------------------------------- ### Install Web3 and Eth-Account Libraries Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Provides bash commands to install the necessary Python libraries for interacting with Ethereum-compatible blockchains, specifically 'web3' for contract interaction and 'eth-account' for key management. ```bash pip install web3 pip install eth-account ``` -------------------------------- ### Install All Project Dependencies Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md A bash command to install all project dependencies listed in the 'requirements.txt' file. This is a standard way to set up a Python project's environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### Start Hyperguard API Server Source: https://context7.com/cwklurks/hyperguard/llms.txt Command to start the Hyperguard API server using uvicorn. Ensure the application is correctly configured and accessible. ```bash uvicorn src.api.main:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Installs all required Python packages for HyperGuard from the requirements.txt file within the activated virtual environment. ```bash # Install production dependencies pip install -r requirements.txt # Verify installation python -c "from src.client import HyperGuardClient; print('✓ Import successful')" ``` -------------------------------- ### Example Environment Variables Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Configure essential credentials and optional settings for HyperGuard in the .env file. Remember to keep this file secure and out of version control. ```dotenv # Required: Exchange credentials HYPERLIQUID_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef HYPERLIQUID_WALLET_ADDRESS=0xYourWalletAddress HYPERLIQUID_NETWORK=testnet # Optional: Logging LOG_LEVEL=INFO LOG_FORMAT=json # Optional: Database HYPERGUARD_DB_PATH=data/hyperguard.db # Optional: Contract (future) HYPERGUARD_CONTRACT_ADDRESS=0x0000000000000000000000000000000000000000 ``` -------------------------------- ### GET /readyz Source: https://context7.com/cwklurks/hyperguard/llms.txt Kubernetes readiness probe endpoint. ```APIDOC ## GET /readyz ### Description Provides a readiness probe endpoint, typically used by container orchestration systems like Kubernetes to check if the application is ready to serve traffic. ### Method GET ### Endpoint /readyz ### Response #### Success Response (200) - Returns an empty response or a simple status message indicating the application is ready. ### Request Example ```bash curl "http://localhost:8000/readyz" ``` ``` -------------------------------- ### Quick Start Usage Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Initialize the client and submit a trade proposal. Check the result for success and print execution details or validation reasons. Retrieve prevented loss metrics. ```python from src.client import HyperGuardClient # Initialize with Hyperliquid client = HyperGuardClient.from_config( policy_path="config/policy.json", exchange_name="hyperliquid", use_testnet=True ) # Submit a trade proposal result = client.submit_trade( asset="ETH", size_usd=5000, action="BUY" ) if result.success: print(f"Trade executed: {result.execution}") else: print(f"Trade blocked: {result.validation.reason}") # Get prevented loss metrics metrics = client.get_prevented_loss() print(f"Total value protected: ${metrics['prevented_loss_total']:,.2f}") ``` -------------------------------- ### Get Metrics Summary via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to retrieve a summary of system metrics from the /metrics/summary endpoint. ```bash # Get metrics summary curl "http://localhost:8000/metrics/summary" ``` -------------------------------- ### Prometheus Format Example Source: https://github.com/cwklurks/hyperguard/blob/main/docs/METRICS.md An example of metrics formatted for Prometheus, including HELP and TYPE directives. This format is standard for Prometheus exposition. ```prometheus # HELP hyperguard_trades_total Total number of trade proposals processed # TYPE hyperguard_trades_total counter hyperguard_trades_total{status="approved",asset="ETH",action="BUY"} 42 # HELP hyperguard_kill_switch_active Kill switch status (1=active, 0=inactive) ``` -------------------------------- ### Install System Dependencies (macOS) Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Installs Python 3.12 and git on macOS using Homebrew. Ensure Homebrew is installed and updated. ```bash brew install python@3.12 git ``` -------------------------------- ### Copy and Secure Environment File Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Copy the example environment file and restrict its permissions to protect sensitive credentials. ```bash cp .env.example .env chmod 600 .env # Restrict access to secrets file ``` -------------------------------- ### Get Account Positions via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to fetch only the open positions from the /account/positions endpoint. ```bash # Get positions only curl "http://localhost:8000/account/positions" ``` -------------------------------- ### Get Account Metrics via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to retrieve account-specific metrics from the /account/metrics endpoint. ```bash # Get account metrics curl "http://localhost:8000/account/metrics" ``` -------------------------------- ### Check for .env File Existence Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Verifies if the .env configuration file exists in the expected directory. If missing, copy from the example and configure. ```bash ls -la /opt/hyperguard/.env ``` -------------------------------- ### Install System Dependencies (Ubuntu/Debian) Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Installs necessary system packages like Python 3.12, venv, pip, and git on Ubuntu or Debian-based systems. Ensure you have sudo privileges. ```bash sudo apt-get update sudo apt-get install -y python3.12 python3.12-venv python3-pip git ``` -------------------------------- ### Get Full Account State via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to retrieve the complete account state from the /account/state endpoint. This includes metrics like NAV, margin usage, and open positions. ```bash # Get full account state curl "http://localhost:8000/account/state" ``` -------------------------------- ### Get Prometheus-Formatted Metrics via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to fetch system metrics formatted for Prometheus scraping from the /metrics/prometheus endpoint. ```bash # Get Prometheus-formatted metrics curl "http://localhost:8000/metrics/prometheus" ``` -------------------------------- ### GET /metrics/summary Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves a summary of system metrics. ```APIDOC ## GET /metrics/summary ### Description Retrieves a summary of key operational metrics for the Hyperguard system. ### Method GET ### Endpoint /metrics/summary ### Response #### Success Response (200) - Returns an object containing aggregated metrics data. ### Request Example ```bash curl "http://localhost:8000/metrics/summary" ``` ``` -------------------------------- ### HyperGuardPolicy Contract Constructor Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Example parameters for deploying the HyperGuardPolicy Solidity contract. Percentages are stored in basis points (1% = 100 bps). ```solidity // Example deployment parameters constructor( string memory _policyName, // "Conservative_V1" uint256 _maxTradePct, // 1000 = 10.00% uint256 _maxDrawdownPct, // 500 = 5.00% string[] memory _whitelistedAssets // ["ETH", "BTC", "SOL"] ) ``` -------------------------------- ### Setup Structured Logging Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Configure Python's logging module for structured JSON output, specifying the log level, file path, and enabling JSON formatting. ```python from src.logging_config import setup_logging setup_logging( log_level="INFO", log_file="logs/hyperguard.log", json_format=True ) ``` -------------------------------- ### Configure Structured Audit Logging Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Set up comprehensive audit logging using Python. This example configures JSON format logging to a file, capturing detailed context for all trade-related events. ```python from src.logging_config import configure_logging configure_logging({ "logging": { "level": "INFO", "format": "json", "file": { "enabled": True, "path": "logs/hyperguard.log", "level": "DEBUG" } } }) ``` -------------------------------- ### Set File Permissions for HyperGuard Directory Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Corrects ownership and permissions for the HyperGuard installation directory. Ensure the user 'hyperguard' exists. ```bash sudo chown -R hyperguard:hyperguard /opt/hyperguard ``` ```bash chmod 600 .env ``` -------------------------------- ### Kubernetes Readiness Probe via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to trigger the Kubernetes readiness probe endpoint (/readyz). This endpoint is used by Kubernetes to check if the application is ready to receive traffic. ```bash # Kubernetes readiness probe curl "http://localhost:8000/readyz" ``` -------------------------------- ### GET /metrics/prometheus Source: https://context7.com/cwklurks/hyperguard/llms.txt Exports system metrics in Prometheus format for scraping. ```APIDOC ## GET /metrics/prometheus ### Description Exports system metrics in the Prometheus exposition format, allowing Prometheus to scrape and collect these metrics. ### Method GET ### Endpoint /metrics/prometheus ### Response #### Success Response (200) - Returns a text-based response formatted according to the Prometheus exposition format. ### Request Example ```bash curl "http://localhost:8000/metrics/prometheus" ``` ``` -------------------------------- ### Record and Export Metrics with MetricsCollector Source: https://context7.com/cwklurks/hyperguard/llms.txt Demonstrates how to use the MetricsCollector to record trades, gate failures, and update portfolio metrics. Includes examples of exporting metrics in Prometheus and JSON formats. Ensure the MetricsCollector is initialized or obtained globally. ```python from src.metrics import MetricsCollector, get_metrics_collector # Get global singleton collector collector = get_metrics_collector() # Record approved trade collector.record_trade( approved=True, asset="ETH", action="BUY", value_usd=5000.0 ) # Record blocked trade (prevented loss) collector.record_trade( approved=False, asset="PEPE", action="BUY", value_usd=25000.0, rejection_reason="whitelist" ) # Record gate failure collector.record_gate_failure("Whitelist Check", asset="PEPE") # Update portfolio metrics collector.update_portfolio_metrics( nav_usd=105000.0, daily_pnl_usd=5000.0, daily_pnl_percent=5.0, daily_drawdown_percent=0.0, margin_utilization_percent=15.0 ) # Get key metrics print(f"Total trades: {collector.get_trades_total()}") print(f"Approval rate: {collector.get_approval_rate():.1f}%") print(f"Prevented loss: ${collector.get_prevented_loss_total():,.2f}") print(f"Gate failures: {collector.get_gate_failures()}") # Export for Prometheus scraping prometheus_output = collector.export_prometheus() print(prometheus_output) # Export as JSON json_output = collector.export_json() print(json_output) ``` -------------------------------- ### Verify Policy Synchronization Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Compare the local policy configuration with the on-chain policy to detect and report any discrepancies. This check ensures consistency between your local setup and the deployed contract. ```python import json # Load local policy with open("config/policy.json") as f: local_policy = json.load(f) # Compare with on-chain policy sync_result = contract.validate_policy_sync(local_policy) if sync_result["in_sync"]: print("✅ Policies are synchronized") else: print("⚠️ Policy discrepancies found:") for key, values in sync_result["discrepancies"].items(): print(f" {key}: {values}") ``` -------------------------------- ### Systemd Service Management Commands Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Commands to manage the HyperGuard systemd service, including user creation, ownership, enabling, starting, checking status, and viewing logs. ```bash # Create dedicated user sudo useradd -r -s /bin/false hyperguard sudo chown -R hyperguard:hyperguard /opt/hyperguard # Enable service sudo systemctl daemon-reload sudo systemctl enable hyperguard sudo systemctl start hyperguard # Check status sudo systemctl status hyperguard # View logs sudo journalctl -u hyperguard -f ``` -------------------------------- ### Query Logs with JQ Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Utilize the `jq` command-line tool to filter and analyze structured JSON logs. Examples include selecting rejected trades, kill switch activations, and high latency events. ```bash # All rejected trades cat logs/hyperguard.log | jq 'select(.approved == false)' # Kill switch activations cat logs/hyperguard.log | jq 'select(.message | contains("Kill switch activated"))' # High latency validations cat logs/hyperguard.log | jq 'select(.validation_latency_ms > 100)' # Errors in last hour cat logs/hyperguard.log | jq 'select(.level == "ERROR")' ``` -------------------------------- ### Get Gate Failure Statistics via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to retrieve statistics on gate failures from the /metrics/gate-failures endpoint. ```bash # Get gate failure statistics curl "http://localhost:8000/metrics/gate-failures" ``` -------------------------------- ### Get Prevented Loss Metric via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to retrieve the total prevented loss metric from the /metrics/prevented-loss endpoint. ```bash # Get prevented loss metric curl "http://localhost:8000/metrics/prevented-loss" ``` -------------------------------- ### Submit Trade for Execution via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to send a POST request to the /trades/submit endpoint. This submits a trade for validation and potential execution. The request body must be in JSON format. ```bash # Submit trade for execution curl -X POST "http://localhost:8000/trades/submit" \ -H "Content-Type: application/json" \ -d '{ "asset": "ETH", "base_unit_amount": 1.5, "action": "BUY", "price": null, "order_type": "market" }' ``` -------------------------------- ### Create and Secure Directories Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Use mkdir to create necessary directories and chmod to restrict access for security. ```bash mkdir -p logs data config chmod 700 logs data # Restrict access to logs and data directories ``` -------------------------------- ### Initialize and Use RiskEngineV2 with Enhanced Gates Source: https://context7.com/cwklurks/hyperguard/llms.txt Shows how to initialize RiskEngineV2 with a custom price fetcher and state file. It demonstrates validating a trade proposal with enhanced gates and inspecting detailed results, including kill switch status. ```python from src.guard import RiskEngineV2 from src.models import TradeProposal, AccountState, TradeAction, PriceQuote from datetime import datetime # Initialize V2 engine with price fetcher def fetch_price(asset: str) -> float: prices = {"ETH": 2500.0, "BTC": 45000.0, "SOL": 100.0} return prices.get(asset) engine = RiskEngineV2( policy_path="config/policy.json", price_fetcher=fetch_price, state_file_path="data/guard_state.json" ) # Check current kill switch state if engine._kill_switch_active: print("Kill switch is active!") engine.deactivate_kill_switch() # Manual override # Create proposal with price quote proposal = TradeProposal( asset="ETH", base_unit_amount=2.0, action=TradeAction.BUY, price_quote=PriceQuote( asset="ETH", price=2500.0, timestamp=datetime.now(), source="api" ) ) # Create detailed account state account = AccountState( nav_usd=100000.0, margin_used_usd=20000.0, daily_start_nav_usd=98000.0, open_positions={ "BTC": { "base_unit_amount": 0.5, "entry_price_usd": 44000.0, "pnl_usd": 500.0 } } ) # Validate through all 14 gates decision = engine.validate_trade(proposal, account) # Inspect all gate results for result in decision.gate_results: emoji = "✓" if result.passed else "✗" print(f" {emoji} {result.gate_name}: {result.message}") ``` -------------------------------- ### Create and Use Exchange Adapters with Factory Source: https://context7.com/cwklurks/hyperguard/llms.txt Demonstrates using the ExchangeAdapterFactory to create adapters for different exchanges, such as Hyperliquid. It shows how to fetch account state, market prices, and metadata, and how to register custom adapters. ```python from src.adapters import ExchangeAdapterFactory, BaseExchangeAdapter # List supported exchanges print(f"Supported: {ExchangeAdapterFactory.supported_exchanges()}") # Output: ['hyperliquid'] # Create adapter for Hyperliquid adapter = ExchangeAdapterFactory.create( exchange_name="hyperliquid", use_testnet=True, private_key="0x...", wallet_address="0x..." ) # Get account state state = adapter.get_account_state() print(f"NAV: ${state.nav:,.2f}") # Get all market prices prices = adapter.get_all_prices() for asset, price in list(prices.items())[:5]: print(f" {asset}: ${float(price):,.2f}") # Get market metadata for sizing metadata = adapter.get_market_metadata("ETH") print(f"ETH tick size: {metadata.tick_size}") print(f"ETH min size: {metadata.min_size}") # Register a custom adapter class MyExchangeAdapter(BaseExchangeAdapter): @property def exchange_name(self) -> str: return "MyExchange" @property def is_testnet(self) -> bool: return True # ... implement required methods ... ExchangeAdapterFactory.register("myexchange", MyExchangeAdapter) ``` -------------------------------- ### Run Demo Modes Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Execute the main script with different flags to enable various demo modes: simulation, dry-run, or live trading. Use the --live flag with caution. ```bash # 1. Simulation mode (no real API, mock data) python main.py # 2. Dry-run mode (real API, ephemeral wallet, mock balance) python main.py --dryrun # 3. Live mode (real API, real wallet - use with caution!) python main.py --live --testnet ``` -------------------------------- ### Initialize HyperGuard Client Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Initialize the HyperGuard client using configuration files for policy and exchange settings. Ensure the policy path and exchange name are correctly specified. ```python client = HyperGuardClient.from_config( policy_path="config/policy.json", exchange_name="myexchange" ) ``` -------------------------------- ### Initialize and Use RiskEngine for Trade Validation Source: https://context7.com/cwklurks/hyperguard/llms.txt Demonstrates initializing the RiskEngine with a policy and validating a trade proposal against an account state. It shows how to inspect validation results and retrieve gate metadata. ```python from src.guard import RiskEngine, TradeProposal, AccountState # Initialize risk engine with policy engine = RiskEngine(policy_path="config/policy.json") # Create trade proposal proposal = TradeProposal( asset="ETH", size=5000.0, # USD value action="BUY" ) # Create account state account = AccountState( nav=100000.0, margin_used=15000.0, daily_start_nav=100000.0, open_positions={ "BTC": {"size": 0.5, "entry_price": 45000, "pnl": 1000} } ) # Validate the trade decision = engine.validate_trade(proposal, account) print(f"Trade approved: {decision.approved}") print(f"Reason: {decision.reason}") print(f"Gates checked: {len(decision.gate_results)}") print(f"Failed gates: {[g.gate_name for g in decision.failed_gates]}") # Get gate metadata gates = engine.get_gates() for gate in gates: print(f" - {gate['name']}: {gate['description']}") ``` -------------------------------- ### Configure Exchange Credentials Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Set up your exchange credentials in the .env file. This includes private keys, wallet addresses, and network settings for supported exchanges. ```bash # Hyperliquid HYPERLIQUID_PRIVATE_KEY=0x... HYPERLIQUID_WALLET_ADDRESS=0x... HYPERLIQUID_NETWORK=testnet # Binance (future) BINANCE_API_KEY=... BINANCE_API_SECRET=... ``` -------------------------------- ### Create Dry-Run Hyperguard Client Source: https://context7.com/cwklurks/hyperguard/llms.txt Initializes a Hyperguard client for dry-run simulations using an ephemeral wallet. It includes mock trade validation and execution callbacks. ```python client = DryRunHyperGuardClient( policy_path="config/policy.json", mock_nav=100000.0, on_trade_validated=lambda d: print(f"Validation: {'PASS' if d.approved else 'FAIL'}"), on_execution_attempt=lambda asset, success, err: print(f"Execution: {asset} - {success}") ) # Verify API connectivity connected, error = client.verify_connectivity() print(f"API Connected: {connected}") # Get LIVE market prices eth_price = client.get_live_price("ETH") print(f"Live ETH price: ${eth_price:,.2f}") # Submit trade (validates with mock balance, attempts real execution) result = client.submit_trade("ETH", 5000, "BUY") # Expected: validation passes, execution fails with "insufficient funds" # This proves the entire pipeline works without risking real money print(f"Pipeline verified: {result.execution_result.get('pipeline_verified', False)}") ``` -------------------------------- ### GET /healthz Source: https://context7.com/cwklurks/hyperguard/llms.txt Kubernetes liveness probe endpoint. ```APIDOC ## GET /healthz ### Description Provides a liveness probe endpoint, typically used by container orchestration systems like Kubernetes to check if the application is running. ### Method GET ### Endpoint /healthz ### Response #### Success Response (200) - Returns an empty response or a simple status message indicating the application is live. ### Request Example ```bash curl "http://localhost:8000/healthz" ``` ``` -------------------------------- ### GET /metrics/gate-failures Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves statistics on validation gate failures. ```APIDOC ## GET /metrics/gate-failures ### Description Retrieves statistics related to failures encountered across different validation gates. ### Method GET ### Endpoint /metrics/gate-failures ### Response #### Success Response (200) - Returns an object or array detailing the count and types of gate failures. ### Request Example ```bash curl "http://localhost:8000/metrics/gate-failures" ``` ``` -------------------------------- ### Initialize and Use MockHyperGuardClient for Testing Source: https://context7.com/cwklurks/hyperguard/llms.txt Initializes a MockHyperGuardClient to simulate the validation pipeline without real API calls. Ideal for testing trading strategies. Use simulate_pnl to test drawdown protection and reset to re-initialize the client. ```python from src.client import MockHyperGuardClient # Initialize mock client with simulated portfolio client = MockHyperGuardClient( policy_path="config/policy.json", initial_nav=100000.0, on_trade_validated=lambda d: print(f"Trade validated: {d.approved}") ) # Execute simulated trades result1 = client.submit_trade("ETH", 5000, "BUY") result2 = client.submit_trade("BTC", 8000, "BUY") # Simulate a P&L loss to test drawdown protection client.simulate_pnl(-6000) # Lose $6,000 # This trade should be blocked by drawdown check result3 = client.submit_trade("SOL", 2000, "BUY") print(f"After drawdown - Trade approved: {result3.validation.approved}") # Output: After drawdown - Trade approved: False # Check mock account state state = client.get_account_state() print(f"Mock NAV: ${state.nav:,.2f}") print(f"Mock positions: {state.open_positions}") # Reset for fresh test client.reset(initial_nav=50000.0) ``` -------------------------------- ### GET /metrics/prevented-loss Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves the total amount of prevented loss. ```APIDOC ## GET /metrics/prevented-loss ### Description Retrieves the total cumulative value of losses that were prevented by the system's validation gates. ### Method GET ### Endpoint /metrics/prevented-loss ### Response #### Success Response (200) - Returns the total prevented loss, typically as a numerical value in USD. ### Request Example ```bash curl "http://localhost:8000/metrics/prevented-loss" ``` ``` -------------------------------- ### Initialize and Use HyperGuardClient Source: https://context7.com/cwklurks/hyperguard/llms.txt Initializes the HyperGuardClient for a specific exchange and submits trades for validation and execution. Handles trade results and retrieves account state. Ensure policy_path is correctly configured. ```python from src.client import HyperGuardClient # Initialize with default Hyperliquid exchange client = HyperGuardClient( policy_path="config/policy.json", use_testnet=True, exchange_name="hyperliquid" ) # Submit a trade for validation and execution result = client.submit_trade( asset="ETH", size=5000.0, # USD value action="BUY", order_type="market", reduce_only=False ) if result.success: print(f"Trade executed: {result.execution_result}") print(f"Normalized order: {result.normalized_order}") else: print(f"Trade blocked: {result.error}") print(f"Validation reason: {result.validation.reason}") print(f"Failed gates: {[g.gate_name for g in result.validation.failed_gates]}") # Check current account state account = client.get_account_state() print(f"NAV: ${account.nav:,.2f}") print(f"Daily P&L: {account.daily_pnl_percent:.2f}%") print(f"Margin used: ${account.margin_used:,.2f}") # Check lockout status is_locked, reason = client.is_locked_out() if is_locked: print(f"System locked: {reason}") ``` -------------------------------- ### GET /health Source: https://context7.com/cwklurks/hyperguard/llms.txt Performs a health check on the system components. ```APIDOC ## GET /health ### Description Checks the overall health status of the Hyperguard system and its various components. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The overall health status (e.g., "healthy"). - **version** (string) - The current version of the Hyperguard application. - **components** (object) - Status of individual system components. - **[COMPONENT_NAME]** (string) - Health status of a specific component (e.g., "client", "risk_engine"). #### Response Example ```json { "status": "healthy", "version": "1.2.0", "components": { "client": "healthy", "risk_engine": "healthy", "metrics": "healthy", "database": "healthy" } } ``` ``` -------------------------------- ### Building Hyperguard Docker Image Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Build a custom Docker image for Hyperguard using the provided Dockerfile. Verify image size and run the container with custom commands or interactively. ```bash # Build with tag docker build -t hyperguard:latest . ``` ```bash # Verify image size (target: <500MB) docker images hyperguard:latest --format "{{.Size}}" ``` ```bash # Run with custom command docker run --rm --env-file .env hyperguard:latest python main.py --live --testnet ``` ```bash # Interactive TUI dashboard docker run -it --rm --env-file .env hyperguard:latest ``` -------------------------------- ### GET /account/metrics Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves key performance metrics for the account. ```APIDOC ## GET /account/metrics ### Description Retrieves key performance metrics related to the account's trading activity and risk management. ### Method GET ### Endpoint /account/metrics ### Response #### Success Response (200) - Returns an object containing various account metrics, such as daily PnL, drawdown, and margin utilization. ### Request Example ```bash curl "http://localhost:8000/account/metrics" ``` ``` -------------------------------- ### Configure Firewall with UFW Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Set up a Uncomplicated Firewall (UFW) to secure your server by denying incoming traffic by default and allowing specific ports like SSH and a metrics endpoint. ```bash # Configure firewall (ufw example) sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow ssh sudo ufw allow 9090/tcp # Metrics endpoint (if exposing) sudo ufw enable # Rate limiting for API endpoints sudo ufw limit ssh/tcp ``` -------------------------------- ### Create Exchange Adapter using Factory Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Instantiate an adapter for a specific exchange using the ExchangeAdapterFactory. Supports testnet/mainnet and requires private key and wallet address. ```python from src.adapters import BaseExchangeAdapter, ExchangeAdapterFactory # Create adapter for any supported exchange adapter = ExchangeAdapterFactory.create( exchange_name="hyperliquid", # or "binance", etc. use_testnet=True, private_key="0x...", wallet_address="0x..." ) ``` -------------------------------- ### GET /account/positions Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves only the open positions within the account. ```APIDOC ## GET /account/positions ### Description Retrieves a summary of all currently open positions in the trading account. ### Method GET ### Endpoint /account/positions ### Response #### Success Response (200) - **open_positions** (object) - An object detailing all currently open positions, structured similarly to the `open_positions` field in `/account/state`. #### Response Example ```json { "open_positions": { "ETH": {"base_unit_amount": 5.0, "entry_price_usd": 2400.0, "pnl_usd": 500.0} } } ``` ``` -------------------------------- ### GET /trades/history Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves the history of submitted trades, with options for limiting and offsetting results. ```APIDOC ## GET /trades/history ### Description Retrieves a list of past trades submitted through the API. Supports pagination via limit and offset parameters. ### Method GET ### Endpoint /trades/history ### Query Parameters - **limit** (integer) - Optional - The maximum number of trades to return. - **offset** (integer) - Optional - The number of trades to skip before starting to collect the result set. ### Response #### Success Response (200) - Returns an array of trade objects, each containing details of a past trade. ### Request Example ```bash curl "http://localhost:8000/trades/history?limit=50&offset=0" ``` ``` -------------------------------- ### Generate Test Keys with eth-account Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Use this command to generate private keys and addresses for development and testing purposes. Ensure to use hardware wallets for production environments. ```bash # Generate test keys using eth-account python -c "from eth_account import Account; acc = Account.create(); print(f'Private Key: {acc.key.hex()}'); print(f'Address: {acc.address}')" ``` -------------------------------- ### Initialize DryRunHyperGuardClient Source: https://context7.com/cwklurks/hyperguard/llms.txt Initializes a DryRunHyperGuardClient, which connects to real exchange APIs with an ephemeral wallet. It uses mock balances for validation but attempts real order execution to verify the complete pipeline. ```python from src.client import DryRunHyperGuardClient ``` -------------------------------- ### GET /account/state Source: https://context7.com/cwklurks/hyperguard/llms.txt Retrieves the current state of the account, including Net Asset Value (NAV), margin usage, and open positions. ```APIDOC ## GET /account/state ### Description Retrieves the current state of the trading account, including financial metrics and details of all open positions. ### Method GET ### Endpoint /account/state ### Response #### Success Response (200) - **nav_usd** (number) - Net Asset Value in USD. - **margin_used_usd** (number) - The amount of margin currently used in USD. - **daily_start_nav_usd** (number) - The NAV at the start of the current trading day in USD. - **daily_pnl_usd** (number) - Profit and Loss for the current day in USD. - **daily_pnl_percent** (number) - Profit and Loss for the current day as a percentage. - **drawdown_percent** (number) - The maximum drawdown percentage experienced. - **available_margin_usd** (number) - The amount of margin available in USD. - **open_positions** (object) - An object detailing all currently open positions. - **[ASSET_SYMBOL]** (object) - Details for a specific open position. - **base_unit_amount** (number) - The amount of the base asset held. - **entry_price_usd** (number) - The average entry price in USD. - **pnl_usd** (number) - The unrealized Profit and Loss for this position in USD. #### Response Example ```json { "nav_usd": 105000.0, "margin_used_usd": 15000.0, "daily_start_nav_usd": 100000.0, "daily_pnl_usd": 5000.0, "daily_pnl_percent": 5.0, "drawdown_percent": 0.0, "available_margin_usd": 90000.0, "open_positions": { "ETH": {"base_unit_amount": 5.0, "entry_price_usd": 2400.0, "pnl_usd": 500.0} } } ``` ``` -------------------------------- ### Multi-Exchange Client Initialization Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Dynamically switch between different exchange adapters using the ExchangeAdapterFactory. Initialize the HyperGuard client with the selected adapter and policy configuration. ```python from src.adapters import ExchangeAdapterFactory # Switch between exchanges dynamically for exchange in ["hyperliquid", "binance"]: try: adapter = ExchangeAdapterFactory.create( exchange_name=exchange, use_testnet=True ) client = HyperGuardClient( adapter=adapter, policy_path="config/policy.json" ) result = client.submit_trade("BTC", 1000, "BUY") print(f"{exchange}: {result.success}") except ValueError as e: print(f"{exchange} not yet implemented") ``` -------------------------------- ### Docker Deployment and Execution Commands Source: https://context7.com/cwklurks/hyperguard/llms.txt Commands for deploying HyperGuard using Docker Compose, including setting up environment variables, running in demo or development modes, executing tests, building the image, and running the API server with production settings. ```bash # Copy and configure environment cp .env.example .env # Edit .env with your credentials: # HYPERLIQUID_PRIVATE_KEY=0x... # HYPERLIQUID_WALLET_ADDRESS=0x... # HYPERLIQUID_NETWORK=testnet # Run in demo mode (simulation) docker compose up # Run with development profile (live-reload) docker compose --profile dev up # Run test suite in container docker compose --profile test run hyperguard-test # Build the image manually docker build -t hyperguard:latest . # Run API server with production settings docker run -d \ -p 8000:8000 \ -e HYPERGUARD_MODE=live \ -e HYPERLIQUID_PRIVATE_KEY=$HYPERLIQUID_PRIVATE_KEY \ -e API_KEY_REQUIRED=true \ -e HYPERGUARD_API_KEY=your_secret_key \ -v $(pwd)/config:/app/config \ -v $(pwd)/data:/app/data \ hyperguard:latest ``` -------------------------------- ### Filter Logs for Slow Operations Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Filters the HyperGuard log file to show entries where validation latency exceeded 100ms. Requires jq to be installed. ```bash cat logs/hyperguard.log | jq 'select(.validation_latency_ms > 100)' ``` -------------------------------- ### Cancel All Open Orders via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to send a POST request to the /account/orders/cancel-all endpoint to cancel all open orders. ```bash # Cancel all open orders curl -X POST "http://localhost:8000/account/orders/cancel-all" ``` -------------------------------- ### Test Hyperliquid API Connectivity Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Performs a basic connectivity test to the Hyperliquid API endpoint using curl and jq for JSON parsing. Requires jq to be installed. ```bash curl -s https://api.hyperliquid-testnet.xyz/info | jq . ``` -------------------------------- ### Kubernetes Deployment Commands Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Apply Kubernetes manifests, check deployment status, view logs, and port-forward for metrics using kubectl commands. Ensure the namespace 'hyperguard' is used. ```bash # Apply manifests kubectl apply -f k8s/ ``` ```bash # Check deployment kubectl get pods -n hyperguard ``` ```bash # View logs kubectl logs -f deployment/hyperguard -n hyperguard ``` ```bash # Port forward for metrics kubectl port-forward -n hyperguard deployment/hyperguard 9090:9090 ``` -------------------------------- ### Disable Market Safety Gates Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Example JSON configuration to disable market safety gates by setting relevant thresholds to null. Adjust based on specific needs. ```json { "market_safety_gates": { "max_volatility_percent": null, "max_slippage_percent": null } } ``` -------------------------------- ### HyperGuardClient Usage Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Demonstrates how to use the HyperGuardClient for seamless integration with on-chain validation when enabled in the policy configuration. ```APIDOC ## HyperGuardClient Usage ### Description This section shows how to initialize and use the `HyperGuardClient` to perform risk assessments, including automatic on-chain validation if configured. ### Method Client Initialization and Trade Validation ### Endpoint N/A (Client-side library) ### Parameters N/A for client initialization. ### Request Body N/A for client initialization. ### Request Example ```python from src.client import HyperGuardClient from src.models import TradeProposal # Assuming TradeProposal is defined elsewhere # Initialize client (automatically loads contract if enabled) client = HyperGuardClient() # Create a trade proposal proposal = TradeProposal( asset="ETH", size=1000.0, is_buy=True, order_type="MARKET" ) # Validate trade (includes on-chain validation if enabled) result = client.risk_engine.validate_trade(proposal, nav=10000.0) if result.approved: print(f"✅ Trade approved: {result.reason}") else: print(f"❌ Trade rejected: {result.reason}") ``` ### Response #### Success Response (Trade Approved) - **approved** (boolean) - True if the trade is approved. - **reason** (string) - Explanation for the approval. #### Response Example ```json { "approved": true, "reason": "Trade within risk limits." } ``` #### Failure Response (Trade Rejected) - **approved** (boolean) - False if the trade is rejected. - **reason** (string) - Explanation for the rejection. #### Response Example ```json { "approved": false, "reason": "Trade size exceeds maximum allowed." } ``` ``` -------------------------------- ### Prometheus Scrape Configuration Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Configure Prometheus to scrape metrics from the HyperGuard application. This example shows a basic configuration to scrape metrics from the default endpoint at port 9090. ```yaml # prometheus.yml scrape_configs: - job_name: 'hyperguard' static_configs: - targets: ['localhost:9090'] scrape_interval: 15s ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Sets up an isolated Python environment using venv and activates it. This is crucial for managing project dependencies separately. ```bash # Create virtual environment python3.12 -m venv venv # Activate virtual environment source venv/bin/activate # Linux/macOS # OR . venv\Scripts\activate # Windows # Upgrade pip pip install --upgrade pip ``` -------------------------------- ### Get Hyperguard Account State Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Retrieves and prints the current account state, including Net Asset Value (NAV) and Profit/Loss (P&L), using the HyperGuardClient. ```python from src.client import HyperGuardClient client = HyperGuardClient.from_config("config/policy.json") state = client.get_account_state() print(f"NAV: ${state.nav:,.2f}") print(f"P&L: ${state.daily_pnl:,.2f} ({state.daily_pnl_percent:.2f}%)") ``` -------------------------------- ### Configure Logging Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Set up basic logging for the contract module to track important events such as connection status, validation results, and errors. ```python import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("src.contract") # Logs include: # - Connection status # - Validation results # - Transaction hashes # - Error conditions ``` -------------------------------- ### Backup Hyperguard Policy Configuration Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Creates a timestamped backup of the current policy JSON file before making modifications. ```bash cp config/policy.json config/policy.json.backup.$(date +%Y%m%d_%H%M%S) ``` -------------------------------- ### Schedule Daily Hyperguard Backups with Cron Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Configures a cron job to execute the backup script daily at 2 AM, redirecting output and errors to a log file. ```bash # Run daily at 2 AM 0 2 * * * /opt/hyperguard/backup.sh >> /var/log/hyperguard-backup.log 2>&1 ``` -------------------------------- ### Retrieve Trade History via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to fetch trade history from the /trades/history endpoint. Query parameters can be used to limit and offset results. ```bash # Get trade history curl "http://localhost:8000/trades/history?limit=50&offset=0" ``` -------------------------------- ### Backup HyperGuard Database Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Create a timestamped backup of the HyperGuard database before performing maintenance. ```bash cp data/hyperguard.db data/hyperguard.db.backup.$(date +%Y%m%d) ``` -------------------------------- ### Kubernetes Liveness Probe via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to trigger the Kubernetes liveness probe endpoint (/healthz). This endpoint is used by Kubernetes to check if the application is running. ```bash # Kubernetes liveness probe curl "http://localhost:8000/healthz" ``` -------------------------------- ### Run Integration Tests Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Execute integration tests with a mocked contract to verify end-to-end validation flows. ```bash pytest tests/test_integration.py::TestOnChainValidation -v ``` -------------------------------- ### Perform Health Check via REST API Source: https://context7.com/cwklurks/hyperguard/llms.txt Example using curl to check the system's health status via the /health endpoint. This is useful for monitoring and orchestration tools. ```bash # Health check curl "http://localhost:8000/health" ``` -------------------------------- ### Example Structured Log Entry Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md This JSON object represents a typical audit log entry, including timestamp, log level, message, and specific trade details. Useful for forensic analysis. ```json { "timestamp": "2026-01-26T10:15:30.123Z", "level": "INFO", "logger": "src.guard", "message": "Trade validated", "module": "guard", "function": "validate_trade", "line": 342, "asset": "ETH", "size_usd": 5000.0, "action": "BUY", "approved": true, "gates_passed": 14, "validation_latency_ms": 12.5 } ``` -------------------------------- ### Optimize Database for Performance Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Applies several SQLite pragmas to improve database performance, including enabling Write-Ahead Logging (WAL) and increasing cache size. ```bash sqlite3 data/hyperguard.db "VACUUM; ANALYZE;" ``` -------------------------------- ### Monitor Daily Drawdown Percentage Source: https://github.com/cwklurks/hyperguard/blob/main/docs/METRICS.md This gauge shows the current drawdown from the daily starting NAV, always reported as a non-negative value. It's crucial for monitoring proximity to the kill switch threshold. ```prometheus hyperguard_daily_drawdown_percent 2.5 ``` -------------------------------- ### Monitor Daily P&L Percentage Source: https://github.com/cwklurks/hyperguard/blob/main/docs/METRICS.md This gauge displays the current daily profit/loss as a percentage of the starting Net Asset Value (NAV). It's useful for real-time monitoring of portfolio performance. ```prometheus hyperguard_daily_pnl_percent -2.5 ``` -------------------------------- ### Get Contract Health Metrics Source: https://github.com/cwklurks/hyperguard/blob/main/docs/ON_CHAIN_VALIDATION.md Retrieve health metrics from the contract to monitor its operational status. Key metrics include connection status, policy name, error presence, and configuration loading. ```python health = contract.health_check() # Key metrics metrics = { "connected": health["connected"], "policy_name": health["policy_name"], "has_errors": len(health["errors"]) > 0, "config_loaded": health["config"] is not None } ``` -------------------------------- ### Monitor Kill Switch Activation Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Use `tail` and `jq` to monitor log files in real-time for kill switch activation messages. This helps in quickly identifying critical security events. ```bash # Monitor logs for kill switch tail -f logs/hyperguard.log | jq 'select(.message | contains("Kill switch activated"))' ``` -------------------------------- ### Backup Hyperguard Database and Logs Source: https://github.com/cwklurks/hyperguard/blob/main/docs/DEPLOYMENT.md Automates the backup of the Hyperguard database, metrics state, and logs to a specified directory. It also manages backup retention by deleting files older than 30 days. ```bash BACKUP_DIR="/backups/hyperguard" DATE=$(date +%Y%m%d_%H%M%S) DB_PATH="data/hyperguard.db" METRICS_PATH="data/metrics_state.json" mkdir -p "$BACKUP_DIR" # Backup database cp "$DB_PATH" "$BACKUP_DIR/hyperguard_${DATE}.db" # Backup metrics state cp "$METRICS_PATH" "$BACKUP_DIR/metrics_${DATE}.json" # Backup logs (last 7 days) tar -czf "$BACKUP_DIR/logs_${DATE}.tar.gz" logs/*.log # Keep only last 30 days of backups find "$BACKUP_DIR" -type f -mtime +30 -delete echo "Backup completed: $DATE" ``` -------------------------------- ### Docker Compose Commands for HyperGuard Source: https://github.com/cwklurks/hyperguard/blob/main/README.md Commands to run HyperGuard in a Docker container for different scenarios like demo mode, development with live-reloading, or running the test suite. Also includes building the Docker image manually. ```bash # Copy and configure environment cp .env.example .env # Edit .env with your credentials # Run in demo mode (simulation) docker compose up # Run with development profile (live-reload) docker compose --profile dev up # Run test suite in container docker compose --profile test run hyperguard-test # Build the image manually docker build -t hyperguard:latest . ```