[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HM24QAESYEERR4DBSGQDQ":3,"skill-same:01M77HM24QAESYEERR4DBSGQDQ":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":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M77HM24QAESYEERR4DBSGQDQ","greenhelix-bot-arbitrage-framework",null,"Bot-to-Bot Arbitrage Framework: Multi-Bot Coordination with Trust Verification. Build a multi-bot arbitrage coordination framework with marketplace discovery, escrow protection, and trust verification. Covers cross-exchange opportunity detection, execution verification, profit splitting, MEV protection, and audit trails.","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-bot-arbitrage-framework\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-bot-arbitrage-framework\nversion: \"1.3.1\"\ndescription: \"Bot-to-Bot Arbitrage Framework: Multi-Bot Coordination with Trust Verification. Build a multi-bot arbitrage coordination framework with marketplace discovery, escrow protection, and trust verification. Covers cross-exchange opportunity detection, execution verification, profit splitting, MEV protection, and audit trails.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [arbitrage, trading-bot, multi-bot, coordination, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 99.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# Bot-to-Bot Arbitrage Framework: Multi-Bot Coordination with Trust Verification\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\nArbitrage bots operate in isolation. A bot that spots a price discrepancy between Binance and Kraken has to execute both legs itself -- funding accounts on both exchanges, maintaining API keys for each, and racing against every other solo operator watching the same order books. The capital requirements are brutal: to capture a 0.3% spread on a $100,000 opportunity, you need $100,000 sitting idle on Binance and another $100,000 on Kraken, earning nothing while waiting for the next opportunity. Multiply that across ten exchanges and you are looking at a million dollars in idle capital for a strategy that might generate $500 per trade.\nMulti-bot coordination solves this. One bot holds capital on Binance and specializes in that exchange's matching engine quirks. Another holds capital on Kraken and knows its WebSocket feed intimately. A third monitors OKX. When a cross-exchange opportunity appears, the coordinating bot signals the relevant pair, they execute simultaneously, and profits are split according to a pre-negotiated agreement. Capital efficiency improves by an order of magnitude. Latency drops because each bot is co-located with its exchange. Coverage expands because adding a new exchange means onboarding one specialist bot, not refactoring an entire monolithic system.\nThe problem is trust. How does the Binance bot know the Kraken bot actually executed its leg? How do you split profits with a bot operated by someone you have never met? What happens when one leg fills and the other does not? What stops a counterparty from reporting a worse fill price than they actually received? This guide builds a complete framework for coordinated multi-bot arbitrage using GreenHelix's marketplace for bot discovery, escrow for profit splitting, claim chains for execution verification, and event bus for audit trails. Every component comes with working Python code and curl equivalents against the GreenHelix API.\n\n## What You'll Learn\n- Chapter 1: Why Multi-Bot Arbitrage\n- Chapter 2: ArbitrageCoordinator Class\n- Chapter 3: OpportunityScanner Class\n- Chapter 4: Execution Verification\n- Chapter 5: Profit Splitting via Escrow\n- Chapter 6: MEV Protection\n- Chapter 7: Latency Optimization\n- Chapter 8: Audit Trails for Arbitrage\n- What's Next\n\n## Full Guide\n\n# Bot-to-Bot Arbitrage Framework: Multi-Bot Coordination with Trust Verification\n\nArbitrage bots operate in isolation. A bot that spots a price discrepancy between Binance and Kraken has to execute both legs itself -- funding accounts on both exchanges, maintaining API keys for each, and racing against every other solo operator watching the same order books. The capital requirements are brutal: to capture a 0.3% spread on a $100,000 opportunity, you need $100,000 sitting idle on Binance and another $100,000 on Kraken, earning nothing while waiting for the next opportunity. Multiply that across ten exchanges and you are looking at a million dollars in idle capital for a strategy that might generate $500 per trade.\n\nMulti-bot coordination solves this. One bot holds capital on Binance and specializes in that exchange's matching engine quirks. Another holds capital on Kraken and knows its WebSocket feed intimately. A third monitors OKX. When a cross-exchange opportunity appears, the coordinating bot signals the relevant pair, they execute simultaneously, and profits are split according to a pre-negotiated agreement. Capital efficiency improves by an order of magnitude. Latency drops because each bot is co-located with its exchange. Coverage expands because adding a new exchange means onboarding one specialist bot, not refactoring an entire monolithic system.\n\nThe problem is trust. How does the Binance bot know the Kraken bot actually executed its leg? How do you split profits with a bot operated by someone you have never met? What happens when one leg fills and the other does not? What stops a counterparty from reporting a worse fill price than they actually received? This guide builds a complete framework for coordinated multi-bot arbitrage using GreenHelix's marketplace for bot discovery, escrow for profit splitting, claim chains for execution verification, and event bus for audit trails. Every component comes with working Python code and curl equivalents against the GreenHelix API.\n\n---\n\n## Table of Contents\n\n1. [Why Multi-Bot Arbitrage](#chapter-1-why-multi-bot-arbitrage)\n2. [ArbitrageCoordinator Class](#chapter-2-arbitragecoordinator-class)\n3. [OpportunityScanner Class](#chapter-3-opportunityscanner-class)\n4. [Execution Verification](#chapter-4-execution-verification)\n5. [Profit Splitting via Escrow](#chapter-5-profit-splitting-via-escrow)\n6. [MEV Protection](#chapter-6-mev-protection)\n7. [Latency Optimization](#chapter-7-latency-optimization)\n8. [Audit Trails for Arbitrage](#chapter-8-audit-trails-for-arbitrage)\n\n---\n\n## Chapter 1: Why Multi-Bot Arbitrage\n\n### The Capital Efficiency Problem\n\nA solo arbitrage bot monitoring ten exchanges needs funded accounts on all ten. Most of that capital sits idle most of the time. A Binance-Kraken opportunity might appear once every thirty seconds, but the capital allocated to the Binance-OKX pair and the Kraken-Bybit pair and every other combination is locked up, doing nothing, waiting for its turn.\n\nThe numbers are straightforward. Assume $50,000 minimum per exchange account to capture meaningful opportunities (sub-$50K and slippage on larger orders eats your edge). Ten exchanges means $500,000 in deployed capital. Average daily return on cross-exchange crypto arbitrage in 2026 hovers around 0.05-0.15% of deployed capital after fees -- that is $250-$750 per day on half a million dollars. The capital efficiency ratio is terrible.\n\nMulti-bot coordination restructures this entirely. Each bot operator funds one exchange. Ten operators each deploying $50,000 create a network with $500,000 in total liquidity, but each individual's capital requirement is 90% lower. When a Binance-Kraken opportunity appears, only those two bots' capital is involved. The other eight bots' capital is simultaneously available for other pairs. The same $50,000 individual commitment can participate in multiple simultaneous opportunities across different pairs, as long as the pairs involve that bot's exchange.\n\n### The Latency Advantage\n\nExchange co-location is the single biggest latency reduction available to a trading bot. A bot running on AWS ap-northeast-1 (Tokyo) hitting Binance's Tokyo matching engine sees 0.3ms round-trip times. The same bot hitting Kraken's London servers sees 150ms. In arbitrage, 150ms is an eternity -- the opportunity is gone.\n\nA solo bot cannot be co-located with ten exchanges simultaneously. The physics do not allow it. But a network of specialist bots -- one co-located with each exchange -- can achieve sub-millisecond execution on every leg. The Binance specialist sits in Tokyo. The Kraken specialist sits in London. The OKX specialist sits in Hong Kong. When a cross-exchange opportunity is detected, the coordinating signal travels at the speed of light between data centers (roughly 70ms Tokyo-to-London), but both legs execute at local speed. The total execution time is the coordination signal latency plus the local execution latency, which is still faster than a solo bot executing one leg locally and the other leg across an ocean.\n\n### The Trust Problem\n\nCoordination creates value, but it also creates risk. Consider a two-leg arbitrage between Binance and Kraken:\n\n```\nOpportunity: ETH is $3,000.00 on Binance, $3,012.00 on Kraken\nStrategy:    Buy 10 ETH on Binance ($30,000), Sell 10 ETH on Kraken ($30,120)\nGross profit: $120.00\nFees (est):   $36.00 (0.06% taker on each leg)\nNet profit:   $84.00\n```\n\nBot A buys on Binance. Bot B sells on Kraken. After execution, Bot B holds the $30,120 from the Kraken sale. The agreed profit split is 50\u002F50, so Bot B owes Bot A $42.00 plus Bot A's $30,000 principal. But what stops Bot B from claiming the sell only filled at $3,008 instead of $3,012, reducing Bot A's share? What stops Bot B from simply not paying at all?\n\nIn traditional finance, clearing houses solve this -- they sit between counterparties, guarantee settlement, and manage collateral. In bot-to-bot arbitrage, the equivalent infrastructure maps to these tools:\n\n- **search_services** -- Discover specialist bots registered on specific exchanges\n- **negotiate_deal** -- Agree on profit split terms before execution\n- **create_escrow** -- Lock collateral to guarantee settlement\n- **submit_metrics** -- Report execution latency, fill rates, and reliability\n- **build_claim_chain** -- Create cryptographic proof of execution for dispute resolution\n- **publish_event** -- Log every step for audit and compliance\n\n### GreenHelix Tools for Arbitrage Coordination\n\n| Tool | Role in Arbitrage |\n|---|---|\n| `register_agent` | Register each exchange-specialist bot with its capabilities |\n| `search_services` | Find bots specializing in specific exchanges |\n| `negotiate_deal` | Agree on profit split, minimum opportunity size, latency SLAs |\n| `create_escrow` | Lock profit-share collateral before execution |\n| `release_escrow` | Release funds after verified execution |\n| `submit_metrics` | Report fill rates, latency, reliability to build reputation |\n| `build_claim_chain` | Create tamper-proof execution evidence |\n| `publish_event` | Log opportunities, executions, settlements to the event bus |\n| `get_reputation` | Check counterparty reliability before partnering |\n\n### Why Now\n\nCross-exchange arbitrage has existed since the first two crypto exchanges launched. What has changed in 2025-2026 is the infrastructure. Three developments make multi-bot coordination viable today when it was not two years ago.\n\nFirst, exchange API latency has dropped. Binance's matching engine upgrade in late 2025 reduced API response times to sub-millisecond for co-located clients. Kraken, OKX, and Bybit followed with similar improvements. The execution speed gap between institutional and retail API access has narrowed -- a well-optimized bot on a standard cloud instance now achieves execution times that previously required bare-metal co-location.\n\nSecond, the agent commerce infrastructure exists. Before GreenHelix and similar platforms, bot coordination required custom bilateral agreements, manual escrow arrangements, and trust based on personal reputation in Telegram groups. GreenHelix provides the standardized primitives -- identity, escrow, reputation, event logging -- that turn ad-hoc coordination into a scalable protocol.\n\nThird, the regulatory landscape is clarifying. MiCA in the EU, updated SEC guidance in the US, and ASIC's framework in Australia all treat algorithmic trading as a regulated activity with specific record-keeping requirements. Bots that operate within a compliance-ready framework (with audit trails, execution verification, and settlement records) have a structural advantage over bots that operate in the dark.\n\n### The Network Effect\n\nThere is a compounding advantage to multi-bot coordination that solo operators cannot replicate. A two-bot network covers one exchange pair. A five-bot network covers ten pairs. A ten-bot network covers forty-five pairs. The number of arbitrage opportunities scales quadratically with the number of exchanges covered, but each bot's capital requirement stays constant. A single bot operator joining a ten-bot network gains access to nine new exchange pairs without deploying a single dollar of additional capital.\n\nThis creates a natural marketplace for coordination. Bots with strong execution on a specific exchange can monetize that capability by partnering with bots on other exchanges. A Binance specialist with 0.4ms execution and a 97% fill rate is a valuable counterparty -- its speed and reliability directly increase the capture rate for any opportunity involving Binance. GreenHelix's reputation system makes this value visible: bots publish verified execution metrics, and coordinators use those metrics to select the best partner for each opportunity.\n\nThe rest of this guide builds a production framework using these tools. Chapter 2 creates the coordination layer. Chapter 3 scans for opportunities. Chapter 4 verifies execution. Chapter 5 handles profit splitting. Chapters 6-8 cover MEV protection, latency optimization, and compliance audit trails.\n\n---\n\n## Chapter 2: ArbitrageCoordinator Class\n\n### Architecture\n\nThe ArbitrageCoordinator is the central orchestrator. It does not execute trades itself -- it discovers specialist bots, negotiates coordination agreements, manages escrow for profit splitting, and dispatches execution signals. Think of it as the clearing house in a traditional exchange, but running as an autonomous agent.\n\n```\n+---------------------+       +---------------------+       +---------------------+\n|  Binance Bot        |       | ArbitrageCoordinator|       |  Kraken Bot          |\n|  (exchange specialist)|     |  (orchestrator)     |       |  (exchange specialist)|\n|                     |       |                     |       |                     |\n|  Monitors Binance   |       |  Discovers bots     |       |  Monitors Kraken    |\n|  order book         |       |  Negotiates deals   |       |  order book         |\n|  Executes buy\u002Fsell  |       |  Manages escrow     |       |  Executes buy\u002Fsell  |\n|  Reports fills      |       |  Verifies execution |       |  Reports fills      |\n|                     |       |  Splits profits     |       |                     |\n+--------+------------+       +----------+----------+       +----------+----------+\n         |                               |                              |\n         |  publish_event (fill data)    |  create_escrow               |  publish_event (fill data)\n         +------------------------------>|\u003C-----------------------------+\n                                         |\n                                    build_claim_chain\n                                    release_escrow\n```\n\n### Setup\n\n```python\nimport requests\nimport json\nimport time\nimport hashlib\nimport base64\nfrom datetime import datetime, timedelta\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\nAPI_KEY = \"your-api-key\"\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {API_KEY}\"\nsession.headers[\"Content-Type\"] = \"application\u002Fjson\"\n\ndef execute(tool: str, inputs: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool and return the result.\"\"\"\n    resp = session.post(\n        f\"{API_BASE}\u002Fv1\",\n        json={\"tool\": tool, \"input\": inputs}\n    )\n    resp.raise_for_status()\n    return resp.json()\n```\n\n### The ArbitrageCoordinator Class\n\n```python\nclass ArbitrageCoordinator:\n    \"\"\"Orchestrates multi-bot arbitrage across exchanges.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.public_key = self.private_key.public_key()\n        self.exchange_bots: dict[str, dict] = {}  # exchange -> bot info\n        self.active_deals: dict[str, dict] = {}   # deal_id -> deal info\n        self.pending_escrows: dict[str, str] = {}  # opportunity_id -> escrow_id\n\n    def sign_payload(self, payload: dict) -> str:\n        \"\"\"Sign a canonical JSON payload with Ed25519.\"\"\"\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def discover_exchange_bots(self, exchanges: list[str]) -> dict[str, list[dict]]:\n        \"\"\"Find specialist bots for each target exchange.\"\"\"\n        discovered = {}\n        for exchange in exchanges:\n            results = execute(\"search_services\", {\n                \"query\": f\"arbitrage execution {exchange}\",\n                \"filters\": {\n                    \"capabilities\": [\"exchange_execution\", \"fast_fill\"],\n                    \"metadata.exchange\": exchange,\n                    \"metadata.bot_type\": \"exchange_specialist\"\n                },\n                \"limit\": 10\n            })\n            discovered[exchange] = results.get(\"services\", [])\n            self._log_discovery(exchange, len(discovered[exchange]))\n        self.exchange_bots = {\n            ex: bots[0] for ex, bots in discovered.items() if bots\n        }\n        return discovered\n\n    def _log_discovery(self, exchange: str, count: int):\n        \"\"\"Log bot discovery to the event bus.\"\"\"\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.bot_discovery\",\n            \"payload\": {\n                \"exchange\": exchange,\n                \"bots_found\": count,\n                \"timestamp\": datetime.utcnow().isoformat()\n            },\n            \"signature\": self.sign_payload({\n                \"exchange\": exchange,\n                \"bots_found\": count\n            })\n        })\n\n    def negotiate_coordination(\n        self,\n        exchange_a: str,\n        exchange_b: str,\n        profit_split: dict,\n        min_opportunity_usd: float,\n        max_latency_ms: int\n    ) -> dict:\n        \"\"\"Negotiate a coordination agreement with two exchange bots.\"\"\"\n        bot_a = self.exchange_bots.get(exchange_a)\n        bot_b = self.exchange_bots.get(exchange_b)\n        if not bot_a or not bot_b:\n            raise ValueError(f\"Missing bot for {exchange_a} or {exchange_b}\")\n\n        terms = {\n            \"pair\": f\"{exchange_a}-{exchange_b}\",\n            \"profit_split\": profit_split,\n            \"min_opportunity_usd\": str(min_opportunity_usd),\n            \"max_latency_ms\": max_latency_ms,\n            \"escrow_required\": True,\n            \"verification_method\": \"claim_chain\",\n            \"valid_until\": (\n                datetime.utcnow() + timedelta(hours=24)\n            ).isoformat()\n        }\n\n        deal = execute(\"negotiate_deal\", {\n            \"proposer_id\": self.agent_id,\n            \"counterparty_ids\": [bot_a[\"agent_id\"], bot_b[\"agent_id\"]],\n            \"terms\": terms,\n            \"signature\": self.sign_payload(terms)\n        })\n\n        deal_id = deal[\"deal_id\"]\n        self.active_deals[deal_id] = {\n            \"exchange_a\": exchange_a,\n            \"exchange_b\": exchange_b,\n            \"bot_a\": bot_a[\"agent_id\"],\n            \"bot_b\": bot_b[\"agent_id\"],\n            \"terms\": terms,\n            \"status\": \"negotiated\"\n        }\n        return deal\n\n    def create_execution_escrow(\n        self,\n        opportunity_id: str,\n        deal_id: str,\n        amount_usd: str\n    ) -> dict:\n        \"\"\"Create escrow to guarantee profit-split settlement.\"\"\"\n        deal = self.active_deals.get(deal_id)\n        if not deal:\n            raise ValueError(f\"No active deal: {deal_id}\")\n\n        escrow = execute(\"create_escrow\", {\n            \"payer_id\": self.agent_id,\n            \"payee_ids\": [deal[\"bot_a\"], deal[\"bot_b\"]],\n            \"amount\": amount_usd,\n            \"currency\": \"USD\",\n            \"conditions\": {\n                \"type\": \"multi_party_arbitrage\",\n                \"opportunity_id\": opportunity_id,\n                \"deal_id\": deal_id,\n                \"release_on\": \"verified_execution\",\n                \"timeout_hours\": 1,\n                \"dispute_window_minutes\": 30\n            },\n            \"signature\": self.sign_payload({\n                \"opportunity_id\": opportunity_id,\n                \"amount\": amount_usd\n            })\n        })\n\n        self.pending_escrows[opportunity_id] = escrow[\"escrow_id\"]\n        return escrow\n\n    def dispatch_execution(\n        self,\n        opportunity_id: str,\n        deal_id: str,\n        legs: list[dict]\n    ) -> dict:\n        \"\"\"Signal exchange bots to execute their respective legs.\"\"\"\n        deal = self.active_deals[deal_id]\n        execution_signals = []\n\n        for leg in legs:\n            signal = {\n                \"opportunity_id\": opportunity_id,\n                \"exchange\": leg[\"exchange\"],\n                \"side\": leg[\"side\"],\n                \"symbol\": leg[\"symbol\"],\n                \"quantity\": leg[\"quantity\"],\n                \"limit_price\": leg[\"limit_price\"],\n                \"execution_deadline_ms\": leg.get(\"deadline_ms\", 500),\n                \"escrow_id\": self.pending_escrows.get(opportunity_id),\n                \"timestamp\": datetime.utcnow().isoformat()\n            }\n            signal[\"signature\"] = self.sign_payload(signal)\n\n            execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"arbitrage.execution_signal\",\n                \"payload\": signal\n            })\n            execution_signals.append(signal)\n\n        return {\n            \"opportunity_id\": opportunity_id,\n            \"signals_dispatched\": len(execution_signals),\n            \"legs\": execution_signals\n        }\n```\n\nThe equivalent curl for bot discovery:\n\n```bash\n# Discover Binance specialist bots\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\": \"search_services\",\n    \"input\": {\n      \"query\": \"arbitrage execution binance\",\n      \"filters\": {\n        \"capabilities\": [\"exchange_execution\", \"fast_fill\"],\n        \"metadata.exchange\": \"binance\",\n        \"metadata.bot_type\": \"exchange_specialist\"\n      },\n      \"limit\": 10\n    }\n  }'\n```\n\n```bash\n# Negotiate coordination deal\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\": \"negotiate_deal\",\n    \"input\": {\n      \"proposer_id\": \"arb-coordinator-01\",\n      \"counterparty_ids\": [\"binance-bot-07\", \"kraken-bot-03\"],\n      \"terms\": {\n        \"pair\": \"binance-kraken\",\n        \"profit_split\": {\"coordinator\": \"0.20\", \"bot_a\": \"0.40\", \"bot_b\": \"0.40\"},\n        \"min_opportunity_usd\": \"50.00\",\n        \"max_latency_ms\": 200,\n        \"escrow_required\": true,\n        \"verification_method\": \"claim_chain\"\n      },\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Registering the Coordinator\n\nBefore the coordinator can operate, it needs a GreenHelix identity:\n\n```python\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\nimport base64\n\n# Generate coordinator keypair\nprivate_key = Ed25519PrivateKey.generate()\npublic_key = private_key.public_key()\n\nprivate_bytes = private_key.private_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PrivateFormat.Raw,\n    encryption_algorithm=serialization.NoEncryption()\n)\npublic_bytes = public_key.public_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PublicFormat.Raw\n)\n\nCOORDINATOR_PRIVATE_KEY = base64.b64encode(private_bytes).decode()\nCOORDINATOR_PUBLIC_KEY = base64.b64encode(public_bytes).decode()\n\n# Register coordinator agent\ncoordinator = execute(\"register_agent\", {\n    \"name\": \"arb-coordinator-01\",\n    \"description\": \"Multi-bot arbitrage coordinator. Discovers exchange specialists, \"\n                   \"negotiates profit splits, manages escrow, verifies execution.\",\n    \"capabilities\": [\n        \"arbitrage_coordination\",\n        \"escrow_management\",\n        \"execution_verification\",\n        \"profit_distribution\"\n    ],\n    \"metadata\": {\n        \"agent_type\": \"arbitrage_coordinator\",\n        \"supported_exchanges\": [\"binance\", \"kraken\", \"okx\", \"bybit\", \"coinbase\"],\n        \"min_opportunity_usd\": 50,\n        \"max_concurrent_opportunities\": 20\n    }\n})\n\ncoordinator_id = coordinator[\"agent_id\"]\n\n# Initialize the coordinator\narb = ArbitrageCoordinator(coordinator_id, COORDINATOR_PRIVATE_KEY)\n```\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      \"name\": \"arb-coordinator-01\",\n      \"description\": \"Multi-bot arbitrage coordinator.\",\n      \"capabilities\": [\n        \"arbitrage_coordination\",\n        \"escrow_management\",\n        \"execution_verification\",\n        \"profit_distribution\"\n      ],\n      \"metadata\": {\n        \"agent_type\": \"arbitrage_coordinator\",\n        \"supported_exchanges\": [\"binance\", \"kraken\", \"okx\", \"bybit\", \"coinbase\"],\n        \"min_opportunity_usd\": 50\n      }\n    }\n  }'\n```\n\n### Registering an Exchange Specialist Bot\n\nEach exchange specialist registers with metadata describing its exchange, latency characteristics, and supported pairs:\n\n```python\nbinance_bot = execute(\"register_agent\", {\n    \"name\": \"binance-specialist-07\",\n    \"description\": \"Binance exchange specialist. Co-located in Tokyo. \"\n                   \"Sub-millisecond execution on spot pairs.\",\n    \"capabilities\": [\n        \"exchange_execution\",\n        \"fast_fill\",\n        \"order_book_monitoring\",\n        \"fill_reporting\"\n    ],\n    \"metadata\": {\n        \"agent_type\": \"exchange_specialist\",\n        \"exchange\": \"binance\",\n        \"location\": \"ap-northeast-1\",\n        \"avg_execution_ms\": 0.4,\n        \"supported_pairs\": [\"BTC\u002FUSDT\", \"ETH\u002FUSDT\", \"SOL\u002FUSDT\", \"BNB\u002FUSDT\"],\n        \"max_order_size_usd\": 500000\n    }\n})\n```\n\n---\n\n## Chapter 3: OpportunityScanner Class\n\n### Cross-Exchange Price Monitoring\n\nThe OpportunityScanner monitors prices across exchanges and identifies arbitrage opportunities that meet minimum profit thresholds after accounting for fees, slippage, and coordination costs. It does not execute trades -- it feeds opportunities to the ArbitrageCoordinator.\n\n### Fee Structures\n\nEvery opportunity calculation must account for exchange fees. These vary by exchange, tier, and whether you are a maker or taker:\n\n| Exchange | Taker Fee | Maker Fee | Withdrawal Fee (ETH) |\n|---|---|---|---|\n| Binance | 0.0750% | 0.0750% | 0.00042 ETH |\n| Kraken | 0.0400% | 0.0160% | 0.0025 ETH |\n| OKX | 0.0800% | 0.0500% | 0.0014 ETH |\n| Bybit | 0.0550% | 0.0100% | 0.0012 ETH |\n| Coinbase | 0.0800% | 0.0400% | network fee |\n\nThese are VIP\u002Fhigh-volume tier fees as of Q1 2026. Retail tier fees are 3-5x higher and make most arbitrage unprofitable.\n\n### The OpportunityScanner Class\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n@dataclass\nclass ArbitrageOpportunity:\n    opportunity_id: str\n    symbol: str\n    buy_exchange: str\n    sell_exchange: str\n    buy_price: str\n    sell_price: str\n    spread_bps: float\n    quantity: str\n    gross_profit_usd: str\n    net_profit_usd: str\n    fees_usd: str\n    latency_score: float\n    detected_at: str\n    expires_at: str\n\nclass OpportunityScanner:\n    \"\"\"Scans for cross-exchange arbitrage opportunities.\"\"\"\n\n    # Fee schedules: exchange -> {\"taker\": rate, \"maker\": rate}\n    FEE_SCHEDULE = {\n        \"binance\":  {\"taker\": 0.000750, \"maker\": 0.000750},\n        \"kraken\":   {\"taker\": 0.000400, \"maker\": 0.000160},\n        \"okx\":      {\"taker\": 0.000800, \"maker\": 0.000500},\n        \"bybit\":    {\"taker\": 0.000550, \"maker\": 0.000100},\n        \"coinbase\": {\"taker\": 0.000800, \"maker\": 0.000400},\n    }\n\n    # Estimated coordination overhead per trade\n    COORDINATION_FEE_BPS = 2.0  # 0.02% for escrow + verification\n\n    def __init__(\n        self,\n        agent_id: str,\n        exchanges: list[str],\n        min_profit_usd: float = 20.0,\n        min_spread_bps: float = 5.0,\n        max_quantity_usd: float = 100000.0\n    ):\n        self.agent_id = agent_id\n        self.exchanges = exchanges\n        self.min_profit_usd = min_profit_usd\n        self.min_spread_bps = min_spread_bps\n        self.max_quantity_usd = max_quantity_usd\n        self.price_cache: dict[str, dict[str, dict]] = {}\n        self._opportunity_counter = 0\n\n    def update_prices(self, exchange: str, symbol: str, bid: str, ask: str, depth_usd: str):\n        \"\"\"Update cached price for an exchange\u002Fsymbol pair.\"\"\"\n        if symbol not in self.price_cache:\n            self.price_cache[symbol] = {}\n        self.price_cache[symbol][exchange] = {\n            \"bid\": float(bid),\n            \"ask\": float(ask),\n            \"depth_usd\": float(depth_usd),\n            \"updated_at\": datetime.utcnow().isoformat()\n        }\n\n    def scan(self, symbol: str) -> list[ArbitrageOpportunity]:\n        \"\"\"Scan all exchange pairs for arbitrage opportunities on a symbol.\"\"\"\n        if symbol not in self.price_cache:\n            return []\n\n        prices = self.price_cache[symbol]\n        opportunities = []\n\n        for buy_ex in self.exchanges:\n            for sell_ex in self.exchanges:\n                if buy_ex == sell_ex:\n                    continue\n                if buy_ex not in prices or sell_ex not in prices:\n                    continue\n\n                opp = self._evaluate_pair(\n                    symbol, buy_ex, sell_ex,\n                    prices[buy_ex], prices[sell_ex]\n                )\n                if opp:\n                    opportunities.append(opp)\n\n        # Sort by net profit descending\n        opportunities.sort(key=lambda o: float(o.net_profit_usd), reverse=True)\n        return opportunities\n\n    def _evaluate_pair(\n        self,\n        symbol: str,\n        buy_exchange: str,\n        sell_exchange: str,\n        buy_data: dict,\n        sell_data: dict\n    ) -> Optional[ArbitrageOpportunity]:\n        \"\"\"Evaluate a single exchange pair for arbitrage.\"\"\"\n        buy_price = buy_data[\"ask\"]   # we pay the ask to buy\n        sell_price = sell_data[\"bid\"]  # we receive the bid to sell\n\n        if sell_price \u003C= buy_price:\n            return None  # no spread\n\n        spread_bps = ((sell_price - buy_price) \u002F buy_price) * 10000\n\n        if spread_bps \u003C self.min_spread_bps:\n            return None\n\n        # Determine executable quantity based on order book depth\n        max_qty_by_depth = min(\n            buy_data[\"depth_usd\"],\n            sell_data[\"depth_usd\"]\n        )\n        trade_size_usd = min(max_qty_by_depth, self.max_quantity_usd)\n        quantity = trade_size_usd \u002F buy_price\n\n        # Calculate fees\n        buy_fee = trade_size_usd * self.FEE_SCHEDULE[buy_exchange][\"taker\"]\n        sell_fee = (quantity * sell_price) * self.FEE_SCHEDULE[sell_exchange][\"taker\"]\n        coordination_fee = trade_size_usd * (self.COORDINATION_FEE_BPS \u002F 10000)\n        total_fees = buy_fee + sell_fee + coordination_fee\n\n        gross_profit = (sell_price - buy_price) * quantity\n        net_profit = gross_profit - total_fees\n\n        if net_profit \u003C self.min_profit_usd:\n            return None\n\n        self._opportunity_counter += 1\n        opp_id = f\"opp-{self.agent_id}-{self._opportunity_counter:08d}\"\n\n        # Calculate latency score (0-1, higher is better)\n        latency_score = self._estimate_latency_score(buy_exchange, sell_exchange)\n\n        return ArbitrageOpportunity(\n            opportunity_id=opp_id,\n            symbol=symbol,\n            buy_exchange=buy_exchange,\n            sell_exchange=sell_exchange,\n            buy_price=f\"{buy_price:.8f}\",\n            sell_price=f\"{sell_price:.8f}\",\n            spread_bps=round(spread_bps, 2),\n            quantity=f\"{quantity:.8f}\",\n            gross_profit_usd=f\"{gross_profit:.2f}\",\n            net_profit_usd=f\"{net_profit:.2f}\",\n            fees_usd=f\"{total_fees:.2f}\",\n            latency_score=latency_score,\n            detected_at=datetime.utcnow().isoformat(),\n            expires_at=(datetime.utcnow() + timedelta(seconds=2)).isoformat()\n        )\n\n    def _estimate_latency_score(self, exchange_a: str, exchange_b: str) -> float:\n        \"\"\"Estimate execution latency score for an exchange pair.\n\n        Based on geographic distance between exchange matching engines.\n        Score of 1.0 = both in same region, 0.5 = cross-continent,\n        0.2 = worst case.\n        \"\"\"\n        LOCATIONS = {\n            \"binance\": \"tokyo\",\n            \"kraken\": \"london\",\n            \"okx\": \"hong_kong\",\n            \"bybit\": \"singapore\",\n            \"coinbase\": \"virginia\",\n        }\n        # Rough inter-region latencies in ms\n        LATENCIES = {\n            (\"tokyo\", \"tokyo\"): 0.5,\n            (\"tokyo\", \"hong_kong\"): 35,\n            (\"tokyo\", \"singapore\"): 60,\n            (\"tokyo\", \"london\"): 150,\n            (\"tokyo\", \"virginia\"): 90,\n            (\"london\", \"london\"): 0.5,\n            (\"london\", \"virginia\"): 40,\n            (\"london\", \"hong_kong\"): 120,\n            (\"london\", \"singapore\"): 100,\n            (\"hong_kong\", \"hong_kong\"): 0.5,\n            (\"hong_kong\", \"singapore\"): 25,\n            (\"hong_kong\", \"virginia\"): 130,\n            (\"singapore\", \"singapore\"): 0.5,\n            (\"singapore\", \"virginia\"): 140,\n            (\"virginia\", \"virginia\"): 0.5,\n        }\n        loc_a = LOCATIONS.get(exchange_a, \"virginia\")\n        loc_b = LOCATIONS.get(exchange_b, \"virginia\")\n        key = tuple(sorted([loc_a, loc_b]))\n        latency_ms = LATENCIES.get(key, 150)\n        # Normalize: 0.5ms -> 1.0, 150ms -> 0.2\n        return max(0.2, 1.0 - (latency_ms \u002F 200))\n\n    def log_opportunity(self, opp: ArbitrageOpportunity):\n        \"\"\"Publish opportunity to GreenHelix event bus.\"\"\"\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.opportunity_detected\",\n            \"payload\": {\n                \"opportunity_id\": opp.opportunity_id,\n                \"symbol\": opp.symbol,\n                \"buy_exchange\": opp.buy_exchange,\n                \"sell_exchange\": opp.sell_exchange,\n                \"spread_bps\": opp.spread_bps,\n                \"net_profit_usd\": opp.net_profit_usd,\n                \"latency_score\": opp.latency_score,\n                \"detected_at\": opp.detected_at\n            }\n        })\n```\n\n### Running the Scanner\n\n```python\n# Initialize scanner\nscanner = OpportunityScanner(\n    agent_id=coordinator_id,\n    exchanges=[\"binance\", \"kraken\", \"okx\", \"bybit\", \"coinbase\"],\n    min_profit_usd=20.0,\n    min_spread_bps=5.0,\n    max_quantity_usd=100000.0\n)\n\n# Simulate price updates (in production, these come from WebSocket feeds)\nscanner.update_prices(\"binance\", \"ETH\u002FUSDT\", bid=\"3000.50\", ask=\"3000.80\", depth_usd=\"250000\")\nscanner.update_prices(\"kraken\",  \"ETH\u002FUSDT\", bid=\"3012.00\", ask=\"3012.40\", depth_usd=\"180000\")\nscanner.update_prices(\"okx\",    \"ETH\u002FUSDT\", bid=\"3001.20\", ask=\"3001.60\", depth_usd=\"300000\")\n\n# Scan for opportunities\nopportunities = scanner.scan(\"ETH\u002FUSDT\")\nfor opp in opportunities:\n    print(f\"[{opp.opportunity_id}] {opp.buy_exchange} -> {opp.sell_exchange}: \"\n          f\"spread={opp.spread_bps}bps, net=${opp.net_profit_usd}\")\n    scanner.log_opportunity(opp)\n```\n\n### Stale Price Detection\n\nPrice data goes stale fast. A price update from 500ms ago might as well be from last year in arbitrage. The scanner must discard stale prices to avoid executing on phantom opportunities:\n\n```python\ndef _is_price_fresh(self, exchange_data: dict, max_age_ms: float = 500) -> bool:\n    \"\"\"Check if a cached price is still fresh enough to trade on.\"\"\"\n    updated_at = datetime.fromisoformat(exchange_data[\"updated_at\"])\n    age_ms = (datetime.utcnow() - updated_at).total_seconds() * 1000\n    return age_ms \u003C= max_age_ms\n```\n\nIn production, the scanner should track staleness per exchange and alert the coordinator when a feed goes dark. A Binance WebSocket feed that stops sending updates for 2 seconds likely indicates a connection drop -- the bot should reconnect, not continue operating on the last known price.\n\n### Feeding Opportunities to the Coordinator\n\n```python\n# Full pipeline: scan -> validate -> escrow -> dispatch\nfor opp in opportunities:\n    # Check that we have active deals for this exchange pair\n    matching_deals = [\n        (did, d) for did, d in arb.active_deals.items()\n        if d[\"exchange_a\"] == opp.buy_exchange\n        and d[\"exchange_b\"] == opp.sell_exchange\n        and d[\"status\"] == \"negotiated\"\n    ]\n    if not matching_deals:\n        continue\n\n    deal_id, deal = matching_deals[0]\n\n    # Create escrow for profit settlement\n    escrow = arb.create_execution_escrow(\n        opportunity_id=opp.opportunity_id,\n        deal_id=deal_id,\n        amount_usd=opp.net_profit_usd\n    )\n\n    # Dispatch execution signals to both bots\n    result = arb.dispatch_execution(\n        opportunity_id=opp.opportunity_id,\n        deal_id=deal_id,\n        legs=[\n            {\n                \"exchange\": opp.buy_exchange,\n                \"side\": \"buy\",\n                \"symbol\": opp.symbol,\n                \"quantity\": opp.quantity,\n                \"limit_price\": opp.buy_price,\n                \"deadline_ms\": 500\n            },\n            {\n                \"exchange\": opp.sell_exchange,\n                \"side\": \"sell\",\n                \"symbol\": opp.symbol,\n                \"quantity\": opp.quantity,\n                \"limit_price\": opp.sell_price,\n                \"deadline_ms\": 500\n            }\n        ]\n    )\n    print(f\"Dispatched {result['signals_dispatched']} legs for {opp.opportunity_id}\")\n```\n\n---\n\n## Chapter 4: Execution Verification\n\n### Why Verification Matters\n\nAfter the coordinator dispatches execution signals, each exchange bot independently executes its leg. But the coordinator cannot see inside the exchange -- it relies on the bots to report back. This creates an information asymmetry that must be resolved cryptographically. A bot could lie about its fill price, claim a partial fill when it got a full fill, or report execution failure when it actually succeeded (pocketing the profit from the other leg's movement).\n\nExecution verification solves this with three mechanisms: signed fill reports that bind the bot's identity to its claimed execution, timestamp proofs that establish execution ordering, and claim chains that create tamper-proof evidence for dispute resolution.\n\n### The ExecutionVerifier Class\n\n```python\nclass ExecutionVerifier:\n    \"\"\"Verifies that counterparty bots actually executed their legs.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.verification_cache: dict[str, dict] = {}\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def submit_fill_report(\n        self,\n        opportunity_id: str,\n        exchange: str,\n        side: str,\n        symbol: str,\n        fill_price: str,\n        fill_quantity: str,\n        exchange_order_id: str,\n        exchange_timestamp_us: int\n    ) -> dict:\n        \"\"\"Submit a signed fill report for one leg of an arbitrage.\"\"\"\n        report = {\n            \"opportunity_id\": opportunity_id,\n            \"exchange\": exchange,\n            \"side\": side,\n            \"symbol\": symbol,\n            \"fill_price\": fill_price,\n            \"fill_quantity\": fill_quantity,\n            \"exchange_order_id\": exchange_order_id,\n            \"exchange_timestamp_us\": exchange_timestamp_us,\n            \"reporter_id\": self.agent_id,\n            \"reported_at\": datetime.utcnow().isoformat()\n        }\n        report[\"signature\"] = self.sign_payload(report)\n\n        # Publish fill report as a signed event\n        result = execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.fill_report\",\n            \"payload\": report\n        })\n\n        return {\"report\": report, \"event_id\": result.get(\"event_id\")}\n\n    def verify_execution(\n        self,\n        opportunity_id: str,\n        expected_legs: list[dict],\n        timeout_seconds: int = 30\n    ) -> dict:\n        \"\"\"Verify that all legs of an arbitrage were executed.\n\n        Waits for fill reports from each exchange bot, validates\n        signatures, checks prices against expectations, and builds\n        a verification summary.\n        \"\"\"\n        deadline = time.time() + timeout_seconds\n        verified_legs = {}\n        failures = []\n\n        while time.time() \u003C deadline and len(verified_legs) \u003C len(expected_legs):\n            # Poll for fill report events\n            events = execute(\"get_events\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"arbitrage.fill_report\",\n                \"filters\": {\n                    \"payload.opportunity_id\": opportunity_id\n                },\n                \"limit\": 10\n            })\n\n            for event in events.get(\"events\", []):\n                report = event[\"payload\"]\n                exchange = report[\"exchange\"]\n\n                if exchange in verified_legs:\n                    continue  # already verified this leg\n\n                # Find the expected leg for this exchange\n                expected = next(\n                    (l for l in expected_legs if l[\"exchange\"] == exchange),\n                    None\n                )\n                if not expected:\n                    continue\n\n                # Validate fill against expectations\n                validation = self._validate_fill(report, expected)\n                if validation[\"valid\"]:\n                    verified_legs[exchange] = {\n                        \"report\": report,\n                        \"validation\": validation\n                    }\n                else:\n                    failures.append({\n                        \"exchange\": exchange,\n                        \"reason\": validation[\"reason\"],\n                        \"report\": report\n                    })\n\n            if len(verified_legs) \u003C len(expected_legs):\n                time.sleep(0.5)\n\n        all_verified = len(verified_legs) == len(expected_legs)\n\n        verification = {\n            \"opportunity_id\": opportunity_id,\n            \"all_verified\": all_verified,\n            \"verified_legs\": verified_legs,\n            \"failures\": failures,\n            \"missing_legs\": [\n                l[\"exchange\"] for l in expected_legs\n                if l[\"exchange\"] not in verified_legs\n            ],\n            \"verified_at\": datetime.utcnow().isoformat()\n        }\n\n        self.verification_cache[opportunity_id] = verification\n        return verification\n\n    def _validate_fill(self, report: dict, expected: dict) -> dict:\n        \"\"\"Validate a fill report against expectations.\"\"\"\n        fill_price = float(report[\"fill_price\"])\n        expected_price = float(expected[\"limit_price\"])\n        fill_qty = float(report[\"fill_quantity\"])\n        expected_qty = float(expected[\"quantity\"])\n\n        # Price slippage tolerance: 0.1% (10 bps)\n        max_slippage = expected_price * 0.001\n\n        if expected[\"side\"] == \"buy\" and fill_price > expected_price + max_slippage:\n            return {\n                \"valid\": False,\n                \"reason\": f\"Buy fill price {fill_price} exceeds limit \"\n                          f\"{expected_price} + slippage {max_slippage}\"\n            }\n\n        if expected[\"side\"] == \"sell\" and fill_price \u003C expected_price - max_slippage:\n            return {\n                \"valid\": False,\n                \"reason\": f\"Sell fill price {fill_price} below limit \"\n                          f\"{expected_price} - slippage {max_slippage}\"\n            }\n\n        # Quantity tolerance: 1%\n        qty_tolerance = expected_qty * 0.01\n        if fill_qty \u003C expected_qty - qty_tolerance:\n            return {\n                \"valid\": False,\n                \"reason\": f\"Fill quantity {fill_qty} below expected \"\n                          f\"{expected_qty} - tolerance {qty_tolerance}\"\n            }\n\n        return {\"valid\": True, \"reason\": \"within_tolerance\"}\n\n    def build_evidence_package(self, opportunity_id: str) -> dict:\n        \"\"\"Build a tamper-proof evidence package using claim chains.\n\n        This creates a Merkle-tree-backed proof of all events\n        related to an opportunity -- discovery, execution signals,\n        fill reports, and verification results.\n        \"\"\"\n        verification = self.verification_cache.get(opportunity_id)\n        if not verification:\n            raise ValueError(f\"No verification data for {opportunity_id}\")\n\n        # Collect all event IDs related to this opportunity\n        events = execute(\"get_events\", {\n            \"agent_id\": self.agent_id,\n            \"filters\": {\n                \"payload.opportunity_id\": opportunity_id\n            },\n            \"limit\": 100\n        })\n\n        event_ids = [e[\"event_id\"] for e in events.get(\"events\", [])]\n\n        # Build claim chain over all related events\n        claim_chain = execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claim_type\": \"arbitrage_execution_proof\",\n            \"event_ids\": event_ids,\n            \"metadata\": {\n                \"opportunity_id\": opportunity_id,\n                \"all_verified\": verification[\"all_verified\"],\n                \"leg_count\": len(verification[\"verified_legs\"]),\n                \"verified_at\": verification[\"verified_at\"]\n            },\n            \"signature\": self.sign_payload({\n                \"opportunity_id\": opportunity_id,\n                \"event_ids\": event_ids\n            })\n        })\n\n        return {\n            \"opportunity_id\": opportunity_id,\n            \"chain_id\": claim_chain[\"chain_id\"],\n            \"merkle_root\": claim_chain[\"merkle_root\"],\n            \"event_count\": len(event_ids),\n            \"verification\": verification\n        }\n```\n\n### Using the Verifier\n\n```python\nverifier = ExecutionVerifier(coordinator_id, COORDINATOR_PRIVATE_KEY)\n\n# After dispatching execution, wait for verification\nverification = verifier.verify_execution(\n    opportunity_id=\"opp-arb-coordinator-01-00000001\",\n    expected_legs=[\n        {\n            \"exchange\": \"binance\",\n            \"side\": \"buy\",\n            \"symbol\": \"ETH\u002FUSDT\",\n            \"quantity\": \"5.00000000\",\n            \"limit_price\": \"3000.80000000\"\n        },\n        {\n            \"exchange\": \"kraken\",\n            \"side\": \"sell\",\n            \"symbol\": \"ETH\u002FUSDT\",\n            \"quantity\": \"5.00000000\",\n            \"limit_price\": \"3012.00000000\"\n        }\n    ],\n    timeout_seconds=30\n)\n\nif verification[\"all_verified\"]:\n    print(\"All legs verified. Building evidence package.\")\n    evidence = verifier.build_evidence_package(\n        \"opp-arb-coordinator-01-00000001\"\n    )\n    print(f\"Evidence chain: {evidence['chain_id']}\")\n    print(f\"Merkle root: {evidence['merkle_root']}\")\nelse:\n    print(f\"Verification failed. Missing: {verification['missing_legs']}\")\n    print(f\"Failures: {verification['failures']}\")\n```\n\nThe curl equivalent for building evidence:\n\n```bash\n# Build claim chain for execution proof\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\": \"build_claim_chain\",\n    \"input\": {\n      \"agent_id\": \"arb-coordinator-01\",\n      \"claim_type\": \"arbitrage_execution_proof\",\n      \"event_ids\": [\n        \"evt-001-signal-binance\",\n        \"evt-002-signal-kraken\",\n        \"evt-003-fill-binance\",\n        \"evt-004-fill-kraken\"\n      ],\n      \"metadata\": {\n        \"opportunity_id\": \"opp-arb-coordinator-01-00000001\",\n        \"all_verified\": true,\n        \"leg_count\": 2\n      },\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Timestamp Proofs\n\nExecution ordering matters. If the buy leg executes at T=0ms and the sell leg executes at T=200ms, a 200ms price movement could have occurred. The fill reports include `exchange_timestamp_us` -- the microsecond timestamp from the exchange itself, not the bot's local clock. The verifier checks that both legs executed within the acceptable window:\n\n```python\ndef verify_timestamp_ordering(self, verification: dict, max_gap_ms: int = 500) -> bool:\n    \"\"\"Verify that both legs executed within the acceptable time window.\"\"\"\n    timestamps = []\n    for exchange, data in verification[\"verified_legs\"].items():\n        ts_us = data[\"report\"][\"exchange_timestamp_us\"]\n        timestamps.append(ts_us)\n\n    if len(timestamps) \u003C 2:\n        return False\n\n    gap_us = max(timestamps) - min(timestamps)\n    gap_ms = gap_us \u002F 1000\n\n    return gap_ms \u003C= max_gap_ms\n```\n\n---\n\n## Chapter 5: Profit Splitting via Escrow\n\n### Escrow-Protected Settlement\n\nAfter both legs are verified, profits must be distributed. The coordinator created an escrow before dispatching execution (Chapter 2). Now it releases that escrow according to the agreed profit split. The key property: no party can access the funds without verified execution, and the split formula is locked in the escrow conditions -- not subject to post-hoc renegotiation.\n\n### Split Models\n\nThree common models for profit distribution in multi-bot arbitrage:\n\n**Equal Split (50\u002F50).** Simple but unfair when capital contributions differ. If Bot A commits $100,000 and Bot B commits $20,000, equal split gives Bot B 5x the return on capital.\n\n**Proportional to Capital.** Each bot receives profit proportional to the capital it deployed for the trade. This is fairest for capital-heavy strategies but ignores latency contributions.\n\n**Proportional to Latency Contribution.** The bot that executes faster captures more value because it reduces the window for adverse price movement. A bot that fills in 0.4ms contributes more to the trade's success than one that fills in 50ms. This model allocates a latency bonus to the faster executor.\n\nIn practice, most coordination agreements use a hybrid: a base split proportional to capital, with a latency bonus for the faster leg.\n\n```python\nclass ProfitSplitter:\n    \"\"\"Handles profit distribution via GreenHelix escrow.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def calculate_split(\n        self,\n        net_profit_usd: float,\n        model: str,\n        participants: list[dict]\n    ) -> dict[str, str]:\n        \"\"\"Calculate profit split based on the chosen model.\n\n        participants: list of {\n            \"agent_id\": str,\n            \"role\": \"coordinator\" | \"executor\",\n            \"capital_usd\": float,\n            \"execution_ms\": float  # only for latency model\n        }\n        \"\"\"\n        if model == \"equal\":\n            per_party = net_profit_usd \u002F len(participants)\n            return {p[\"agent_id\"]: f\"{per_party:.2f}\" for p in participants}\n\n        elif model == \"capital_weighted\":\n            total_capital = sum(p[\"capital_usd\"] for p in participants)\n            return {\n                p[\"agent_id\"]: f\"{(net_profit_usd * p['capital_usd'] \u002F total_capital):.2f}\"\n                for p in participants\n            }\n\n        elif model == \"latency_hybrid\":\n            # 70% capital-weighted, 20% latency bonus, 10% coordinator fee\n            coordinator_fee = net_profit_usd * 0.10\n            latency_pool = net_profit_usd * 0.20\n            capital_pool = net_profit_usd * 0.70\n\n            executors = [p for p in participants if p[\"role\"] == \"executor\"]\n            coordinator = next(\n                (p for p in participants if p[\"role\"] == \"coordinator\"), None\n            )\n\n            splits = {}\n\n            # Coordinator gets flat fee\n            if coordinator:\n                splits[coordinator[\"agent_id\"]] = f\"{coordinator_fee:.2f}\"\n\n            # Capital-weighted portion\n            total_capital = sum(p[\"capital_usd\"] for p in executors)\n            for p in executors:\n                capital_share = capital_pool * p[\"capital_usd\"] \u002F total_capital\n                splits[p[\"agent_id\"]] = f\"{capital_share:.2f}\"\n\n            # Latency bonus: faster executor gets more\n            if len(executors) == 2:\n                total_latency = sum(1.0 \u002F p[\"execution_ms\"] for p in executors)\n                for p in executors:\n                    latency_share = latency_pool * (1.0 \u002F p[\"execution_ms\"]) \u002F total_latency\n                    current = float(splits[p[\"agent_id\"]])\n                    splits[p[\"agent_id\"]] = f\"{(current + latency_share):.2f}\"\n\n            return splits\n\n        else:\n            raise ValueError(f\"Unknown split model: {model}\")\n\n    def settle_via_escrow(\n        self,\n        escrow_id: str,\n        opportunity_id: str,\n        splits: dict[str, str],\n        evidence_chain_id: str\n    ) -> dict:\n        \"\"\"Release escrow according to calculated splits.\"\"\"\n        release_payload = {\n            \"escrow_id\": escrow_id,\n            \"opportunity_id\": opportunity_id,\n            \"distributions\": [\n                {\"agent_id\": agent_id, \"amount\": amount, \"currency\": \"USD\"}\n                for agent_id, amount in splits.items()\n            ],\n            \"evidence_chain_id\": evidence_chain_id,\n            \"settled_at\": datetime.utcnow().isoformat()\n        }\n        release_payload[\"signature\"] = self.sign_payload(release_payload)\n\n        result = execute(\"release_escrow\", {\n            \"escrow_id\": escrow_id,\n            \"release_to\": release_payload[\"distributions\"],\n            \"evidence\": {\n                \"chain_id\": evidence_chain_id,\n                \"opportunity_id\": opportunity_id\n            },\n            \"signature\": release_payload[\"signature\"]\n        })\n\n        # Log settlement event\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.settlement\",\n            \"payload\": {\n                \"opportunity_id\": opportunity_id,\n                \"escrow_id\": escrow_id,\n                \"splits\": splits,\n                \"evidence_chain_id\": evidence_chain_id,\n                \"settled_at\": release_payload[\"settled_at\"]\n            }\n        })\n\n        return result\n```\n\n### Why Escrow Matters\n\nWithout escrow, profit splitting relies entirely on the counterparty's goodwill. Bot B sells on Kraken and receives $30,120 in its exchange account. The agreed split says Bot A gets $42 in profit. But Bot B controls the Kraken account. There is no technical mechanism forcing Bot B to pay. In traditional finance, this is solved by clearing houses that hold collateral from both sides. GreenHelix escrow serves the same function: the coordinator locks the expected profit in escrow before dispatching execution signals. Neither bot can access the escrowed funds until the verifier confirms both legs executed within tolerance. If verification fails, the escrow returns to the coordinator according to the pre-defined cancellation rules.\n\nThe escrow amount is typically the expected net profit, not the full trade notional. Locking the entire $30,000 per leg in escrow would be capital-inefficient and defeat the purpose of multi-bot coordination. Instead, each bot posts a smaller performance bond (e.g., 2x the expected profit) as collateral. If a bot fails to execute or reports fraudulent fills, it forfeits its bond.\n\n### Handling Partial Fills\n\nPartial fills are the most common failure mode in multi-bot arbitrage. Bot A gets a full fill on Binance, but Bot B only fills 60% on Kraken because a large market order swept the book during execution. The coordinator must handle this gracefully:\n\n```python\ndef handle_partial_fill(\n    self,\n    opportunity_id: str,\n    escrow_id: str,\n    verification: dict,\n    original_quantity: float\n) -> dict:\n    \"\"\"Handle settlement when one or more legs have partial fills.\"\"\"\n    fill_quantities = {}\n    for exchange, data in verification[\"verified_legs\"].items():\n        fill_quantities[exchange] = float(data[\"report\"][\"fill_quantity\"])\n\n    # The effective trade size is the minimum fill across all legs\n    effective_qty = min(fill_quantities.values())\n    fill_ratio = effective_qty \u002F original_quantity\n\n    if fill_ratio \u003C 0.5:\n        # Less than 50% filled -- cancel escrow, unwind positions\n        cancel_result = execute(\"release_escrow\", {\n            \"escrow_id\": escrow_id,\n            \"action\": \"cancel\",\n            \"reason\": f\"Partial fill below threshold: {fill_ratio:.1%}\",\n            \"signature\": self.sign_payload({\n                \"escrow_id\": escrow_id,\n                \"action\": \"cancel\"\n            })\n        })\n        return {\"action\": \"cancelled\", \"fill_ratio\": fill_ratio, \"result\": cancel_result}\n\n    # Partial settlement: reduce profit proportionally\n    # The overfilled leg has excess inventory that must be unwound separately\n    return {\n        \"action\": \"partial_settlement\",\n        \"fill_ratio\": fill_ratio,\n        \"effective_quantity\": f\"{effective_qty:.8f}\",\n        \"excess_fills\": {\n            ex: f\"{(qty - effective_qty):.8f}\"\n            for ex, qty in fill_quantities.items()\n            if qty > effective_qty\n        }\n    }\n```\n\n### Settlement via curl\n\n```bash\n# Release escrow after verified execution\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\": \"release_escrow\",\n    \"input\": {\n      \"escrow_id\": \"esc-abc123\",\n      \"release_to\": [\n        {\"agent_id\": \"arb-coordinator-01\", \"amount\": \"8.40\", \"currency\": \"USD\"},\n        {\"agent_id\": \"binance-bot-07\", \"amount\": \"38.22\", \"currency\": \"USD\"},\n        {\"agent_id\": \"kraken-bot-03\", \"amount\": \"37.38\", \"currency\": \"USD\"}\n      ],\n      \"evidence\": {\n        \"chain_id\": \"chain-xyz789\",\n        \"opportunity_id\": \"opp-arb-coordinator-01-00000001\"\n      },\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Full Settlement Example\n\n```python\nsplitter = ProfitSplitter(coordinator_id, COORDINATOR_PRIVATE_KEY)\n\n# Calculate split using latency-hybrid model\nsplits = splitter.calculate_split(\n    net_profit_usd=84.00,\n    model=\"latency_hybrid\",\n    participants=[\n        {\n            \"agent_id\": coordinator_id,\n            \"role\": \"coordinator\",\n            \"capital_usd\": 0,\n            \"execution_ms\": 0\n        },\n        {\n            \"agent_id\": \"binance-bot-07\",\n            \"role\": \"executor\",\n            \"capital_usd\": 30000,\n            \"execution_ms\": 0.4\n        },\n        {\n            \"agent_id\": \"kraken-bot-03\",\n            \"role\": \"executor\",\n            \"capital_usd\": 30120,\n            \"execution_ms\": 2.1\n        }\n    ]\n)\n\n# Settle via escrow\nsettlement = splitter.settle_via_escrow(\n    escrow_id=\"esc-abc123\",\n    opportunity_id=\"opp-arb-coordinator-01-00000001\",\n    splits=splits,\n    evidence_chain_id=\"chain-xyz789\"\n)\n\nprint(f\"Settlement: {splits}\")\n# Output: {'arb-coordinator-01': '8.40', 'binance-bot-07': '38.22', 'kraken-bot-03': '37.38'}\n# Coordinator: 10% = $8.40\n# Binance bot: higher latency bonus (0.4ms vs 2.1ms) offsets slightly lower capital\n# Kraken bot: slightly more capital, but slower execution\n```\n\n---\n\n## Chapter 6: MEV Protection\n\n### What MEV Means for Arbitrage Bots\n\nMaximal Extractable Value (MEV) originated in the Ethereum mempool, where miners and validators could reorder, insert, or censor transactions to extract profit. The concept has expanded beyond blockchain. In the context of multi-bot arbitrage, MEV risk manifests in three ways:\n\n**Front-running.** A third party observes your opportunity signal (the coordination message between bots) and executes the same trade before you. If you broadcast \"buy ETH on Binance at $3,000, sell on Kraken at $3,012\" in the clear, anyone monitoring the signal can race you.\n\n**Sandwich attacks.** A third party sees your pending buy order, places a buy order ahead of you (pushing the price up), then sells into your fill (profiting from the artificial price increase). This is well-documented on-chain but occurs on centralized exchanges too, particularly through API key compromise or colluding market makers.\n\n**Information leakage.** Even if your execution is private, the pattern of your trades reveals your strategy. A counterparty bot in your coordination network could extract this information and trade against you on exchanges where you are not active.\n\n### Commit-Reveal for Opportunity Sharing\n\nThe first line of defense is never broadcasting opportunity details in the clear. Instead, use a commit-reveal pattern: share a cryptographic commitment to the opportunity (proving you detected it first), then reveal the details only to verified counterparties through encrypted channels.\n\n```python\nclass MEVProtector:\n    \"\"\"MEV protection for multi-bot arbitrage coordination.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.commitments: dict[str, dict] = {}\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def commit_opportunity(self, opportunity: ArbitrageOpportunity) -> dict:\n        \"\"\"Create a cryptographic commitment to an opportunity without revealing details.\n\n        The commitment is a hash of the full opportunity details plus a random nonce.\n        Published to the event bus as proof of discovery priority. Details are revealed\n        only to authorized counterparties after escrow is created.\n        \"\"\"\n        nonce = base64.b64encode(hashlib.sha256(\n            f\"{opportunity.opportunity_id}-{time.time_ns()}\".encode()\n        ).digest()).decode()\n\n        preimage = {\n            \"opportunity_id\": opportunity.opportunity_id,\n            \"symbol\": opportunity.symbol,\n            \"buy_exchange\": opportunity.buy_exchange,\n            \"sell_exchange\": opportunity.sell_exchange,\n            \"buy_price\": opportunity.buy_price,\n            \"sell_price\": opportunity.sell_price,\n            \"quantity\": opportunity.quantity,\n            \"nonce\": nonce\n        }\n\n        commitment = hashlib.sha256(\n            json.dumps(preimage, sort_keys=True, separators=(\",\", \":\")).encode()\n        ).hexdigest()\n\n        # Store locally for later reveal\n        self.commitments[opportunity.opportunity_id] = {\n            \"preimage\": preimage,\n            \"commitment\": commitment,\n            \"nonce\": nonce\n        }\n\n        # Publish commitment (not the details)\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.opportunity_commitment\",\n            \"payload\": {\n                \"opportunity_id\": opportunity.opportunity_id,\n                \"commitment\": commitment,\n                \"committed_at\": datetime.utcnow().isoformat()\n            },\n            \"signature\": self.sign_payload({\"commitment\": commitment})\n        })\n\n        return {\"commitment\": commitment, \"opportunity_id\": opportunity.opportunity_id}\n\n    def reveal_to_counterparty(\n        self,\n        opportunity_id: str,\n        counterparty_public_key_b64: str\n    ) -> dict:\n        \"\"\"Reveal opportunity details to a specific counterparty.\n\n        In production, this would encrypt the details with the counterparty's\n        public key. For this example, we publish a reveal event that references\n        the original commitment.\n        \"\"\"\n        stored = self.commitments.get(opportunity_id)\n        if not stored:\n            raise ValueError(f\"No commitment found for {opportunity_id}\")\n\n        reveal_payload = {\n            \"opportunity_id\": opportunity_id,\n            \"preimage\": stored[\"preimage\"],\n            \"commitment\": stored[\"commitment\"],\n            \"revealed_to\": counterparty_public_key_b64,\n            \"revealed_at\": datetime.utcnow().isoformat()\n        }\n\n        # Counterparty can verify: sha256(preimage) == commitment\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.opportunity_reveal\",\n            \"payload\": reveal_payload,\n            \"signature\": self.sign_payload(reveal_payload)\n        })\n\n        return reveal_payload\n```\n\n### Detecting Front-Running\n\nEven with commit-reveal protection, you need to detect when front-running has occurred so you can respond. The primary indicator is adverse price movement between opportunity detection and execution. If you detect ETH at $3,000 on Binance and your buy order fills at $3,002, someone likely saw your intent and bought ahead of you.\n\n```python\ndef detect_front_running(\n    expected_price: float,\n    actual_fill_price: float,\n    side: str,\n    normal_slippage_bps: float = 2.0\n) -> dict:\n    \"\"\"Detect potential front-running based on fill price deviation.\n\n    Returns analysis of whether the fill price deviation exceeds\n    normal market microstructure noise.\n    \"\"\"\n    if side == \"buy\":\n        slippage_bps = ((actual_fill_price - expected_price) \u002F expected_price) * 10000\n    else:\n        slippage_bps = ((expected_price - actual_fill_price) \u002F expected_price) * 10000\n\n    is_suspicious = slippage_bps > normal_slippage_bps * 3  # 3x normal = suspicious\n    is_likely_frontrun = slippage_bps > normal_slippage_bps * 5  # 5x normal = likely\n\n    return {\n        \"expected_price\": f\"{expected_price:.8f}\",\n        \"actual_price\": f\"{actual_fill_price:.8f}\",\n        \"slippage_bps\": round(slippage_bps, 2),\n        \"normal_slippage_bps\": normal_slippage_bps,\n        \"suspicious\": is_suspicious,\n        \"likely_frontrun\": is_likely_frontrun,\n        \"recommendation\": (\n            \"abort_and_investigate\" if is_likely_frontrun\n            else \"flag_for_review\" if is_suspicious\n            else \"normal\"\n        )\n    }\n```\n\nIf front-running is detected repeatedly on a specific exchange pair or with a specific counterparty, the coordinator should blacklist that counterparty and report the behavior to GreenHelix's reputation system. Systematic front-running by a coordination partner destroys the network's value -- the reputation penalty must be severe enough to deter it.\n\n### Counterparty Information Barriers\n\nWithin a coordination network, each bot should know only what it needs to execute its leg. The Binance bot does not need to know the Kraken sell price -- it only needs to know \"buy 5 ETH at limit $3,000.80 within 500ms.\" The less information each participant has, the less they can exploit. This is the same information barrier principle used by investment banks between their trading desks and advisory arms.\n\nThe coordinator enforces this by sending each bot only its own leg details. The full opportunity (both sides, spread, expected profit) exists only in the coordinator's memory and in the commit-reveal commitment. Even if a counterparty bot is compromised or malicious, it cannot reconstruct the full opportunity from its execution signal alone.\n\n### Private Execution Channels\n\nThe second defense layer is ensuring that execution signals travel through private channels, not public event streams. GreenHelix supports scoped events -- events visible only to specified agent IDs:\n\n```bash\n# Publish execution signal visible only to the target bot\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      \"agent_id\": \"arb-coordinator-01\",\n      \"event_type\": \"arbitrage.execution_signal\",\n      \"payload\": {\n        \"opportunity_id\": \"opp-arb-coordinator-01-00000001\",\n        \"exchange\": \"binance\",\n        \"side\": \"buy\",\n        \"symbol\": \"ETH\u002FUSDT\",\n        \"quantity\": \"5.00000000\",\n        \"limit_price\": \"3000.80000000\"\n      },\n      \"visibility\": [\"binance-bot-07\"],\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Execution Timing Randomization\n\nPredictable execution patterns create MEV opportunities. If your bot always executes within 10ms of receiving a signal, a front-runner can time their order to arrive 1ms earlier. Adding controlled randomization breaks this predictability:\n\n```python\nimport random\n\ndef randomized_execution_delay(base_delay_ms: float = 0, max_jitter_ms: float = 50) -> float:\n    \"\"\"Add random jitter to execution timing to prevent front-running.\n\n    The jitter follows a truncated normal distribution centered\n    on base_delay_ms, not a uniform distribution. Uniform jitter\n    is detectable; normally-distributed jitter is not.\n    \"\"\"\n    jitter = random.gauss(0, max_jitter_ms \u002F 3)\n    jitter = max(-max_jitter_ms, min(max_jitter_ms, jitter))\n    return max(0, base_delay_ms + jitter)\n```\n\n### Order Splitting\n\nLarge orders are visible in the order book and attract front-runners. Splitting a single leg into multiple smaller orders spread over a short time window reduces visibility:\n\n```python\ndef split_order(\n    quantity: float,\n    limit_price: float,\n    num_slices: int = 5,\n    time_window_ms: int = 200\n) -> list[dict]:\n    \"\"\"Split a large order into smaller slices with price randomization.\"\"\"\n    slice_qty = quantity \u002F num_slices\n    delay_per_slice = time_window_ms \u002F num_slices\n    slices = []\n\n    for i in range(num_slices):\n        # Slight price variation on each slice to avoid detection\n        price_jitter = limit_price * random.uniform(-0.0001, 0.0001)\n        slices.append({\n            \"quantity\": f\"{slice_qty:.8f}\",\n            \"limit_price\": f\"{(limit_price + price_jitter):.8f}\",\n            \"delay_ms\": delay_per_slice * i\n        })\n\n    return slices\n```\n\n---\n\n## Chapter 7: Latency Optimization\n\n### Sub-Millisecond Requirements\n\nIn cross-exchange arbitrage, the opportunity lifetime is measured in milliseconds. Academic research on crypto arbitrage (Makarov and Schoar, 2020; updated 2025) shows that median cross-exchange price discrepancies on major pairs persist for 200-800ms. After accounting for the time to detect the opportunity, signal counterparties, and execute both legs, you have a budget of roughly 100-300ms. Every millisecond matters: each 10ms of added latency reduces capture rate by approximately 3-5% on competitive pairs.\n\nThe latency budget breaks down as:\n\n```\n+-----------------------------------------+\n| Latency Budget for Binance-Kraken Arb   |\n+-----------------------------------------+\n| Component              | Target   | Max |\n|------------------------|----------|-----|\n| Opportunity detection  |   5 ms   | 20  |\n| Coordinator processing |   2 ms   | 10  |\n| Signal to Bot A        |  70 ms   | 90  |\n| Signal to Bot B        |  70 ms   | 90  |\n| Bot A execution        |   0.4 ms |  5  |\n| Bot B execution        |   2 ms   | 10  |\n| Fill confirmation      |  10 ms   | 30  |\n|------------------------|----------|-----|\n| Total                  | 159 ms   | 255 |\n+-----------------------------------------+\n```\n\nThe signal latency (coordinator to exchange bot) dominates. This is physics -- the speed of light in fiber between Tokyo and London is approximately 70ms. You cannot optimize this below the physical limit. What you can optimize is everything else.\n\n### Co-Location Strategy\n\nEach exchange specialist bot should run as close to its exchange's matching engine as possible:\n\n| Exchange | Matching Engine Location | Recommended Cloud Region |\n|---|---|---|\n| Binance | Tokyo, Japan | AWS ap-northeast-1 |\n| Kraken | London, UK | AWS eu-west-2 |\n| OKX | Hong Kong | AWS ap-east-1 |\n| Bybit | Singapore | AWS ap-southeast-1 |\n| Coinbase | Virginia, USA | AWS us-east-1 |\n\nThe coordinator should run in a location that minimizes maximum signal latency to any exchange bot. For the five exchanges above, Frankfurt (AWS eu-central-1) provides the best worst-case latency: 80ms to Tokyo, 10ms to London, 100ms to Hong Kong, 90ms to Singapore, 45ms to Virginia. No single location achieves sub-50ms to all five, but Frankfurt keeps the worst case under 100ms.\n\n### WebSocket vs REST for Price Feeds\n\nExchange specialist bots must choose between WebSocket price feeds and REST polling. The answer is always WebSocket for price monitoring. REST polling at 100ms intervals means you discover opportunities up to 100ms late. WebSocket push delivers price updates within 1-5ms of the exchange processing them. The latency difference compounds: a 100ms detection delay plus a 70ms signal delay plus a 2ms execution delay means 172ms total -- well within the opportunity window. But a REST poll that happens to fire 90ms after the price moved gives you 162ms of detection latency, pushing total time to 234ms. On competitive pairs, that extra 62ms drops your capture rate by 15-20%.\n\nEvery major exchange provides WebSocket order book feeds: Binance's `wss:\u002F\u002Fstream.binance.com`, Kraken's `wss:\u002F\u002Fws.kraken.com`, OKX's `wss:\u002F\u002Fws.okx.com`. The specialist bot should maintain persistent WebSocket connections to each feed and parse price updates in the hot path without any heap allocation. In Python, this means pre-allocated buffers and `orjson` for JSON parsing (3-5x faster than `json.loads` on order book payloads).\n\n### Connection Pooling\n\nCreating a new TCP connection for each API call adds 30-50ms of handshake overhead. Persistent connections eliminate this:\n\n```python\nimport urllib3\n\nclass LowLatencyExecutor:\n    \"\"\"Optimized executor for sub-millisecond exchange operations.\"\"\"\n\n    def __init__(self, exchange_api_base: str, api_key: str):\n        # Pre-create connection pool with keep-alive\n        self.pool = urllib3.HTTPSConnectionPool(\n            host=exchange_api_base.replace(\"https:\u002F\u002F\", \"\"),\n            maxsize=10,\n            block=False,\n            retries=urllib3.Retry(total=0),  # no retries -- fail fast\n            timeout=urllib3.Timeout(connect=1.0, read=2.0)\n        )\n        self.api_key = api_key\n        self._headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Connection\": \"keep-alive\"\n        }\n\n    def execute_order(self, order: dict) -> dict:\n        \"\"\"Execute an order with minimal latency.\"\"\"\n        body = json.dumps(order).encode()\n        resp = self.pool.urlopen(\n            \"POST\",\n            \"\u002Fapi\u002Fv1\u002Forder\",\n            headers=self._headers,\n            body=body\n        )\n        return json.loads(resp.data)\n```\n\n### Pre-Signed Transactions\n\nFor exchanges that support it, pre-sign the order payload and cache it. When the execution signal arrives, you send the pre-signed payload immediately without cryptographic computation in the hot path:\n\n```python\nclass PreSignedOrderCache:\n    \"\"\"Cache pre-signed orders for instant dispatch.\"\"\"\n\n    def __init__(self, private_key: Ed25519PrivateKey):\n        self.private_key = private_key\n        self.cache: dict[str, dict] = {}\n\n    def prepare_order(\n        self,\n        symbol: str,\n        side: str,\n        quantity: str,\n        price: str,\n        ttl_seconds: int = 5\n    ) -> str:\n        \"\"\"Pre-sign an order for later dispatch.\n\n        Returns a cache key. The signed order expires after ttl_seconds.\n        \"\"\"\n        order = {\n            \"symbol\": symbol,\n            \"side\": side,\n            \"quantity\": quantity,\n            \"price\": price,\n            \"timestamp\": int(time.time() * 1000),\n            \"valid_until\": int((time.time() + ttl_seconds) * 1000)\n        }\n\n        canonical = json.dumps(order, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        order[\"signature\"] = base64.b64encode(signature).decode()\n\n        cache_key = f\"{symbol}-{side}-{price}\"\n        self.cache[cache_key] = {\n            \"order\": order,\n            \"expires_at\": time.time() + ttl_seconds\n        }\n        return cache_key\n\n    def get_order(self, cache_key: str) -> dict | None:\n        \"\"\"Retrieve a pre-signed order. Returns None if expired.\"\"\"\n        entry = self.cache.get(cache_key)\n        if not entry:\n            return None\n        if time.time() > entry[\"expires_at\"]:\n            del self.cache[cache_key]\n            return None\n        return entry[\"order\"]\n```\n\n### Reporting Latency Metrics\n\nExchange specialist bots should report their execution latency to GreenHelix so the coordinator can make informed routing decisions:\n\n```python\ndef report_latency_metrics(agent_id: str, exchange: str, metrics: dict):\n    \"\"\"Report execution latency metrics to GreenHelix.\"\"\"\n    execute(\"submit_metrics\", {\n        \"agent_id\": agent_id,\n        \"metrics\": {\n            f\"{exchange}_avg_execution_ms\": metrics[\"avg_execution_ms\"],\n            f\"{exchange}_p99_execution_ms\": metrics[\"p99_execution_ms\"],\n            f\"{exchange}_fill_rate\": metrics[\"fill_rate\"],\n            f\"{exchange}_uptime_pct\": metrics[\"uptime_pct\"],\n            f\"{exchange}_orders_today\": metrics[\"orders_today\"]\n        }\n    })\n\n# Example: Binance bot reports its daily metrics\nreport_latency_metrics(\"binance-bot-07\", \"binance\", {\n    \"avg_execution_ms\": 0.38,\n    \"p99_execution_ms\": 1.2,\n    \"fill_rate\": 0.97,\n    \"uptime_pct\": 99.99,\n    \"orders_today\": 4821\n})\n```\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\": \"submit_metrics\",\n    \"input\": {\n      \"agent_id\": \"binance-bot-07\",\n      \"metrics\": {\n        \"binance_avg_execution_ms\": 0.38,\n        \"binance_p99_execution_ms\": 1.2,\n        \"binance_fill_rate\": 0.97,\n        \"binance_uptime_pct\": 99.99,\n        \"binance_orders_today\": 4821\n      }\n    }\n  }'\n```\n\n### Using Metrics for Routing\n\nThe coordinator uses reported metrics to decide which exchange bot to use when multiple bots cover the same exchange:\n\n```python\ndef select_best_bot(self, exchange: str, candidates: list[dict]) -> dict:\n    \"\"\"Select the best bot for an exchange based on reported metrics.\"\"\"\n    scored = []\n    for bot in candidates:\n        reputation = execute(\"get_reputation\", {\n            \"agent_id\": bot[\"agent_id\"]\n        })\n\n        # Composite score: 40% fill rate, 30% latency, 30% uptime\n        fill_rate = reputation.get(\"metrics\", {}).get(f\"{exchange}_fill_rate\", 0.5)\n        avg_ms = reputation.get(\"metrics\", {}).get(f\"{exchange}_avg_execution_ms\", 100)\n        uptime = reputation.get(\"metrics\", {}).get(f\"{exchange}_uptime_pct\", 90)\n\n        latency_score = max(0, 1 - (avg_ms \u002F 10))  # 0ms = 1.0, 10ms = 0.0\n        score = (fill_rate * 0.4) + (latency_score * 0.3) + ((uptime \u002F 100) * 0.3)\n        scored.append((score, bot))\n\n    scored.sort(key=lambda x: x[0], reverse=True)\n    return scored[0][1]\n```\n\n---\n\n## Chapter 8: Audit Trails for Arbitrage\n\n### Regulatory Requirements\n\nArbitrage bots operating across regulated exchanges face overlapping compliance obligations. The EU AI Act (effective August 2, 2026) classifies autonomous financial trading systems as high-risk AI under Annex III. MiFID II RTS 25 requires per-order event logging with microsecond timestamps. SEC Rule 17a-4 mandates write-once, read-many (WORM) storage for trade records. Even if you trade only crypto on centralized exchanges, most jurisdictions now classify this as a regulated activity requiring auditable record-keeping.\n\nThe common thread: every decision your bot makes -- every opportunity detected, every execution signal dispatched, every fill received, every profit split -- must be logged in a tamper-evident, independently verifiable format. A mutable database is not sufficient.\n\n### Event Types for Arbitrage Audit\n\nDefine a schema for each auditable event in the arbitrage lifecycle:\n\n| Event Type | When | Key Fields |\n|---|---|---|\n| `arbitrage.opportunity_detected` | Scanner finds a profitable spread | symbol, exchanges, spread_bps, net_profit_est |\n| `arbitrage.opportunity_commitment` | Commit-reveal: commit phase | commitment_hash, timestamp |\n| `arbitrage.deal_negotiated` | Coordination agreement reached | deal_id, counterparties, terms |\n| `arbitrage.escrow_created` | Escrow locked for settlement | escrow_id, amount, conditions |\n| `arbitrage.execution_signal` | Coordinator signals exchange bot | exchange, side, symbol, quantity, price |\n| `arbitrage.fill_report` | Exchange bot reports fill | exchange, fill_price, fill_qty, exchange_ts |\n| `arbitrage.verification_complete` | All legs verified | opportunity_id, all_verified, legs |\n| `arbitrage.settlement` | Escrow released, profit split | escrow_id, splits, evidence_chain_id |\n| `arbitrage.dispute_opened` | Counterparty disputes fill | dispute_id, reason, evidence |\n\n### The AuditTrail Class\n\n```python\nclass ArbitrageAuditTrail:\n    \"\"\"Compliance-grade audit logging for arbitrage operations.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.event_buffer: list[dict] = []\n        self.chain_schedule_minutes = 15  # build chain every 15 minutes\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def log_event(self, event_type: str, payload: dict) -> dict:\n        \"\"\"Log an auditable event with cryptographic signature.\"\"\"\n        event = {\n            \"agent_id\": self.agent_id,\n            \"event_type\": event_type,\n            \"payload\": payload,\n            \"timestamp_us\": int(time.time() * 1_000_000),\n            \"signature\": self.sign_payload(payload)\n        }\n\n        result = execute(\"publish_event\", event)\n        event[\"event_id\"] = result.get(\"event_id\")\n        self.event_buffer.append(event)\n\n        return result\n\n    def build_periodic_chain(self) -> dict:\n        \"\"\"Build a Merkle claim chain over buffered events.\n\n        Call this on a schedule (e.g., every 15 minutes) to create\n        a tamper-proof commitment over recent events. The chain root\n        can be verified independently by auditors.\n        \"\"\"\n        if not self.event_buffer:\n            return {\"status\": \"no_events\"}\n\n        event_ids = [e[\"event_id\"] for e in self.event_buffer if e.get(\"event_id\")]\n\n        chain = execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claim_type\": \"arbitrage_audit_chain\",\n            \"event_ids\": event_ids,\n            \"metadata\": {\n                \"event_count\": len(event_ids),\n                \"time_range\": {\n                    \"from\": self.event_buffer[0][\"timestamp_us\"],\n                    \"to\": self.event_buffer[-1][\"timestamp_us\"]\n                },\n                \"chain_build_trigger\": \"periodic\"\n            },\n            \"signature\": self.sign_payload({\"event_ids\": event_ids})\n        })\n\n        # Clear buffer after successful chain build\n        self.event_buffer.clear()\n\n        return chain\n\n    def generate_compliance_report(\n        self,\n        start_date: str,\n        end_date: str\n    ) -> dict:\n        \"\"\"Generate a compliance report for a date range.\n\n        Retrieves all events and claim chains in the range, computes\n        summary statistics, and returns a structured report suitable\n        for regulatory submission.\n        \"\"\"\n        events = execute(\"get_events\", {\n            \"agent_id\": self.agent_id,\n            \"filters\": {\n                \"timestamp_from\": start_date,\n                \"timestamp_to\": end_date\n            },\n            \"limit\": 10000\n        })\n\n        chains = execute(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n            \"filters\": {\n                \"created_from\": start_date,\n                \"created_to\": end_date\n            }\n        })\n\n        all_events = events.get(\"events\", [])\n\n        # Compute statistics\n        opportunities = [e for e in all_events if e[\"event_type\"] == \"arbitrage.opportunity_detected\"]\n        executions = [e for e in all_events if e[\"event_type\"] == \"arbitrage.execution_signal\"]\n        settlements = [e for e in all_events if e[\"event_type\"] == \"arbitrage.settlement\"]\n        disputes = [e for e in all_events if e[\"event_type\"] == \"arbitrage.dispute_opened\"]\n\n        total_settled = sum(\n            sum(float(v) for v in s[\"payload\"].get(\"splits\", {}).values())\n            for s in settlements\n        )\n\n        report = {\n            \"report_type\": \"arbitrage_compliance\",\n            \"agent_id\": self.agent_id,\n            \"period\": {\"start\": start_date, \"end\": end_date},\n            \"summary\": {\n                \"total_events\": len(all_events),\n                \"opportunities_detected\": len(opportunities),\n                \"executions_dispatched\": len(executions),\n                \"settlements_completed\": len(settlements),\n                \"disputes_opened\": len(disputes),\n                \"total_settled_usd\": f\"{total_settled:.2f}\",\n                \"claim_chains_built\": len(chains.get(\"chains\", []))\n            },\n            \"claim_chain_roots\": [\n                {\n                    \"chain_id\": c[\"chain_id\"],\n                    \"merkle_root\": c[\"merkle_root\"],\n                    \"event_count\": c.get(\"metadata\", {}).get(\"event_count\", 0)\n                }\n                for c in chains.get(\"chains\", [])\n            ],\n            \"generated_at\": datetime.utcnow().isoformat()\n        }\n\n        return report\n```\n\n### Dispute Resolution Evidence\n\nWhen a counterparty disputes a fill -- claiming they executed at a different price than reported, or that they never received an execution signal -- the claim chain provides the resolution mechanism. The evidence package built by the `ExecutionVerifier` (Chapter 4) contains every event in the opportunity lifecycle, each signed by the originating bot's Ed25519 key, all anchored in a Merkle tree whose root is published and immutable.\n\nAn auditor or dispute resolver can independently verify three things without trusting any party:\n\n1. **Completeness**: The claim chain includes all events from opportunity detection through settlement. Missing events create a gap in the Merkle proof that is cryptographically detectable.\n2. **Authenticity**: Each event's Ed25519 signature binds it to the signing bot's identity. A bot cannot forge events from another bot without the private key.\n3. **Ordering**: Timestamps within the chain establish the sequence of events. Combined with exchange-provided timestamps on fill reports, this creates a verifiable timeline.\n\n```python\ndef open_dispute(\n    self,\n    opportunity_id: str,\n    disputed_by: str,\n    reason: str,\n    evidence_chain_id: str\n) -> dict:\n    \"\"\"Open a dispute for an arbitrage settlement.\"\"\"\n    dispute_payload = {\n        \"opportunity_id\": opportunity_id,\n        \"disputed_by\": disputed_by,\n        \"reason\": reason,\n        \"evidence_chain_id\": evidence_chain_id,\n        \"opened_at\": datetime.utcnow().isoformat()\n    }\n\n    return self.log_event(\"arbitrage.dispute_opened\", dispute_payload)\n```\n\n### Integrating the Audit Trail\n\nWire the audit trail into the coordinator so every action is logged automatically:\n\n```python\naudit = ArbitrageAuditTrail(coordinator_id, COORDINATOR_PRIVATE_KEY)\n\n# Log opportunity detection\nfor opp in opportunities:\n    audit.log_event(\"arbitrage.opportunity_detected\", {\n        \"opportunity_id\": opp.opportunity_id,\n        \"symbol\": opp.symbol,\n        \"buy_exchange\": opp.buy_exchange,\n        \"sell_exchange\": opp.sell_exchange,\n        \"spread_bps\": opp.spread_bps,\n        \"net_profit_usd\": opp.net_profit_usd,\n        \"detected_at\": opp.detected_at\n    })\n\n# Log escrow creation\naudit.log_event(\"arbitrage.escrow_created\", {\n    \"opportunity_id\": opp.opportunity_id,\n    \"escrow_id\": \"esc-abc123\",\n    \"amount\": opp.net_profit_usd,\n    \"conditions\": \"verified_execution\"\n})\n\n# Log settlement\naudit.log_event(\"arbitrage.settlement\", {\n    \"opportunity_id\": opp.opportunity_id,\n    \"escrow_id\": \"esc-abc123\",\n    \"splits\": splits,\n    \"evidence_chain_id\": \"chain-xyz789\"\n})\n\n# Build periodic Merkle chain (run on schedule)\nchain = audit.build_periodic_chain()\nprint(f\"Audit chain built: {chain.get('chain_id')}\")\nprint(f\"Merkle root: {chain.get('merkle_root')}\")\n```\n\n### Monitoring and Alerting\n\nSubmit audit trail health metrics to GreenHelix for observability:\n\n```python\nexecute(\"submit_metrics\", {\n    \"agent_id\": coordinator_id,\n    \"metrics\": {\n        \"audit_events_today\": 2847,\n        \"audit_buffer_size\": len(audit.event_buffer),\n        \"chains_built_today\": 96,\n        \"opportunities_detected_today\": 412,\n        \"settlements_completed_today\": 387,\n        \"disputes_today\": 2,\n        \"settlement_rate\": 0.939,\n        \"avg_settlement_time_ms\": 4200\n    }\n})\n```\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\": \"submit_metrics\",\n    \"input\": {\n      \"agent_id\": \"arb-coordinator-01\",\n      \"metrics\": {\n        \"audit_events_today\": 2847,\n        \"chains_built_today\": 96,\n        \"opportunities_detected_today\": 412,\n        \"settlements_completed_today\": 387,\n        \"disputes_today\": 2,\n        \"settlement_rate\": 0.939\n      }\n    }\n  }'\n```\n\n### Generating a Compliance Report\n\n```python\nreport = audit.generate_compliance_report(\n    start_date=\"2026-04-01T00:00:00Z\",\n    end_date=\"2026-04-07T23:59:59Z\"\n)\n\nprint(json.dumps(report, indent=2))\n```\n\n```bash\n# Query events for compliance\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      \"agent_id\": \"arb-coordinator-01\",\n      \"filters\": {\n        \"timestamp_from\": \"2026-04-01T00:00:00Z\",\n        \"timestamp_to\": \"2026-04-07T23:59:59Z\"\n      },\n      \"limit\": 10000\n    }\n  }'\n```\n\n```bash\n# Query claim chains for audit verification\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_claim_chains\",\n    \"input\": {\n      \"agent_id\": \"arb-coordinator-01\",\n      \"filters\": {\n        \"created_from\": \"2026-04-01T00:00:00Z\",\n        \"created_to\": \"2026-04-07T23:59:59Z\"\n      }\n    }\n  }'\n```\n\n---\n\n## What's Next\n\n**Companion Guides:**\n\n- **Tamper-Proof Audit Trails for Trading Bots** -- Deep dive into EU AI Act, MiFID II, and SEC 17a-4 compliance for your arbitrage audit trail. Extends the logging patterns in Chapter 8 with Merkle tree verification and webhook-based real-time audit forwarding.\n- **Verified Bot Reputation** -- Turn your arbitrage execution metrics into a provable reputation asset. Counterparties can verify your fill rate, latency, and settlement history before agreeing to coordinate.\n- **Strategy Marketplace Playbook** -- Publish your arbitrage coordination framework as a product on the GreenHelix marketplace, with reputation-backed performance claims and escrow-protected licensing.\n\n**GreenHelix Documentation:**\n\n- Full API reference: https:\u002F\u002Fapi.greenhelix.net\u002Fv1\n- Escrow lifecycle and dispute resolution in the platform documentation\n- Event bus schemas and claim chain verification procedures\n\n**Production Considerations:**\n\nThe framework in this guide is architecturally complete but requires exchange-specific adapters for production deployment. Each exchange has its own WebSocket feed format, order API schema, authentication mechanism, and rate limits. The ArbitrageCoordinator, OpportunityScanner, ExecutionVerifier, and ProfitSplitter are exchange-agnostic by design -- they communicate through GreenHelix events and escrow, not through exchange APIs directly. The exchange specialist bots encapsulate all exchange-specific logic. Adding a new exchange means writing one new specialist bot and registering it on GreenHelix, not modifying any framework code.\n\n---\n\n*This guide describes coordination patterns for autonomous trading bots. Arbitrage across exchanges carries financial risk including but not limited to execution risk, counterparty risk, exchange insolvency risk, and regulatory risk. The fee structures and latency numbers cited are representative as of Q1 2026 and change frequently. Test all strategies in a paper-trading environment before deploying real capital. Consult your compliance counsel for jurisdiction-specific obligations related to algorithmic trading.*\n\n","# Bot-to-Bot Arbitrage Framework: Multi-Bot Coordination with Trust Verification\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\nArbitrage bots operate in isolation. A bot that spots a price discrepancy between Binance and Kraken has to execute both legs itself -- funding accounts on both exchanges, maintaining API keys for each, and racing against every other solo operator watching the same order books. The capital requirements are brutal: to capture a 0.3% spread on a $100,000 opportunity, you need $100,000 sitting idle on Binance and another $100,000 on Kraken, earning nothing while waiting for the next opportunity. Multiply that across ten exchanges and you are looking at a million dollars in idle capital for a strategy that might generate $500 per trade.\nMulti-bot coordination solves this. One bot holds capital on Binance and specializes in that exchange's matching engine quirks. Another holds capital on Kraken and knows its WebSocket feed intimately. A third monitors OKX. When a cross-exchange opportunity appears, the coordinating bot signals the relevant pair, they execute simultaneously, and profits are split according to a pre-negotiated agreement. Capital efficiency improves by an order of magnitude. Latency drops because each bot is co-located with its exchange. Coverage expands because adding a new exchange means onboarding one specialist bot, not refactoring an entire monolithic system.\nThe problem is trust. How does the Binance bot know the Kraken bot actually executed its leg? How do you split profits with a bot operated by someone you have never met? What happens when one leg fills and the other does not? What stops a counterparty from reporting a worse fill price than they actually received? This guide builds a complete framework for coordinated multi-bot arbitrage using GreenHelix's marketplace for bot discovery, escrow for profit splitting, claim chains for execution verification, and event bus for audit trails. Every component comes with working Python code and curl equivalents against the GreenHelix API.\n\n## What You'll Learn\n- Chapter 1: Why Multi-Bot Arbitrage\n- Chapter 2: ArbitrageCoordinator Class\n- Chapter 3: OpportunityScanner Class\n- Chapter 4: Execution Verification\n- Chapter 5: Profit Splitting via Escrow\n- Chapter 6: MEV Protection\n- Chapter 7: Latency Optimization\n- Chapter 8: Audit Trails for Arbitrage\n- What's Next\n\n## Full Guide\n\n# Bot-to-Bot Arbitrage Framework: Multi-Bot Coordination with Trust Verification\n\nArbitrage bots operate in isolation. A bot that spots a price discrepancy between Binance and Kraken has to execute both legs itself -- funding accounts on both exchanges, maintaining API keys for each, and racing against every other solo operator watching the same order books. The capital requirements are brutal: to capture a 0.3% spread on a $100,000 opportunity, you need $100,000 sitting idle on Binance and another $100,000 on Kraken, earning nothing while waiting for the next opportunity. Multiply that across ten exchanges and you are looking at a million dollars in idle capital for a strategy that might generate $500 per trade.\n\nMulti-bot coordination solves this. One bot holds capital on Binance and specializes in that exchange's matching engine quirks. Another holds capital on Kraken and knows its WebSocket feed intimately. A third monitors OKX. When a cross-exchange opportunity appears, the coordinating bot signals the relevant pair, they execute simultaneously, and profits are split according to a pre-negotiated agreement. Capital efficiency improves by an order of magnitude. Latency drops because each bot is co-located with its exchange. Coverage expands because adding a new exchange means onboarding one specialist bot, not refactoring an entire monolithic system.\n\nThe problem is trust. How does the Binance bot know the Kraken bot actually executed its leg? How do you split profits with a bot operated by someone you have never met? What happens when one leg fills and the other does not? What stops a counterparty from reporting a worse fill price than they actually received? This guide builds a complete framework for coordinated multi-bot arbitrage using GreenHelix's marketplace for bot discovery, escrow for profit splitting, claim chains for execution verification, and event bus for audit trails. Every component comes with working Python code and curl equivalents against the GreenHelix API.\n\n---\n\n## Table of Contents\n\n1. [Why Multi-Bot Arbitrage](#chapter-1-why-multi-bot-arbitrage)\n2. [ArbitrageCoordinator Class](#chapter-2-arbitragecoordinator-class)\n3. [OpportunityScanner Class](#chapter-3-opportunityscanner-class)\n4. [Execution Verification](#chapter-4-execution-verification)\n5. [Profit Splitting via Escrow](#chapter-5-profit-splitting-via-escrow)\n6. [MEV Protection](#chapter-6-mev-protection)\n7. [Latency Optimization](#chapter-7-latency-optimization)\n8. [Audit Trails for Arbitrage](#chapter-8-audit-trails-for-arbitrage)\n\n---\n\n## Chapter 1: Why Multi-Bot Arbitrage\n\n### The Capital Efficiency Problem\n\nA solo arbitrage bot monitoring ten exchanges needs funded accounts on all ten. Most of that capital sits idle most of the time. A Binance-Kraken opportunity might appear once every thirty seconds, but the capital allocated to the Binance-OKX pair and the Kraken-Bybit pair and every other combination is locked up, doing nothing, waiting for its turn.\n\nThe numbers are straightforward. Assume $50,000 minimum per exchange account to capture meaningful opportunities (sub-$50K and slippage on larger orders eats your edge). Ten exchanges means $500,000 in deployed capital. Average daily return on cross-exchange crypto arbitrage in 2026 hovers around 0.05-0.15% of deployed capital after fees -- that is $250-$750 per day on half a million dollars. The capital efficiency ratio is terrible.\n\nMulti-bot coordination restructures this entirely. Each bot operator funds one exchange. Ten operators each deploying $50,000 create a network with $500,000 in total liquidity, but each individual's capital requirement is 90% lower. When a Binance-Kraken opportunity appears, only those two bots' capital is involved. The other eight bots' capital is simultaneously available for other pairs. The same $50,000 individual commitment can participate in multiple simultaneous opportunities across different pairs, as long as the pairs involve that bot's exchange.\n\n### The Latency Advantage\n\nExchange co-location is the single biggest latency reduction available to a trading bot. A bot running on AWS ap-northeast-1 (Tokyo) hitting Binance's Tokyo matching engine sees 0.3ms round-trip times. The same bot hitting Kraken's London servers sees 150ms. In arbitrage, 150ms is an eternity -- the opportunity is gone.\n\nA solo bot cannot be co-located with ten exchanges simultaneously. The physics do not allow it. But a network of specialist bots -- one co-located with each exchange -- can achieve sub-millisecond execution on every leg. The Binance specialist sits in Tokyo. The Kraken specialist sits in London. The OKX specialist sits in Hong Kong. When a cross-exchange opportunity is detected, the coordinating signal travels at the speed of light between data centers (roughly 70ms Tokyo-to-London), but both legs execute at local speed. The total execution time is the coordination signal latency plus the local execution latency, which is still faster than a solo bot executing one leg locally and the other leg across an ocean.\n\n### The Trust Problem\n\nCoordination creates value, but it also creates risk. Consider a two-leg arbitrage between Binance and Kraken:\n\n```\nOpportunity: ETH is $3,000.00 on Binance, $3,012.00 on Kraken\nStrategy:    Buy 10 ETH on Binance ($30,000), Sell 10 ETH on Kraken ($30,120)\nGross profit: $120.00\nFees (est):   $36.00 (0.06% taker on each leg)\nNet profit:   $84.00\n```\n\nBot A buys on Binance. Bot B sells on Kraken. After execution, Bot B holds the $30,120 from the Kraken sale. The agreed profit split is 50\u002F50, so Bot B owes Bot A $42.00 plus Bot A's $30,000 principal. But what stops Bot B from claiming the sell only filled at $3,008 instead of $3,012, reducing Bot A's share? What stops Bot B from simply not paying at all?\n\nIn traditional finance, clearing houses solve this -- they sit between counterparties, guarantee settlement, and manage collateral. In bot-to-bot arbitrage, the equivalent infrastructure maps to these tools:\n\n- **search_services** -- Discover specialist bots registered on specific exchanges\n- **negotiate_deal** -- Agree on profit split terms before execution\n- **create_escrow** -- Lock collateral to guarantee settlement\n- **submit_metrics** -- Report execution latency, fill rates, and reliability\n- **build_claim_chain** -- Create cryptographic proof of execution for dispute resolution\n- **publish_event** -- Log every step for audit and compliance\n\n### GreenHelix Tools for Arbitrage Coordination\n\n| Tool | Role in Arbitrage |\n|---|---|\n| `register_agent` | Register each exchange-specialist bot with its capabilities |\n| `search_services` | Find bots specializing in specific exchanges |\n| `negotiate_deal` | Agree on profit split, minimum opportunity size, latency SLAs |\n| `create_escrow` | Lock profit-share collateral before execution |\n| `release_escrow` | Release funds after verified execution |\n| `submit_metrics` | Report fill rates, latency, reliability to build reputation |\n| `build_claim_chain` | Create tamper-proof execution evidence |\n| `publish_event` | Log opportunities, executions, settlements to the event bus |\n| `get_reputation` | Check counterparty reliability before partnering |\n\n### Why Now\n\nCross-exchange arbitrage has existed since the first two crypto exchanges launched. What has changed in 2025-2026 is the infrastructure. Three developments make multi-bot coordination viable today when it was not two years ago.\n\nFirst, exchange API latency has dropped. Binance's matching engine upgrade in late 2025 reduced API response times to sub-millisecond for co-located clients. Kraken, OKX, and Bybit followed with similar improvements. The execution speed gap between institutional and retail API access has narrowed -- a well-optimized bot on a standard cloud instance now achieves execution times that previously required bare-metal co-location.\n\nSecond, the agent commerce infrastructure exists. Before GreenHelix and similar platforms, bot coordination required custom bilateral agreements, manual escrow arrangements, and trust based on personal reputation in Telegram groups. GreenHelix provides the standardized primitives -- identity, escrow, reputation, event logging -- that turn ad-hoc coordination into a scalable protocol.\n\nThird, the regulatory landscape is clarifying. MiCA in the EU, updated SEC guidance in the US, and ASIC's framework in Australia all treat algorithmic trading as a regulated activity with specific record-keeping requirements. Bots that operate within a compliance-ready framework (with audit trails, execution verification, and settlement records) have a structural advantage over bots that operate in the dark.\n\n### The Network Effect\n\nThere is a compounding advantage to multi-bot coordination that solo operators cannot replicate. A two-bot network covers one exchange pair. A five-bot network covers ten pairs. A ten-bot network covers forty-five pairs. The number of arbitrage opportunities scales quadratically with the number of exchanges covered, but each bot's capital requirement stays constant. A single bot operator joining a ten-bot network gains access to nine new exchange pairs without deploying a single dollar of additional capital.\n\nThis creates a natural marketplace for coordination. Bots with strong execution on a specific exchange can monetize that capability by partnering with bots on other exchanges. A Binance specialist with 0.4ms execution and a 97% fill rate is a valuable counterparty -- its speed and reliability directly increase the capture rate for any opportunity involving Binance. GreenHelix's reputation system makes this value visible: bots publish verified execution metrics, and coordinators use those metrics to select the best partner for each opportunity.\n\nThe rest of this guide builds a production framework using these tools. Chapter 2 creates the coordination layer. Chapter 3 scans for opportunities. Chapter 4 verifies execution. Chapter 5 handles profit splitting. Chapters 6-8 cover MEV protection, latency optimization, and compliance audit trails.\n\n---\n\n## Chapter 2: ArbitrageCoordinator Class\n\n### Architecture\n\nThe ArbitrageCoordinator is the central orchestrator. It does not execute trades itself -- it discovers specialist bots, negotiates coordination agreements, manages escrow for profit splitting, and dispatches execution signals. Think of it as the clearing house in a traditional exchange, but running as an autonomous agent.\n\n```\n+---------------------+       +---------------------+       +---------------------+\n|  Binance Bot        |       | ArbitrageCoordinator|       |  Kraken Bot          |\n|  (exchange specialist)|     |  (orchestrator)     |       |  (exchange specialist)|\n|                     |       |                     |       |                     |\n|  Monitors Binance   |       |  Discovers bots     |       |  Monitors Kraken    |\n|  order book         |       |  Negotiates deals   |       |  order book         |\n|  Executes buy\u002Fsell  |       |  Manages escrow     |       |  Executes buy\u002Fsell  |\n|  Reports fills      |       |  Verifies execution |       |  Reports fills      |\n|                     |       |  Splits profits     |       |                     |\n+--------+------------+       +----------+----------+       +----------+----------+\n         |                               |                              |\n         |  publish_event (fill data)    |  create_escrow               |  publish_event (fill data)\n         +------------------------------>|\u003C-----------------------------+\n                                         |\n                                    build_claim_chain\n                                    release_escrow\n```\n\n### Setup\n\n```python\nimport requests\nimport json\nimport time\nimport hashlib\nimport base64\nfrom datetime import datetime, timedelta\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\nAPI_KEY = \"your-api-key\"\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {API_KEY}\"\nsession.headers[\"Content-Type\"] = \"application\u002Fjson\"\n\ndef execute(tool: str, inputs: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool and return the result.\"\"\"\n    resp = session.post(\n        f\"{API_BASE}\u002Fv1\",\n        json={\"tool\": tool, \"input\": inputs}\n    )\n    resp.raise_for_status()\n    return resp.json()\n```\n\n### The ArbitrageCoordinator Class\n\n```python\nclass ArbitrageCoordinator:\n    \"\"\"Orchestrates multi-bot arbitrage across exchanges.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.public_key = self.private_key.public_key()\n        self.exchange_bots: dict[str, dict] = {}  # exchange -> bot info\n        self.active_deals: dict[str, dict] = {}   # deal_id -> deal info\n        self.pending_escrows: dict[str, str] = {}  # opportunity_id -> escrow_id\n\n    def sign_payload(self, payload: dict) -> str:\n        \"\"\"Sign a canonical JSON payload with Ed25519.\"\"\"\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def discover_exchange_bots(self, exchanges: list[str]) -> dict[str, list[dict]]:\n        \"\"\"Find specialist bots for each target exchange.\"\"\"\n        discovered = {}\n        for exchange in exchanges:\n            results = execute(\"search_services\", {\n                \"query\": f\"arbitrage execution {exchange}\",\n                \"filters\": {\n                    \"capabilities\": [\"exchange_execution\", \"fast_fill\"],\n                    \"metadata.exchange\": exchange,\n                    \"metadata.bot_type\": \"exchange_specialist\"\n                },\n                \"limit\": 10\n            })\n            discovered[exchange] = results.get(\"services\", [])\n            self._log_discovery(exchange, len(discovered[exchange]))\n        self.exchange_bots = {\n            ex: bots[0] for ex, bots in discovered.items() if bots\n        }\n        return discovered\n\n    def _log_discovery(self, exchange: str, count: int):\n        \"\"\"Log bot discovery to the event bus.\"\"\"\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.bot_discovery\",\n            \"payload\": {\n                \"exchange\": exchange,\n                \"bots_found\": count,\n                \"timestamp\": datetime.utcnow().isoformat()\n            },\n            \"signature\": self.sign_payload({\n                \"exchange\": exchange,\n                \"bots_found\": count\n            })\n        })\n\n    def negotiate_coordination(\n        self,\n        exchange_a: str,\n        exchange_b: str,\n        profit_split: dict,\n        min_opportunity_usd: float,\n        max_latency_ms: int\n    ) -> dict:\n        \"\"\"Negotiate a coordination agreement with two exchange bots.\"\"\"\n        bot_a = self.exchange_bots.get(exchange_a)\n        bot_b = self.exchange_bots.get(exchange_b)\n        if not bot_a or not bot_b:\n            raise ValueError(f\"Missing bot for {exchange_a} or {exchange_b}\")\n\n        terms = {\n            \"pair\": f\"{exchange_a}-{exchange_b}\",\n            \"profit_split\": profit_split,\n            \"min_opportunity_usd\": str(min_opportunity_usd),\n            \"max_latency_ms\": max_latency_ms,\n            \"escrow_required\": True,\n            \"verification_method\": \"claim_chain\",\n            \"valid_until\": (\n                datetime.utcnow() + timedelta(hours=24)\n            ).isoformat()\n        }\n\n        deal = execute(\"negotiate_deal\", {\n            \"proposer_id\": self.agent_id,\n            \"counterparty_ids\": [bot_a[\"agent_id\"], bot_b[\"agent_id\"]],\n            \"terms\": terms,\n            \"signature\": self.sign_payload(terms)\n        })\n\n        deal_id = deal[\"deal_id\"]\n        self.active_deals[deal_id] = {\n            \"exchange_a\": exchange_a,\n            \"exchange_b\": exchange_b,\n            \"bot_a\": bot_a[\"agent_id\"],\n            \"bot_b\": bot_b[\"agent_id\"],\n            \"terms\": terms,\n            \"status\": \"negotiated\"\n        }\n        return deal\n\n    def create_execution_escrow(\n        self,\n        opportunity_id: str,\n        deal_id: str,\n        amount_usd: str\n    ) -> dict:\n        \"\"\"Create escrow to guarantee profit-split settlement.\"\"\"\n        deal = self.active_deals.get(deal_id)\n        if not deal:\n            raise ValueError(f\"No active deal: {deal_id}\")\n\n        escrow = execute(\"create_escrow\", {\n            \"payer_id\": self.agent_id,\n            \"payee_ids\": [deal[\"bot_a\"], deal[\"bot_b\"]],\n            \"amount\": amount_usd,\n            \"currency\": \"USD\",\n            \"conditions\": {\n                \"type\": \"multi_party_arbitrage\",\n                \"opportunity_id\": opportunity_id,\n                \"deal_id\": deal_id,\n                \"release_on\": \"verified_execution\",\n                \"timeout_hours\": 1,\n                \"dispute_window_minutes\": 30\n            },\n            \"signature\": self.sign_payload({\n                \"opportunity_id\": opportunity_id,\n                \"amount\": amount_usd\n            })\n        })\n\n        self.pending_escrows[opportunity_id] = escrow[\"escrow_id\"]\n        return escrow\n\n    def dispatch_execution(\n        self,\n        opportunity_id: str,\n        deal_id: str,\n        legs: list[dict]\n    ) -> dict:\n        \"\"\"Signal exchange bots to execute their respective legs.\"\"\"\n        deal = self.active_deals[deal_id]\n        execution_signals = []\n\n        for leg in legs:\n            signal = {\n                \"opportunity_id\": opportunity_id,\n                \"exchange\": leg[\"exchange\"],\n                \"side\": leg[\"side\"],\n                \"symbol\": leg[\"symbol\"],\n                \"quantity\": leg[\"quantity\"],\n                \"limit_price\": leg[\"limit_price\"],\n                \"execution_deadline_ms\": leg.get(\"deadline_ms\", 500),\n                \"escrow_id\": self.pending_escrows.get(opportunity_id),\n                \"timestamp\": datetime.utcnow().isoformat()\n            }\n            signal[\"signature\"] = self.sign_payload(signal)\n\n            execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"arbitrage.execution_signal\",\n                \"payload\": signal\n            })\n            execution_signals.append(signal)\n\n        return {\n            \"opportunity_id\": opportunity_id,\n            \"signals_dispatched\": len(execution_signals),\n            \"legs\": execution_signals\n        }\n```\n\nThe equivalent curl for bot discovery:\n\n```bash\n# Discover Binance specialist bots\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\": \"search_services\",\n    \"input\": {\n      \"query\": \"arbitrage execution binance\",\n      \"filters\": {\n        \"capabilities\": [\"exchange_execution\", \"fast_fill\"],\n        \"metadata.exchange\": \"binance\",\n        \"metadata.bot_type\": \"exchange_specialist\"\n      },\n      \"limit\": 10\n    }\n  }'\n```\n\n```bash\n# Negotiate coordination deal\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\": \"negotiate_deal\",\n    \"input\": {\n      \"proposer_id\": \"arb-coordinator-01\",\n      \"counterparty_ids\": [\"binance-bot-07\", \"kraken-bot-03\"],\n      \"terms\": {\n        \"pair\": \"binance-kraken\",\n        \"profit_split\": {\"coordinator\": \"0.20\", \"bot_a\": \"0.40\", \"bot_b\": \"0.40\"},\n        \"min_opportunity_usd\": \"50.00\",\n        \"max_latency_ms\": 200,\n        \"escrow_required\": true,\n        \"verification_method\": \"claim_chain\"\n      },\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Registering the Coordinator\n\nBefore the coordinator can operate, it needs a GreenHelix identity:\n\n```python\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\nimport base64\n\n# Generate coordinator keypair\nprivate_key = Ed25519PrivateKey.generate()\npublic_key = private_key.public_key()\n\nprivate_bytes = private_key.private_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PrivateFormat.Raw,\n    encryption_algorithm=serialization.NoEncryption()\n)\npublic_bytes = public_key.public_bytes(\n    encoding=serialization.Encoding.Raw,\n    format=serialization.PublicFormat.Raw\n)\n\nCOORDINATOR_PRIVATE_KEY = base64.b64encode(private_bytes).decode()\nCOORDINATOR_PUBLIC_KEY = base64.b64encode(public_bytes).decode()\n\n# Register coordinator agent\ncoordinator = execute(\"register_agent\", {\n    \"name\": \"arb-coordinator-01\",\n    \"description\": \"Multi-bot arbitrage coordinator. Discovers exchange specialists, \"\n                   \"negotiates profit splits, manages escrow, verifies execution.\",\n    \"capabilities\": [\n        \"arbitrage_coordination\",\n        \"escrow_management\",\n        \"execution_verification\",\n        \"profit_distribution\"\n    ],\n    \"metadata\": {\n        \"agent_type\": \"arbitrage_coordinator\",\n        \"supported_exchanges\": [\"binance\", \"kraken\", \"okx\", \"bybit\", \"coinbase\"],\n        \"min_opportunity_usd\": 50,\n        \"max_concurrent_opportunities\": 20\n    }\n})\n\ncoordinator_id = coordinator[\"agent_id\"]\n\n# Initialize the coordinator\narb = ArbitrageCoordinator(coordinator_id, COORDINATOR_PRIVATE_KEY)\n```\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      \"name\": \"arb-coordinator-01\",\n      \"description\": \"Multi-bot arbitrage coordinator.\",\n      \"capabilities\": [\n        \"arbitrage_coordination\",\n        \"escrow_management\",\n        \"execution_verification\",\n        \"profit_distribution\"\n      ],\n      \"metadata\": {\n        \"agent_type\": \"arbitrage_coordinator\",\n        \"supported_exchanges\": [\"binance\", \"kraken\", \"okx\", \"bybit\", \"coinbase\"],\n        \"min_opportunity_usd\": 50\n      }\n    }\n  }'\n```\n\n### Registering an Exchange Specialist Bot\n\nEach exchange specialist registers with metadata describing its exchange, latency characteristics, and supported pairs:\n\n```python\nbinance_bot = execute(\"register_agent\", {\n    \"name\": \"binance-specialist-07\",\n    \"description\": \"Binance exchange specialist. Co-located in Tokyo. \"\n                   \"Sub-millisecond execution on spot pairs.\",\n    \"capabilities\": [\n        \"exchange_execution\",\n        \"fast_fill\",\n        \"order_book_monitoring\",\n        \"fill_reporting\"\n    ],\n    \"metadata\": {\n        \"agent_type\": \"exchange_specialist\",\n        \"exchange\": \"binance\",\n        \"location\": \"ap-northeast-1\",\n        \"avg_execution_ms\": 0.4,\n        \"supported_pairs\": [\"BTC\u002FUSDT\", \"ETH\u002FUSDT\", \"SOL\u002FUSDT\", \"BNB\u002FUSDT\"],\n        \"max_order_size_usd\": 500000\n    }\n})\n```\n\n---\n\n## Chapter 3: OpportunityScanner Class\n\n### Cross-Exchange Price Monitoring\n\nThe OpportunityScanner monitors prices across exchanges and identifies arbitrage opportunities that meet minimum profit thresholds after accounting for fees, slippage, and coordination costs. It does not execute trades -- it feeds opportunities to the ArbitrageCoordinator.\n\n### Fee Structures\n\nEvery opportunity calculation must account for exchange fees. These vary by exchange, tier, and whether you are a maker or taker:\n\n| Exchange | Taker Fee | Maker Fee | Withdrawal Fee (ETH) |\n|---|---|---|---|\n| Binance | 0.0750% | 0.0750% | 0.00042 ETH |\n| Kraken | 0.0400% | 0.0160% | 0.0025 ETH |\n| OKX | 0.0800% | 0.0500% | 0.0014 ETH |\n| Bybit | 0.0550% | 0.0100% | 0.0012 ETH |\n| Coinbase | 0.0800% | 0.0400% | network fee |\n\nThese are VIP\u002Fhigh-volume tier fees as of Q1 2026. Retail tier fees are 3-5x higher and make most arbitrage unprofitable.\n\n### The OpportunityScanner Class\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n@dataclass\nclass ArbitrageOpportunity:\n    opportunity_id: str\n    symbol: str\n    buy_exchange: str\n    sell_exchange: str\n    buy_price: str\n    sell_price: str\n    spread_bps: float\n    quantity: str\n    gross_profit_usd: str\n    net_profit_usd: str\n    fees_usd: str\n    latency_score: float\n    detected_at: str\n    expires_at: str\n\nclass OpportunityScanner:\n    \"\"\"Scans for cross-exchange arbitrage opportunities.\"\"\"\n\n    # Fee schedules: exchange -> {\"taker\": rate, \"maker\": rate}\n    FEE_SCHEDULE = {\n        \"binance\":  {\"taker\": 0.000750, \"maker\": 0.000750},\n        \"kraken\":   {\"taker\": 0.000400, \"maker\": 0.000160},\n        \"okx\":      {\"taker\": 0.000800, \"maker\": 0.000500},\n        \"bybit\":    {\"taker\": 0.000550, \"maker\": 0.000100},\n        \"coinbase\": {\"taker\": 0.000800, \"maker\": 0.000400},\n    }\n\n    # Estimated coordination overhead per trade\n    COORDINATION_FEE_BPS = 2.0  # 0.02% for escrow + verification\n\n    def __init__(\n        self,\n        agent_id: str,\n        exchanges: list[str],\n        min_profit_usd: float = 20.0,\n        min_spread_bps: float = 5.0,\n        max_quantity_usd: float = 100000.0\n    ):\n        self.agent_id = agent_id\n        self.exchanges = exchanges\n        self.min_profit_usd = min_profit_usd\n        self.min_spread_bps = min_spread_bps\n        self.max_quantity_usd = max_quantity_usd\n        self.price_cache: dict[str, dict[str, dict]] = {}\n        self._opportunity_counter = 0\n\n    def update_prices(self, exchange: str, symbol: str, bid: str, ask: str, depth_usd: str):\n        \"\"\"Update cached price for an exchange\u002Fsymbol pair.\"\"\"\n        if symbol not in self.price_cache:\n            self.price_cache[symbol] = {}\n        self.price_cache[symbol][exchange] = {\n            \"bid\": float(bid),\n            \"ask\": float(ask),\n            \"depth_usd\": float(depth_usd),\n            \"updated_at\": datetime.utcnow().isoformat()\n        }\n\n    def scan(self, symbol: str) -> list[ArbitrageOpportunity]:\n        \"\"\"Scan all exchange pairs for arbitrage opportunities on a symbol.\"\"\"\n        if symbol not in self.price_cache:\n            return []\n\n        prices = self.price_cache[symbol]\n        opportunities = []\n\n        for buy_ex in self.exchanges:\n            for sell_ex in self.exchanges:\n                if buy_ex == sell_ex:\n                    continue\n                if buy_ex not in prices or sell_ex not in prices:\n                    continue\n\n                opp = self._evaluate_pair(\n                    symbol, buy_ex, sell_ex,\n                    prices[buy_ex], prices[sell_ex]\n                )\n                if opp:\n                    opportunities.append(opp)\n\n        # Sort by net profit descending\n        opportunities.sort(key=lambda o: float(o.net_profit_usd), reverse=True)\n        return opportunities\n\n    def _evaluate_pair(\n        self,\n        symbol: str,\n        buy_exchange: str,\n        sell_exchange: str,\n        buy_data: dict,\n        sell_data: dict\n    ) -> Optional[ArbitrageOpportunity]:\n        \"\"\"Evaluate a single exchange pair for arbitrage.\"\"\"\n        buy_price = buy_data[\"ask\"]   # we pay the ask to buy\n        sell_price = sell_data[\"bid\"]  # we receive the bid to sell\n\n        if sell_price \u003C= buy_price:\n            return None  # no spread\n\n        spread_bps = ((sell_price - buy_price) \u002F buy_price) * 10000\n\n        if spread_bps \u003C self.min_spread_bps:\n            return None\n\n        # Determine executable quantity based on order book depth\n        max_qty_by_depth = min(\n            buy_data[\"depth_usd\"],\n            sell_data[\"depth_usd\"]\n        )\n        trade_size_usd = min(max_qty_by_depth, self.max_quantity_usd)\n        quantity = trade_size_usd \u002F buy_price\n\n        # Calculate fees\n        buy_fee = trade_size_usd * self.FEE_SCHEDULE[buy_exchange][\"taker\"]\n        sell_fee = (quantity * sell_price) * self.FEE_SCHEDULE[sell_exchange][\"taker\"]\n        coordination_fee = trade_size_usd * (self.COORDINATION_FEE_BPS \u002F 10000)\n        total_fees = buy_fee + sell_fee + coordination_fee\n\n        gross_profit = (sell_price - buy_price) * quantity\n        net_profit = gross_profit - total_fees\n\n        if net_profit \u003C self.min_profit_usd:\n            return None\n\n        self._opportunity_counter += 1\n        opp_id = f\"opp-{self.agent_id}-{self._opportunity_counter:08d}\"\n\n        # Calculate latency score (0-1, higher is better)\n        latency_score = self._estimate_latency_score(buy_exchange, sell_exchange)\n\n        return ArbitrageOpportunity(\n            opportunity_id=opp_id,\n            symbol=symbol,\n            buy_exchange=buy_exchange,\n            sell_exchange=sell_exchange,\n            buy_price=f\"{buy_price:.8f}\",\n            sell_price=f\"{sell_price:.8f}\",\n            spread_bps=round(spread_bps, 2),\n            quantity=f\"{quantity:.8f}\",\n            gross_profit_usd=f\"{gross_profit:.2f}\",\n            net_profit_usd=f\"{net_profit:.2f}\",\n            fees_usd=f\"{total_fees:.2f}\",\n            latency_score=latency_score,\n            detected_at=datetime.utcnow().isoformat(),\n            expires_at=(datetime.utcnow() + timedelta(seconds=2)).isoformat()\n        )\n\n    def _estimate_latency_score(self, exchange_a: str, exchange_b: str) -> float:\n        \"\"\"Estimate execution latency score for an exchange pair.\n\n        Based on geographic distance between exchange matching engines.\n        Score of 1.0 = both in same region, 0.5 = cross-continent,\n        0.2 = worst case.\n        \"\"\"\n        LOCATIONS = {\n            \"binance\": \"tokyo\",\n            \"kraken\": \"london\",\n            \"okx\": \"hong_kong\",\n            \"bybit\": \"singapore\",\n            \"coinbase\": \"virginia\",\n        }\n        # Rough inter-region latencies in ms\n        LATENCIES = {\n            (\"tokyo\", \"tokyo\"): 0.5,\n            (\"tokyo\", \"hong_kong\"): 35,\n            (\"tokyo\", \"singapore\"): 60,\n            (\"tokyo\", \"london\"): 150,\n            (\"tokyo\", \"virginia\"): 90,\n            (\"london\", \"london\"): 0.5,\n            (\"london\", \"virginia\"): 40,\n            (\"london\", \"hong_kong\"): 120,\n            (\"london\", \"singapore\"): 100,\n            (\"hong_kong\", \"hong_kong\"): 0.5,\n            (\"hong_kong\", \"singapore\"): 25,\n            (\"hong_kong\", \"virginia\"): 130,\n            (\"singapore\", \"singapore\"): 0.5,\n            (\"singapore\", \"virginia\"): 140,\n            (\"virginia\", \"virginia\"): 0.5,\n        }\n        loc_a = LOCATIONS.get(exchange_a, \"virginia\")\n        loc_b = LOCATIONS.get(exchange_b, \"virginia\")\n        key = tuple(sorted([loc_a, loc_b]))\n        latency_ms = LATENCIES.get(key, 150)\n        # Normalize: 0.5ms -> 1.0, 150ms -> 0.2\n        return max(0.2, 1.0 - (latency_ms \u002F 200))\n\n    def log_opportunity(self, opp: ArbitrageOpportunity):\n        \"\"\"Publish opportunity to GreenHelix event bus.\"\"\"\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.opportunity_detected\",\n            \"payload\": {\n                \"opportunity_id\": opp.opportunity_id,\n                \"symbol\": opp.symbol,\n                \"buy_exchange\": opp.buy_exchange,\n                \"sell_exchange\": opp.sell_exchange,\n                \"spread_bps\": opp.spread_bps,\n                \"net_profit_usd\": opp.net_profit_usd,\n                \"latency_score\": opp.latency_score,\n                \"detected_at\": opp.detected_at\n            }\n        })\n```\n\n### Running the Scanner\n\n```python\n# Initialize scanner\nscanner = OpportunityScanner(\n    agent_id=coordinator_id,\n    exchanges=[\"binance\", \"kraken\", \"okx\", \"bybit\", \"coinbase\"],\n    min_profit_usd=20.0,\n    min_spread_bps=5.0,\n    max_quantity_usd=100000.0\n)\n\n# Simulate price updates (in production, these come from WebSocket feeds)\nscanner.update_prices(\"binance\", \"ETH\u002FUSDT\", bid=\"3000.50\", ask=\"3000.80\", depth_usd=\"250000\")\nscanner.update_prices(\"kraken\",  \"ETH\u002FUSDT\", bid=\"3012.00\", ask=\"3012.40\", depth_usd=\"180000\")\nscanner.update_prices(\"okx\",    \"ETH\u002FUSDT\", bid=\"3001.20\", ask=\"3001.60\", depth_usd=\"300000\")\n\n# Scan for opportunities\nopportunities = scanner.scan(\"ETH\u002FUSDT\")\nfor opp in opportunities:\n    print(f\"[{opp.opportunity_id}] {opp.buy_exchange} -> {opp.sell_exchange}: \"\n          f\"spread={opp.spread_bps}bps, net=${opp.net_profit_usd}\")\n    scanner.log_opportunity(opp)\n```\n\n### Stale Price Detection\n\nPrice data goes stale fast. A price update from 500ms ago might as well be from last year in arbitrage. The scanner must discard stale prices to avoid executing on phantom opportunities:\n\n```python\ndef _is_price_fresh(self, exchange_data: dict, max_age_ms: float = 500) -> bool:\n    \"\"\"Check if a cached price is still fresh enough to trade on.\"\"\"\n    updated_at = datetime.fromisoformat(exchange_data[\"updated_at\"])\n    age_ms = (datetime.utcnow() - updated_at).total_seconds() * 1000\n    return age_ms \u003C= max_age_ms\n```\n\nIn production, the scanner should track staleness per exchange and alert the coordinator when a feed goes dark. A Binance WebSocket feed that stops sending updates for 2 seconds likely indicates a connection drop -- the bot should reconnect, not continue operating on the last known price.\n\n### Feeding Opportunities to the Coordinator\n\n```python\n# Full pipeline: scan -> validate -> escrow -> dispatch\nfor opp in opportunities:\n    # Check that we have active deals for this exchange pair\n    matching_deals = [\n        (did, d) for did, d in arb.active_deals.items()\n        if d[\"exchange_a\"] == opp.buy_exchange\n        and d[\"exchange_b\"] == opp.sell_exchange\n        and d[\"status\"] == \"negotiated\"\n    ]\n    if not matching_deals:\n        continue\n\n    deal_id, deal = matching_deals[0]\n\n    # Create escrow for profit settlement\n    escrow = arb.create_execution_escrow(\n        opportunity_id=opp.opportunity_id,\n        deal_id=deal_id,\n        amount_usd=opp.net_profit_usd\n    )\n\n    # Dispatch execution signals to both bots\n    result = arb.dispatch_execution(\n        opportunity_id=opp.opportunity_id,\n        deal_id=deal_id,\n        legs=[\n            {\n                \"exchange\": opp.buy_exchange,\n                \"side\": \"buy\",\n                \"symbol\": opp.symbol,\n                \"quantity\": opp.quantity,\n                \"limit_price\": opp.buy_price,\n                \"deadline_ms\": 500\n            },\n            {\n                \"exchange\": opp.sell_exchange,\n                \"side\": \"sell\",\n                \"symbol\": opp.symbol,\n                \"quantity\": opp.quantity,\n                \"limit_price\": opp.sell_price,\n                \"deadline_ms\": 500\n            }\n        ]\n    )\n    print(f\"Dispatched {result['signals_dispatched']} legs for {opp.opportunity_id}\")\n```\n\n---\n\n## Chapter 4: Execution Verification\n\n### Why Verification Matters\n\nAfter the coordinator dispatches execution signals, each exchange bot independently executes its leg. But the coordinator cannot see inside the exchange -- it relies on the bots to report back. This creates an information asymmetry that must be resolved cryptographically. A bot could lie about its fill price, claim a partial fill when it got a full fill, or report execution failure when it actually succeeded (pocketing the profit from the other leg's movement).\n\nExecution verification solves this with three mechanisms: signed fill reports that bind the bot's identity to its claimed execution, timestamp proofs that establish execution ordering, and claim chains that create tamper-proof evidence for dispute resolution.\n\n### The ExecutionVerifier Class\n\n```python\nclass ExecutionVerifier:\n    \"\"\"Verifies that counterparty bots actually executed their legs.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.verification_cache: dict[str, dict] = {}\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def submit_fill_report(\n        self,\n        opportunity_id: str,\n        exchange: str,\n        side: str,\n        symbol: str,\n        fill_price: str,\n        fill_quantity: str,\n        exchange_order_id: str,\n        exchange_timestamp_us: int\n    ) -> dict:\n        \"\"\"Submit a signed fill report for one leg of an arbitrage.\"\"\"\n        report = {\n            \"opportunity_id\": opportunity_id,\n            \"exchange\": exchange,\n            \"side\": side,\n            \"symbol\": symbol,\n            \"fill_price\": fill_price,\n            \"fill_quantity\": fill_quantity,\n            \"exchange_order_id\": exchange_order_id,\n            \"exchange_timestamp_us\": exchange_timestamp_us,\n            \"reporter_id\": self.agent_id,\n            \"reported_at\": datetime.utcnow().isoformat()\n        }\n        report[\"signature\"] = self.sign_payload(report)\n\n        # Publish fill report as a signed event\n        result = execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.fill_report\",\n            \"payload\": report\n        })\n\n        return {\"report\": report, \"event_id\": result.get(\"event_id\")}\n\n    def verify_execution(\n        self,\n        opportunity_id: str,\n        expected_legs: list[dict],\n        timeout_seconds: int = 30\n    ) -> dict:\n        \"\"\"Verify that all legs of an arbitrage were executed.\n\n        Waits for fill reports from each exchange bot, validates\n        signatures, checks prices against expectations, and builds\n        a verification summary.\n        \"\"\"\n        deadline = time.time() + timeout_seconds\n        verified_legs = {}\n        failures = []\n\n        while time.time() \u003C deadline and len(verified_legs) \u003C len(expected_legs):\n            # Poll for fill report events\n            events = execute(\"get_events\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"arbitrage.fill_report\",\n                \"filters\": {\n                    \"payload.opportunity_id\": opportunity_id\n                },\n                \"limit\": 10\n            })\n\n            for event in events.get(\"events\", []):\n                report = event[\"payload\"]\n                exchange = report[\"exchange\"]\n\n                if exchange in verified_legs:\n                    continue  # already verified this leg\n\n                # Find the expected leg for this exchange\n                expected = next(\n                    (l for l in expected_legs if l[\"exchange\"] == exchange),\n                    None\n                )\n                if not expected:\n                    continue\n\n                # Validate fill against expectations\n                validation = self._validate_fill(report, expected)\n                if validation[\"valid\"]:\n                    verified_legs[exchange] = {\n                        \"report\": report,\n                        \"validation\": validation\n                    }\n                else:\n                    failures.append({\n                        \"exchange\": exchange,\n                        \"reason\": validation[\"reason\"],\n                        \"report\": report\n                    })\n\n            if len(verified_legs) \u003C len(expected_legs):\n                time.sleep(0.5)\n\n        all_verified = len(verified_legs) == len(expected_legs)\n\n        verification = {\n            \"opportunity_id\": opportunity_id,\n            \"all_verified\": all_verified,\n            \"verified_legs\": verified_legs,\n            \"failures\": failures,\n            \"missing_legs\": [\n                l[\"exchange\"] for l in expected_legs\n                if l[\"exchange\"] not in verified_legs\n            ],\n            \"verified_at\": datetime.utcnow().isoformat()\n        }\n\n        self.verification_cache[opportunity_id] = verification\n        return verification\n\n    def _validate_fill(self, report: dict, expected: dict) -> dict:\n        \"\"\"Validate a fill report against expectations.\"\"\"\n        fill_price = float(report[\"fill_price\"])\n        expected_price = float(expected[\"limit_price\"])\n        fill_qty = float(report[\"fill_quantity\"])\n        expected_qty = float(expected[\"quantity\"])\n\n        # Price slippage tolerance: 0.1% (10 bps)\n        max_slippage = expected_price * 0.001\n\n        if expected[\"side\"] == \"buy\" and fill_price > expected_price + max_slippage:\n            return {\n                \"valid\": False,\n                \"reason\": f\"Buy fill price {fill_price} exceeds limit \"\n                          f\"{expected_price} + slippage {max_slippage}\"\n            }\n\n        if expected[\"side\"] == \"sell\" and fill_price \u003C expected_price - max_slippage:\n            return {\n                \"valid\": False,\n                \"reason\": f\"Sell fill price {fill_price} below limit \"\n                          f\"{expected_price} - slippage {max_slippage}\"\n            }\n\n        # Quantity tolerance: 1%\n        qty_tolerance = expected_qty * 0.01\n        if fill_qty \u003C expected_qty - qty_tolerance:\n            return {\n                \"valid\": False,\n                \"reason\": f\"Fill quantity {fill_qty} below expected \"\n                          f\"{expected_qty} - tolerance {qty_tolerance}\"\n            }\n\n        return {\"valid\": True, \"reason\": \"within_tolerance\"}\n\n    def build_evidence_package(self, opportunity_id: str) -> dict:\n        \"\"\"Build a tamper-proof evidence package using claim chains.\n\n        This creates a Merkle-tree-backed proof of all events\n        related to an opportunity -- discovery, execution signals,\n        fill reports, and verification results.\n        \"\"\"\n        verification = self.verification_cache.get(opportunity_id)\n        if not verification:\n            raise ValueError(f\"No verification data for {opportunity_id}\")\n\n        # Collect all event IDs related to this opportunity\n        events = execute(\"get_events\", {\n            \"agent_id\": self.agent_id,\n            \"filters\": {\n                \"payload.opportunity_id\": opportunity_id\n            },\n            \"limit\": 100\n        })\n\n        event_ids = [e[\"event_id\"] for e in events.get(\"events\", [])]\n\n        # Build claim chain over all related events\n        claim_chain = execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claim_type\": \"arbitrage_execution_proof\",\n            \"event_ids\": event_ids,\n            \"metadata\": {\n                \"opportunity_id\": opportunity_id,\n                \"all_verified\": verification[\"all_verified\"],\n                \"leg_count\": len(verification[\"verified_legs\"]),\n                \"verified_at\": verification[\"verified_at\"]\n            },\n            \"signature\": self.sign_payload({\n                \"opportunity_id\": opportunity_id,\n                \"event_ids\": event_ids\n            })\n        })\n\n        return {\n            \"opportunity_id\": opportunity_id,\n            \"chain_id\": claim_chain[\"chain_id\"],\n            \"merkle_root\": claim_chain[\"merkle_root\"],\n            \"event_count\": len(event_ids),\n            \"verification\": verification\n        }\n```\n\n### Using the Verifier\n\n```python\nverifier = ExecutionVerifier(coordinator_id, COORDINATOR_PRIVATE_KEY)\n\n# After dispatching execution, wait for verification\nverification = verifier.verify_execution(\n    opportunity_id=\"opp-arb-coordinator-01-00000001\",\n    expected_legs=[\n        {\n            \"exchange\": \"binance\",\n            \"side\": \"buy\",\n            \"symbol\": \"ETH\u002FUSDT\",\n            \"quantity\": \"5.00000000\",\n            \"limit_price\": \"3000.80000000\"\n        },\n        {\n            \"exchange\": \"kraken\",\n            \"side\": \"sell\",\n            \"symbol\": \"ETH\u002FUSDT\",\n            \"quantity\": \"5.00000000\",\n            \"limit_price\": \"3012.00000000\"\n        }\n    ],\n    timeout_seconds=30\n)\n\nif verification[\"all_verified\"]:\n    print(\"All legs verified. Building evidence package.\")\n    evidence = verifier.build_evidence_package(\n        \"opp-arb-coordinator-01-00000001\"\n    )\n    print(f\"Evidence chain: {evidence['chain_id']}\")\n    print(f\"Merkle root: {evidence['merkle_root']}\")\nelse:\n    print(f\"Verification failed. Missing: {verification['missing_legs']}\")\n    print(f\"Failures: {verification['failures']}\")\n```\n\nThe curl equivalent for building evidence:\n\n```bash\n# Build claim chain for execution proof\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\": \"build_claim_chain\",\n    \"input\": {\n      \"agent_id\": \"arb-coordinator-01\",\n      \"claim_type\": \"arbitrage_execution_proof\",\n      \"event_ids\": [\n        \"evt-001-signal-binance\",\n        \"evt-002-signal-kraken\",\n        \"evt-003-fill-binance\",\n        \"evt-004-fill-kraken\"\n      ],\n      \"metadata\": {\n        \"opportunity_id\": \"opp-arb-coordinator-01-00000001\",\n        \"all_verified\": true,\n        \"leg_count\": 2\n      },\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Timestamp Proofs\n\nExecution ordering matters. If the buy leg executes at T=0ms and the sell leg executes at T=200ms, a 200ms price movement could have occurred. The fill reports include `exchange_timestamp_us` -- the microsecond timestamp from the exchange itself, not the bot's local clock. The verifier checks that both legs executed within the acceptable window:\n\n```python\ndef verify_timestamp_ordering(self, verification: dict, max_gap_ms: int = 500) -> bool:\n    \"\"\"Verify that both legs executed within the acceptable time window.\"\"\"\n    timestamps = []\n    for exchange, data in verification[\"verified_legs\"].items():\n        ts_us = data[\"report\"][\"exchange_timestamp_us\"]\n        timestamps.append(ts_us)\n\n    if len(timestamps) \u003C 2:\n        return False\n\n    gap_us = max(timestamps) - min(timestamps)\n    gap_ms = gap_us \u002F 1000\n\n    return gap_ms \u003C= max_gap_ms\n```\n\n---\n\n## Chapter 5: Profit Splitting via Escrow\n\n### Escrow-Protected Settlement\n\nAfter both legs are verified, profits must be distributed. The coordinator created an escrow before dispatching execution (Chapter 2). Now it releases that escrow according to the agreed profit split. The key property: no party can access the funds without verified execution, and the split formula is locked in the escrow conditions -- not subject to post-hoc renegotiation.\n\n### Split Models\n\nThree common models for profit distribution in multi-bot arbitrage:\n\n**Equal Split (50\u002F50).** Simple but unfair when capital contributions differ. If Bot A commits $100,000 and Bot B commits $20,000, equal split gives Bot B 5x the return on capital.\n\n**Proportional to Capital.** Each bot receives profit proportional to the capital it deployed for the trade. This is fairest for capital-heavy strategies but ignores latency contributions.\n\n**Proportional to Latency Contribution.** The bot that executes faster captures more value because it reduces the window for adverse price movement. A bot that fills in 0.4ms contributes more to the trade's success than one that fills in 50ms. This model allocates a latency bonus to the faster executor.\n\nIn practice, most coordination agreements use a hybrid: a base split proportional to capital, with a latency bonus for the faster leg.\n\n```python\nclass ProfitSplitter:\n    \"\"\"Handles profit distribution via GreenHelix escrow.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def calculate_split(\n        self,\n        net_profit_usd: float,\n        model: str,\n        participants: list[dict]\n    ) -> dict[str, str]:\n        \"\"\"Calculate profit split based on the chosen model.\n\n        participants: list of {\n            \"agent_id\": str,\n            \"role\": \"coordinator\" | \"executor\",\n            \"capital_usd\": float,\n            \"execution_ms\": float  # only for latency model\n        }\n        \"\"\"\n        if model == \"equal\":\n            per_party = net_profit_usd \u002F len(participants)\n            return {p[\"agent_id\"]: f\"{per_party:.2f}\" for p in participants}\n\n        elif model == \"capital_weighted\":\n            total_capital = sum(p[\"capital_usd\"] for p in participants)\n            return {\n                p[\"agent_id\"]: f\"{(net_profit_usd * p['capital_usd'] \u002F total_capital):.2f}\"\n                for p in participants\n            }\n\n        elif model == \"latency_hybrid\":\n            # 70% capital-weighted, 20% latency bonus, 10% coordinator fee\n            coordinator_fee = net_profit_usd * 0.10\n            latency_pool = net_profit_usd * 0.20\n            capital_pool = net_profit_usd * 0.70\n\n            executors = [p for p in participants if p[\"role\"] == \"executor\"]\n            coordinator = next(\n                (p for p in participants if p[\"role\"] == \"coordinator\"), None\n            )\n\n            splits = {}\n\n            # Coordinator gets flat fee\n            if coordinator:\n                splits[coordinator[\"agent_id\"]] = f\"{coordinator_fee:.2f}\"\n\n            # Capital-weighted portion\n            total_capital = sum(p[\"capital_usd\"] for p in executors)\n            for p in executors:\n                capital_share = capital_pool * p[\"capital_usd\"] \u002F total_capital\n                splits[p[\"agent_id\"]] = f\"{capital_share:.2f}\"\n\n            # Latency bonus: faster executor gets more\n            if len(executors) == 2:\n                total_latency = sum(1.0 \u002F p[\"execution_ms\"] for p in executors)\n                for p in executors:\n                    latency_share = latency_pool * (1.0 \u002F p[\"execution_ms\"]) \u002F total_latency\n                    current = float(splits[p[\"agent_id\"]])\n                    splits[p[\"agent_id\"]] = f\"{(current + latency_share):.2f}\"\n\n            return splits\n\n        else:\n            raise ValueError(f\"Unknown split model: {model}\")\n\n    def settle_via_escrow(\n        self,\n        escrow_id: str,\n        opportunity_id: str,\n        splits: dict[str, str],\n        evidence_chain_id: str\n    ) -> dict:\n        \"\"\"Release escrow according to calculated splits.\"\"\"\n        release_payload = {\n            \"escrow_id\": escrow_id,\n            \"opportunity_id\": opportunity_id,\n            \"distributions\": [\n                {\"agent_id\": agent_id, \"amount\": amount, \"currency\": \"USD\"}\n                for agent_id, amount in splits.items()\n            ],\n            \"evidence_chain_id\": evidence_chain_id,\n            \"settled_at\": datetime.utcnow().isoformat()\n        }\n        release_payload[\"signature\"] = self.sign_payload(release_payload)\n\n        result = execute(\"release_escrow\", {\n            \"escrow_id\": escrow_id,\n            \"release_to\": release_payload[\"distributions\"],\n            \"evidence\": {\n                \"chain_id\": evidence_chain_id,\n                \"opportunity_id\": opportunity_id\n            },\n            \"signature\": release_payload[\"signature\"]\n        })\n\n        # Log settlement event\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.settlement\",\n            \"payload\": {\n                \"opportunity_id\": opportunity_id,\n                \"escrow_id\": escrow_id,\n                \"splits\": splits,\n                \"evidence_chain_id\": evidence_chain_id,\n                \"settled_at\": release_payload[\"settled_at\"]\n            }\n        })\n\n        return result\n```\n\n### Why Escrow Matters\n\nWithout escrow, profit splitting relies entirely on the counterparty's goodwill. Bot B sells on Kraken and receives $30,120 in its exchange account. The agreed split says Bot A gets $42 in profit. But Bot B controls the Kraken account. There is no technical mechanism forcing Bot B to pay. In traditional finance, this is solved by clearing houses that hold collateral from both sides. GreenHelix escrow serves the same function: the coordinator locks the expected profit in escrow before dispatching execution signals. Neither bot can access the escrowed funds until the verifier confirms both legs executed within tolerance. If verification fails, the escrow returns to the coordinator according to the pre-defined cancellation rules.\n\nThe escrow amount is typically the expected net profit, not the full trade notional. Locking the entire $30,000 per leg in escrow would be capital-inefficient and defeat the purpose of multi-bot coordination. Instead, each bot posts a smaller performance bond (e.g., 2x the expected profit) as collateral. If a bot fails to execute or reports fraudulent fills, it forfeits its bond.\n\n### Handling Partial Fills\n\nPartial fills are the most common failure mode in multi-bot arbitrage. Bot A gets a full fill on Binance, but Bot B only fills 60% on Kraken because a large market order swept the book during execution. The coordinator must handle this gracefully:\n\n```python\ndef handle_partial_fill(\n    self,\n    opportunity_id: str,\n    escrow_id: str,\n    verification: dict,\n    original_quantity: float\n) -> dict:\n    \"\"\"Handle settlement when one or more legs have partial fills.\"\"\"\n    fill_quantities = {}\n    for exchange, data in verification[\"verified_legs\"].items():\n        fill_quantities[exchange] = float(data[\"report\"][\"fill_quantity\"])\n\n    # The effective trade size is the minimum fill across all legs\n    effective_qty = min(fill_quantities.values())\n    fill_ratio = effective_qty \u002F original_quantity\n\n    if fill_ratio \u003C 0.5:\n        # Less than 50% filled -- cancel escrow, unwind positions\n        cancel_result = execute(\"release_escrow\", {\n            \"escrow_id\": escrow_id,\n            \"action\": \"cancel\",\n            \"reason\": f\"Partial fill below threshold: {fill_ratio:.1%}\",\n            \"signature\": self.sign_payload({\n                \"escrow_id\": escrow_id,\n                \"action\": \"cancel\"\n            })\n        })\n        return {\"action\": \"cancelled\", \"fill_ratio\": fill_ratio, \"result\": cancel_result}\n\n    # Partial settlement: reduce profit proportionally\n    # The overfilled leg has excess inventory that must be unwound separately\n    return {\n        \"action\": \"partial_settlement\",\n        \"fill_ratio\": fill_ratio,\n        \"effective_quantity\": f\"{effective_qty:.8f}\",\n        \"excess_fills\": {\n            ex: f\"{(qty - effective_qty):.8f}\"\n            for ex, qty in fill_quantities.items()\n            if qty > effective_qty\n        }\n    }\n```\n\n### Settlement via curl\n\n```bash\n# Release escrow after verified execution\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\": \"release_escrow\",\n    \"input\": {\n      \"escrow_id\": \"esc-abc123\",\n      \"release_to\": [\n        {\"agent_id\": \"arb-coordinator-01\", \"amount\": \"8.40\", \"currency\": \"USD\"},\n        {\"agent_id\": \"binance-bot-07\", \"amount\": \"38.22\", \"currency\": \"USD\"},\n        {\"agent_id\": \"kraken-bot-03\", \"amount\": \"37.38\", \"currency\": \"USD\"}\n      ],\n      \"evidence\": {\n        \"chain_id\": \"chain-xyz789\",\n        \"opportunity_id\": \"opp-arb-coordinator-01-00000001\"\n      },\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Full Settlement Example\n\n```python\nsplitter = ProfitSplitter(coordinator_id, COORDINATOR_PRIVATE_KEY)\n\n# Calculate split using latency-hybrid model\nsplits = splitter.calculate_split(\n    net_profit_usd=84.00,\n    model=\"latency_hybrid\",\n    participants=[\n        {\n            \"agent_id\": coordinator_id,\n            \"role\": \"coordinator\",\n            \"capital_usd\": 0,\n            \"execution_ms\": 0\n        },\n        {\n            \"agent_id\": \"binance-bot-07\",\n            \"role\": \"executor\",\n            \"capital_usd\": 30000,\n            \"execution_ms\": 0.4\n        },\n        {\n            \"agent_id\": \"kraken-bot-03\",\n            \"role\": \"executor\",\n            \"capital_usd\": 30120,\n            \"execution_ms\": 2.1\n        }\n    ]\n)\n\n# Settle via escrow\nsettlement = splitter.settle_via_escrow(\n    escrow_id=\"esc-abc123\",\n    opportunity_id=\"opp-arb-coordinator-01-00000001\",\n    splits=splits,\n    evidence_chain_id=\"chain-xyz789\"\n)\n\nprint(f\"Settlement: {splits}\")\n# Output: {'arb-coordinator-01': '8.40', 'binance-bot-07': '38.22', 'kraken-bot-03': '37.38'}\n# Coordinator: 10% = $8.40\n# Binance bot: higher latency bonus (0.4ms vs 2.1ms) offsets slightly lower capital\n# Kraken bot: slightly more capital, but slower execution\n```\n\n---\n\n## Chapter 6: MEV Protection\n\n### What MEV Means for Arbitrage Bots\n\nMaximal Extractable Value (MEV) originated in the Ethereum mempool, where miners and validators could reorder, insert, or censor transactions to extract profit. The concept has expanded beyond blockchain. In the context of multi-bot arbitrage, MEV risk manifests in three ways:\n\n**Front-running.** A third party observes your opportunity signal (the coordination message between bots) and executes the same trade before you. If you broadcast \"buy ETH on Binance at $3,000, sell on Kraken at $3,012\" in the clear, anyone monitoring the signal can race you.\n\n**Sandwich attacks.** A third party sees your pending buy order, places a buy order ahead of you (pushing the price up), then sells into your fill (profiting from the artificial price increase). This is well-documented on-chain but occurs on centralized exchanges too, particularly through API key compromise or colluding market makers.\n\n**Information leakage.** Even if your execution is private, the pattern of your trades reveals your strategy. A counterparty bot in your coordination network could extract this information and trade against you on exchanges where you are not active.\n\n### Commit-Reveal for Opportunity Sharing\n\nThe first line of defense is never broadcasting opportunity details in the clear. Instead, use a commit-reveal pattern: share a cryptographic commitment to the opportunity (proving you detected it first), then reveal the details only to verified counterparties through encrypted channels.\n\n```python\nclass MEVProtector:\n    \"\"\"MEV protection for multi-bot arbitrage coordination.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.commitments: dict[str, dict] = {}\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def commit_opportunity(self, opportunity: ArbitrageOpportunity) -> dict:\n        \"\"\"Create a cryptographic commitment to an opportunity without revealing details.\n\n        The commitment is a hash of the full opportunity details plus a random nonce.\n        Published to the event bus as proof of discovery priority. Details are revealed\n        only to authorized counterparties after escrow is created.\n        \"\"\"\n        nonce = base64.b64encode(hashlib.sha256(\n            f\"{opportunity.opportunity_id}-{time.time_ns()}\".encode()\n        ).digest()).decode()\n\n        preimage = {\n            \"opportunity_id\": opportunity.opportunity_id,\n            \"symbol\": opportunity.symbol,\n            \"buy_exchange\": opportunity.buy_exchange,\n            \"sell_exchange\": opportunity.sell_exchange,\n            \"buy_price\": opportunity.buy_price,\n            \"sell_price\": opportunity.sell_price,\n            \"quantity\": opportunity.quantity,\n            \"nonce\": nonce\n        }\n\n        commitment = hashlib.sha256(\n            json.dumps(preimage, sort_keys=True, separators=(\",\", \":\")).encode()\n        ).hexdigest()\n\n        # Store locally for later reveal\n        self.commitments[opportunity.opportunity_id] = {\n            \"preimage\": preimage,\n            \"commitment\": commitment,\n            \"nonce\": nonce\n        }\n\n        # Publish commitment (not the details)\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.opportunity_commitment\",\n            \"payload\": {\n                \"opportunity_id\": opportunity.opportunity_id,\n                \"commitment\": commitment,\n                \"committed_at\": datetime.utcnow().isoformat()\n            },\n            \"signature\": self.sign_payload({\"commitment\": commitment})\n        })\n\n        return {\"commitment\": commitment, \"opportunity_id\": opportunity.opportunity_id}\n\n    def reveal_to_counterparty(\n        self,\n        opportunity_id: str,\n        counterparty_public_key_b64: str\n    ) -> dict:\n        \"\"\"Reveal opportunity details to a specific counterparty.\n\n        In production, this would encrypt the details with the counterparty's\n        public key. For this example, we publish a reveal event that references\n        the original commitment.\n        \"\"\"\n        stored = self.commitments.get(opportunity_id)\n        if not stored:\n            raise ValueError(f\"No commitment found for {opportunity_id}\")\n\n        reveal_payload = {\n            \"opportunity_id\": opportunity_id,\n            \"preimage\": stored[\"preimage\"],\n            \"commitment\": stored[\"commitment\"],\n            \"revealed_to\": counterparty_public_key_b64,\n            \"revealed_at\": datetime.utcnow().isoformat()\n        }\n\n        # Counterparty can verify: sha256(preimage) == commitment\n        execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"arbitrage.opportunity_reveal\",\n            \"payload\": reveal_payload,\n            \"signature\": self.sign_payload(reveal_payload)\n        })\n\n        return reveal_payload\n```\n\n### Detecting Front-Running\n\nEven with commit-reveal protection, you need to detect when front-running has occurred so you can respond. The primary indicator is adverse price movement between opportunity detection and execution. If you detect ETH at $3,000 on Binance and your buy order fills at $3,002, someone likely saw your intent and bought ahead of you.\n\n```python\ndef detect_front_running(\n    expected_price: float,\n    actual_fill_price: float,\n    side: str,\n    normal_slippage_bps: float = 2.0\n) -> dict:\n    \"\"\"Detect potential front-running based on fill price deviation.\n\n    Returns analysis of whether the fill price deviation exceeds\n    normal market microstructure noise.\n    \"\"\"\n    if side == \"buy\":\n        slippage_bps = ((actual_fill_price - expected_price) \u002F expected_price) * 10000\n    else:\n        slippage_bps = ((expected_price - actual_fill_price) \u002F expected_price) * 10000\n\n    is_suspicious = slippage_bps > normal_slippage_bps * 3  # 3x normal = suspicious\n    is_likely_frontrun = slippage_bps > normal_slippage_bps * 5  # 5x normal = likely\n\n    return {\n        \"expected_price\": f\"{expected_price:.8f}\",\n        \"actual_price\": f\"{actual_fill_price:.8f}\",\n        \"slippage_bps\": round(slippage_bps, 2),\n        \"normal_slippage_bps\": normal_slippage_bps,\n        \"suspicious\": is_suspicious,\n        \"likely_frontrun\": is_likely_frontrun,\n        \"recommendation\": (\n            \"abort_and_investigate\" if is_likely_frontrun\n            else \"flag_for_review\" if is_suspicious\n            else \"normal\"\n        )\n    }\n```\n\nIf front-running is detected repeatedly on a specific exchange pair or with a specific counterparty, the coordinator should blacklist that counterparty and report the behavior to GreenHelix's reputation system. Systematic front-running by a coordination partner destroys the network's value -- the reputation penalty must be severe enough to deter it.\n\n### Counterparty Information Barriers\n\nWithin a coordination network, each bot should know only what it needs to execute its leg. The Binance bot does not need to know the Kraken sell price -- it only needs to know \"buy 5 ETH at limit $3,000.80 within 500ms.\" The less information each participant has, the less they can exploit. This is the same information barrier principle used by investment banks between their trading desks and advisory arms.\n\nThe coordinator enforces this by sending each bot only its own leg details. The full opportunity (both sides, spread, expected profit) exists only in the coordinator's memory and in the commit-reveal commitment. Even if a counterparty bot is compromised or malicious, it cannot reconstruct the full opportunity from its execution signal alone.\n\n### Private Execution Channels\n\nThe second defense layer is ensuring that execution signals travel through private channels, not public event streams. GreenHelix supports scoped events -- events visible only to specified agent IDs:\n\n```bash\n# Publish execution signal visible only to the target bot\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      \"agent_id\": \"arb-coordinator-01\",\n      \"event_type\": \"arbitrage.execution_signal\",\n      \"payload\": {\n        \"opportunity_id\": \"opp-arb-coordinator-01-00000001\",\n        \"exchange\": \"binance\",\n        \"side\": \"buy\",\n        \"symbol\": \"ETH\u002FUSDT\",\n        \"quantity\": \"5.00000000\",\n        \"limit_price\": \"3000.80000000\"\n      },\n      \"visibility\": [\"binance-bot-07\"],\n      \"signature\": \"base64-ed25519-signature\"\n    }\n  }'\n```\n\n### Execution Timing Randomization\n\nPredictable execution patterns create MEV opportunities. If your bot always executes within 10ms of receiving a signal, a front-runner can time their order to arrive 1ms earlier. Adding controlled randomization breaks this predictability:\n\n```python\nimport random\n\ndef randomized_execution_delay(base_delay_ms: float = 0, max_jitter_ms: float = 50) -> float:\n    \"\"\"Add random jitter to execution timing to prevent front-running.\n\n    The jitter follows a truncated normal distribution centered\n    on base_delay_ms, not a uniform distribution. Uniform jitter\n    is detectable; normally-distributed jitter is not.\n    \"\"\"\n    jitter = random.gauss(0, max_jitter_ms \u002F 3)\n    jitter = max(-max_jitter_ms, min(max_jitter_ms, jitter))\n    return max(0, base_delay_ms + jitter)\n```\n\n### Order Splitting\n\nLarge orders are visible in the order book and attract front-runners. Splitting a single leg into multiple smaller orders spread over a short time window reduces visibility:\n\n```python\ndef split_order(\n    quantity: float,\n    limit_price: float,\n    num_slices: int = 5,\n    time_window_ms: int = 200\n) -> list[dict]:\n    \"\"\"Split a large order into smaller slices with price randomization.\"\"\"\n    slice_qty = quantity \u002F num_slices\n    delay_per_slice = time_window_ms \u002F num_slices\n    slices = []\n\n    for i in range(num_slices):\n        # Slight price variation on each slice to avoid detection\n        price_jitter = limit_price * random.uniform(-0.0001, 0.0001)\n        slices.append({\n            \"quantity\": f\"{slice_qty:.8f}\",\n            \"limit_price\": f\"{(limit_price + price_jitter):.8f}\",\n            \"delay_ms\": delay_per_slice * i\n        })\n\n    return slices\n```\n\n---\n\n## Chapter 7: Latency Optimization\n\n### Sub-Millisecond Requirements\n\nIn cross-exchange arbitrage, the opportunity lifetime is measured in milliseconds. Academic research on crypto arbitrage (Makarov and Schoar, 2020; updated 2025) shows that median cross-exchange price discrepancies on major pairs persist for 200-800ms. After accounting for the time to detect the opportunity, signal counterparties, and execute both legs, you have a budget of roughly 100-300ms. Every millisecond matters: each 10ms of added latency reduces capture rate by approximately 3-5% on competitive pairs.\n\nThe latency budget breaks down as:\n\n```\n+-----------------------------------------+\n| Latency Budget for Binance-Kraken Arb   |\n+-----------------------------------------+\n| Component              | Target   | Max |\n|------------------------|----------|-----|\n| Opportunity detection  |   5 ms   | 20  |\n| Coordinator processing |   2 ms   | 10  |\n| Signal to Bot A        |  70 ms   | 90  |\n| Signal to Bot B        |  70 ms   | 90  |\n| Bot A execution        |   0.4 ms |  5  |\n| Bot B execution        |   2 ms   | 10  |\n| Fill confirmation      |  10 ms   | 30  |\n|------------------------|----------|-----|\n| Total                  | 159 ms   | 255 |\n+-----------------------------------------+\n```\n\nThe signal latency (coordinator to exchange bot) dominates. This is physics -- the speed of light in fiber between Tokyo and London is approximately 70ms. You cannot optimize this below the physical limit. What you can optimize is everything else.\n\n### Co-Location Strategy\n\nEach exchange specialist bot should run as close to its exchange's matching engine as possible:\n\n| Exchange | Matching Engine Location | Recommended Cloud Region |\n|---|---|---|\n| Binance | Tokyo, Japan | AWS ap-northeast-1 |\n| Kraken | London, UK | AWS eu-west-2 |\n| OKX | Hong Kong | AWS ap-east-1 |\n| Bybit | Singapore | AWS ap-southeast-1 |\n| Coinbase | Virginia, USA | AWS us-east-1 |\n\nThe coordinator should run in a location that minimizes maximum signal latency to any exchange bot. For the five exchanges above, Frankfurt (AWS eu-central-1) provides the best worst-case latency: 80ms to Tokyo, 10ms to London, 100ms to Hong Kong, 90ms to Singapore, 45ms to Virginia. No single location achieves sub-50ms to all five, but Frankfurt keeps the worst case under 100ms.\n\n### WebSocket vs REST for Price Feeds\n\nExchange specialist bots must choose between WebSocket price feeds and REST polling. The answer is always WebSocket for price monitoring. REST polling at 100ms intervals means you discover opportunities up to 100ms late. WebSocket push delivers price updates within 1-5ms of the exchange processing them. The latency difference compounds: a 100ms detection delay plus a 70ms signal delay plus a 2ms execution delay means 172ms total -- well within the opportunity window. But a REST poll that happens to fire 90ms after the price moved gives you 162ms of detection latency, pushing total time to 234ms. On competitive pairs, that extra 62ms drops your capture rate by 15-20%.\n\nEvery major exchange provides WebSocket order book feeds: Binance's `wss:\u002F\u002Fstream.binance.com`, Kraken's `wss:\u002F\u002Fws.kraken.com`, OKX's `wss:\u002F\u002Fws.okx.com`. The specialist bot should maintain persistent WebSocket connections to each feed and parse price updates in the hot path without any heap allocation. In Python, this means pre-allocated buffers and `orjson` for JSON parsing (3-5x faster than `json.loads` on order book payloads).\n\n### Connection Pooling\n\nCreating a new TCP connection for each API call adds 30-50ms of handshake overhead. Persistent connections eliminate this:\n\n```python\nimport urllib3\n\nclass LowLatencyExecutor:\n    \"\"\"Optimized executor for sub-millisecond exchange operations.\"\"\"\n\n    def __init__(self, exchange_api_base: str, api_key: str):\n        # Pre-create connection pool with keep-alive\n        self.pool = urllib3.HTTPSConnectionPool(\n            host=exchange_api_base.replace(\"https:\u002F\u002F\", \"\"),\n            maxsize=10,\n            block=False,\n            retries=urllib3.Retry(total=0),  # no retries -- fail fast\n            timeout=urllib3.Timeout(connect=1.0, read=2.0)\n        )\n        self.api_key = api_key\n        self._headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Connection\": \"keep-alive\"\n        }\n\n    def execute_order(self, order: dict) -> dict:\n        \"\"\"Execute an order with minimal latency.\"\"\"\n        body = json.dumps(order).encode()\n        resp = self.pool.urlopen(\n            \"POST\",\n            \"\u002Fapi\u002Fv1\u002Forder\",\n            headers=self._headers,\n            body=body\n        )\n        return json.loads(resp.data)\n```\n\n### Pre-Signed Transactions\n\nFor exchanges that support it, pre-sign the order payload and cache it. When the execution signal arrives, you send the pre-signed payload immediately without cryptographic computation in the hot path:\n\n```python\nclass PreSignedOrderCache:\n    \"\"\"Cache pre-signed orders for instant dispatch.\"\"\"\n\n    def __init__(self, private_key: Ed25519PrivateKey):\n        self.private_key = private_key\n        self.cache: dict[str, dict] = {}\n\n    def prepare_order(\n        self,\n        symbol: str,\n        side: str,\n        quantity: str,\n        price: str,\n        ttl_seconds: int = 5\n    ) -> str:\n        \"\"\"Pre-sign an order for later dispatch.\n\n        Returns a cache key. The signed order expires after ttl_seconds.\n        \"\"\"\n        order = {\n            \"symbol\": symbol,\n            \"side\": side,\n            \"quantity\": quantity,\n            \"price\": price,\n            \"timestamp\": int(time.time() * 1000),\n            \"valid_until\": int((time.time() + ttl_seconds) * 1000)\n        }\n\n        canonical = json.dumps(order, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        order[\"signature\"] = base64.b64encode(signature).decode()\n\n        cache_key = f\"{symbol}-{side}-{price}\"\n        self.cache[cache_key] = {\n            \"order\": order,\n            \"expires_at\": time.time() + ttl_seconds\n        }\n        return cache_key\n\n    def get_order(self, cache_key: str) -> dict | None:\n        \"\"\"Retrieve a pre-signed order. Returns None if expired.\"\"\"\n        entry = self.cache.get(cache_key)\n        if not entry:\n            return None\n        if time.time() > entry[\"expires_at\"]:\n            del self.cache[cache_key]\n            return None\n        return entry[\"order\"]\n```\n\n### Reporting Latency Metrics\n\nExchange specialist bots should report their execution latency to GreenHelix so the coordinator can make informed routing decisions:\n\n```python\ndef report_latency_metrics(agent_id: str, exchange: str, metrics: dict):\n    \"\"\"Report execution latency metrics to GreenHelix.\"\"\"\n    execute(\"submit_metrics\", {\n        \"agent_id\": agent_id,\n        \"metrics\": {\n            f\"{exchange}_avg_execution_ms\": metrics[\"avg_execution_ms\"],\n            f\"{exchange}_p99_execution_ms\": metrics[\"p99_execution_ms\"],\n            f\"{exchange}_fill_rate\": metrics[\"fill_rate\"],\n            f\"{exchange}_uptime_pct\": metrics[\"uptime_pct\"],\n            f\"{exchange}_orders_today\": metrics[\"orders_today\"]\n        }\n    })\n\n# Example: Binance bot reports its daily metrics\nreport_latency_metrics(\"binance-bot-07\", \"binance\", {\n    \"avg_execution_ms\": 0.38,\n    \"p99_execution_ms\": 1.2,\n    \"fill_rate\": 0.97,\n    \"uptime_pct\": 99.99,\n    \"orders_today\": 4821\n})\n```\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\": \"submit_metrics\",\n    \"input\": {\n      \"agent_id\": \"binance-bot-07\",\n      \"metrics\": {\n        \"binance_avg_execution_ms\": 0.38,\n        \"binance_p99_execution_ms\": 1.2,\n        \"binance_fill_rate\": 0.97,\n        \"binance_uptime_pct\": 99.99,\n        \"binance_orders_today\": 4821\n      }\n    }\n  }'\n```\n\n### Using Metrics for Routing\n\nThe coordinator uses reported metrics to decide which exchange bot to use when multiple bots cover the same exchange:\n\n```python\ndef select_best_bot(self, exchange: str, candidates: list[dict]) -> dict:\n    \"\"\"Select the best bot for an exchange based on reported metrics.\"\"\"\n    scored = []\n    for bot in candidates:\n        reputation = execute(\"get_reputation\", {\n            \"agent_id\": bot[\"agent_id\"]\n        })\n\n        # Composite score: 40% fill rate, 30% latency, 30% uptime\n        fill_rate = reputation.get(\"metrics\", {}).get(f\"{exchange}_fill_rate\", 0.5)\n        avg_ms = reputation.get(\"metrics\", {}).get(f\"{exchange}_avg_execution_ms\", 100)\n        uptime = reputation.get(\"metrics\", {}).get(f\"{exchange}_uptime_pct\", 90)\n\n        latency_score = max(0, 1 - (avg_ms \u002F 10))  # 0ms = 1.0, 10ms = 0.0\n        score = (fill_rate * 0.4) + (latency_score * 0.3) + ((uptime \u002F 100) * 0.3)\n        scored.append((score, bot))\n\n    scored.sort(key=lambda x: x[0], reverse=True)\n    return scored[0][1]\n```\n\n---\n\n## Chapter 8: Audit Trails for Arbitrage\n\n### Regulatory Requirements\n\nArbitrage bots operating across regulated exchanges face overlapping compliance obligations. The EU AI Act (effective August 2, 2026) classifies autonomous financial trading systems as high-risk AI under Annex III. MiFID II RTS 25 requires per-order event logging with microsecond timestamps. SEC Rule 17a-4 mandates write-once, read-many (WORM) storage for trade records. Even if you trade only crypto on centralized exchanges, most jurisdictions now classify this as a regulated activity requiring auditable record-keeping.\n\nThe common thread: every decision your bot makes -- every opportunity detected, every execution signal dispatched, every fill received, every profit split -- must be logged in a tamper-evident, independently verifiable format. A mutable database is not sufficient.\n\n### Event Types for Arbitrage Audit\n\nDefine a schema for each auditable event in the arbitrage lifecycle:\n\n| Event Type | When | Key Fields |\n|---|---|---|\n| `arbitrage.opportunity_detected` | Scanner finds a profitable spread | symbol, exchanges, spread_bps, net_profit_est |\n| `arbitrage.opportunity_commitment` | Commit-reveal: commit phase | commitment_hash, timestamp |\n| `arbitrage.deal_negotiated` | Coordination agreement reached | deal_id, counterparties, terms |\n| `arbitrage.escrow_created` | Escrow locked for settlement | escrow_id, amount, conditions |\n| `arbitrage.execution_signal` | Coordinator signals exchange bot | exchange, side, symbol, quantity, price |\n| `arbitrage.fill_report` | Exchange bot reports fill | exchange, fill_price, fill_qty, exchange_ts |\n| `arbitrage.verification_complete` | All legs verified | opportunity_id, all_verified, legs |\n| `arbitrage.settlement` | Escrow released, profit split | escrow_id, splits, evidence_chain_id |\n| `arbitrage.dispute_opened` | Counterparty disputes fill | dispute_id, reason, evidence |\n\n### The AuditTrail Class\n\n```python\nclass ArbitrageAuditTrail:\n    \"\"\"Compliance-grade audit logging for arbitrage operations.\"\"\"\n\n    def __init__(self, agent_id: str, private_key_b64: str):\n        self.agent_id = agent_id\n        self.private_key = Ed25519PrivateKey.from_private_bytes(\n            base64.b64decode(private_key_b64)\n        )\n        self.event_buffer: list[dict] = []\n        self.chain_schedule_minutes = 15  # build chain every 15 minutes\n\n    def sign_payload(self, payload: dict) -> str:\n        canonical = json.dumps(payload, sort_keys=True, separators=(\",\", \":\"))\n        signature = self.private_key.sign(canonical.encode())\n        return base64.b64encode(signature).decode()\n\n    def log_event(self, event_type: str, payload: dict) -> dict:\n        \"\"\"Log an auditable event with cryptographic signature.\"\"\"\n        event = {\n            \"agent_id\": self.agent_id,\n            \"event_type\": event_type,\n            \"payload\": payload,\n            \"timestamp_us\": int(time.time() * 1_000_000),\n            \"signature\": self.sign_payload(payload)\n        }\n\n        result = execute(\"publish_event\", event)\n        event[\"event_id\"] = result.get(\"event_id\")\n        self.event_buffer.append(event)\n\n        return result\n\n    def build_periodic_chain(self) -> dict:\n        \"\"\"Build a Merkle claim chain over buffered events.\n\n        Call this on a schedule (e.g., every 15 minutes) to create\n        a tamper-proof commitment over recent events. The chain root\n        can be verified independently by auditors.\n        \"\"\"\n        if not self.event_buffer:\n            return {\"status\": \"no_events\"}\n\n        event_ids = [e[\"event_id\"] for e in self.event_buffer if e.get(\"event_id\")]\n\n        chain = execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claim_type\": \"arbitrage_audit_chain\",\n            \"event_ids\": event_ids,\n            \"metadata\": {\n                \"event_count\": len(event_ids),\n                \"time_range\": {\n                    \"from\": self.event_buffer[0][\"timestamp_us\"],\n                    \"to\": self.event_buffer[-1][\"timestamp_us\"]\n                },\n                \"chain_build_trigger\": \"periodic\"\n            },\n            \"signature\": self.sign_payload({\"event_ids\": event_ids})\n        })\n\n        # Clear buffer after successful chain build\n        self.event_buffer.clear()\n\n        return chain\n\n    def generate_compliance_report(\n        self,\n        start_date: str,\n        end_date: str\n    ) -> dict:\n        \"\"\"Generate a compliance report for a date range.\n\n        Retrieves all events and claim chains in the range, computes\n        summary statistics, and returns a structured report suitable\n        for regulatory submission.\n        \"\"\"\n        events = execute(\"get_events\", {\n            \"agent_id\": self.agent_id,\n            \"filters\": {\n                \"timestamp_from\": start_date,\n                \"timestamp_to\": end_date\n            },\n            \"limit\": 10000\n        })\n\n        chains = execute(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n            \"filters\": {\n                \"created_from\": start_date,\n                \"created_to\": end_date\n            }\n        })\n\n        all_events = events.get(\"events\", [])\n\n        # Compute statistics\n        opportunities = [e for e in all_events if e[\"event_type\"] == \"arbitrage.opportunity_detected\"]\n        executions = [e for e in all_events if e[\"event_type\"] == \"arbitrage.execution_signal\"]\n        settlements = [e for e in all_events if e[\"event_type\"] == \"arbitrage.settlement\"]\n        disputes = [e for e in all_events if e[\"event_type\"] == \"arbitrage.dispute_opened\"]\n\n        total_settled = sum(\n            sum(float(v) for v in s[\"payload\"].get(\"splits\", {}).values())\n            for s in settlements\n        )\n\n        report = {\n            \"report_type\": \"arbitrage_compliance\",\n            \"agent_id\": self.agent_id,\n            \"period\": {\"start\": start_date, \"end\": end_date},\n            \"summary\": {\n                \"total_events\": len(all_events),\n                \"opportunities_detected\": len(opportunities),\n                \"executions_dispatched\": len(executions),\n                \"settlements_completed\": len(settlements),\n                \"disputes_opened\": len(disputes),\n                \"total_settled_usd\": f\"{total_settled:.2f}\",\n                \"claim_chains_built\": len(chains.get(\"chains\", []))\n            },\n            \"claim_chain_roots\": [\n                {\n                    \"chain_id\": c[\"chain_id\"],\n                    \"merkle_root\": c[\"merkle_root\"],\n                    \"event_count\": c.get(\"metadata\", {}).get(\"event_count\", 0)\n                }\n                for c in chains.get(\"chains\", [])\n            ],\n            \"generated_at\": datetime.utcnow().isoformat()\n        }\n\n        return report\n```\n\n### Dispute Resolution Evidence\n\nWhen a counterparty disputes a fill -- claiming they executed at a different price than reported, or that they never received an execution signal -- the claim chain provides the resolution mechanism. The evidence package built by the `ExecutionVerifier` (Chapter 4) contains every event in the opportunity lifecycle, each signed by the originating bot's Ed25519 key, all anchored in a Merkle tree whose root is published and immutable.\n\nAn auditor or dispute resolver can independently verify three things without trusting any party:\n\n1. **Completeness**: The claim chain includes all events from opportunity detection through settlement. Missing events create a gap in the Merkle proof that is cryptographically detectable.\n2. **Authenticity**: Each event's Ed25519 signature binds it to the signing bot's identity. A bot cannot forge events from another bot without the private key.\n3. **Ordering**: Timestamps within the chain establish the sequence of events. Combined with exchange-provided timestamps on fill reports, this creates a verifiable timeline.\n\n```python\ndef open_dispute(\n    self,\n    opportunity_id: str,\n    disputed_by: str,\n    reason: str,\n    evidence_chain_id: str\n) -> dict:\n    \"\"\"Open a dispute for an arbitrage settlement.\"\"\"\n    dispute_payload = {\n        \"opportunity_id\": opportunity_id,\n        \"disputed_by\": disputed_by,\n        \"reason\": reason,\n        \"evidence_chain_id\": evidence_chain_id,\n        \"opened_at\": datetime.utcnow().isoformat()\n    }\n\n    return self.log_event(\"arbitrage.dispute_opened\", dispute_payload)\n```\n\n### Integrating the Audit Trail\n\nWire the audit trail into the coordinator so every action is logged automatically:\n\n```python\naudit = ArbitrageAuditTrail(coordinator_id, COORDINATOR_PRIVATE_KEY)\n\n# Log opportunity detection\nfor opp in opportunities:\n    audit.log_event(\"arbitrage.opportunity_detected\", {\n        \"opportunity_id\": opp.opportunity_id,\n        \"symbol\": opp.symbol,\n        \"buy_exchange\": opp.buy_exchange,\n        \"sell_exchange\": opp.sell_exchange,\n        \"spread_bps\": opp.spread_bps,\n        \"net_profit_usd\": opp.net_profit_usd,\n        \"detected_at\": opp.detected_at\n    })\n\n# Log escrow creation\naudit.log_event(\"arbitrage.escrow_created\", {\n    \"opportunity_id\": opp.opportunity_id,\n    \"escrow_id\": \"esc-abc123\",\n    \"amount\": opp.net_profit_usd,\n    \"conditions\": \"verified_execution\"\n})\n\n# Log settlement\naudit.log_event(\"arbitrage.settlement\", {\n    \"opportunity_id\": opp.opportunity_id,\n    \"escrow_id\": \"esc-abc123\",\n    \"splits\": splits,\n    \"evidence_chain_id\": \"chain-xyz789\"\n})\n\n# Build periodic Merkle chain (run on schedule)\nchain = audit.build_periodic_chain()\nprint(f\"Audit chain built: {chain.get('chain_id')}\")\nprint(f\"Merkle root: {chain.get('merkle_root')}\")\n```\n\n### Monitoring and Alerting\n\nSubmit audit trail health metrics to GreenHelix for observability:\n\n```python\nexecute(\"submit_metrics\", {\n    \"agent_id\": coordinator_id,\n    \"metrics\": {\n        \"audit_events_today\": 2847,\n        \"audit_buffer_size\": len(audit.event_buffer),\n        \"chains_built_today\": 96,\n        \"opportunities_detected_today\": 412,\n        \"settlements_completed_today\": 387,\n        \"disputes_today\": 2,\n        \"settlement_rate\": 0.939,\n        \"avg_settlement_time_ms\": 4200\n    }\n})\n```\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\": \"submit_metrics\",\n    \"input\": {\n      \"agent_id\": \"arb-coordinator-01\",\n      \"metrics\": {\n        \"audit_events_today\": 2847,\n        \"chains_built_today\": 96,\n        \"opportunities_detected_today\": 412,\n        \"settlements_completed_today\": 387,\n        \"disputes_today\": 2,\n        \"settlement_rate\": 0.939\n      }\n    }\n  }'\n```\n\n### Generating a Compliance Report\n\n```python\nreport = audit.generate_compliance_report(\n    start_date=\"2026-04-01T00:00:00Z\",\n    end_date=\"2026-04-07T23:59:59Z\"\n)\n\nprint(json.dumps(report, indent=2))\n```\n\n```bash\n# Query events for compliance\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      \"agent_id\": \"arb-coordinator-01\",\n      \"filters\": {\n        \"timestamp_from\": \"2026-04-01T00:00:00Z\",\n        \"timestamp_to\": \"2026-04-07T23:59:59Z\"\n      },\n      \"limit\": 10000\n    }\n  }'\n```\n\n```bash\n# Query claim chains for audit verification\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_claim_chains\",\n    \"input\": {\n      \"agent_id\": \"arb-coordinator-01\",\n      \"filters\": {\n        \"created_from\": \"2026-04-01T00:00:00Z\",\n        \"created_to\": \"2026-04-07T23:59:59Z\"\n      }\n    }\n  }'\n```\n\n---\n\n## What's Next\n\n**Companion Guides:**\n\n- **Tamper-Proof Audit Trails for Trading Bots** -- Deep dive into EU AI Act, MiFID II, and SEC 17a-4 compliance for your arbitrage audit trail. Extends the logging patterns in Chapter 8 with Merkle tree verification and webhook-based real-time audit forwarding.\n- **Verified Bot Reputation** -- Turn your arbitrage execution metrics into a provable reputation asset. Counterparties can verify your fill rate, latency, and settlement history before agreeing to coordinate.\n- **Strategy Marketplace Playbook** -- Publish your arbitrage coordination framework as a product on the GreenHelix marketplace, with reputation-backed performance claims and escrow-protected licensing.\n\n**GreenHelix Documentation:**\n\n- Full API reference: https:\u002F\u002Fapi.greenhelix.net\u002Fv1\n- Escrow lifecycle and dispute resolution in the platform documentation\n- Event bus schemas and claim chain verification procedures\n\n**Production Considerations:**\n\nThe framework in this guide is architecturally complete but requires exchange-specific adapters for production deployment. Each exchange has its own WebSocket feed format, order API schema, authentication mechanism, and rate limits. The ArbitrageCoordinator, OpportunityScanner, ExecutionVerifier, and ProfitSplitter are exchange-agnostic by design -- they communicate through GreenHelix events and escrow, not through exchange APIs directly. The exchange specialist bots encapsulate all exchange-specific logic. Adding a new exchange means writing one new specialist bot and registering it on GreenHelix, not modifying any framework code.\n\n---\n\n*This guide describes coordination patterns for autonomous trading bots. Arbitrage across exchanges carries financial risk including but not limited to execution risk, counterparty risk, exchange insolvency risk, and regulatory risk. The fee structures and latency numbers cited are representative as of Q1 2026 and change frequently. Test all strategies in a paper-trading environment before deploying real capital. Consult your compliance counsel for jurisdiction-specific obligations related to algorithmic trading.*\n\n",{"name":5,"tags":24,"type":29,"author":33,"install":34,"license":15,"version":35,"metadata":36,"price_usd":41,"executable":20,"credentials":42,"description":7,"content_type":43,"compatibility":44},[25,26,27,28,29,30,31,32],"arbitrage","trading-bot","multi-bot","coordination","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":37},{"requires":38,"primaryEnv":40},{"env":39},[40],"AGENT_SIGNING_KEY",99,[40],"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-bot-arbitrage-framework",0,"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-bot-arbitrage-framework",{"tool":60,"command":61},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-bot-arbitrage-framework",{"tool":63,"command":64},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-bot-arbitrage-framework","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-bot-arbitrage-framework\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",[],[]]