[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HSPA174YN8BP6J958K3RT":3,"skill-same:01M77HSPA174YN8BP6J958K3RT":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":42,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M77HSPA174YN8BP6J958K3RT","greenhelix-trading-bot-risk-service",null,"Trading Bot Risk-as-a-Service: Real-Time Portfolio Risk Monitoring for Multi-Exchange Operations. Build a cross-exchange, cross-strategy real-time portfolio risk monitoring system with webhooks, event bus, and SLA compliance enforcement. Covers drawdown alerts, correlation monitoring, liquidation proximity, circuit breakers, and production deployment.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-trading-bot-risk-service\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-trading-bot-risk-service\nversion: \"1.3.1\"\ndescription: \"Trading Bot Risk-as-a-Service: Real-Time Portfolio Risk Monitoring for Multi-Exchange Operations. Build a cross-exchange, cross-strategy real-time portfolio risk monitoring system with webhooks, event bus, and SLA compliance enforcement. Covers drawdown alerts, correlation monitoring, liquidation proximity, circuit breakers, and production deployment.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [trading-bot, risk-management, portfolio, monitoring, circuit-breaker, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [AGENT_SIGNING_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - AGENT_SIGNING_KEY\n    primaryEnv: AGENT_SIGNING_KEY\n---\n# Trading Bot Risk-as-a-Service: Real-Time Portfolio Risk Monitoring for Multi-Exchange Operations\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nIf you run trading bots across multiple exchanges, you have a visibility problem. Binance shows you Binance positions. Coinbase shows you Coinbase positions. Kraken shows you Kraken positions. Nobody shows you the aggregate. Nobody tells you that your mean-reversion strategy on Binance and your momentum strategy on Coinbase have become 0.94 correlated over the last four hours -- meaning a single market move will hit both simultaneously. Nobody warns you that your combined leverage across three exchanges has crept from 3x to 7x because each exchange only sees its own slice. The May 2025 cascade liquidations on BitMEX made this concrete: bots running isolated risk checks per exchange missed the aggregate exposure building across venues, and when BTC dropped 12% in ninety minutes, the cross-exchange margin calls arrived simultaneously. Operators who had $200K in aggregate equity across four exchanges discovered they were effectively running 11x leverage when positions were netted. The liquidation cascade took 47 seconds from first margin call to full wipeout. This guide builds a complete, production-grade risk monitoring system that sits above your exchange connections and provides a unified view of portfolio risk. It uses GreenHelix's event bus for real-time data aggregation, webhooks for alert delivery, and SLA compliance monitoring for operational health tracking. You will build drawdown trackers, correlation monitors, liquidation proximity engines, and circuit breakers -- all wired together through a single risk management layer that treats your entire multi-exchange operation as one portfolio.\n1. [Risk Architecture Overview](#chapter-1-risk-architecture-overview)\n2. [The RiskMonitor Class](#chapter-2-the-riskmonitor-class)\n\n## What You'll Learn\n- Chapter 1: Risk Architecture Overview\n- Chapter 2: The RiskMonitor Class\n- Chapter 3: Drawdown Monitoring and Alerts\n- Chapter 4: Correlation Monitoring\n- Chapter 5: Liquidation Proximity Engine\n- Chapter 6: Circuit Breaker Implementation\n- Chapter 7: Multi-Exchange Aggregation\n- Next Steps\n- What's Next\n\n## Full Guide\n\n# Trading Bot Risk-as-a-Service: Real-Time Portfolio Risk Monitoring for Multi-Exchange Operations\n\nIf you run trading bots across multiple exchanges, you have a visibility problem. Binance shows you Binance positions. Coinbase shows you Coinbase positions. Kraken shows you Kraken positions. Nobody shows you the aggregate. Nobody tells you that your mean-reversion strategy on Binance and your momentum strategy on Coinbase have become 0.94 correlated over the last four hours -- meaning a single market move will hit both simultaneously. Nobody warns you that your combined leverage across three exchanges has crept from 3x to 7x because each exchange only sees its own slice. The May 2025 cascade liquidations on BitMEX made this concrete: bots running isolated risk checks per exchange missed the aggregate exposure building across venues, and when BTC dropped 12% in ninety minutes, the cross-exchange margin calls arrived simultaneously. Operators who had $200K in aggregate equity across four exchanges discovered they were effectively running 11x leverage when positions were netted. The liquidation cascade took 47 seconds from first margin call to full wipeout. This guide builds a complete, production-grade risk monitoring system that sits above your exchange connections and provides a unified view of portfolio risk. It uses GreenHelix's event bus for real-time data aggregation, webhooks for alert delivery, and SLA compliance monitoring for operational health tracking. You will build drawdown trackers, correlation monitors, liquidation proximity engines, and circuit breakers -- all wired together through a single risk management layer that treats your entire multi-exchange operation as one portfolio.\n\n---\n\n## Table of Contents\n\n1. [Risk Architecture Overview](#chapter-1-risk-architecture-overview)\n2. [The RiskMonitor Class](#chapter-2-the-riskmonitor-class)\n3. [Drawdown Monitoring and Alerts](#chapter-3-drawdown-monitoring-and-alerts)\n4. [Correlation Monitoring](#chapter-4-correlation-monitoring)\n5. [Liquidation Proximity Engine](#chapter-5-liquidation-proximity-engine)\n6. [Circuit Breaker Implementation](#chapter-6-circuit-breaker-implementation)\n7. [Multi-Exchange Aggregation](#chapter-7-multi-exchange-aggregation)\n9. [What's Next](#whats-next)\n\n---\n\n## Chapter 1: Risk Architecture Overview\n\n### Why Centralized Risk Monitoring Matters\n\nEvery professional trading desk has a risk management layer that sits above the execution layer. The risk system sees all positions, all strategies, all venues. It computes aggregate exposure, monitors correlation regimes, and has the authority to halt trading when thresholds are breached. Retail and semi-professional bot operators skip this layer because building it is hard and the exchanges do not provide the APIs to do it natively across venues. The result is that a $500K multi-exchange bot operation runs with less risk infrastructure than a single-desk prop trader at a regional firm.\n\nThe failure modes are specific and predictable:\n\n- **Cross-exchange leverage accumulation**: Each exchange computes margin independently. A 3x position on Binance and a 3x position on Coinbase in correlated assets is effectively 6x aggregate leverage against your total equity -- but neither exchange reports it that way.\n- **Correlation regime changes**: Two strategies that were uncorrelated during backtesting become highly correlated during market stress. The diversification benefit you assumed in your position sizing disappears exactly when you need it.\n- **Cascading liquidations**: A liquidation on one exchange reduces your total equity, which increases your leverage ratio on other exchanges, which triggers further liquidations. This feedback loop operates faster than human reaction time.\n- **Silent risk drift**: Without continuous monitoring, risk parameters drift over days and weeks. A portfolio that started at 2x aggregate leverage creeps to 5x through a series of individually reasonable position additions.\n\n### Architecture\n\nThe system has four layers:\n\n```\n+------------------+    +------------------+    +------------------+\n|  Binance Bot     |    |  Coinbase Bot    |    |  Kraken Bot      |\n|  (execution)     |    |  (execution)     |    |  (execution)     |\n+--------+---------+    +--------+---------+    +--------+---------+\n         |                       |                       |\n         |   publish_event       |   publish_event       |   publish_event\n         v                       v                       v\n+------------------------------------------------------------------------+\n|                     GreenHelix Event Bus                                |\n|  (real-time event ingestion, schema validation, ordering)              |\n+--------+---------------------+-----------------------+-----------------+\n         |                     |                       |\n         |   get_events        |   webhooks            |   get_sla_compliance\n         v                     v                       v\n+------------------------------------------------------------------------+\n|                     Risk Engine                                        |\n|  +----------------+  +------------------+  +------------------------+  |\n|  | DrawdownTracker|  | CorrelationMon   |  | LiquidationProximity   |  |\n|  +----------------+  +------------------+  +------------------------+  |\n|  +----------------+  +------------------+  +------------------------+  |\n|  | CircuitBreaker |  | ExchangeAggr     |  | AlertManager           |  |\n|  +----------------+  +------------------+  +------------------------+  |\n+--------+---------------------------------------------------------------+\n         |\n         |   send_message \u002F register_webhook\n         v\n+------------------------------------------------------------------------+\n|                     Alert Delivery                                      |\n|  Slack, PagerDuty, Telegram, Email, SMS                                |\n+------------------------------------------------------------------------+\n```\n\n### GreenHelix Tools Used\n\nThis guide uses seven GreenHelix tools:\n\n| Tool | Purpose |\n|------|---------|\n| `register_agent` | Register the risk monitoring agent |\n| `register_webhook` | Set up alert delivery endpoints |\n| `publish_event` | Bots publish position and trade events |\n| `get_events` | Risk engine retrieves events for analysis |\n| `get_sla_compliance` | Monitor risk engine uptime and latency |\n| `submit_metrics` | Report risk metrics for observability |\n| `send_message` | Deliver alerts to operators |\n\n### Risk Metrics Hierarchy\n\nRisk metrics are computed at four levels, each aggregating from the level below:\n\n1. **Position-level**: Per-position P&L, unrealized P&L, distance to liquidation, margin utilization\n2. **Strategy-level**: Strategy drawdown, strategy Sharpe ratio (rolling), strategy exposure, number of open positions\n3. **Portfolio-level**: Aggregate drawdown, cross-strategy correlation matrix, net exposure by asset, aggregate leverage\n4. **Fleet-level**: Total equity at risk, number of active strategies, circuit breaker status, SLA compliance score\n\nEach level publishes events to the GreenHelix event bus, and higher levels consume events from lower levels. This creates a clean data flow where the risk engine never polls exchanges directly -- it only reads from the event bus.\n\n### Event Types for Risk Monitoring\n\nDefine one event type per risk signal:\n\n| Event Type | Trigger | Key Fields |\n|---|---|---|\n| `risk.portfolio_check` | Periodic risk scan completes | total_equity, aggregate_leverage, alerts |\n| `risk.drawdown_alert` | Drawdown exceeds threshold | level, threshold_pct, current_pct, trigger_timeframe |\n| `risk.correlation_matrix` | Correlation matrix updated | matrix, strategy_count |\n| `risk.correlation_regime_change` | Correlation shift detected | avg_change, max_change |\n| `risk.liquidation_proximity` | Liquidation check completes | positions, min_distance_pct |\n| `risk.circuit_breaker_transition` | State change | from, to, reason, trip_count |\n| `risk.circuit_breaker_config` | Triggers updated | triggers |\n| `risk.aggregate_snapshot` | Cross-exchange aggregation | total_equity, aggregate_leverage, net_exposure |\n| `risk.thresholds_updated` | Risk thresholds changed | thresholds |\n| `risk.key_rotated` | Agent key rotation | new_public_key |\n\nEach event is signed with the risk agent's Ed25519 private key. The signature covers the canonical JSON serialization of the payload (keys sorted, no whitespace), ensuring that risk events cannot be fabricated or tampered with after the fact. This matters when you need to prove to auditors or investors that a circuit breaker tripped at a specific time for a specific reason.\n\n### Verifying the API Connection\n\nBefore building the full risk engine, verify that your GreenHelix API credentials work:\n\n```bash\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"risk-monitor-prod-01\",\n      \"public_key\": \"'\"$PUBLIC_KEY_B64\"'\",\n      \"name\": \"Portfolio Risk Monitor\"\n    }\n  }'\n```\n\n```python\nimport requests\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\nAPI_KEY = \"your-api-key\"\n\nresponse = requests.post(\n    f\"{API_BASE}\u002Fv1\",\n    headers={\n        \"Authorization\": f\"Bearer {API_KEY}\",\n        \"Content-Type\": \"application\u002Fjson\",\n    },\n    json={\n        \"tool\": \"register_agent\",\n        \"input\": {\n            \"agent_id\": \"risk-monitor-prod-01\",\n            \"public_key\": \"your-public-key-base64\",\n            \"name\": \"Portfolio Risk Monitor\",\n        },\n    },\n)\nprint(response.json())\n```\n\nIf both return a success response with your agent ID, the foundation is in place.\n\n---\n\n## Chapter 2: The RiskMonitor Class\n\n### Core Infrastructure\n\nThe `RiskMonitor` class is the foundation for all risk monitoring in this guide. Every subsequent chapter builds on it.\n\n```bash\n# Generate an Ed25519 keypair for the risk monitor agent\npython3 -c \"\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\nimport base64\n\nprivate_key = Ed25519PrivateKey.generate()\npublic_key = private_key.public_key()\n\npriv_bytes = private_key.private_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PrivateFormat.Raw,\n    encryption_algorithm=serialization.NoEncryption()\n)\npub_bytes = public_key.public_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PublicFormat.Raw\n)\n\nprint(f'PRIVATE_KEY_B64={base64.b64encode(priv_bytes).decode()}')\nprint(f'PUBLIC_KEY_B64={base64.b64encode(pub_bytes).decode()}')\n\"\n```\n\n```bash\n# Register the risk monitor agent\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"risk-monitor-prod-01\",\n      \"public_key\": \"'\"$PUBLIC_KEY_B64\"'\",\n      \"name\": \"Portfolio Risk Monitor\"\n    }\n  }'\n```\n\n### Python Implementation\n\n```python\nimport json\nimport time\nimport base64\nimport hashlib\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional, Any\n\nimport requests\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\n\nclass RiskMonitor:\n    \"\"\"Cross-exchange portfolio risk monitoring using GreenHelix APIs.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        private_key_b64: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        })\n\n        # Load Ed25519 private key\n        key_bytes = base64.b64decode(private_key_b64)\n        self._private_key = Ed25519PrivateKey.from_private_bytes(key_bytes)\n        self._public_key = self._private_key.public_key()\n\n        # Risk thresholds (defaults)\n        self.thresholds = {\n            \"max_drawdown_pct\": 15.0,\n            \"max_correlation\": 0.85,\n            \"max_leverage\": 5.0,\n            \"min_margin_ratio\": 0.20,\n            \"max_single_position_pct\": 25.0,\n        }\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        response = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        response.raise_for_status()\n        return response.json()\n\n    def _sign(self, payload: dict) -> str:\n        \"\"\"Sign a payload with Ed25519.\"\"\"\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self._private_key.sign(canonical.encode(\"utf-8\"))\n        return base64.b64encode(signature).decode()\n\n    def register_risk_agent(self) -> dict:\n        \"\"\"Register this risk monitor as a GreenHelix agent.\"\"\"\n        pub_bytes = self._public_key.public_bytes(\n            encoding=serialization.Encoding.Raw,\n            format=serialization.PublicFormat.Raw,\n        )\n        return self._execute(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"public_key\": base64.b64encode(pub_bytes).decode(),\n            \"name\": f\"Risk Monitor ({self.agent_id})\",\n        })\n\n    def configure_thresholds(\n        self,\n        max_drawdown_pct: float = 15.0,\n        max_correlation: float = 0.85,\n        max_leverage: float = 5.0,\n        min_margin_ratio: float = 0.20,\n        max_single_position_pct: float = 25.0,\n    ) -> dict:\n        \"\"\"Set risk thresholds and publish them as a configuration event.\"\"\"\n        self.thresholds = {\n            \"max_drawdown_pct\": max_drawdown_pct,\n            \"max_correlation\": max_correlation,\n            \"max_leverage\": max_leverage,\n            \"min_margin_ratio\": min_margin_ratio,\n            \"max_single_position_pct\": max_single_position_pct,\n        }\n\n        event_payload = {\n            \"agent_id\": self.agent_id,\n            \"thresholds\": self.thresholds,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        event_payload[\"signature\"] = self._sign(self.thresholds)\n\n        return self._execute(\"publish_event\", {\n            \"event_type\": \"risk.thresholds_updated\",\n            \"payload\": event_payload,\n        })\n\n    def check_portfolio_risk(self, positions: List[dict]) -> dict:\n        \"\"\"\n        Run all risk checks against current positions.\n\n        Returns a dict with risk metrics and any triggered alerts.\n        \"\"\"\n        total_equity = sum(p.get(\"equity\", 0) for p in positions)\n        total_notional = sum(abs(p.get(\"notional\", 0)) for p in positions)\n        leverage = total_notional \u002F total_equity if total_equity > 0 else float(\"inf\")\n\n        alerts = []\n\n        # Check leverage\n        if leverage > self.thresholds[\"max_leverage\"]:\n            alerts.append({\n                \"type\": \"leverage_breach\",\n                \"current\": round(leverage, 2),\n                \"threshold\": self.thresholds[\"max_leverage\"],\n                \"severity\": \"critical\",\n            })\n\n        # Check concentration\n        for pos in positions:\n            if total_notional > 0:\n                concentration = abs(pos.get(\"notional\", 0)) \u002F total_notional * 100\n                if concentration > self.thresholds[\"max_single_position_pct\"]:\n                    alerts.append({\n                        \"type\": \"concentration_breach\",\n                        \"position\": pos.get(\"symbol\", \"unknown\"),\n                        \"current_pct\": round(concentration, 2),\n                        \"threshold\": self.thresholds[\"max_single_position_pct\"],\n                        \"severity\": \"warning\",\n                    })\n\n        risk_summary = {\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"total_equity\": total_equity,\n            \"total_notional\": total_notional,\n            \"aggregate_leverage\": round(leverage, 2),\n            \"position_count\": len(positions),\n            \"alerts\": alerts,\n            \"status\": \"critical\" if any(a[\"severity\"] == \"critical\" for a in alerts)\n                      else \"warning\" if alerts\n                      else \"healthy\",\n        }\n\n        # Publish risk check result as event\n        event_payload = {\n            \"agent_id\": self.agent_id,\n            **risk_summary,\n        }\n        event_payload[\"signature\"] = self._sign(risk_summary)\n\n        self._execute(\"publish_event\", {\n            \"event_type\": \"risk.portfolio_check\",\n            \"payload\": event_payload,\n        })\n\n        return risk_summary\n```\n\n### Configuring Thresholds via curl\n\n```bash\n# Publish a threshold configuration event\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"publish_event\",\n    \"input\": {\n      \"event_type\": \"risk.thresholds_updated\",\n      \"payload\": {\n        \"agent_id\": \"risk-monitor-prod-01\",\n        \"thresholds\": {\n          \"max_drawdown_pct\": 15.0,\n          \"max_correlation\": 0.85,\n          \"max_leverage\": 5.0,\n          \"min_margin_ratio\": 0.20,\n          \"max_single_position_pct\": 25.0\n        },\n        \"timestamp\": \"2026-04-07T12:00:00Z\",\n        \"signature\": \"base64-ed25519-signature\"\n      }\n    }\n  }'\n```\n\n### Usage Example\n\n```python\nmonitor = RiskMonitor(\n    api_key=\"your-api-key\",\n    agent_id=\"risk-monitor-prod-01\",\n    private_key_b64=\"your-private-key-base64\",\n)\n\n# Register and configure\nmonitor.register_risk_agent()\nmonitor.configure_thresholds(\n    max_drawdown_pct=12.0,\n    max_leverage=4.0,\n    min_margin_ratio=0.25,\n)\n\n# Check risk against current positions\npositions = [\n    {\"symbol\": \"BTC-USD\", \"notional\": 50000, \"equity\": 15000, \"exchange\": \"binance\"},\n    {\"symbol\": \"ETH-USD\", \"notional\": 30000, \"equity\": 10000, \"exchange\": \"coinbase\"},\n    {\"symbol\": \"SOL-USD\", \"notional\": 20000, \"equity\": 8000, \"exchange\": \"kraken\"},\n]\n\nresult = monitor.check_portfolio_risk(positions)\nprint(f\"Status: {result['status']}, Leverage: {result['aggregate_leverage']}x\")\n```\n\nThe `RiskMonitor` class provides the transport layer and basic risk checks. The following chapters build specialized risk engines that integrate with it.\n\n---\n\n## Chapter 3: Drawdown Monitoring and Alerts\n\n### Why Drawdown Is the Primary Risk Metric\n\nDrawdown measures peak-to-trough decline. Unlike volatility (which is symmetric) or VaR (which is model-dependent), drawdown directly answers the question operators care about: \"How much have I lost from my best point?\" A 15% drawdown means your portfolio is worth 85% of its highest recorded value. Drawdown is also the metric most directly tied to survival -- a 50% drawdown requires a 100% gain to recover, and a 75% drawdown requires a 300% gain. Bot operators who monitor drawdown at multiple timeframes catch problems before they become existential.\n\n### The DrawdownTracker Class\n\n```python\nimport time\nfrom collections import defaultdict\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional, Tuple\n\n\nclass DrawdownTracker:\n    \"\"\"Tracks drawdown across multiple timeframes with alert escalation.\"\"\"\n\n    # Timeframe windows in seconds\n    TIMEFRAMES = {\n        \"1h\": 3600,\n        \"4h\": 14400,\n        \"24h\": 86400,\n        \"7d\": 604800,\n    }\n\n    # Alert escalation levels\n    ALERT_LEVELS = {\n        \"warning\": 5.0,\n        \"critical\": 8.0,\n        \"emergency\": 12.0,\n        \"circuit_breaker\": 15.0,\n    }\n\n    def __init__(self, risk_monitor: \"RiskMonitor\"):\n        self.risk_monitor = risk_monitor\n        self._equity_history: List[Tuple[float, float]] = []  # (timestamp, equity)\n        self._peaks: Dict[str, float] = {}  # timeframe -> peak equity\n        self._current_drawdowns: Dict[str, float] = {}\n        self._alert_history: List[dict] = []\n\n    def update(self, equity: float, timestamp: Optional[float] = None) -> dict:\n        \"\"\"\n        Record a new equity value and compute drawdowns across all timeframes.\n\n        Returns the current drawdown state.\n        \"\"\"\n        ts = timestamp or time.time()\n        self._equity_history.append((ts, equity))\n\n        # Prune history older than 7 days\n        cutoff = ts - self.TIMEFRAMES[\"7d\"]\n        self._equity_history = [\n            (t, e) for t, e in self._equity_history if t >= cutoff\n        ]\n\n        drawdowns = {}\n        for tf_name, tf_seconds in self.TIMEFRAMES.items():\n            tf_cutoff = ts - tf_seconds\n            tf_values = [e for t, e in self._equity_history if t >= tf_cutoff]\n\n            if not tf_values:\n                drawdowns[tf_name] = 0.0\n                continue\n\n            peak = max(tf_values)\n            self._peaks[tf_name] = peak\n            current_dd = ((peak - equity) \u002F peak) * 100 if peak > 0 else 0.0\n            drawdowns[tf_name] = round(current_dd, 4)\n\n        self._current_drawdowns = drawdowns\n        return drawdowns\n\n    def check_alerts(self) -> List[dict]:\n        \"\"\"\n        Check current drawdowns against alert thresholds.\n\n        Returns a list of triggered alerts, sorted by severity.\n        \"\"\"\n        alerts = []\n        worst_dd = max(self._current_drawdowns.values()) if self._current_drawdowns else 0.0\n\n        for level_name, level_threshold in sorted(\n            self.ALERT_LEVELS.items(), key=lambda x: x[1]\n        ):\n            if worst_dd >= level_threshold:\n                # Find which timeframe triggered\n                trigger_tf = max(\n                    self._current_drawdowns, key=self._current_drawdowns.get\n                )\n\n                alert = {\n                    \"level\": level_name,\n                    \"threshold_pct\": level_threshold,\n                    \"current_pct\": round(worst_dd, 4),\n                    \"trigger_timeframe\": trigger_tf,\n                    \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                    \"peak_equity\": self._peaks.get(trigger_tf, 0),\n                }\n                alerts.append(alert)\n\n        if alerts:\n            self._alert_history.extend(alerts)\n            # Publish the most severe alert\n            worst_alert = alerts[-1]\n            payload = {\n                \"agent_id\": self.risk_monitor.agent_id,\n                \"alert_type\": \"drawdown\",\n                **worst_alert,\n            }\n            payload[\"signature\"] = self.risk_monitor._sign(worst_alert)\n\n            self.risk_monitor._execute(\"publish_event\", {\n                \"event_type\": \"risk.drawdown_alert\",\n                \"payload\": payload,\n            })\n\n        return alerts\n\n    def get_history(self, timeframe: str = \"24h\") -> List[dict]:\n        \"\"\"Get drawdown history for a specific timeframe.\"\"\"\n        tf_seconds = self.TIMEFRAMES.get(timeframe, 86400)\n        cutoff = time.time() - tf_seconds\n        return [\n            {\"timestamp\": t, \"equity\": e}\n            for t, e in self._equity_history\n            if t >= cutoff\n        ]\n```\n\n### Webhook-Based Alert Delivery\n\nRegister a webhook to receive drawdown alerts in real time:\n\n```bash\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_webhook\",\n    \"input\": {\n      \"url\": \"https:\u002F\u002Fyour-ops-server.example.com\u002Frisk\u002Fdrawdown\",\n      \"event_types\": [\n        \"risk.drawdown_alert\",\n        \"risk.portfolio_check\"\n      ],\n      \"secret\": \"your-webhook-hmac-secret\"\n    }\n  }'\n```\n\n```python\n# Register webhooks for drawdown alerts\nmonitor.register_risk_agent()\n\nwebhook_result = monitor._execute(\"register_webhook\", {\n    \"url\": \"https:\u002F\u002Fyour-ops-server.example.com\u002Frisk\u002Fdrawdown\",\n    \"event_types\": [\"risk.drawdown_alert\", \"risk.portfolio_check\"],\n    \"secret\": \"your-webhook-hmac-secret\",\n})\nprint(f\"Webhook registered: {webhook_result}\")\n```\n\n### Alert Escalation in Practice\n\nThe four-level escalation model maps directly to operational responses:\n\n| Level | Threshold | Action |\n|-------|-----------|--------|\n| Warning | 5% drawdown | Log and notify via Slack |\n| Critical | 8% drawdown | Page the on-call operator, reduce position sizes by 50% |\n| Emergency | 12% drawdown | Halt new position opens, begin unwinding existing positions |\n| Circuit Breaker | 15% drawdown | Cancel all open orders, close all positions, halt all strategies |\n\n### Running the Drawdown Loop\n\n```python\ntracker = DrawdownTracker(risk_monitor=monitor)\n\n# Simulate a monitoring loop (in production, this runs continuously)\ndef run_drawdown_monitor(monitor: RiskMonitor, tracker: DrawdownTracker):\n    \"\"\"Poll equity every 10 seconds and check drawdown alerts.\"\"\"\n    while True:\n        # Fetch latest equity from your exchange aggregation layer\n        events = monitor._execute(\"get_events\", {\n            \"event_type\": \"exchange.equity_update\",\n            \"limit\": 1,\n            \"order\": \"desc\",\n        })\n\n        if events.get(\"events\"):\n            equity = events[\"events\"][0][\"payload\"].get(\"total_equity\", 0)\n            drawdowns = tracker.update(equity)\n            alerts = tracker.check_alerts()\n\n            if alerts:\n                worst = alerts[-1]\n                print(\n                    f\"[{worst['level'].upper()}] Drawdown: {worst['current_pct']}% \"\n                    f\"(threshold: {worst['threshold_pct']}%, \"\n                    f\"timeframe: {worst['trigger_timeframe']})\"\n                )\n\n                # Send alert via messaging\n                if worst[\"level\"] in (\"emergency\", \"circuit_breaker\"):\n                    monitor._execute(\"send_message\", {\n                        \"to\": \"ops-team\",\n                        \"subject\": f\"RISK ALERT: {worst['level'].upper()} drawdown\",\n                        \"body\": (\n                            f\"Drawdown: {worst['current_pct']}% \"\n                            f\"(threshold: {worst['threshold_pct']}%)\\n\"\n                            f\"Timeframe: {worst['trigger_timeframe']}\\n\"\n                            f\"Peak equity: ${worst['peak_equity']:,.2f}\"\n                        ),\n                    })\n\n        time.sleep(10)\n```\n\n```bash\n# Query drawdown alert history via curl\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.drawdown_alert\",\n      \"limit\": 20,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n### Drawdown Severity Classification\n\nNot all drawdowns are equal. A 10% drawdown in a trending market during high volatility is qualitatively different from a 10% drawdown in a ranging market during low volatility. The tracker uses the drawdown across multiple timeframes to classify severity:\n\n- **Shallow, slow drawdown** (24h drawdown > 1h drawdown): The portfolio is grinding lower. This is typically caused by a losing trend-following position. Monitor but do not panic -- the strategy may recover when the trend reverses.\n- **Deep, fast drawdown** (1h drawdown > 24h drawdown): The portfolio is in rapid decline. This pattern is characteristic of liquidation cascades, flash crashes, or correlated position blowups. Immediate attention required.\n- **Oscillating drawdown** (1h and 4h drawdowns similar, both \u003C 24h): The portfolio is whipsawing. This pattern is common during high-volatility news events. Reduce position sizes rather than closing positions -- the whipsaw may resolve in either direction.\n\nThe drawdown tracker publishes this classification in the event payload, allowing downstream consumers (the circuit breaker, alert manager) to tailor their response to the type of drawdown, not just the magnitude.\n\nThe drawdown tracker is intentionally simple. It uses empirical peaks, not modeled ones. It does not try to predict future drawdown -- it measures what has already happened and triggers actions based on predefined thresholds. Predictive models add complexity without adding reliability under stress conditions.\n\n---\n\n## Chapter 4: Correlation Monitoring\n\n### Why Correlation Kills Portfolios\n\nDiversification is the only free lunch in finance -- until it isn't. Portfolio theory assumes that combining uncorrelated strategies reduces total risk. If Strategy A has a Sharpe of 1.5 and Strategy B has a Sharpe of 1.5, and they are uncorrelated, the combined portfolio has a Sharpe of roughly 2.1. But correlation is not static. During market stress, correlations spike. The 2020 COVID crash saw BTC-ETH correlation go from 0.6 to 0.95 in 48 hours. The 2022 LUNA collapse pushed correlations across all crypto assets above 0.9 for weeks. Strategies that appeared diversified during calm markets became a single concentrated bet during the exact conditions where diversification mattered most.\n\nMonitoring correlation in real time -- and detecting regime changes -- lets you reduce exposure before the diversification illusion costs you capital.\n\n### The CorrelationMonitor Class\n\n```python\nimport math\nfrom collections import deque\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional, Tuple\n\n\nclass CorrelationMonitor:\n    \"\"\"\n    Rolling correlation computation between strategies\n    with regime change detection.\n    \"\"\"\n\n    def __init__(\n        self,\n        risk_monitor: \"RiskMonitor\",\n        window_size: int = 100,\n        regime_change_threshold: float = 0.3,\n    ):\n        self.risk_monitor = risk_monitor\n        self.window_size = window_size\n        self.regime_change_threshold = regime_change_threshold\n\n        # Returns buffer per strategy\n        self._returns: Dict[str, deque] = {}\n        self._correlation_history: List[dict] = []\n        self._previous_matrix: Optional[Dict[str, Dict[str, float]]] = None\n\n    def add_returns(self, strategy_id: str, returns_value: float) -> None:\n        \"\"\"Add a return observation for a strategy.\"\"\"\n        if strategy_id not in self._returns:\n            self._returns[strategy_id] = deque(maxlen=self.window_size)\n        self._returns[strategy_id].append(returns_value)\n\n    def _pearson(self, x: List[float], y: List[float]) -> float:\n        \"\"\"Compute Pearson correlation between two series.\"\"\"\n        n = min(len(x), len(y))\n        if n \u003C 10:\n            return 0.0\n\n        x, y = x[:n], y[:n]\n        mean_x = sum(x) \u002F n\n        mean_y = sum(y) \u002F n\n\n        cov = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))\n        std_x = math.sqrt(sum((xi - mean_x) ** 2 for xi in x))\n        std_y = math.sqrt(sum((yi - mean_y) ** 2 for yi in y))\n\n        if std_x == 0 or std_y == 0:\n            return 0.0\n\n        return cov \u002F (std_x * std_y)\n\n    def compute_matrix(self) -> Dict[str, Dict[str, float]]:\n        \"\"\"Compute the full correlation matrix across all strategies.\"\"\"\n        strategies = sorted(self._returns.keys())\n        matrix = {}\n\n        for s1 in strategies:\n            matrix[s1] = {}\n            for s2 in strategies:\n                if s1 == s2:\n                    matrix[s1][s2] = 1.0\n                else:\n                    corr = self._pearson(\n                        list(self._returns[s1]),\n                        list(self._returns[s2]),\n                    )\n                    matrix[s1][s2] = round(corr, 4)\n\n        # Publish the matrix as an event\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"matrix\": matrix,\n            \"strategy_count\": len(strategies),\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        payload[\"signature\"] = self.risk_monitor._sign({\"matrix\": matrix})\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.correlation_matrix\",\n            \"payload\": payload,\n        })\n\n        self._correlation_history.append({\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"matrix\": matrix,\n        })\n\n        return matrix\n\n    def detect_regime_change(self) -> Optional[dict]:\n        \"\"\"\n        Detect if the correlation regime has changed significantly.\n\n        Compares current matrix to previous matrix. A regime change is\n        detected when the average absolute change in correlations exceeds\n        the threshold.\n        \"\"\"\n        current = self.compute_matrix()\n\n        if self._previous_matrix is None:\n            self._previous_matrix = current\n            return None\n\n        strategies = sorted(current.keys())\n        changes = []\n\n        for s1 in strategies:\n            for s2 in strategies:\n                if s1 >= s2:\n                    continue\n                prev = self._previous_matrix.get(s1, {}).get(s2, 0.0)\n                curr = current.get(s1, {}).get(s2, 0.0)\n                changes.append(abs(curr - prev))\n\n        if not changes:\n            self._previous_matrix = current\n            return None\n\n        avg_change = sum(changes) \u002F len(changes)\n        max_change = max(changes)\n\n        self._previous_matrix = current\n\n        if avg_change > self.regime_change_threshold:\n            alert = {\n                \"type\": \"correlation_regime_change\",\n                \"avg_change\": round(avg_change, 4),\n                \"max_change\": round(max_change, 4),\n                \"threshold\": self.regime_change_threshold,\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                \"matrix\": current,\n            }\n\n            # Publish regime change event\n            event_payload = {\n                \"agent_id\": self.risk_monitor.agent_id,\n                **alert,\n            }\n            event_payload[\"signature\"] = self.risk_monitor._sign(alert)\n\n            self.risk_monitor._execute(\"publish_event\", {\n                \"event_type\": \"risk.correlation_regime_change\",\n                \"payload\": event_payload,\n            })\n\n            return alert\n\n        return None\n```\n\n### Querying Correlation History via curl\n\n```bash\n# Get recent correlation matrix events\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.correlation_matrix\",\n      \"limit\": 10,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Get regime change alerts\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.correlation_regime_change\",\n      \"limit\": 5,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n### Usage Example\n\n```python\ncorr_monitor = CorrelationMonitor(\n    risk_monitor=monitor,\n    window_size=100,\n    regime_change_threshold=0.3,\n)\n\n# Feed returns from each strategy (in production, these come from trade events)\nimport random\nfor i in range(120):\n    corr_monitor.add_returns(\"mean-reversion-btc\", random.gauss(0.001, 0.02))\n    corr_monitor.add_returns(\"momentum-eth\", random.gauss(0.0005, 0.025))\n    corr_monitor.add_returns(\"arb-sol-perps\", random.gauss(0.0008, 0.015))\n\nmatrix = corr_monitor.compute_matrix()\nfor s1, row in matrix.items():\n    print(f\"{s1}: {row}\")\n\nregime = corr_monitor.detect_regime_change()\nif regime:\n    print(f\"REGIME CHANGE detected: avg change {regime['avg_change']}\")\n```\n\n### Interpreting the Correlation Matrix\n\nThe correlation matrix is symmetric with 1.0 on the diagonal. Off-diagonal values range from -1.0 (perfectly inverse) to +1.0 (perfectly correlated). For risk management purposes:\n\n- **Below 0.3**: Strategies are effectively uncorrelated. Diversification benefit is real.\n- **0.3 to 0.6**: Moderate correlation. Some diversification benefit remains, but not full.\n- **0.6 to 0.85**: High correlation. The strategies will draw down together in stressed markets. Position sizes should account for this.\n- **Above 0.85**: The strategies are effectively the same bet. The circuit breaker should consider triggering if this persists.\n\n### Practical Considerations for Correlation Monitoring\n\n**Window size selection**: The `window_size` parameter controls how many return observations are used to compute correlation. Smaller windows (30-50) are more responsive to recent correlation changes but produce noisier estimates. Larger windows (100-200) are more stable but slower to detect regime changes. A common compromise is to run two correlation monitors in parallel -- one with a 50-observation window for early detection and one with a 150-observation window for confirmation.\n\n**Return frequency**: The correlation monitor needs returns at a consistent frequency. If Strategy A reports returns every minute and Strategy B reports every 15 minutes, the correlation estimate will be unreliable. Normalize to the lowest common frequency across all strategies. For most crypto bot operations, 5-minute or 15-minute returns provide a good balance between responsiveness and stability.\n\n**Handling missing data**: If a strategy stops reporting returns (e.g., because the bot crashed or the exchange is down), the correlation monitor should flag this rather than computing correlation with stale data. A strategy that has not reported in 30 minutes should be excluded from the matrix with a note, not included with its last known returns repeated.\n\n**Correlation is not causation**: Two strategies can be highly correlated because they both respond to the same market factor (e.g., BTC price), not because they are redundant. If Strategy A goes long BTC on momentum signals and Strategy B goes long ETH on mean-reversion signals, they may be correlated during strong BTC moves (because ETH follows BTC) but serve different functions in the portfolio. Use correlation as an input to risk decisions, not as the sole decision criterion.\n\n---\n\n## Chapter 5: Liquidation Proximity Engine\n\n### Why Distance to Liquidation Matters\n\nA position's P&L tells you what has happened. Distance to liquidation tells you what will happen if the market moves against you by a specific amount. A position might be profitable but dangerously close to liquidation if leverage is high. Exchange liquidation engines are not gentle -- they liquidate at market, often at prices significantly worse than the liquidation price, and they charge liquidation fees. Getting liquidated on a leveraged position typically costs 2-5% more than closing the position manually at the same price. Binance charges a liquidation clearance fee that can be as high as 1.5% of the position's notional value. Coinbase's liquidation engine can execute up to 5% below the liquidation price during fast markets. These costs are invisible until they hit -- and they always hit at the worst possible time, during exactly the market conditions where your portfolio can least afford the additional loss.\n\nThe liquidation proximity engine monitors distance to liquidation across all positions on all exchanges and triggers alerts before the exchange's liquidation engine takes over. The goal is simple: never get liquidated. Always close the position yourself, at a better price, before the exchange does it for you.\n\n### Exchange Margin Models\n\nDifferent exchanges use different margin models, and this affects liquidation price calculation:\n\n- **Isolated margin** (per-position): Each position has its own margin. Liquidation price depends only on that position's margin and entry price. Simple to calculate, but does not benefit from cross-position netting.\n- **Cross margin** (per-account): All positions on the account share a single margin pool. A profitable position's unrealized P&L can offset a losing position's margin requirement. Liquidation depends on the aggregate account equity vs total maintenance margin.\n\n### The LiquidationProximityEngine Class\n\n```python\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional\n\n\nclass LiquidationProximityEngine:\n    \"\"\"\n    Monitors distance to liquidation across exchanges and margin modes.\n    \"\"\"\n\n    # Maintenance margin rates by exchange (simplified)\n    MAINTENANCE_MARGIN = {\n        \"binance\": 0.004,   # 0.4% for BTC\n        \"coinbase\": 0.005,  # 0.5%\n        \"kraken\": 0.005,    # 0.5%\n    }\n\n    def __init__(\n        self,\n        risk_monitor: \"RiskMonitor\",\n        alert_threshold_pct: float = 20.0,\n        critical_threshold_pct: float = 10.0,\n    ):\n        self.risk_monitor = risk_monitor\n        self.alert_threshold_pct = alert_threshold_pct\n        self.critical_threshold_pct = critical_threshold_pct\n        self._positions: List[dict] = []\n        self._alerts: List[dict] = []\n\n    def _calc_liquidation_price_isolated(\n        self,\n        entry_price: float,\n        side: str,\n        leverage: float,\n        maint_margin_rate: float,\n    ) -> float:\n        \"\"\"\n        Calculate liquidation price for an isolated-margin position.\n\n        For longs: liq = entry * (1 - 1\u002Fleverage + maint_margin_rate)\n        For shorts: liq = entry * (1 + 1\u002Fleverage - maint_margin_rate)\n        \"\"\"\n        if side == \"long\":\n            return entry_price * (1 - 1 \u002F leverage + maint_margin_rate)\n        else:\n            return entry_price * (1 + 1 \u002F leverage - maint_margin_rate)\n\n    def _calc_distance_to_liquidation(\n        self,\n        current_price: float,\n        liquidation_price: float,\n        side: str,\n    ) -> float:\n        \"\"\"Calculate percentage distance from current price to liquidation.\"\"\"\n        if side == \"long\":\n            distance = (current_price - liquidation_price) \u002F current_price * 100\n        else:\n            distance = (liquidation_price - current_price) \u002F current_price * 100\n        return max(0.0, round(distance, 4))\n\n    def update_positions(self, positions: List[dict]) -> List[dict]:\n        \"\"\"\n        Update tracked positions and compute liquidation proximity.\n\n        Each position dict should have:\n        - symbol, exchange, side, entry_price, current_price,\n          leverage, margin_mode, quantity\n        \"\"\"\n        self._positions = positions\n        results = []\n\n        for pos in positions:\n            exchange = pos.get(\"exchange\", \"binance\")\n            maint_rate = self.MAINTENANCE_MARGIN.get(exchange, 0.005)\n            margin_mode = pos.get(\"margin_mode\", \"isolated\")\n\n            if margin_mode == \"isolated\":\n                liq_price = self._calc_liquidation_price_isolated(\n                    entry_price=pos[\"entry_price\"],\n                    side=pos[\"side\"],\n                    leverage=pos[\"leverage\"],\n                    maint_margin_rate=maint_rate,\n                )\n            else:\n                # Cross margin: use account-level equity\n                # Simplified: treat as isolated with effective leverage\n                liq_price = self._calc_liquidation_price_isolated(\n                    entry_price=pos[\"entry_price\"],\n                    side=pos[\"side\"],\n                    leverage=pos.get(\"effective_leverage\", pos[\"leverage\"]),\n                    maint_margin_rate=maint_rate,\n                )\n\n            distance = self._calc_distance_to_liquidation(\n                current_price=pos[\"current_price\"],\n                liquidation_price=liq_price,\n                side=pos[\"side\"],\n            )\n\n            result = {\n                \"symbol\": pos[\"symbol\"],\n                \"exchange\": exchange,\n                \"side\": pos[\"side\"],\n                \"entry_price\": pos[\"entry_price\"],\n                \"current_price\": pos[\"current_price\"],\n                \"liquidation_price\": round(liq_price, 2),\n                \"distance_pct\": distance,\n                \"leverage\": pos[\"leverage\"],\n                \"status\": \"critical\" if distance \u003C self.critical_threshold_pct\n                          else \"warning\" if distance \u003C self.alert_threshold_pct\n                          else \"safe\",\n            }\n            results.append(result)\n\n        # Publish positions with liquidation data\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"positions\": results,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        payload[\"signature\"] = self.risk_monitor._sign(\n            {\"positions_count\": len(results)}\n        )\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.liquidation_proximity\",\n            \"payload\": payload,\n        })\n\n        return results\n\n    def get_alerts(self) -> List[dict]:\n        \"\"\"Get all positions within alert thresholds.\"\"\"\n        alerts = []\n        for pos in self._positions:\n            result = self.update_positions([pos])[0]\n            if result[\"status\"] in (\"warning\", \"critical\"):\n                alerts.append(result)\n        return alerts\n\n    def get_aggregate_risk(self) -> dict:\n        \"\"\"Compute aggregate liquidation risk across all positions.\"\"\"\n        if not self._positions:\n            return {\"status\": \"no_positions\", \"min_distance_pct\": 100.0}\n\n        results = self.update_positions(self._positions)\n        distances = [r[\"distance_pct\"] for r in results]\n\n        return {\n            \"position_count\": len(results),\n            \"min_distance_pct\": min(distances),\n            \"avg_distance_pct\": round(sum(distances) \u002F len(distances), 2),\n            \"critical_count\": sum(1 for r in results if r[\"status\"] == \"critical\"),\n            \"warning_count\": sum(1 for r in results if r[\"status\"] == \"warning\"),\n            \"closest_position\": min(results, key=lambda r: r[\"distance_pct\"]),\n        }\n```\n\n### Checking Liquidation Proximity via curl\n\n```bash\n# Query recent liquidation proximity events\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.liquidation_proximity\",\n      \"limit\": 5,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Send an alert when a position is close to liquidation\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"send_message\",\n    \"input\": {\n      \"to\": \"ops-team\",\n      \"subject\": \"LIQUIDATION WARNING: BTC-USD on Binance\",\n      \"body\": \"BTC-USD long position is 8.5% from liquidation.\\nEntry: $67,200 | Current: $63,100 | Liq: $57,800\\nLeverage: 10x | Margin mode: isolated\\nAction required: reduce position or add margin.\"\n    }\n  }'\n```\n\n### Usage Example\n\n```python\nliq_engine = LiquidationProximityEngine(\n    risk_monitor=monitor,\n    alert_threshold_pct=20.0,\n    critical_threshold_pct=10.0,\n)\n\npositions = [\n    {\n        \"symbol\": \"BTC-USD\",\n        \"exchange\": \"binance\",\n        \"side\": \"long\",\n        \"entry_price\": 67200,\n        \"current_price\": 63100,\n        \"leverage\": 10,\n        \"margin_mode\": \"isolated\",\n        \"quantity\": 0.5,\n    },\n    {\n        \"symbol\": \"ETH-USD\",\n        \"exchange\": \"coinbase\",\n        \"side\": \"short\",\n        \"entry_price\": 3400,\n        \"current_price\": 3520,\n        \"leverage\": 5,\n        \"margin_mode\": \"cross\",\n        \"effective_leverage\": 4.2,\n        \"quantity\": 10,\n    },\n]\n\nresults = liq_engine.update_positions(positions)\nfor r in results:\n    print(\n        f\"{r['symbol']} ({r['exchange']}): {r['distance_pct']}% from liquidation \"\n        f\"[{r['status']}] | Liq price: ${r['liquidation_price']:,.2f}\"\n    )\n\nagg = liq_engine.get_aggregate_risk()\nprint(f\"\\nAggregate: min distance {agg['min_distance_pct']}%, \"\n      f\"{agg['critical_count']} critical, {agg['warning_count']} warnings\")\n```\n\n### Aggregate Liquidation Risk\n\nIndividual position liquidation distances do not capture the full picture. In cross-margin mode, a losing position's margin requirement is covered by the account's total equity -- including unrealized profits from other positions. If those other positions reverse, the aggregate margin coverage can collapse rapidly. The `get_aggregate_risk()` method computes the minimum distance to liquidation across all positions and counts how many positions are in warning or critical states. When multiple positions are simultaneously close to liquidation, the aggregate risk is higher than what any individual position metric suggests because a liquidation on one position can cascade to others through shared margin.\n\nThe right operational response depends on the aggregate picture:\n- **One position critical, others safe**: Add margin to the critical position or reduce its size. The rest of the portfolio is fine.\n- **Multiple positions warning**: The portfolio is stressed. Reduce aggregate leverage by closing the weakest positions first.\n- **Multiple positions critical**: This is the circuit breaker scenario. The risk of cascade liquidation is high. Close positions starting from the most leveraged.\n\nThe engine intentionally uses simplified liquidation calculations. Real exchange liquidation engines have additional factors (funding rate accruals, insurance fund contributions, ADL priority). The simplified model provides a conservative lower bound -- your actual liquidation price is slightly further away than what this engine computes, which means alerts will fire slightly early. This is the correct failure mode for a safety system.\n\n---\n\n## Chapter 6: Circuit Breaker Implementation\n\n### The Case for Automated Trading Halts\n\nHuman reaction time to a risk event is measured in minutes. Market cascades are measured in seconds. The May 2025 BitMEX incident saw a $180M liquidation cascade complete in 47 seconds. No operator, no matter how attentive, can evaluate risk, make a decision, and execute that decision across three exchanges in under a minute. Circuit breakers are the solution: automated systems that halt trading when predefined conditions are met, without waiting for human approval. The human's role shifts from \"react to the crisis\" to \"review the circuit breaker's decision after the fact and decide when to re-enable trading.\"\n\nThe concept is borrowed from stock exchanges, which have used circuit breakers since the 1987 crash. The NYSE halts trading when the S&P 500 drops 7% (Level 1), 13% (Level 2), or 20% (Level 3) from the previous day's close. These thresholds were calibrated through decades of experience. Your trading bot needs its own calibrated thresholds, tuned to your specific strategies, capital base, and risk tolerance. The circuit breaker in this chapter is fully configurable and integrates with the drawdown, correlation, and liquidation monitors from previous chapters to make holistic risk decisions.\n\n### Circuit Breaker State Machine\n\nThe circuit breaker has three states:\n\n```\n                    +---------+\n                    |         |\n           +------>| CLOSED  |\u003C------+\n           |       | (normal)|       |\n           |       +----+----+       |\n           |            |            |\n           |    trigger condition    |\n           |    exceeded             |\n           |            |            |\n           |            v            |\n     recovery      +----+----+      |\n     period        |         |      |\n     elapsed       |  OPEN   |      |\n           |       | (halted)|      |\n           |       +----+----+      |\n           |            |            |\n           |   cooldown elapsed     |\n           |            |            |\n           |            v            |\n           |       +----+----+      |\n           |       |         |      |  test trade\n           +-------+HALF_OPEN+------+  fails\n                   | (test)  |\n                   +---------+\n```\n\n- **CLOSED**: Normal operation. All strategies execute freely. Risk monitors are active.\n- **OPEN**: Trading is halted. All open orders are cancelled. No new positions are opened. Existing positions may be closed (configurable). A cooldown timer starts.\n- **HALF_OPEN**: After the cooldown, one test trade is allowed with reduced position size. If it succeeds without triggering another alert, transition to CLOSED. If it fails, transition back to OPEN with a longer cooldown.\n\n### The CircuitBreakerManager Class\n\n```python\nimport enum\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Callable, Dict, List, Optional\n\n\nclass CircuitState(enum.Enum):\n    CLOSED = \"closed\"\n    OPEN = \"open\"\n    HALF_OPEN = \"half_open\"\n\n\nclass CircuitBreakerManager:\n    \"\"\"\n    Circuit breaker for trading operations with configurable triggers\n    and GreenHelix SLA compliance integration.\n    \"\"\"\n\n    def __init__(\n        self,\n        risk_monitor: \"RiskMonitor\",\n        cooldown_seconds: int = 300,\n        max_cooldown_seconds: int = 3600,\n        cooldown_multiplier: float = 2.0,\n        test_position_fraction: float = 0.1,\n    ):\n        self.risk_monitor = risk_monitor\n        self.cooldown_seconds = cooldown_seconds\n        self.max_cooldown_seconds = max_cooldown_seconds\n        self.cooldown_multiplier = cooldown_multiplier\n        self.test_position_fraction = test_position_fraction\n\n        self._state = CircuitState.CLOSED\n        self._open_since: Optional[float] = None\n        self._current_cooldown = cooldown_seconds\n        self._trip_count = 0\n        self._trip_history: List[dict] = []\n\n        # Configurable trigger thresholds\n        self.triggers = {\n            \"drawdown_pct\": 15.0,\n            \"correlation_max\": 0.95,\n            \"liquidation_distance_pct\": 10.0,\n            \"rapid_loss_pct\": 5.0,\n            \"rapid_loss_window_seconds\": 300,\n        }\n\n        # Callbacks for state transitions\n        self._on_open_callbacks: List[Callable] = []\n        self._on_close_callbacks: List[Callable] = []\n\n    @property\n    def state(self) -> CircuitState:\n        return self._state\n\n    def configure_triggers(self, **kwargs) -> None:\n        \"\"\"Update trigger thresholds.\"\"\"\n        for key, value in kwargs.items():\n            if key in self.triggers:\n                self.triggers[key] = value\n\n        # Publish trigger configuration\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"triggers\": self.triggers,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        payload[\"signature\"] = self.risk_monitor._sign(self.triggers)\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.circuit_breaker_config\",\n            \"payload\": payload,\n        })\n\n    def on_open(self, callback: Callable) -> None:\n        \"\"\"Register a callback for when the circuit breaker opens.\"\"\"\n        self._on_open_callbacks.append(callback)\n\n    def on_close(self, callback: Callable) -> None:\n        \"\"\"Register a callback for when the circuit breaker closes.\"\"\"\n        self._on_close_callbacks.append(callback)\n\n    def evaluate(\n        self,\n        drawdown_pct: float = 0.0,\n        max_correlation: float = 0.0,\n        min_liq_distance_pct: float = 100.0,\n        rapid_loss_pct: float = 0.0,\n    ) -> dict:\n        \"\"\"\n        Evaluate current risk metrics against circuit breaker triggers.\n\n        Returns the current state and any state transitions.\n        \"\"\"\n        now = time.time()\n\n        if self._state == CircuitState.OPEN:\n            # Check if cooldown has elapsed\n            if self._open_since and (now - self._open_since) >= self._current_cooldown:\n                self._transition_to(CircuitState.HALF_OPEN)\n                return self._status(\"cooldown_elapsed\")\n            return self._status(\"waiting_cooldown\")\n\n        if self._state == CircuitState.HALF_OPEN:\n            # In half-open state, check if conditions have improved\n            if self._should_trip(\n                drawdown_pct, max_correlation, min_liq_distance_pct, rapid_loss_pct\n            ):\n                # Conditions still bad -- back to OPEN with longer cooldown\n                self._current_cooldown = min(\n                    self._current_cooldown * self.cooldown_multiplier,\n                    self.max_cooldown_seconds,\n                )\n                self._transition_to(CircuitState.OPEN, reason=\"half_open_test_failed\")\n                return self._status(\"test_failed\")\n            else:\n                self._transition_to(CircuitState.CLOSED)\n                return self._status(\"recovered\")\n\n        # CLOSED state -- check triggers\n        trip_reasons = self._should_trip(\n            drawdown_pct, max_correlation, min_liq_distance_pct, rapid_loss_pct\n        )\n\n        if trip_reasons:\n            self._current_cooldown = self.cooldown_seconds\n            self._transition_to(CircuitState.OPEN, reason=trip_reasons)\n            return self._status(\"tripped\")\n\n        return self._status(\"healthy\")\n\n    def _should_trip(\n        self,\n        drawdown_pct: float,\n        max_correlation: float,\n        min_liq_distance_pct: float,\n        rapid_loss_pct: float,\n    ) -> Optional[List[str]]:\n        \"\"\"Check if any trigger condition is met. Returns reasons or None.\"\"\"\n        reasons = []\n\n        if drawdown_pct >= self.triggers[\"drawdown_pct\"]:\n            reasons.append(\n                f\"drawdown {drawdown_pct:.1f}% >= {self.triggers['drawdown_pct']}%\"\n            )\n        if max_correlation >= self.triggers[\"correlation_max\"]:\n            reasons.append(\n                f\"correlation {max_correlation:.2f} >= {self.triggers['correlation_max']}\"\n            )\n        if min_liq_distance_pct \u003C= self.triggers[\"liquidation_distance_pct\"]:\n            reasons.append(\n                f\"liq distance {min_liq_distance_pct:.1f}% \"\n                f\"\u003C= {self.triggers['liquidation_distance_pct']}%\"\n            )\n        if rapid_loss_pct >= self.triggers[\"rapid_loss_pct\"]:\n            reasons.append(\n                f\"rapid loss {rapid_loss_pct:.1f}% \"\n                f\"in {self.triggers['rapid_loss_window_seconds']}s\"\n            )\n\n        return reasons if reasons else None\n\n    def _transition_to(\n        self, new_state: CircuitState, reason: Optional[str] = None\n    ) -> None:\n        \"\"\"Execute a state transition.\"\"\"\n        old_state = self._state\n        self._state = new_state\n\n        if new_state == CircuitState.OPEN:\n            self._open_since = time.time()\n            self._trip_count += 1\n\n        transition = {\n            \"from\": old_state.value,\n            \"to\": new_state.value,\n            \"reason\": str(reason) if reason else \"normal_transition\",\n            \"trip_count\": self._trip_count,\n            \"cooldown_seconds\": self._current_cooldown,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        self._trip_history.append(transition)\n\n        # Publish state transition event\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            **transition,\n        }\n        payload[\"signature\"] = self.risk_monitor._sign(transition)\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.circuit_breaker_transition\",\n            \"payload\": payload,\n        })\n\n        # Fire callbacks\n        if new_state == CircuitState.OPEN:\n            for cb in self._on_open_callbacks:\n                cb(transition)\n        elif new_state == CircuitState.CLOSED:\n            for cb in self._on_close_callbacks:\n                cb(transition)\n\n    def _status(self, description: str) -> dict:\n        \"\"\"Return current circuit breaker status.\"\"\"\n        elapsed = 0\n        if self._open_since:\n            elapsed = time.time() - self._open_since\n\n        return {\n            \"state\": self._state.value,\n            \"description\": description,\n            \"trip_count\": self._trip_count,\n            \"cooldown_seconds\": self._current_cooldown,\n            \"elapsed_seconds\": round(elapsed, 1),\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n\n    def check_sla_compliance(self) -> dict:\n        \"\"\"\n        Check circuit breaker SLA compliance via GreenHelix.\n\n        Tracks uptime (time in CLOSED state) as a percentage.\n        \"\"\"\n        return self.risk_monitor._execute(\"get_sla_compliance\", {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"metric\": \"circuit_breaker_uptime\",\n        })\n```\n\n### Circuit Breaker Operations via curl\n\n```bash\n# Register a webhook for circuit breaker state transitions\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_webhook\",\n    \"input\": {\n      \"url\": \"https:\u002F\u002Fyour-ops-server.example.com\u002Frisk\u002Fcircuit-breaker\",\n      \"event_types\": [\n        \"risk.circuit_breaker_transition\",\n        \"risk.circuit_breaker_config\"\n      ],\n      \"secret\": \"your-webhook-hmac-secret\"\n    }\n  }'\n```\n\n```bash\n# Query circuit breaker history\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.circuit_breaker_transition\",\n      \"limit\": 20,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Check SLA compliance for the circuit breaker\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_sla_compliance\",\n    \"input\": {\n      \"agent_id\": \"risk-monitor-prod-01\",\n      \"metric\": \"circuit_breaker_uptime\"\n    }\n  }'\n```\n\n### Wiring the Circuit Breaker to Risk Monitors\n\n```python\ncircuit_breaker = CircuitBreakerManager(\n    risk_monitor=monitor,\n    cooldown_seconds=300,\n    max_cooldown_seconds=3600,\n)\n\ncircuit_breaker.configure_triggers(\n    drawdown_pct=12.0,\n    correlation_max=0.92,\n    liquidation_distance_pct=8.0,\n    rapid_loss_pct=4.0,\n)\n\n# Register callbacks\ndef on_circuit_open(transition):\n    \"\"\"Cancel all open orders and notify ops.\"\"\"\n    print(f\"CIRCUIT BREAKER OPEN: {transition['reason']}\")\n    monitor._execute(\"send_message\", {\n        \"to\": \"ops-team\",\n        \"subject\": \"CIRCUIT BREAKER TRIPPED\",\n        \"body\": (\n            f\"Reason: {transition['reason']}\\n\"\n            f\"Trip count: {transition['trip_count']}\\n\"\n            f\"Cooldown: {transition['cooldown_seconds']}s\"\n        ),\n    })\n\ncircuit_breaker.on_open(on_circuit_open)\n\n# In the main risk loop\nstatus = circuit_breaker.evaluate(\n    drawdown_pct=13.5,\n    max_correlation=0.88,\n    min_liq_distance_pct=15.0,\n    rapid_loss_pct=2.0,\n)\nprint(f\"Circuit breaker: {status['state']} ({status['description']})\")\n```\n\n---\n\n## Chapter 7: Multi-Exchange Aggregation\n\n### The Normalization Problem\n\nEvery exchange has its own API format. Binance returns positions as an array with `positionAmt` and `entryPrice`. Coinbase returns `size` and `average_entry_price`. Kraken returns `vol` and `cost`. Symbol naming varies: Binance uses `BTCUSDT`, Coinbase uses `BTC-USD`, Kraken uses `XXBTZUSD`. Margin types, leverage formats, and P&L calculations differ across every API. Before the risk engine can compute aggregate exposure, it needs a unified position format. The exchange adapter pattern solves this: one adapter per exchange, all implementing the same interface, all returning the same normalized data structure. This is the same pattern used by CCXT (a popular open-source library for cryptocurrency exchange APIs), but implemented here with the minimum surface area needed for risk monitoring rather than the full trading API.\n\n### The Exchange Adapter Pattern\n\n```python\nimport abc\nimport hashlib\nimport hmac\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional\n\nimport requests\n\n\nclass NormalizedPosition:\n    \"\"\"Unified position representation across exchanges.\"\"\"\n\n    def __init__(\n        self,\n        symbol: str,\n        exchange: str,\n        side: str,\n        quantity: float,\n        entry_price: float,\n        current_price: float,\n        notional: float,\n        leverage: float,\n        margin_mode: str,\n        unrealized_pnl: float,\n        margin_used: float,\n    ):\n        self.symbol = symbol\n        self.exchange = exchange\n        self.side = side\n        self.quantity = quantity\n        self.entry_price = entry_price\n        self.current_price = current_price\n        self.notional = notional\n        self.leverage = leverage\n        self.margin_mode = margin_mode\n        self.unrealized_pnl = unrealized_pnl\n        self.margin_used = margin_used\n\n    def to_dict(self) -> dict:\n        return {\n            \"symbol\": self.symbol,\n            \"exchange\": self.exchange,\n            \"side\": self.side,\n            \"quantity\": self.quantity,\n            \"entry_price\": self.entry_price,\n            \"current_price\": self.current_price,\n            \"notional\": self.notional,\n            \"leverage\": self.leverage,\n            \"margin_mode\": self.margin_mode,\n            \"unrealized_pnl\": self.unrealized_pnl,\n            \"margin_used\": self.margin_used,\n        }\n\n\nclass ExchangeAdapter(abc.ABC):\n    \"\"\"Base class for exchange adapters.\"\"\"\n\n    @abc.abstractmethod\n    def get_positions(self) -> List[NormalizedPosition]:\n        \"\"\"Fetch and normalize all open positions.\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def get_account_equity(self) -> float:\n        \"\"\"Fetch total account equity in USD.\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def cancel_all_orders(self) -> dict:\n        \"\"\"Cancel all open orders (used by circuit breaker).\"\"\"\n        ...\n\n\nclass BinanceAdapter(ExchangeAdapter):\n    \"\"\"Adapter for Binance Futures API.\"\"\"\n\n    def __init__(self, api_key: str, secret_key: str):\n        self.api_key = api_key\n        self.secret_key = secret_key\n        self.base_url = \"https:\u002F\u002Ffapi.binance.com\"\n        self.session = requests.Session()\n        self.session.headers.update({\"X-MBX-APIKEY\": api_key})\n\n    def _sign(self, params: dict) -> dict:\n        \"\"\"Add timestamp and HMAC signature to request params.\"\"\"\n        params[\"timestamp\"] = int(time.time() * 1000)\n        query_string = \"&\".join(f\"{k}={v}\" for k, v in sorted(params.items()))\n        signature = hmac.new(\n            self.secret_key.encode(), query_string.encode(), hashlib.sha256\n        ).hexdigest()\n        params[\"signature\"] = signature\n        return params\n\n    def get_positions(self) -> List[NormalizedPosition]:\n        params = self._sign({})\n        response = self.session.get(\n            f\"{self.base_url}\u002Ffapi\u002Fv2\u002FpositionRisk\", params=params\n        )\n        response.raise_for_status()\n\n        positions = []\n        for p in response.json():\n            amt = float(p[\"positionAmt\"])\n            if amt == 0:\n                continue\n\n            positions.append(NormalizedPosition(\n                symbol=p[\"symbol\"].replace(\"USDT\", \"-USD\"),\n                exchange=\"binance\",\n                side=\"long\" if amt > 0 else \"short\",\n                quantity=abs(amt),\n                entry_price=float(p[\"entryPrice\"]),\n                current_price=float(p[\"markPrice\"]),\n                notional=abs(float(p[\"notional\"])),\n                leverage=float(p[\"leverage\"]),\n                margin_mode=\"isolated\" if p[\"marginType\"] == \"isolated\" else \"cross\",\n                unrealized_pnl=float(p[\"unRealizedProfit\"]),\n                margin_used=float(p.get(\"isolatedMargin\", 0)),\n            ))\n\n        return positions\n\n    def get_account_equity(self) -> float:\n        params = self._sign({})\n        response = self.session.get(\n            f\"{self.base_url}\u002Ffapi\u002Fv2\u002Faccount\", params=params\n        )\n        response.raise_for_status()\n        return float(response.json()[\"totalWalletBalance\"])\n\n    def cancel_all_orders(self) -> dict:\n        # Cancel for each active symbol\n        positions = self.get_positions()\n        results = {}\n        for pos in positions:\n            symbol = pos.symbol.replace(\"-USD\", \"USDT\")\n            params = self._sign({\"symbol\": symbol})\n            response = self.session.delete(\n                f\"{self.base_url}\u002Ffapi\u002Fv1\u002FallOpenOrders\", params=params\n            )\n            results[symbol] = response.status_code\n        return results\n```\n\n### Aggregating Across Exchanges\n\n```python\ndef aggregate_positions(\n    adapters: List[ExchangeAdapter],\n    risk_monitor: \"RiskMonitor\",\n) -> dict:\n    \"\"\"\n    Fetch positions from all exchanges and compute aggregate metrics.\n    Publishes the aggregated view as a GreenHelix event.\n    \"\"\"\n    all_positions = []\n    total_equity = 0.0\n\n    for adapter in adapters:\n        positions = adapter.get_positions()\n        equity = adapter.get_account_equity()\n        all_positions.extend(positions)\n        total_equity += equity\n\n    # Compute aggregate metrics\n    total_notional = sum(p.notional for p in all_positions)\n    total_unrealized_pnl = sum(p.unrealized_pnl for p in all_positions)\n    aggregate_leverage = total_notional \u002F total_equity if total_equity > 0 else 0.0\n\n    # Net exposure by base asset\n    net_exposure: Dict[str, float] = {}\n    for p in all_positions:\n        base = p.symbol.split(\"-\")[0]\n        signed_notional = p.notional if p.side == \"long\" else -p.notional\n        net_exposure[base] = net_exposure.get(base, 0) + signed_notional\n\n    # Per-exchange breakdown\n    exchange_breakdown: Dict[str, dict] = {}\n    for p in all_positions:\n        if p.exchange not in exchange_breakdown:\n            exchange_breakdown[p.exchange] = {\n                \"position_count\": 0,\n                \"total_notional\": 0.0,\n                \"unrealized_pnl\": 0.0,\n            }\n        eb = exchange_breakdown[p.exchange]\n        eb[\"position_count\"] += 1\n        eb[\"total_notional\"] += p.notional\n        eb[\"unrealized_pnl\"] += p.unrealized_pnl\n\n    result = {\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        \"total_equity\": round(total_equity, 2),\n        \"total_notional\": round(total_notional, 2),\n        \"aggregate_leverage\": round(aggregate_leverage, 2),\n        \"total_unrealized_pnl\": round(total_unrealized_pnl, 2),\n        \"position_count\": len(all_positions),\n        \"exchange_count\": len(exchange_breakdown),\n        \"net_exposure\": {k: round(v, 2) for k, v in net_exposure.items()},\n        \"exchange_breakdown\": exchange_breakdown,\n        \"positions\": [p.to_dict() for p in all_positions],\n    }\n\n    # Publish aggregated snapshot to GreenHelix\n    payload = {\n        \"agent_id\": risk_monitor.agent_id,\n        **{k: v for k, v in result.items() if k != \"positions\"},\n    }\n    payload[\"signature\"] = risk_monitor._sign(\n        {\"equity\": total_equity, \"leverage\": aggregate_leverage}\n    )\n\n    risk_monitor._execute(\"publish_event\", {\n        \"event_type\": \"risk.aggregate_snapshot\",\n        \"payload\": payload,\n    })\n\n    return result\n```\n\n### Querying Aggregate Snapshots via curl\n\n```bash\n# Get the latest aggregate portfolio snapshot\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.aggregate_snapshot\",\n      \"limit\": 1,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Publish an aggregate snapshot manually (e.g., from a cron job)\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"publish_event\",\n    \"input\": {\n      \"event_type\": \"risk.aggregate_snapshot\",\n      \"payload\": {\n        \"agent_id\": \"risk-monitor-prod-01\",\n        \"total_equity\": 98500.00,\n        \"total_notional\": 312000.00,\n        \"aggregate_leverage\": 3.17,\n        \"total_unrealized_pnl\": -1240.50,\n        \"position_count\": 7,\n        \"exchange_count\": 3,\n        \"net_exposure\": {\n          \"BTC\": 142000.00,\n          \"ETH\": 95000.00,\n          \"SOL\": 75000.00\n        },\n        \"timestamp\": \"2026-04-07T14:30:00Z\",\n        \"signature\": \"base64-ed25519-signature\"\n      }\n    }\n  }'\n```\n\n### Usage Example\n\n```python\n# Wire up exchange adapters\nbinance = BinanceAdapter(\n    api_key=\"your-binance-api-key\",\n    secret_key=\"your-binance-secret-key\",\n)\n# (Similarly for CoinbaseAdapter, KrakenAdapter)\n\nadapters = [binance]  # Add more adapters as needed\n\n# Run aggregation\nsnapshot = aggregate_positions(adapters, monitor)\nprint(f\"Total equity: ${snapshot['total_equity']:,.2f}\")\nprint(f\"Aggregate leverage: {snapshot['aggregate_leverage']}x\")\nprint(f\"Positions across {snapshot['exchange_count']} exchanges: {snapshot['position_count']}\")\n\nfor asset, exposure in snapshot[\"net_exposure\"].items():\n    direction = \"LONG\" if exposure > 0 else \"SHORT\"\n    print(f\"  {asset}: ${abs(exposure):,.2f} {direction}\")\n```\n\nAdding a new exchange requires implementing only three methods: `get_positions()`, `get_account_equity()`, and `cancel_all_orders()`. The rest of the risk engine works without modification because it operates on `NormalizedPosition` objects, not exchange-specific data structures.\n\n### Handling Exchange API Failures\n\nExchange APIs fail. Rate limits are hit, connections time out, maintenance windows arrive without notice. The aggregation layer needs to handle partial data gracefully:\n\n```python\ndef safe_aggregate_positions(\n    adapters: Dict[str, ExchangeAdapter],\n    risk_monitor: \"RiskMonitor\",\n) -> dict:\n    \"\"\"\n    Aggregate positions with exchange failure resilience.\n    \"\"\"\n    all_positions = []\n    total_equity = 0.0\n    failures = {}\n    successes = {}\n\n    for name, adapter in adapters.items():\n        try:\n            positions = adapter.get_positions()\n            equity = adapter.get_account_equity()\n            all_positions.extend(positions)\n            total_equity += equity\n            successes[name] = len(positions)\n        except requests.exceptions.RequestException as e:\n            failures[name] = str(e)\n\n    if failures:\n        # Publish a partial data warning\n        risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.exchange_failure\",\n            \"payload\": {\n                \"agent_id\": risk_monitor.agent_id,\n                \"failures\": failures,\n                \"successes\": successes,\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                \"signature\": risk_monitor._sign({\"failures\": list(failures.keys())}),\n            },\n        })\n\n        # Alert the operator\n        risk_monitor._execute(\"send_message\", {\n            \"to\": \"ops-team\",\n            \"subject\": f\"EXCHANGE API FAILURE: {', '.join(failures.keys())}\",\n            \"body\": (\n                f\"Failed exchanges: {json.dumps(failures, indent=2)}\\n\"\n                f\"Successful exchanges: {json.dumps(successes, indent=2)}\\n\"\n                f\"Risk metrics are computed from partial data.\"\n            ),\n        })\n\n    total_notional = sum(p.notional for p in all_positions)\n    aggregate_leverage = total_notional \u002F total_equity if total_equity > 0 else 0.0\n\n    return {\n        \"total_equity\": round(total_equity, 2),\n        \"aggregate_leverage\": round(aggregate_leverage, 2),\n        \"position_count\": len(all_positions),\n        \"exchange_failures\": failures,\n        \"positions\": [p.to_dict() for p in all_positions],\n    }\n```\n\nWhen an exchange API fails, the risk engine computes metrics from the exchanges that are reachable. This means the reported aggregate leverage and total equity may understate the true values. The operator is notified so they can decide whether to act conservatively (assume the unreachable exchange has unfavorable positions) or wait for the connection to recover.\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n---\n\n## What's Next\n\n**Companion Guides:**\n\n- **Tamper-Proof Audit Trails for Trading Bots** -- Add cryptographic verification and regulatory compliance (EU AI Act, MiFID II, SEC 17a-4) to the risk events generated by this system.\n- **Bot Reputation System** -- Turn your risk management track record into verifiable reputation. Prove to copy traders and capital allocators that your risk controls are real, not just claimed.\n- **Strategy Marketplace Playbook** -- Publish risk-managed strategies on the GreenHelix marketplace with provable drawdown limits and circuit breaker guarantees.\n- **AgentOps: Fleet Management** -- Scale from monitoring a single portfolio to managing risk across a fleet of trading bots with centralized governance.\n\n**GreenHelix Documentation:**\n\n- Full API reference: https:\u002F\u002Fapi.greenhelix.net\u002Fv1\n- Event bus deep dive and webhook configuration in the platform documentation\n- SLA compliance tracking and metrics ingestion reference\n\n**Architecture Decisions Worth Revisiting:**\n\nAs your operation scales, revisit these trade-offs:\n- **Polling vs. streaming**: This guide uses polling (10-second cycles). For sub-second risk monitoring, switch to WebSocket connections to exchanges and stream position updates to the GreenHelix event bus in real time.\n- **Single risk engine vs. distributed**: A single risk engine is a single point of failure. For operations above $1M in aggregate equity, run two instances in active-passive mode, with the passive instance consuming the same events and ready to take over if the primary fails.\n- **Alert fatigue**: Tune your thresholds aggressively at first (tight thresholds, frequent alerts), then loosen them as you learn what your portfolio's normal behavior looks like. A circuit breaker that trips every week will be ignored or disabled -- defeating its purpose.\n\n---\n\n*Published by GreenHelix Labs. All code examples are provided under the MIT License. For the full product catalog, visit the GreenHelix storefront.*\n\n","# Trading Bot Risk-as-a-Service: Real-Time Portfolio Risk Monitoring for Multi-Exchange Operations\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nIf you run trading bots across multiple exchanges, you have a visibility problem. Binance shows you Binance positions. Coinbase shows you Coinbase positions. Kraken shows you Kraken positions. Nobody shows you the aggregate. Nobody tells you that your mean-reversion strategy on Binance and your momentum strategy on Coinbase have become 0.94 correlated over the last four hours -- meaning a single market move will hit both simultaneously. Nobody warns you that your combined leverage across three exchanges has crept from 3x to 7x because each exchange only sees its own slice. The May 2025 cascade liquidations on BitMEX made this concrete: bots running isolated risk checks per exchange missed the aggregate exposure building across venues, and when BTC dropped 12% in ninety minutes, the cross-exchange margin calls arrived simultaneously. Operators who had $200K in aggregate equity across four exchanges discovered they were effectively running 11x leverage when positions were netted. The liquidation cascade took 47 seconds from first margin call to full wipeout. This guide builds a complete, production-grade risk monitoring system that sits above your exchange connections and provides a unified view of portfolio risk. It uses GreenHelix's event bus for real-time data aggregation, webhooks for alert delivery, and SLA compliance monitoring for operational health tracking. You will build drawdown trackers, correlation monitors, liquidation proximity engines, and circuit breakers -- all wired together through a single risk management layer that treats your entire multi-exchange operation as one portfolio.\n1. [Risk Architecture Overview](#chapter-1-risk-architecture-overview)\n2. [The RiskMonitor Class](#chapter-2-the-riskmonitor-class)\n\n## What You'll Learn\n- Chapter 1: Risk Architecture Overview\n- Chapter 2: The RiskMonitor Class\n- Chapter 3: Drawdown Monitoring and Alerts\n- Chapter 4: Correlation Monitoring\n- Chapter 5: Liquidation Proximity Engine\n- Chapter 6: Circuit Breaker Implementation\n- Chapter 7: Multi-Exchange Aggregation\n- Next Steps\n- What's Next\n\n## Full Guide\n\n# Trading Bot Risk-as-a-Service: Real-Time Portfolio Risk Monitoring for Multi-Exchange Operations\n\nIf you run trading bots across multiple exchanges, you have a visibility problem. Binance shows you Binance positions. Coinbase shows you Coinbase positions. Kraken shows you Kraken positions. Nobody shows you the aggregate. Nobody tells you that your mean-reversion strategy on Binance and your momentum strategy on Coinbase have become 0.94 correlated over the last four hours -- meaning a single market move will hit both simultaneously. Nobody warns you that your combined leverage across three exchanges has crept from 3x to 7x because each exchange only sees its own slice. The May 2025 cascade liquidations on BitMEX made this concrete: bots running isolated risk checks per exchange missed the aggregate exposure building across venues, and when BTC dropped 12% in ninety minutes, the cross-exchange margin calls arrived simultaneously. Operators who had $200K in aggregate equity across four exchanges discovered they were effectively running 11x leverage when positions were netted. The liquidation cascade took 47 seconds from first margin call to full wipeout. This guide builds a complete, production-grade risk monitoring system that sits above your exchange connections and provides a unified view of portfolio risk. It uses GreenHelix's event bus for real-time data aggregation, webhooks for alert delivery, and SLA compliance monitoring for operational health tracking. You will build drawdown trackers, correlation monitors, liquidation proximity engines, and circuit breakers -- all wired together through a single risk management layer that treats your entire multi-exchange operation as one portfolio.\n\n---\n\n## Table of Contents\n\n1. [Risk Architecture Overview](#chapter-1-risk-architecture-overview)\n2. [The RiskMonitor Class](#chapter-2-the-riskmonitor-class)\n3. [Drawdown Monitoring and Alerts](#chapter-3-drawdown-monitoring-and-alerts)\n4. [Correlation Monitoring](#chapter-4-correlation-monitoring)\n5. [Liquidation Proximity Engine](#chapter-5-liquidation-proximity-engine)\n6. [Circuit Breaker Implementation](#chapter-6-circuit-breaker-implementation)\n7. [Multi-Exchange Aggregation](#chapter-7-multi-exchange-aggregation)\n9. [What's Next](#whats-next)\n\n---\n\n## Chapter 1: Risk Architecture Overview\n\n### Why Centralized Risk Monitoring Matters\n\nEvery professional trading desk has a risk management layer that sits above the execution layer. The risk system sees all positions, all strategies, all venues. It computes aggregate exposure, monitors correlation regimes, and has the authority to halt trading when thresholds are breached. Retail and semi-professional bot operators skip this layer because building it is hard and the exchanges do not provide the APIs to do it natively across venues. The result is that a $500K multi-exchange bot operation runs with less risk infrastructure than a single-desk prop trader at a regional firm.\n\nThe failure modes are specific and predictable:\n\n- **Cross-exchange leverage accumulation**: Each exchange computes margin independently. A 3x position on Binance and a 3x position on Coinbase in correlated assets is effectively 6x aggregate leverage against your total equity -- but neither exchange reports it that way.\n- **Correlation regime changes**: Two strategies that were uncorrelated during backtesting become highly correlated during market stress. The diversification benefit you assumed in your position sizing disappears exactly when you need it.\n- **Cascading liquidations**: A liquidation on one exchange reduces your total equity, which increases your leverage ratio on other exchanges, which triggers further liquidations. This feedback loop operates faster than human reaction time.\n- **Silent risk drift**: Without continuous monitoring, risk parameters drift over days and weeks. A portfolio that started at 2x aggregate leverage creeps to 5x through a series of individually reasonable position additions.\n\n### Architecture\n\nThe system has four layers:\n\n```\n+------------------+    +------------------+    +------------------+\n|  Binance Bot     |    |  Coinbase Bot    |    |  Kraken Bot      |\n|  (execution)     |    |  (execution)     |    |  (execution)     |\n+--------+---------+    +--------+---------+    +--------+---------+\n         |                       |                       |\n         |   publish_event       |   publish_event       |   publish_event\n         v                       v                       v\n+------------------------------------------------------------------------+\n|                     GreenHelix Event Bus                                |\n|  (real-time event ingestion, schema validation, ordering)              |\n+--------+---------------------+-----------------------+-----------------+\n         |                     |                       |\n         |   get_events        |   webhooks            |   get_sla_compliance\n         v                     v                       v\n+------------------------------------------------------------------------+\n|                     Risk Engine                                        |\n|  +----------------+  +------------------+  +------------------------+  |\n|  | DrawdownTracker|  | CorrelationMon   |  | LiquidationProximity   |  |\n|  +----------------+  +------------------+  +------------------------+  |\n|  +----------------+  +------------------+  +------------------------+  |\n|  | CircuitBreaker |  | ExchangeAggr     |  | AlertManager           |  |\n|  +----------------+  +------------------+  +------------------------+  |\n+--------+---------------------------------------------------------------+\n         |\n         |   send_message \u002F register_webhook\n         v\n+------------------------------------------------------------------------+\n|                     Alert Delivery                                      |\n|  Slack, PagerDuty, Telegram, Email, SMS                                |\n+------------------------------------------------------------------------+\n```\n\n### GreenHelix Tools Used\n\nThis guide uses seven GreenHelix tools:\n\n| Tool | Purpose |\n|------|---------|\n| `register_agent` | Register the risk monitoring agent |\n| `register_webhook` | Set up alert delivery endpoints |\n| `publish_event` | Bots publish position and trade events |\n| `get_events` | Risk engine retrieves events for analysis |\n| `get_sla_compliance` | Monitor risk engine uptime and latency |\n| `submit_metrics` | Report risk metrics for observability |\n| `send_message` | Deliver alerts to operators |\n\n### Risk Metrics Hierarchy\n\nRisk metrics are computed at four levels, each aggregating from the level below:\n\n1. **Position-level**: Per-position P&L, unrealized P&L, distance to liquidation, margin utilization\n2. **Strategy-level**: Strategy drawdown, strategy Sharpe ratio (rolling), strategy exposure, number of open positions\n3. **Portfolio-level**: Aggregate drawdown, cross-strategy correlation matrix, net exposure by asset, aggregate leverage\n4. **Fleet-level**: Total equity at risk, number of active strategies, circuit breaker status, SLA compliance score\n\nEach level publishes events to the GreenHelix event bus, and higher levels consume events from lower levels. This creates a clean data flow where the risk engine never polls exchanges directly -- it only reads from the event bus.\n\n### Event Types for Risk Monitoring\n\nDefine one event type per risk signal:\n\n| Event Type | Trigger | Key Fields |\n|---|---|---|\n| `risk.portfolio_check` | Periodic risk scan completes | total_equity, aggregate_leverage, alerts |\n| `risk.drawdown_alert` | Drawdown exceeds threshold | level, threshold_pct, current_pct, trigger_timeframe |\n| `risk.correlation_matrix` | Correlation matrix updated | matrix, strategy_count |\n| `risk.correlation_regime_change` | Correlation shift detected | avg_change, max_change |\n| `risk.liquidation_proximity` | Liquidation check completes | positions, min_distance_pct |\n| `risk.circuit_breaker_transition` | State change | from, to, reason, trip_count |\n| `risk.circuit_breaker_config` | Triggers updated | triggers |\n| `risk.aggregate_snapshot` | Cross-exchange aggregation | total_equity, aggregate_leverage, net_exposure |\n| `risk.thresholds_updated` | Risk thresholds changed | thresholds |\n| `risk.key_rotated` | Agent key rotation | new_public_key |\n\nEach event is signed with the risk agent's Ed25519 private key. The signature covers the canonical JSON serialization of the payload (keys sorted, no whitespace), ensuring that risk events cannot be fabricated or tampered with after the fact. This matters when you need to prove to auditors or investors that a circuit breaker tripped at a specific time for a specific reason.\n\n### Verifying the API Connection\n\nBefore building the full risk engine, verify that your GreenHelix API credentials work:\n\n```bash\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"risk-monitor-prod-01\",\n      \"public_key\": \"'\"$PUBLIC_KEY_B64\"'\",\n      \"name\": \"Portfolio Risk Monitor\"\n    }\n  }'\n```\n\n```python\nimport requests\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\nAPI_KEY = \"your-api-key\"\n\nresponse = requests.post(\n    f\"{API_BASE}\u002Fv1\",\n    headers={\n        \"Authorization\": f\"Bearer {API_KEY}\",\n        \"Content-Type\": \"application\u002Fjson\",\n    },\n    json={\n        \"tool\": \"register_agent\",\n        \"input\": {\n            \"agent_id\": \"risk-monitor-prod-01\",\n            \"public_key\": \"your-public-key-base64\",\n            \"name\": \"Portfolio Risk Monitor\",\n        },\n    },\n)\nprint(response.json())\n```\n\nIf both return a success response with your agent ID, the foundation is in place.\n\n---\n\n## Chapter 2: The RiskMonitor Class\n\n### Core Infrastructure\n\nThe `RiskMonitor` class is the foundation for all risk monitoring in this guide. Every subsequent chapter builds on it.\n\n```bash\n# Generate an Ed25519 keypair for the risk monitor agent\npython3 -c \"\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\nimport base64\n\nprivate_key = Ed25519PrivateKey.generate()\npublic_key = private_key.public_key()\n\npriv_bytes = private_key.private_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PrivateFormat.Raw,\n    encryption_algorithm=serialization.NoEncryption()\n)\npub_bytes = public_key.public_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PublicFormat.Raw\n)\n\nprint(f'PRIVATE_KEY_B64={base64.b64encode(priv_bytes).decode()}')\nprint(f'PUBLIC_KEY_B64={base64.b64encode(pub_bytes).decode()}')\n\"\n```\n\n```bash\n# Register the risk monitor agent\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"risk-monitor-prod-01\",\n      \"public_key\": \"'\"$PUBLIC_KEY_B64\"'\",\n      \"name\": \"Portfolio Risk Monitor\"\n    }\n  }'\n```\n\n### Python Implementation\n\n```python\nimport json\nimport time\nimport base64\nimport hashlib\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional, Any\n\nimport requests\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\n\nclass RiskMonitor:\n    \"\"\"Cross-exchange portfolio risk monitoring using GreenHelix APIs.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        private_key_b64: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        })\n\n        # Load Ed25519 private key\n        key_bytes = base64.b64decode(private_key_b64)\n        self._private_key = Ed25519PrivateKey.from_private_bytes(key_bytes)\n        self._public_key = self._private_key.public_key()\n\n        # Risk thresholds (defaults)\n        self.thresholds = {\n            \"max_drawdown_pct\": 15.0,\n            \"max_correlation\": 0.85,\n            \"max_leverage\": 5.0,\n            \"min_margin_ratio\": 0.20,\n            \"max_single_position_pct\": 25.0,\n        }\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        response = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        response.raise_for_status()\n        return response.json()\n\n    def _sign(self, payload: dict) -> str:\n        \"\"\"Sign a payload with Ed25519.\"\"\"\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self._private_key.sign(canonical.encode(\"utf-8\"))\n        return base64.b64encode(signature).decode()\n\n    def register_risk_agent(self) -> dict:\n        \"\"\"Register this risk monitor as a GreenHelix agent.\"\"\"\n        pub_bytes = self._public_key.public_bytes(\n            encoding=serialization.Encoding.Raw,\n            format=serialization.PublicFormat.Raw,\n        )\n        return self._execute(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"public_key\": base64.b64encode(pub_bytes).decode(),\n            \"name\": f\"Risk Monitor ({self.agent_id})\",\n        })\n\n    def configure_thresholds(\n        self,\n        max_drawdown_pct: float = 15.0,\n        max_correlation: float = 0.85,\n        max_leverage: float = 5.0,\n        min_margin_ratio: float = 0.20,\n        max_single_position_pct: float = 25.0,\n    ) -> dict:\n        \"\"\"Set risk thresholds and publish them as a configuration event.\"\"\"\n        self.thresholds = {\n            \"max_drawdown_pct\": max_drawdown_pct,\n            \"max_correlation\": max_correlation,\n            \"max_leverage\": max_leverage,\n            \"min_margin_ratio\": min_margin_ratio,\n            \"max_single_position_pct\": max_single_position_pct,\n        }\n\n        event_payload = {\n            \"agent_id\": self.agent_id,\n            \"thresholds\": self.thresholds,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        event_payload[\"signature\"] = self._sign(self.thresholds)\n\n        return self._execute(\"publish_event\", {\n            \"event_type\": \"risk.thresholds_updated\",\n            \"payload\": event_payload,\n        })\n\n    def check_portfolio_risk(self, positions: List[dict]) -> dict:\n        \"\"\"\n        Run all risk checks against current positions.\n\n        Returns a dict with risk metrics and any triggered alerts.\n        \"\"\"\n        total_equity = sum(p.get(\"equity\", 0) for p in positions)\n        total_notional = sum(abs(p.get(\"notional\", 0)) for p in positions)\n        leverage = total_notional \u002F total_equity if total_equity > 0 else float(\"inf\")\n\n        alerts = []\n\n        # Check leverage\n        if leverage > self.thresholds[\"max_leverage\"]:\n            alerts.append({\n                \"type\": \"leverage_breach\",\n                \"current\": round(leverage, 2),\n                \"threshold\": self.thresholds[\"max_leverage\"],\n                \"severity\": \"critical\",\n            })\n\n        # Check concentration\n        for pos in positions:\n            if total_notional > 0:\n                concentration = abs(pos.get(\"notional\", 0)) \u002F total_notional * 100\n                if concentration > self.thresholds[\"max_single_position_pct\"]:\n                    alerts.append({\n                        \"type\": \"concentration_breach\",\n                        \"position\": pos.get(\"symbol\", \"unknown\"),\n                        \"current_pct\": round(concentration, 2),\n                        \"threshold\": self.thresholds[\"max_single_position_pct\"],\n                        \"severity\": \"warning\",\n                    })\n\n        risk_summary = {\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"total_equity\": total_equity,\n            \"total_notional\": total_notional,\n            \"aggregate_leverage\": round(leverage, 2),\n            \"position_count\": len(positions),\n            \"alerts\": alerts,\n            \"status\": \"critical\" if any(a[\"severity\"] == \"critical\" for a in alerts)\n                      else \"warning\" if alerts\n                      else \"healthy\",\n        }\n\n        # Publish risk check result as event\n        event_payload = {\n            \"agent_id\": self.agent_id,\n            **risk_summary,\n        }\n        event_payload[\"signature\"] = self._sign(risk_summary)\n\n        self._execute(\"publish_event\", {\n            \"event_type\": \"risk.portfolio_check\",\n            \"payload\": event_payload,\n        })\n\n        return risk_summary\n```\n\n### Configuring Thresholds via curl\n\n```bash\n# Publish a threshold configuration event\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"publish_event\",\n    \"input\": {\n      \"event_type\": \"risk.thresholds_updated\",\n      \"payload\": {\n        \"agent_id\": \"risk-monitor-prod-01\",\n        \"thresholds\": {\n          \"max_drawdown_pct\": 15.0,\n          \"max_correlation\": 0.85,\n          \"max_leverage\": 5.0,\n          \"min_margin_ratio\": 0.20,\n          \"max_single_position_pct\": 25.0\n        },\n        \"timestamp\": \"2026-04-07T12:00:00Z\",\n        \"signature\": \"base64-ed25519-signature\"\n      }\n    }\n  }'\n```\n\n### Usage Example\n\n```python\nmonitor = RiskMonitor(\n    api_key=\"your-api-key\",\n    agent_id=\"risk-monitor-prod-01\",\n    private_key_b64=\"your-private-key-base64\",\n)\n\n# Register and configure\nmonitor.register_risk_agent()\nmonitor.configure_thresholds(\n    max_drawdown_pct=12.0,\n    max_leverage=4.0,\n    min_margin_ratio=0.25,\n)\n\n# Check risk against current positions\npositions = [\n    {\"symbol\": \"BTC-USD\", \"notional\": 50000, \"equity\": 15000, \"exchange\": \"binance\"},\n    {\"symbol\": \"ETH-USD\", \"notional\": 30000, \"equity\": 10000, \"exchange\": \"coinbase\"},\n    {\"symbol\": \"SOL-USD\", \"notional\": 20000, \"equity\": 8000, \"exchange\": \"kraken\"},\n]\n\nresult = monitor.check_portfolio_risk(positions)\nprint(f\"Status: {result['status']}, Leverage: {result['aggregate_leverage']}x\")\n```\n\nThe `RiskMonitor` class provides the transport layer and basic risk checks. The following chapters build specialized risk engines that integrate with it.\n\n---\n\n## Chapter 3: Drawdown Monitoring and Alerts\n\n### Why Drawdown Is the Primary Risk Metric\n\nDrawdown measures peak-to-trough decline. Unlike volatility (which is symmetric) or VaR (which is model-dependent), drawdown directly answers the question operators care about: \"How much have I lost from my best point?\" A 15% drawdown means your portfolio is worth 85% of its highest recorded value. Drawdown is also the metric most directly tied to survival -- a 50% drawdown requires a 100% gain to recover, and a 75% drawdown requires a 300% gain. Bot operators who monitor drawdown at multiple timeframes catch problems before they become existential.\n\n### The DrawdownTracker Class\n\n```python\nimport time\nfrom collections import defaultdict\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional, Tuple\n\n\nclass DrawdownTracker:\n    \"\"\"Tracks drawdown across multiple timeframes with alert escalation.\"\"\"\n\n    # Timeframe windows in seconds\n    TIMEFRAMES = {\n        \"1h\": 3600,\n        \"4h\": 14400,\n        \"24h\": 86400,\n        \"7d\": 604800,\n    }\n\n    # Alert escalation levels\n    ALERT_LEVELS = {\n        \"warning\": 5.0,\n        \"critical\": 8.0,\n        \"emergency\": 12.0,\n        \"circuit_breaker\": 15.0,\n    }\n\n    def __init__(self, risk_monitor: \"RiskMonitor\"):\n        self.risk_monitor = risk_monitor\n        self._equity_history: List[Tuple[float, float]] = []  # (timestamp, equity)\n        self._peaks: Dict[str, float] = {}  # timeframe -> peak equity\n        self._current_drawdowns: Dict[str, float] = {}\n        self._alert_history: List[dict] = []\n\n    def update(self, equity: float, timestamp: Optional[float] = None) -> dict:\n        \"\"\"\n        Record a new equity value and compute drawdowns across all timeframes.\n\n        Returns the current drawdown state.\n        \"\"\"\n        ts = timestamp or time.time()\n        self._equity_history.append((ts, equity))\n\n        # Prune history older than 7 days\n        cutoff = ts - self.TIMEFRAMES[\"7d\"]\n        self._equity_history = [\n            (t, e) for t, e in self._equity_history if t >= cutoff\n        ]\n\n        drawdowns = {}\n        for tf_name, tf_seconds in self.TIMEFRAMES.items():\n            tf_cutoff = ts - tf_seconds\n            tf_values = [e for t, e in self._equity_history if t >= tf_cutoff]\n\n            if not tf_values:\n                drawdowns[tf_name] = 0.0\n                continue\n\n            peak = max(tf_values)\n            self._peaks[tf_name] = peak\n            current_dd = ((peak - equity) \u002F peak) * 100 if peak > 0 else 0.0\n            drawdowns[tf_name] = round(current_dd, 4)\n\n        self._current_drawdowns = drawdowns\n        return drawdowns\n\n    def check_alerts(self) -> List[dict]:\n        \"\"\"\n        Check current drawdowns against alert thresholds.\n\n        Returns a list of triggered alerts, sorted by severity.\n        \"\"\"\n        alerts = []\n        worst_dd = max(self._current_drawdowns.values()) if self._current_drawdowns else 0.0\n\n        for level_name, level_threshold in sorted(\n            self.ALERT_LEVELS.items(), key=lambda x: x[1]\n        ):\n            if worst_dd >= level_threshold:\n                # Find which timeframe triggered\n                trigger_tf = max(\n                    self._current_drawdowns, key=self._current_drawdowns.get\n                )\n\n                alert = {\n                    \"level\": level_name,\n                    \"threshold_pct\": level_threshold,\n                    \"current_pct\": round(worst_dd, 4),\n                    \"trigger_timeframe\": trigger_tf,\n                    \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                    \"peak_equity\": self._peaks.get(trigger_tf, 0),\n                }\n                alerts.append(alert)\n\n        if alerts:\n            self._alert_history.extend(alerts)\n            # Publish the most severe alert\n            worst_alert = alerts[-1]\n            payload = {\n                \"agent_id\": self.risk_monitor.agent_id,\n                \"alert_type\": \"drawdown\",\n                **worst_alert,\n            }\n            payload[\"signature\"] = self.risk_monitor._sign(worst_alert)\n\n            self.risk_monitor._execute(\"publish_event\", {\n                \"event_type\": \"risk.drawdown_alert\",\n                \"payload\": payload,\n            })\n\n        return alerts\n\n    def get_history(self, timeframe: str = \"24h\") -> List[dict]:\n        \"\"\"Get drawdown history for a specific timeframe.\"\"\"\n        tf_seconds = self.TIMEFRAMES.get(timeframe, 86400)\n        cutoff = time.time() - tf_seconds\n        return [\n            {\"timestamp\": t, \"equity\": e}\n            for t, e in self._equity_history\n            if t >= cutoff\n        ]\n```\n\n### Webhook-Based Alert Delivery\n\nRegister a webhook to receive drawdown alerts in real time:\n\n```bash\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_webhook\",\n    \"input\": {\n      \"url\": \"https:\u002F\u002Fyour-ops-server.example.com\u002Frisk\u002Fdrawdown\",\n      \"event_types\": [\n        \"risk.drawdown_alert\",\n        \"risk.portfolio_check\"\n      ],\n      \"secret\": \"your-webhook-hmac-secret\"\n    }\n  }'\n```\n\n```python\n# Register webhooks for drawdown alerts\nmonitor.register_risk_agent()\n\nwebhook_result = monitor._execute(\"register_webhook\", {\n    \"url\": \"https:\u002F\u002Fyour-ops-server.example.com\u002Frisk\u002Fdrawdown\",\n    \"event_types\": [\"risk.drawdown_alert\", \"risk.portfolio_check\"],\n    \"secret\": \"your-webhook-hmac-secret\",\n})\nprint(f\"Webhook registered: {webhook_result}\")\n```\n\n### Alert Escalation in Practice\n\nThe four-level escalation model maps directly to operational responses:\n\n| Level | Threshold | Action |\n|-------|-----------|--------|\n| Warning | 5% drawdown | Log and notify via Slack |\n| Critical | 8% drawdown | Page the on-call operator, reduce position sizes by 50% |\n| Emergency | 12% drawdown | Halt new position opens, begin unwinding existing positions |\n| Circuit Breaker | 15% drawdown | Cancel all open orders, close all positions, halt all strategies |\n\n### Running the Drawdown Loop\n\n```python\ntracker = DrawdownTracker(risk_monitor=monitor)\n\n# Simulate a monitoring loop (in production, this runs continuously)\ndef run_drawdown_monitor(monitor: RiskMonitor, tracker: DrawdownTracker):\n    \"\"\"Poll equity every 10 seconds and check drawdown alerts.\"\"\"\n    while True:\n        # Fetch latest equity from your exchange aggregation layer\n        events = monitor._execute(\"get_events\", {\n            \"event_type\": \"exchange.equity_update\",\n            \"limit\": 1,\n            \"order\": \"desc\",\n        })\n\n        if events.get(\"events\"):\n            equity = events[\"events\"][0][\"payload\"].get(\"total_equity\", 0)\n            drawdowns = tracker.update(equity)\n            alerts = tracker.check_alerts()\n\n            if alerts:\n                worst = alerts[-1]\n                print(\n                    f\"[{worst['level'].upper()}] Drawdown: {worst['current_pct']}% \"\n                    f\"(threshold: {worst['threshold_pct']}%, \"\n                    f\"timeframe: {worst['trigger_timeframe']})\"\n                )\n\n                # Send alert via messaging\n                if worst[\"level\"] in (\"emergency\", \"circuit_breaker\"):\n                    monitor._execute(\"send_message\", {\n                        \"to\": \"ops-team\",\n                        \"subject\": f\"RISK ALERT: {worst['level'].upper()} drawdown\",\n                        \"body\": (\n                            f\"Drawdown: {worst['current_pct']}% \"\n                            f\"(threshold: {worst['threshold_pct']}%)\\n\"\n                            f\"Timeframe: {worst['trigger_timeframe']}\\n\"\n                            f\"Peak equity: ${worst['peak_equity']:,.2f}\"\n                        ),\n                    })\n\n        time.sleep(10)\n```\n\n```bash\n# Query drawdown alert history via curl\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.drawdown_alert\",\n      \"limit\": 20,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n### Drawdown Severity Classification\n\nNot all drawdowns are equal. A 10% drawdown in a trending market during high volatility is qualitatively different from a 10% drawdown in a ranging market during low volatility. The tracker uses the drawdown across multiple timeframes to classify severity:\n\n- **Shallow, slow drawdown** (24h drawdown > 1h drawdown): The portfolio is grinding lower. This is typically caused by a losing trend-following position. Monitor but do not panic -- the strategy may recover when the trend reverses.\n- **Deep, fast drawdown** (1h drawdown > 24h drawdown): The portfolio is in rapid decline. This pattern is characteristic of liquidation cascades, flash crashes, or correlated position blowups. Immediate attention required.\n- **Oscillating drawdown** (1h and 4h drawdowns similar, both \u003C 24h): The portfolio is whipsawing. This pattern is common during high-volatility news events. Reduce position sizes rather than closing positions -- the whipsaw may resolve in either direction.\n\nThe drawdown tracker publishes this classification in the event payload, allowing downstream consumers (the circuit breaker, alert manager) to tailor their response to the type of drawdown, not just the magnitude.\n\nThe drawdown tracker is intentionally simple. It uses empirical peaks, not modeled ones. It does not try to predict future drawdown -- it measures what has already happened and triggers actions based on predefined thresholds. Predictive models add complexity without adding reliability under stress conditions.\n\n---\n\n## Chapter 4: Correlation Monitoring\n\n### Why Correlation Kills Portfolios\n\nDiversification is the only free lunch in finance -- until it isn't. Portfolio theory assumes that combining uncorrelated strategies reduces total risk. If Strategy A has a Sharpe of 1.5 and Strategy B has a Sharpe of 1.5, and they are uncorrelated, the combined portfolio has a Sharpe of roughly 2.1. But correlation is not static. During market stress, correlations spike. The 2020 COVID crash saw BTC-ETH correlation go from 0.6 to 0.95 in 48 hours. The 2022 LUNA collapse pushed correlations across all crypto assets above 0.9 for weeks. Strategies that appeared diversified during calm markets became a single concentrated bet during the exact conditions where diversification mattered most.\n\nMonitoring correlation in real time -- and detecting regime changes -- lets you reduce exposure before the diversification illusion costs you capital.\n\n### The CorrelationMonitor Class\n\n```python\nimport math\nfrom collections import deque\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional, Tuple\n\n\nclass CorrelationMonitor:\n    \"\"\"\n    Rolling correlation computation between strategies\n    with regime change detection.\n    \"\"\"\n\n    def __init__(\n        self,\n        risk_monitor: \"RiskMonitor\",\n        window_size: int = 100,\n        regime_change_threshold: float = 0.3,\n    ):\n        self.risk_monitor = risk_monitor\n        self.window_size = window_size\n        self.regime_change_threshold = regime_change_threshold\n\n        # Returns buffer per strategy\n        self._returns: Dict[str, deque] = {}\n        self._correlation_history: List[dict] = []\n        self._previous_matrix: Optional[Dict[str, Dict[str, float]]] = None\n\n    def add_returns(self, strategy_id: str, returns_value: float) -> None:\n        \"\"\"Add a return observation for a strategy.\"\"\"\n        if strategy_id not in self._returns:\n            self._returns[strategy_id] = deque(maxlen=self.window_size)\n        self._returns[strategy_id].append(returns_value)\n\n    def _pearson(self, x: List[float], y: List[float]) -> float:\n        \"\"\"Compute Pearson correlation between two series.\"\"\"\n        n = min(len(x), len(y))\n        if n \u003C 10:\n            return 0.0\n\n        x, y = x[:n], y[:n]\n        mean_x = sum(x) \u002F n\n        mean_y = sum(y) \u002F n\n\n        cov = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))\n        std_x = math.sqrt(sum((xi - mean_x) ** 2 for xi in x))\n        std_y = math.sqrt(sum((yi - mean_y) ** 2 for yi in y))\n\n        if std_x == 0 or std_y == 0:\n            return 0.0\n\n        return cov \u002F (std_x * std_y)\n\n    def compute_matrix(self) -> Dict[str, Dict[str, float]]:\n        \"\"\"Compute the full correlation matrix across all strategies.\"\"\"\n        strategies = sorted(self._returns.keys())\n        matrix = {}\n\n        for s1 in strategies:\n            matrix[s1] = {}\n            for s2 in strategies:\n                if s1 == s2:\n                    matrix[s1][s2] = 1.0\n                else:\n                    corr = self._pearson(\n                        list(self._returns[s1]),\n                        list(self._returns[s2]),\n                    )\n                    matrix[s1][s2] = round(corr, 4)\n\n        # Publish the matrix as an event\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"matrix\": matrix,\n            \"strategy_count\": len(strategies),\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        payload[\"signature\"] = self.risk_monitor._sign({\"matrix\": matrix})\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.correlation_matrix\",\n            \"payload\": payload,\n        })\n\n        self._correlation_history.append({\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"matrix\": matrix,\n        })\n\n        return matrix\n\n    def detect_regime_change(self) -> Optional[dict]:\n        \"\"\"\n        Detect if the correlation regime has changed significantly.\n\n        Compares current matrix to previous matrix. A regime change is\n        detected when the average absolute change in correlations exceeds\n        the threshold.\n        \"\"\"\n        current = self.compute_matrix()\n\n        if self._previous_matrix is None:\n            self._previous_matrix = current\n            return None\n\n        strategies = sorted(current.keys())\n        changes = []\n\n        for s1 in strategies:\n            for s2 in strategies:\n                if s1 >= s2:\n                    continue\n                prev = self._previous_matrix.get(s1, {}).get(s2, 0.0)\n                curr = current.get(s1, {}).get(s2, 0.0)\n                changes.append(abs(curr - prev))\n\n        if not changes:\n            self._previous_matrix = current\n            return None\n\n        avg_change = sum(changes) \u002F len(changes)\n        max_change = max(changes)\n\n        self._previous_matrix = current\n\n        if avg_change > self.regime_change_threshold:\n            alert = {\n                \"type\": \"correlation_regime_change\",\n                \"avg_change\": round(avg_change, 4),\n                \"max_change\": round(max_change, 4),\n                \"threshold\": self.regime_change_threshold,\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                \"matrix\": current,\n            }\n\n            # Publish regime change event\n            event_payload = {\n                \"agent_id\": self.risk_monitor.agent_id,\n                **alert,\n            }\n            event_payload[\"signature\"] = self.risk_monitor._sign(alert)\n\n            self.risk_monitor._execute(\"publish_event\", {\n                \"event_type\": \"risk.correlation_regime_change\",\n                \"payload\": event_payload,\n            })\n\n            return alert\n\n        return None\n```\n\n### Querying Correlation History via curl\n\n```bash\n# Get recent correlation matrix events\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.correlation_matrix\",\n      \"limit\": 10,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Get regime change alerts\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.correlation_regime_change\",\n      \"limit\": 5,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n### Usage Example\n\n```python\ncorr_monitor = CorrelationMonitor(\n    risk_monitor=monitor,\n    window_size=100,\n    regime_change_threshold=0.3,\n)\n\n# Feed returns from each strategy (in production, these come from trade events)\nimport random\nfor i in range(120):\n    corr_monitor.add_returns(\"mean-reversion-btc\", random.gauss(0.001, 0.02))\n    corr_monitor.add_returns(\"momentum-eth\", random.gauss(0.0005, 0.025))\n    corr_monitor.add_returns(\"arb-sol-perps\", random.gauss(0.0008, 0.015))\n\nmatrix = corr_monitor.compute_matrix()\nfor s1, row in matrix.items():\n    print(f\"{s1}: {row}\")\n\nregime = corr_monitor.detect_regime_change()\nif regime:\n    print(f\"REGIME CHANGE detected: avg change {regime['avg_change']}\")\n```\n\n### Interpreting the Correlation Matrix\n\nThe correlation matrix is symmetric with 1.0 on the diagonal. Off-diagonal values range from -1.0 (perfectly inverse) to +1.0 (perfectly correlated). For risk management purposes:\n\n- **Below 0.3**: Strategies are effectively uncorrelated. Diversification benefit is real.\n- **0.3 to 0.6**: Moderate correlation. Some diversification benefit remains, but not full.\n- **0.6 to 0.85**: High correlation. The strategies will draw down together in stressed markets. Position sizes should account for this.\n- **Above 0.85**: The strategies are effectively the same bet. The circuit breaker should consider triggering if this persists.\n\n### Practical Considerations for Correlation Monitoring\n\n**Window size selection**: The `window_size` parameter controls how many return observations are used to compute correlation. Smaller windows (30-50) are more responsive to recent correlation changes but produce noisier estimates. Larger windows (100-200) are more stable but slower to detect regime changes. A common compromise is to run two correlation monitors in parallel -- one with a 50-observation window for early detection and one with a 150-observation window for confirmation.\n\n**Return frequency**: The correlation monitor needs returns at a consistent frequency. If Strategy A reports returns every minute and Strategy B reports every 15 minutes, the correlation estimate will be unreliable. Normalize to the lowest common frequency across all strategies. For most crypto bot operations, 5-minute or 15-minute returns provide a good balance between responsiveness and stability.\n\n**Handling missing data**: If a strategy stops reporting returns (e.g., because the bot crashed or the exchange is down), the correlation monitor should flag this rather than computing correlation with stale data. A strategy that has not reported in 30 minutes should be excluded from the matrix with a note, not included with its last known returns repeated.\n\n**Correlation is not causation**: Two strategies can be highly correlated because they both respond to the same market factor (e.g., BTC price), not because they are redundant. If Strategy A goes long BTC on momentum signals and Strategy B goes long ETH on mean-reversion signals, they may be correlated during strong BTC moves (because ETH follows BTC) but serve different functions in the portfolio. Use correlation as an input to risk decisions, not as the sole decision criterion.\n\n---\n\n## Chapter 5: Liquidation Proximity Engine\n\n### Why Distance to Liquidation Matters\n\nA position's P&L tells you what has happened. Distance to liquidation tells you what will happen if the market moves against you by a specific amount. A position might be profitable but dangerously close to liquidation if leverage is high. Exchange liquidation engines are not gentle -- they liquidate at market, often at prices significantly worse than the liquidation price, and they charge liquidation fees. Getting liquidated on a leveraged position typically costs 2-5% more than closing the position manually at the same price. Binance charges a liquidation clearance fee that can be as high as 1.5% of the position's notional value. Coinbase's liquidation engine can execute up to 5% below the liquidation price during fast markets. These costs are invisible until they hit -- and they always hit at the worst possible time, during exactly the market conditions where your portfolio can least afford the additional loss.\n\nThe liquidation proximity engine monitors distance to liquidation across all positions on all exchanges and triggers alerts before the exchange's liquidation engine takes over. The goal is simple: never get liquidated. Always close the position yourself, at a better price, before the exchange does it for you.\n\n### Exchange Margin Models\n\nDifferent exchanges use different margin models, and this affects liquidation price calculation:\n\n- **Isolated margin** (per-position): Each position has its own margin. Liquidation price depends only on that position's margin and entry price. Simple to calculate, but does not benefit from cross-position netting.\n- **Cross margin** (per-account): All positions on the account share a single margin pool. A profitable position's unrealized P&L can offset a losing position's margin requirement. Liquidation depends on the aggregate account equity vs total maintenance margin.\n\n### The LiquidationProximityEngine Class\n\n```python\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional\n\n\nclass LiquidationProximityEngine:\n    \"\"\"\n    Monitors distance to liquidation across exchanges and margin modes.\n    \"\"\"\n\n    # Maintenance margin rates by exchange (simplified)\n    MAINTENANCE_MARGIN = {\n        \"binance\": 0.004,   # 0.4% for BTC\n        \"coinbase\": 0.005,  # 0.5%\n        \"kraken\": 0.005,    # 0.5%\n    }\n\n    def __init__(\n        self,\n        risk_monitor: \"RiskMonitor\",\n        alert_threshold_pct: float = 20.0,\n        critical_threshold_pct: float = 10.0,\n    ):\n        self.risk_monitor = risk_monitor\n        self.alert_threshold_pct = alert_threshold_pct\n        self.critical_threshold_pct = critical_threshold_pct\n        self._positions: List[dict] = []\n        self._alerts: List[dict] = []\n\n    def _calc_liquidation_price_isolated(\n        self,\n        entry_price: float,\n        side: str,\n        leverage: float,\n        maint_margin_rate: float,\n    ) -> float:\n        \"\"\"\n        Calculate liquidation price for an isolated-margin position.\n\n        For longs: liq = entry * (1 - 1\u002Fleverage + maint_margin_rate)\n        For shorts: liq = entry * (1 + 1\u002Fleverage - maint_margin_rate)\n        \"\"\"\n        if side == \"long\":\n            return entry_price * (1 - 1 \u002F leverage + maint_margin_rate)\n        else:\n            return entry_price * (1 + 1 \u002F leverage - maint_margin_rate)\n\n    def _calc_distance_to_liquidation(\n        self,\n        current_price: float,\n        liquidation_price: float,\n        side: str,\n    ) -> float:\n        \"\"\"Calculate percentage distance from current price to liquidation.\"\"\"\n        if side == \"long\":\n            distance = (current_price - liquidation_price) \u002F current_price * 100\n        else:\n            distance = (liquidation_price - current_price) \u002F current_price * 100\n        return max(0.0, round(distance, 4))\n\n    def update_positions(self, positions: List[dict]) -> List[dict]:\n        \"\"\"\n        Update tracked positions and compute liquidation proximity.\n\n        Each position dict should have:\n        - symbol, exchange, side, entry_price, current_price,\n          leverage, margin_mode, quantity\n        \"\"\"\n        self._positions = positions\n        results = []\n\n        for pos in positions:\n            exchange = pos.get(\"exchange\", \"binance\")\n            maint_rate = self.MAINTENANCE_MARGIN.get(exchange, 0.005)\n            margin_mode = pos.get(\"margin_mode\", \"isolated\")\n\n            if margin_mode == \"isolated\":\n                liq_price = self._calc_liquidation_price_isolated(\n                    entry_price=pos[\"entry_price\"],\n                    side=pos[\"side\"],\n                    leverage=pos[\"leverage\"],\n                    maint_margin_rate=maint_rate,\n                )\n            else:\n                # Cross margin: use account-level equity\n                # Simplified: treat as isolated with effective leverage\n                liq_price = self._calc_liquidation_price_isolated(\n                    entry_price=pos[\"entry_price\"],\n                    side=pos[\"side\"],\n                    leverage=pos.get(\"effective_leverage\", pos[\"leverage\"]),\n                    maint_margin_rate=maint_rate,\n                )\n\n            distance = self._calc_distance_to_liquidation(\n                current_price=pos[\"current_price\"],\n                liquidation_price=liq_price,\n                side=pos[\"side\"],\n            )\n\n            result = {\n                \"symbol\": pos[\"symbol\"],\n                \"exchange\": exchange,\n                \"side\": pos[\"side\"],\n                \"entry_price\": pos[\"entry_price\"],\n                \"current_price\": pos[\"current_price\"],\n                \"liquidation_price\": round(liq_price, 2),\n                \"distance_pct\": distance,\n                \"leverage\": pos[\"leverage\"],\n                \"status\": \"critical\" if distance \u003C self.critical_threshold_pct\n                          else \"warning\" if distance \u003C self.alert_threshold_pct\n                          else \"safe\",\n            }\n            results.append(result)\n\n        # Publish positions with liquidation data\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"positions\": results,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        payload[\"signature\"] = self.risk_monitor._sign(\n            {\"positions_count\": len(results)}\n        )\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.liquidation_proximity\",\n            \"payload\": payload,\n        })\n\n        return results\n\n    def get_alerts(self) -> List[dict]:\n        \"\"\"Get all positions within alert thresholds.\"\"\"\n        alerts = []\n        for pos in self._positions:\n            result = self.update_positions([pos])[0]\n            if result[\"status\"] in (\"warning\", \"critical\"):\n                alerts.append(result)\n        return alerts\n\n    def get_aggregate_risk(self) -> dict:\n        \"\"\"Compute aggregate liquidation risk across all positions.\"\"\"\n        if not self._positions:\n            return {\"status\": \"no_positions\", \"min_distance_pct\": 100.0}\n\n        results = self.update_positions(self._positions)\n        distances = [r[\"distance_pct\"] for r in results]\n\n        return {\n            \"position_count\": len(results),\n            \"min_distance_pct\": min(distances),\n            \"avg_distance_pct\": round(sum(distances) \u002F len(distances), 2),\n            \"critical_count\": sum(1 for r in results if r[\"status\"] == \"critical\"),\n            \"warning_count\": sum(1 for r in results if r[\"status\"] == \"warning\"),\n            \"closest_position\": min(results, key=lambda r: r[\"distance_pct\"]),\n        }\n```\n\n### Checking Liquidation Proximity via curl\n\n```bash\n# Query recent liquidation proximity events\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.liquidation_proximity\",\n      \"limit\": 5,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Send an alert when a position is close to liquidation\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"send_message\",\n    \"input\": {\n      \"to\": \"ops-team\",\n      \"subject\": \"LIQUIDATION WARNING: BTC-USD on Binance\",\n      \"body\": \"BTC-USD long position is 8.5% from liquidation.\\nEntry: $67,200 | Current: $63,100 | Liq: $57,800\\nLeverage: 10x | Margin mode: isolated\\nAction required: reduce position or add margin.\"\n    }\n  }'\n```\n\n### Usage Example\n\n```python\nliq_engine = LiquidationProximityEngine(\n    risk_monitor=monitor,\n    alert_threshold_pct=20.0,\n    critical_threshold_pct=10.0,\n)\n\npositions = [\n    {\n        \"symbol\": \"BTC-USD\",\n        \"exchange\": \"binance\",\n        \"side\": \"long\",\n        \"entry_price\": 67200,\n        \"current_price\": 63100,\n        \"leverage\": 10,\n        \"margin_mode\": \"isolated\",\n        \"quantity\": 0.5,\n    },\n    {\n        \"symbol\": \"ETH-USD\",\n        \"exchange\": \"coinbase\",\n        \"side\": \"short\",\n        \"entry_price\": 3400,\n        \"current_price\": 3520,\n        \"leverage\": 5,\n        \"margin_mode\": \"cross\",\n        \"effective_leverage\": 4.2,\n        \"quantity\": 10,\n    },\n]\n\nresults = liq_engine.update_positions(positions)\nfor r in results:\n    print(\n        f\"{r['symbol']} ({r['exchange']}): {r['distance_pct']}% from liquidation \"\n        f\"[{r['status']}] | Liq price: ${r['liquidation_price']:,.2f}\"\n    )\n\nagg = liq_engine.get_aggregate_risk()\nprint(f\"\\nAggregate: min distance {agg['min_distance_pct']}%, \"\n      f\"{agg['critical_count']} critical, {agg['warning_count']} warnings\")\n```\n\n### Aggregate Liquidation Risk\n\nIndividual position liquidation distances do not capture the full picture. In cross-margin mode, a losing position's margin requirement is covered by the account's total equity -- including unrealized profits from other positions. If those other positions reverse, the aggregate margin coverage can collapse rapidly. The `get_aggregate_risk()` method computes the minimum distance to liquidation across all positions and counts how many positions are in warning or critical states. When multiple positions are simultaneously close to liquidation, the aggregate risk is higher than what any individual position metric suggests because a liquidation on one position can cascade to others through shared margin.\n\nThe right operational response depends on the aggregate picture:\n- **One position critical, others safe**: Add margin to the critical position or reduce its size. The rest of the portfolio is fine.\n- **Multiple positions warning**: The portfolio is stressed. Reduce aggregate leverage by closing the weakest positions first.\n- **Multiple positions critical**: This is the circuit breaker scenario. The risk of cascade liquidation is high. Close positions starting from the most leveraged.\n\nThe engine intentionally uses simplified liquidation calculations. Real exchange liquidation engines have additional factors (funding rate accruals, insurance fund contributions, ADL priority). The simplified model provides a conservative lower bound -- your actual liquidation price is slightly further away than what this engine computes, which means alerts will fire slightly early. This is the correct failure mode for a safety system.\n\n---\n\n## Chapter 6: Circuit Breaker Implementation\n\n### The Case for Automated Trading Halts\n\nHuman reaction time to a risk event is measured in minutes. Market cascades are measured in seconds. The May 2025 BitMEX incident saw a $180M liquidation cascade complete in 47 seconds. No operator, no matter how attentive, can evaluate risk, make a decision, and execute that decision across three exchanges in under a minute. Circuit breakers are the solution: automated systems that halt trading when predefined conditions are met, without waiting for human approval. The human's role shifts from \"react to the crisis\" to \"review the circuit breaker's decision after the fact and decide when to re-enable trading.\"\n\nThe concept is borrowed from stock exchanges, which have used circuit breakers since the 1987 crash. The NYSE halts trading when the S&P 500 drops 7% (Level 1), 13% (Level 2), or 20% (Level 3) from the previous day's close. These thresholds were calibrated through decades of experience. Your trading bot needs its own calibrated thresholds, tuned to your specific strategies, capital base, and risk tolerance. The circuit breaker in this chapter is fully configurable and integrates with the drawdown, correlation, and liquidation monitors from previous chapters to make holistic risk decisions.\n\n### Circuit Breaker State Machine\n\nThe circuit breaker has three states:\n\n```\n                    +---------+\n                    |         |\n           +------>| CLOSED  |\u003C------+\n           |       | (normal)|       |\n           |       +----+----+       |\n           |            |            |\n           |    trigger condition    |\n           |    exceeded             |\n           |            |            |\n           |            v            |\n     recovery      +----+----+      |\n     period        |         |      |\n     elapsed       |  OPEN   |      |\n           |       | (halted)|      |\n           |       +----+----+      |\n           |            |            |\n           |   cooldown elapsed     |\n           |            |            |\n           |            v            |\n           |       +----+----+      |\n           |       |         |      |  test trade\n           +-------+HALF_OPEN+------+  fails\n                   | (test)  |\n                   +---------+\n```\n\n- **CLOSED**: Normal operation. All strategies execute freely. Risk monitors are active.\n- **OPEN**: Trading is halted. All open orders are cancelled. No new positions are opened. Existing positions may be closed (configurable). A cooldown timer starts.\n- **HALF_OPEN**: After the cooldown, one test trade is allowed with reduced position size. If it succeeds without triggering another alert, transition to CLOSED. If it fails, transition back to OPEN with a longer cooldown.\n\n### The CircuitBreakerManager Class\n\n```python\nimport enum\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Callable, Dict, List, Optional\n\n\nclass CircuitState(enum.Enum):\n    CLOSED = \"closed\"\n    OPEN = \"open\"\n    HALF_OPEN = \"half_open\"\n\n\nclass CircuitBreakerManager:\n    \"\"\"\n    Circuit breaker for trading operations with configurable triggers\n    and GreenHelix SLA compliance integration.\n    \"\"\"\n\n    def __init__(\n        self,\n        risk_monitor: \"RiskMonitor\",\n        cooldown_seconds: int = 300,\n        max_cooldown_seconds: int = 3600,\n        cooldown_multiplier: float = 2.0,\n        test_position_fraction: float = 0.1,\n    ):\n        self.risk_monitor = risk_monitor\n        self.cooldown_seconds = cooldown_seconds\n        self.max_cooldown_seconds = max_cooldown_seconds\n        self.cooldown_multiplier = cooldown_multiplier\n        self.test_position_fraction = test_position_fraction\n\n        self._state = CircuitState.CLOSED\n        self._open_since: Optional[float] = None\n        self._current_cooldown = cooldown_seconds\n        self._trip_count = 0\n        self._trip_history: List[dict] = []\n\n        # Configurable trigger thresholds\n        self.triggers = {\n            \"drawdown_pct\": 15.0,\n            \"correlation_max\": 0.95,\n            \"liquidation_distance_pct\": 10.0,\n            \"rapid_loss_pct\": 5.0,\n            \"rapid_loss_window_seconds\": 300,\n        }\n\n        # Callbacks for state transitions\n        self._on_open_callbacks: List[Callable] = []\n        self._on_close_callbacks: List[Callable] = []\n\n    @property\n    def state(self) -> CircuitState:\n        return self._state\n\n    def configure_triggers(self, **kwargs) -> None:\n        \"\"\"Update trigger thresholds.\"\"\"\n        for key, value in kwargs.items():\n            if key in self.triggers:\n                self.triggers[key] = value\n\n        # Publish trigger configuration\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"triggers\": self.triggers,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        payload[\"signature\"] = self.risk_monitor._sign(self.triggers)\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.circuit_breaker_config\",\n            \"payload\": payload,\n        })\n\n    def on_open(self, callback: Callable) -> None:\n        \"\"\"Register a callback for when the circuit breaker opens.\"\"\"\n        self._on_open_callbacks.append(callback)\n\n    def on_close(self, callback: Callable) -> None:\n        \"\"\"Register a callback for when the circuit breaker closes.\"\"\"\n        self._on_close_callbacks.append(callback)\n\n    def evaluate(\n        self,\n        drawdown_pct: float = 0.0,\n        max_correlation: float = 0.0,\n        min_liq_distance_pct: float = 100.0,\n        rapid_loss_pct: float = 0.0,\n    ) -> dict:\n        \"\"\"\n        Evaluate current risk metrics against circuit breaker triggers.\n\n        Returns the current state and any state transitions.\n        \"\"\"\n        now = time.time()\n\n        if self._state == CircuitState.OPEN:\n            # Check if cooldown has elapsed\n            if self._open_since and (now - self._open_since) >= self._current_cooldown:\n                self._transition_to(CircuitState.HALF_OPEN)\n                return self._status(\"cooldown_elapsed\")\n            return self._status(\"waiting_cooldown\")\n\n        if self._state == CircuitState.HALF_OPEN:\n            # In half-open state, check if conditions have improved\n            if self._should_trip(\n                drawdown_pct, max_correlation, min_liq_distance_pct, rapid_loss_pct\n            ):\n                # Conditions still bad -- back to OPEN with longer cooldown\n                self._current_cooldown = min(\n                    self._current_cooldown * self.cooldown_multiplier,\n                    self.max_cooldown_seconds,\n                )\n                self._transition_to(CircuitState.OPEN, reason=\"half_open_test_failed\")\n                return self._status(\"test_failed\")\n            else:\n                self._transition_to(CircuitState.CLOSED)\n                return self._status(\"recovered\")\n\n        # CLOSED state -- check triggers\n        trip_reasons = self._should_trip(\n            drawdown_pct, max_correlation, min_liq_distance_pct, rapid_loss_pct\n        )\n\n        if trip_reasons:\n            self._current_cooldown = self.cooldown_seconds\n            self._transition_to(CircuitState.OPEN, reason=trip_reasons)\n            return self._status(\"tripped\")\n\n        return self._status(\"healthy\")\n\n    def _should_trip(\n        self,\n        drawdown_pct: float,\n        max_correlation: float,\n        min_liq_distance_pct: float,\n        rapid_loss_pct: float,\n    ) -> Optional[List[str]]:\n        \"\"\"Check if any trigger condition is met. Returns reasons or None.\"\"\"\n        reasons = []\n\n        if drawdown_pct >= self.triggers[\"drawdown_pct\"]:\n            reasons.append(\n                f\"drawdown {drawdown_pct:.1f}% >= {self.triggers['drawdown_pct']}%\"\n            )\n        if max_correlation >= self.triggers[\"correlation_max\"]:\n            reasons.append(\n                f\"correlation {max_correlation:.2f} >= {self.triggers['correlation_max']}\"\n            )\n        if min_liq_distance_pct \u003C= self.triggers[\"liquidation_distance_pct\"]:\n            reasons.append(\n                f\"liq distance {min_liq_distance_pct:.1f}% \"\n                f\"\u003C= {self.triggers['liquidation_distance_pct']}%\"\n            )\n        if rapid_loss_pct >= self.triggers[\"rapid_loss_pct\"]:\n            reasons.append(\n                f\"rapid loss {rapid_loss_pct:.1f}% \"\n                f\"in {self.triggers['rapid_loss_window_seconds']}s\"\n            )\n\n        return reasons if reasons else None\n\n    def _transition_to(\n        self, new_state: CircuitState, reason: Optional[str] = None\n    ) -> None:\n        \"\"\"Execute a state transition.\"\"\"\n        old_state = self._state\n        self._state = new_state\n\n        if new_state == CircuitState.OPEN:\n            self._open_since = time.time()\n            self._trip_count += 1\n\n        transition = {\n            \"from\": old_state.value,\n            \"to\": new_state.value,\n            \"reason\": str(reason) if reason else \"normal_transition\",\n            \"trip_count\": self._trip_count,\n            \"cooldown_seconds\": self._current_cooldown,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n        self._trip_history.append(transition)\n\n        # Publish state transition event\n        payload = {\n            \"agent_id\": self.risk_monitor.agent_id,\n            **transition,\n        }\n        payload[\"signature\"] = self.risk_monitor._sign(transition)\n\n        self.risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.circuit_breaker_transition\",\n            \"payload\": payload,\n        })\n\n        # Fire callbacks\n        if new_state == CircuitState.OPEN:\n            for cb in self._on_open_callbacks:\n                cb(transition)\n        elif new_state == CircuitState.CLOSED:\n            for cb in self._on_close_callbacks:\n                cb(transition)\n\n    def _status(self, description: str) -> dict:\n        \"\"\"Return current circuit breaker status.\"\"\"\n        elapsed = 0\n        if self._open_since:\n            elapsed = time.time() - self._open_since\n\n        return {\n            \"state\": self._state.value,\n            \"description\": description,\n            \"trip_count\": self._trip_count,\n            \"cooldown_seconds\": self._current_cooldown,\n            \"elapsed_seconds\": round(elapsed, 1),\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        }\n\n    def check_sla_compliance(self) -> dict:\n        \"\"\"\n        Check circuit breaker SLA compliance via GreenHelix.\n\n        Tracks uptime (time in CLOSED state) as a percentage.\n        \"\"\"\n        return self.risk_monitor._execute(\"get_sla_compliance\", {\n            \"agent_id\": self.risk_monitor.agent_id,\n            \"metric\": \"circuit_breaker_uptime\",\n        })\n```\n\n### Circuit Breaker Operations via curl\n\n```bash\n# Register a webhook for circuit breaker state transitions\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"register_webhook\",\n    \"input\": {\n      \"url\": \"https:\u002F\u002Fyour-ops-server.example.com\u002Frisk\u002Fcircuit-breaker\",\n      \"event_types\": [\n        \"risk.circuit_breaker_transition\",\n        \"risk.circuit_breaker_config\"\n      ],\n      \"secret\": \"your-webhook-hmac-secret\"\n    }\n  }'\n```\n\n```bash\n# Query circuit breaker history\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.circuit_breaker_transition\",\n      \"limit\": 20,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Check SLA compliance for the circuit breaker\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_sla_compliance\",\n    \"input\": {\n      \"agent_id\": \"risk-monitor-prod-01\",\n      \"metric\": \"circuit_breaker_uptime\"\n    }\n  }'\n```\n\n### Wiring the Circuit Breaker to Risk Monitors\n\n```python\ncircuit_breaker = CircuitBreakerManager(\n    risk_monitor=monitor,\n    cooldown_seconds=300,\n    max_cooldown_seconds=3600,\n)\n\ncircuit_breaker.configure_triggers(\n    drawdown_pct=12.0,\n    correlation_max=0.92,\n    liquidation_distance_pct=8.0,\n    rapid_loss_pct=4.0,\n)\n\n# Register callbacks\ndef on_circuit_open(transition):\n    \"\"\"Cancel all open orders and notify ops.\"\"\"\n    print(f\"CIRCUIT BREAKER OPEN: {transition['reason']}\")\n    monitor._execute(\"send_message\", {\n        \"to\": \"ops-team\",\n        \"subject\": \"CIRCUIT BREAKER TRIPPED\",\n        \"body\": (\n            f\"Reason: {transition['reason']}\\n\"\n            f\"Trip count: {transition['trip_count']}\\n\"\n            f\"Cooldown: {transition['cooldown_seconds']}s\"\n        ),\n    })\n\ncircuit_breaker.on_open(on_circuit_open)\n\n# In the main risk loop\nstatus = circuit_breaker.evaluate(\n    drawdown_pct=13.5,\n    max_correlation=0.88,\n    min_liq_distance_pct=15.0,\n    rapid_loss_pct=2.0,\n)\nprint(f\"Circuit breaker: {status['state']} ({status['description']})\")\n```\n\n---\n\n## Chapter 7: Multi-Exchange Aggregation\n\n### The Normalization Problem\n\nEvery exchange has its own API format. Binance returns positions as an array with `positionAmt` and `entryPrice`. Coinbase returns `size` and `average_entry_price`. Kraken returns `vol` and `cost`. Symbol naming varies: Binance uses `BTCUSDT`, Coinbase uses `BTC-USD`, Kraken uses `XXBTZUSD`. Margin types, leverage formats, and P&L calculations differ across every API. Before the risk engine can compute aggregate exposure, it needs a unified position format. The exchange adapter pattern solves this: one adapter per exchange, all implementing the same interface, all returning the same normalized data structure. This is the same pattern used by CCXT (a popular open-source library for cryptocurrency exchange APIs), but implemented here with the minimum surface area needed for risk monitoring rather than the full trading API.\n\n### The Exchange Adapter Pattern\n\n```python\nimport abc\nimport hashlib\nimport hmac\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Dict, List, Optional\n\nimport requests\n\n\nclass NormalizedPosition:\n    \"\"\"Unified position representation across exchanges.\"\"\"\n\n    def __init__(\n        self,\n        symbol: str,\n        exchange: str,\n        side: str,\n        quantity: float,\n        entry_price: float,\n        current_price: float,\n        notional: float,\n        leverage: float,\n        margin_mode: str,\n        unrealized_pnl: float,\n        margin_used: float,\n    ):\n        self.symbol = symbol\n        self.exchange = exchange\n        self.side = side\n        self.quantity = quantity\n        self.entry_price = entry_price\n        self.current_price = current_price\n        self.notional = notional\n        self.leverage = leverage\n        self.margin_mode = margin_mode\n        self.unrealized_pnl = unrealized_pnl\n        self.margin_used = margin_used\n\n    def to_dict(self) -> dict:\n        return {\n            \"symbol\": self.symbol,\n            \"exchange\": self.exchange,\n            \"side\": self.side,\n            \"quantity\": self.quantity,\n            \"entry_price\": self.entry_price,\n            \"current_price\": self.current_price,\n            \"notional\": self.notional,\n            \"leverage\": self.leverage,\n            \"margin_mode\": self.margin_mode,\n            \"unrealized_pnl\": self.unrealized_pnl,\n            \"margin_used\": self.margin_used,\n        }\n\n\nclass ExchangeAdapter(abc.ABC):\n    \"\"\"Base class for exchange adapters.\"\"\"\n\n    @abc.abstractmethod\n    def get_positions(self) -> List[NormalizedPosition]:\n        \"\"\"Fetch and normalize all open positions.\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def get_account_equity(self) -> float:\n        \"\"\"Fetch total account equity in USD.\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def cancel_all_orders(self) -> dict:\n        \"\"\"Cancel all open orders (used by circuit breaker).\"\"\"\n        ...\n\n\nclass BinanceAdapter(ExchangeAdapter):\n    \"\"\"Adapter for Binance Futures API.\"\"\"\n\n    def __init__(self, api_key: str, secret_key: str):\n        self.api_key = api_key\n        self.secret_key = secret_key\n        self.base_url = \"https:\u002F\u002Ffapi.binance.com\"\n        self.session = requests.Session()\n        self.session.headers.update({\"X-MBX-APIKEY\": api_key})\n\n    def _sign(self, params: dict) -> dict:\n        \"\"\"Add timestamp and HMAC signature to request params.\"\"\"\n        params[\"timestamp\"] = int(time.time() * 1000)\n        query_string = \"&\".join(f\"{k}={v}\" for k, v in sorted(params.items()))\n        signature = hmac.new(\n            self.secret_key.encode(), query_string.encode(), hashlib.sha256\n        ).hexdigest()\n        params[\"signature\"] = signature\n        return params\n\n    def get_positions(self) -> List[NormalizedPosition]:\n        params = self._sign({})\n        response = self.session.get(\n            f\"{self.base_url}\u002Ffapi\u002Fv2\u002FpositionRisk\", params=params\n        )\n        response.raise_for_status()\n\n        positions = []\n        for p in response.json():\n            amt = float(p[\"positionAmt\"])\n            if amt == 0:\n                continue\n\n            positions.append(NormalizedPosition(\n                symbol=p[\"symbol\"].replace(\"USDT\", \"-USD\"),\n                exchange=\"binance\",\n                side=\"long\" if amt > 0 else \"short\",\n                quantity=abs(amt),\n                entry_price=float(p[\"entryPrice\"]),\n                current_price=float(p[\"markPrice\"]),\n                notional=abs(float(p[\"notional\"])),\n                leverage=float(p[\"leverage\"]),\n                margin_mode=\"isolated\" if p[\"marginType\"] == \"isolated\" else \"cross\",\n                unrealized_pnl=float(p[\"unRealizedProfit\"]),\n                margin_used=float(p.get(\"isolatedMargin\", 0)),\n            ))\n\n        return positions\n\n    def get_account_equity(self) -> float:\n        params = self._sign({})\n        response = self.session.get(\n            f\"{self.base_url}\u002Ffapi\u002Fv2\u002Faccount\", params=params\n        )\n        response.raise_for_status()\n        return float(response.json()[\"totalWalletBalance\"])\n\n    def cancel_all_orders(self) -> dict:\n        # Cancel for each active symbol\n        positions = self.get_positions()\n        results = {}\n        for pos in positions:\n            symbol = pos.symbol.replace(\"-USD\", \"USDT\")\n            params = self._sign({\"symbol\": symbol})\n            response = self.session.delete(\n                f\"{self.base_url}\u002Ffapi\u002Fv1\u002FallOpenOrders\", params=params\n            )\n            results[symbol] = response.status_code\n        return results\n```\n\n### Aggregating Across Exchanges\n\n```python\ndef aggregate_positions(\n    adapters: List[ExchangeAdapter],\n    risk_monitor: \"RiskMonitor\",\n) -> dict:\n    \"\"\"\n    Fetch positions from all exchanges and compute aggregate metrics.\n    Publishes the aggregated view as a GreenHelix event.\n    \"\"\"\n    all_positions = []\n    total_equity = 0.0\n\n    for adapter in adapters:\n        positions = adapter.get_positions()\n        equity = adapter.get_account_equity()\n        all_positions.extend(positions)\n        total_equity += equity\n\n    # Compute aggregate metrics\n    total_notional = sum(p.notional for p in all_positions)\n    total_unrealized_pnl = sum(p.unrealized_pnl for p in all_positions)\n    aggregate_leverage = total_notional \u002F total_equity if total_equity > 0 else 0.0\n\n    # Net exposure by base asset\n    net_exposure: Dict[str, float] = {}\n    for p in all_positions:\n        base = p.symbol.split(\"-\")[0]\n        signed_notional = p.notional if p.side == \"long\" else -p.notional\n        net_exposure[base] = net_exposure.get(base, 0) + signed_notional\n\n    # Per-exchange breakdown\n    exchange_breakdown: Dict[str, dict] = {}\n    for p in all_positions:\n        if p.exchange not in exchange_breakdown:\n            exchange_breakdown[p.exchange] = {\n                \"position_count\": 0,\n                \"total_notional\": 0.0,\n                \"unrealized_pnl\": 0.0,\n            }\n        eb = exchange_breakdown[p.exchange]\n        eb[\"position_count\"] += 1\n        eb[\"total_notional\"] += p.notional\n        eb[\"unrealized_pnl\"] += p.unrealized_pnl\n\n    result = {\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        \"total_equity\": round(total_equity, 2),\n        \"total_notional\": round(total_notional, 2),\n        \"aggregate_leverage\": round(aggregate_leverage, 2),\n        \"total_unrealized_pnl\": round(total_unrealized_pnl, 2),\n        \"position_count\": len(all_positions),\n        \"exchange_count\": len(exchange_breakdown),\n        \"net_exposure\": {k: round(v, 2) for k, v in net_exposure.items()},\n        \"exchange_breakdown\": exchange_breakdown,\n        \"positions\": [p.to_dict() for p in all_positions],\n    }\n\n    # Publish aggregated snapshot to GreenHelix\n    payload = {\n        \"agent_id\": risk_monitor.agent_id,\n        **{k: v for k, v in result.items() if k != \"positions\"},\n    }\n    payload[\"signature\"] = risk_monitor._sign(\n        {\"equity\": total_equity, \"leverage\": aggregate_leverage}\n    )\n\n    risk_monitor._execute(\"publish_event\", {\n        \"event_type\": \"risk.aggregate_snapshot\",\n        \"payload\": payload,\n    })\n\n    return result\n```\n\n### Querying Aggregate Snapshots via curl\n\n```bash\n# Get the latest aggregate portfolio snapshot\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_events\",\n    \"input\": {\n      \"event_type\": \"risk.aggregate_snapshot\",\n      \"limit\": 1,\n      \"order\": \"desc\"\n    }\n  }'\n```\n\n```bash\n# Publish an aggregate snapshot manually (e.g., from a cron job)\ncurl -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"publish_event\",\n    \"input\": {\n      \"event_type\": \"risk.aggregate_snapshot\",\n      \"payload\": {\n        \"agent_id\": \"risk-monitor-prod-01\",\n        \"total_equity\": 98500.00,\n        \"total_notional\": 312000.00,\n        \"aggregate_leverage\": 3.17,\n        \"total_unrealized_pnl\": -1240.50,\n        \"position_count\": 7,\n        \"exchange_count\": 3,\n        \"net_exposure\": {\n          \"BTC\": 142000.00,\n          \"ETH\": 95000.00,\n          \"SOL\": 75000.00\n        },\n        \"timestamp\": \"2026-04-07T14:30:00Z\",\n        \"signature\": \"base64-ed25519-signature\"\n      }\n    }\n  }'\n```\n\n### Usage Example\n\n```python\n# Wire up exchange adapters\nbinance = BinanceAdapter(\n    api_key=\"your-binance-api-key\",\n    secret_key=\"your-binance-secret-key\",\n)\n# (Similarly for CoinbaseAdapter, KrakenAdapter)\n\nadapters = [binance]  # Add more adapters as needed\n\n# Run aggregation\nsnapshot = aggregate_positions(adapters, monitor)\nprint(f\"Total equity: ${snapshot['total_equity']:,.2f}\")\nprint(f\"Aggregate leverage: {snapshot['aggregate_leverage']}x\")\nprint(f\"Positions across {snapshot['exchange_count']} exchanges: {snapshot['position_count']}\")\n\nfor asset, exposure in snapshot[\"net_exposure\"].items():\n    direction = \"LONG\" if exposure > 0 else \"SHORT\"\n    print(f\"  {asset}: ${abs(exposure):,.2f} {direction}\")\n```\n\nAdding a new exchange requires implementing only three methods: `get_positions()`, `get_account_equity()`, and `cancel_all_orders()`. The rest of the risk engine works without modification because it operates on `NormalizedPosition` objects, not exchange-specific data structures.\n\n### Handling Exchange API Failures\n\nExchange APIs fail. Rate limits are hit, connections time out, maintenance windows arrive without notice. The aggregation layer needs to handle partial data gracefully:\n\n```python\ndef safe_aggregate_positions(\n    adapters: Dict[str, ExchangeAdapter],\n    risk_monitor: \"RiskMonitor\",\n) -> dict:\n    \"\"\"\n    Aggregate positions with exchange failure resilience.\n    \"\"\"\n    all_positions = []\n    total_equity = 0.0\n    failures = {}\n    successes = {}\n\n    for name, adapter in adapters.items():\n        try:\n            positions = adapter.get_positions()\n            equity = adapter.get_account_equity()\n            all_positions.extend(positions)\n            total_equity += equity\n            successes[name] = len(positions)\n        except requests.exceptions.RequestException as e:\n            failures[name] = str(e)\n\n    if failures:\n        # Publish a partial data warning\n        risk_monitor._execute(\"publish_event\", {\n            \"event_type\": \"risk.exchange_failure\",\n            \"payload\": {\n                \"agent_id\": risk_monitor.agent_id,\n                \"failures\": failures,\n                \"successes\": successes,\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                \"signature\": risk_monitor._sign({\"failures\": list(failures.keys())}),\n            },\n        })\n\n        # Alert the operator\n        risk_monitor._execute(\"send_message\", {\n            \"to\": \"ops-team\",\n            \"subject\": f\"EXCHANGE API FAILURE: {', '.join(failures.keys())}\",\n            \"body\": (\n                f\"Failed exchanges: {json.dumps(failures, indent=2)}\\n\"\n                f\"Successful exchanges: {json.dumps(successes, indent=2)}\\n\"\n                f\"Risk metrics are computed from partial data.\"\n            ),\n        })\n\n    total_notional = sum(p.notional for p in all_positions)\n    aggregate_leverage = total_notional \u002F total_equity if total_equity > 0 else 0.0\n\n    return {\n        \"total_equity\": round(total_equity, 2),\n        \"aggregate_leverage\": round(aggregate_leverage, 2),\n        \"position_count\": len(all_positions),\n        \"exchange_failures\": failures,\n        \"positions\": [p.to_dict() for p in all_positions],\n    }\n```\n\nWhen an exchange API fails, the risk engine computes metrics from the exchanges that are reachable. This means the reported aggregate leverage and total equity may understate the true values. The operator is notified so they can decide whether to act conservatively (assume the unreachable exchange has unfavorable positions) or wait for the connection to recover.\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n---\n\n## What's Next\n\n**Companion Guides:**\n\n- **Tamper-Proof Audit Trails for Trading Bots** -- Add cryptographic verification and regulatory compliance (EU AI Act, MiFID II, SEC 17a-4) to the risk events generated by this system.\n- **Bot Reputation System** -- Turn your risk management track record into verifiable reputation. Prove to copy traders and capital allocators that your risk controls are real, not just claimed.\n- **Strategy Marketplace Playbook** -- Publish risk-managed strategies on the GreenHelix marketplace with provable drawdown limits and circuit breaker guarantees.\n- **AgentOps: Fleet Management** -- Scale from monitoring a single portfolio to managing risk across a fleet of trading bots with centralized governance.\n\n**GreenHelix Documentation:**\n\n- Full API reference: https:\u002F\u002Fapi.greenhelix.net\u002Fv1\n- Event bus deep dive and webhook configuration in the platform documentation\n- SLA compliance tracking and metrics ingestion reference\n\n**Architecture Decisions Worth Revisiting:**\n\nAs your operation scales, revisit these trade-offs:\n- **Polling vs. streaming**: This guide uses polling (10-second cycles). For sub-second risk monitoring, switch to WebSocket connections to exchanges and stream position updates to the GreenHelix event bus in real time.\n- **Single risk engine vs. distributed**: A single risk engine is a single point of failure. For operations above $1M in aggregate equity, run two instances in active-passive mode, with the passive instance consuming the same events and ready to take over if the primary fails.\n- **Alert fatigue**: Tune your thresholds aggressively at first (tight thresholds, frequent alerts), then loosen them as you learn what your portfolio's normal behavior looks like. A circuit breaker that trips every week will be ignored or disabled -- defeating its purpose.\n\n---\n\n*Published by GreenHelix Labs. All code examples are provided under the MIT License. For the full product catalog, visit the GreenHelix storefront.*\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"metadata":37,"price_usd":42,"executable":20,"credentials":43,"description":7,"content_type":44,"compatibility":45},[25,26,27,28,29,30,31,32,33],"trading-bot","risk-management","portfolio","monitoring","circuit-breaker","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":38},{"requires":39,"primaryEnv":41},{"env":40},[41],"AGENT_SIGNING_KEY",0,[41],"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-trading-bot-risk-service","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-trading-bot-risk-service",{"tool":60,"command":61},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-trading-bot-risk-service",{"tool":63,"command":64},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-trading-bot-risk-service","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-trading-bot-risk-service\u002FSKILL.md",true,[],[69,76,83,90,97,104],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]