{"slug": "show-hn-tradegate-deterministic-pre-trade-firewall-for-ai-trading-agents", "title": "Show HN: TradeGate – Deterministic pre-trade firewall for AI trading agents", "summary": "A developer released TradeGate, an open-source deterministic pre-trade execution firewall for AI trading agents, published on Show HN and requiring Python 3.12+. TradeGate sits between an AI agent or strategy loop and a paper or sandbox broker adapter, enforcing 17 fail-closed gate rules and 8 monotone sizing rules, an OS-level single-writer lock, a persistent latching kill switch, and an fsynced SHA-256 hash-chained audit.jsonl; both included adapters, LocalPaperBroker and AlpacaPaperBroker, refuse LIVE mode, and the project states it contains no trading strategies, alpha models, or return claims.", "body_md": "Deterministic pre-trade execution firewall, tamper-evident audit log, and MCP server for AI trading agents.\n\nTradeGate sits between an AI agent (or strategy loop) and a paper/sandbox broker adapter. Every order passes through fail-closed pre-trade gates, monotone sizing rules, an OS-level single-writer lock, a persistent latching kill switch, and an fsynced SHA-256 hash-chained `audit.jsonl`.\n\n**Scope and limitations:** TradeGate is **paper and sandbox only**. Both included broker adapters (`LocalPaperBroker` and `AlpacaPaperBroker`) refuse `LIVE` mode and live broker endpoints fail-closed. TradeGate enforces execution safety and auditability; it contains no trading strategies, alpha models, or return claims.\n\nFor a full walkthrough of the codebase, data flows, Mermaid diagrams, invariants, and extension guide, see **[docs/ARCHITECTURE.md](https://github.com/hkedia08/tradegate/blob/main/docs/ARCHITECTURE.md)**.\n\n```\nAI Agent / MCP Client (Claude, Copilot, Cursor)\n                    |\n                    |  MCP over stdio (`tradegate mcp` / `tradegate-mcp`)\n                    v\n             +--------------+\n             | TradeGateway |\n             +--------------+\n               |          |\n               v          v\n  +------------------+  +------------------------------------+\n  | DefaultRiskEngine|  | BrokerAdapter (Paper/Sandbox only) |\n  |------------------|  |------------------------------------|\n  | 17 gate rules    |  | - LocalPaperBroker (SQLite)        |\n  |  8 sizing rules  |  | - AlpacaPaperBroker (HTTPS paper   |\n  | Monotone bsearch |  |   allowlist only; refuses live)    |\n  | OS writer lock   |  +------------------------------------+\n  | Latching KillSw  |\n  | SHA-256 audit    |\n  +------------------+\n```\n\n- **Fail-closed pre-trade engine (`DefaultRiskEngine`):** 17 gate rules (mode, order sanity, restricted lists, exchange hours & holiday calendar, order/account snapshot staleness, duplicate`client_order_id` & fingerprint window, price collar, daily order count, stale open-order reconciliation, unpriced holdings, start-of-day baseline, durable persistence) and 8 monotone sizing rules (per-order notional, daily turnover, no shorting, per-instrument position weight, drawdown/vol-scaled gross exposure, cash + fee buffer, strategy allocation, sector weight).\n- **Monotone binary-search downsize:** Because every sizing rule is monotone in quantity, optional`allow_downsize=True` finds the exact largest tradeable increment (lot size or fractional`qty_step` ) that satisfies all sizing limits simultaneously.\n- **OS single-writer lock:** Holds a non-blocking OS file lock (`msvcrt` on Windows,`fcntl.flock` on POSIX) on`risk_state.json.engine.lock` ; a second process targeting the same state file fails closed and rejects every order.\n- **Persistent latching kill switch:** Triggered programmatically, by drawdown/daily-loss breaches, by reconciliation failures (e.g., an unapproved or overfilled broker fill), or by dropping a flag file on disk. Deleting the flag file or state file never re-enables trading; clearing requires an explicit operator reset with a reasoned audit entry.\n- **Tamper-evident audit chain:** Every startup, dry-run check, decision, fill, close, and kill-switch transition is appended to`audit.jsonl` with`seq` ,`prev_hash` , and`hash = SHA-256(canonical_json(record))` , flushed and fsynced. Startup verifies the chain and fails closed on edits, deletions, reordering, or truncation.\n\nRequires Python 3.12+.\n\n```\n# Core risk engine + local SQLite paper broker + CLI\npip install -e .\n\n# With MCP server and Alpaca Paper adapter\npip install -e \".[all]\"\n\n# Development & test suite (pytest, hypothesis, ruff)\npip install -e \".[dev]\"\n```\n\nRun the reproducible local demo (zero credentials, zero network calls):\n\n```\ntradegate demo\n```\n\nSample output captured directly from `tradegate demo` on Windows (Python 3.12.10):\n\n```\nTradeGate Execution Firewall - Reproducible Local Demo\n====================================================================\n[1] valid_guarded_buy -> APPROVED_AND_FILLED (51.742 ms, hash=a67b6d724b0c)\n    BUY 50 AAPL filled @ $200.04 (fees $5.00)\n[2] duplicate_client_order_id -> BLOCKED (15.927 ms, hash=254f3ebe4cdb)\n    duplicate: client_order_id 'demo-ord-001' was already approved\n[3] oversized_monotone_downsize -> DOWNSIZED_AND_FILLED (35.749 ms, hash=e55e4d5fc87b)\n    Requested 200 MSFT -> downsized to 49 (downsized 200 -> 49: order notional: 81600.00 exceeds cap 19998.60; position weight: US:MSFT would be 81.61% of equity (max 20.00%))\n[4] stale_account_snapshot -> BLOCKED (13.992 ms, hash=bf8cdfcecaaa)\n    account snapshot: 720s old (max 300s)\n[5] unpriced_holding_valuation -> BLOCKED (14.951 ms, hash=36581126ea30)\n    valuation: no price for held US:UNPRICED; buys blocked until all holdings are priced\n[6] exchange_holiday_rejection -> BLOCKED (4.082 ms, hash=d5ddaf51f202)\n    market hours: US is closed on 2026-07-03 (non-trading day)\n[7] unapproved_fill_latches_kill_switch -> LATCHED_AND_BLOCKED (28.237 ms, hash=7e8a08aa7514)\n    kill switch active: reconciliation failure on rogue-unapproved-999: fill for an order this engine never approved; reconcile with the broker before resetting\n[8] sha256_audit_tamper_detection -> VERIFIED_AND_TAMPER_CAUGHT (13.682 ms, hash=7e8a08aa7514)\n    Intact chain: 14 records OK (tail 7e8a08aa7514...); tampered copy caught: record 14: content hash mismatch (edited?)\n--------------------------------------------------------------------\nMeasured wall-clock latency (8 scenarios): median=15.439 ms | p95=51.742 ms | max=51.742 ms\n```\n\n*(Latency includes full durable fsync of state JSON, SQLite paper execution, and SHA-256 audit log writes on local disk; actual values vary by machine and filesystem.)*\n\nVerify any audit log independently (exits `0` if intact, `1` on any tamper or missing file):\n\n```\ntradegate verify-audit path/to/audit.jsonl\n```\n\nLaunch the local interactive execution firewall desk in your browser (zero extra dependencies, zero network calls, 100% backed by `TradeGateway`, `DefaultRiskEngine`, `LocalPaperBroker`, `KillSwitch`, and fsynced `audit.jsonl`):\n\n```\ntradegate ui\n# Persistent local state dir:\ntradegate ui --host 127.0.0.1 --port 8790 --state-dir ./var/ui-sandbox --no-browser\n# Multi-visitor isolated hosted mode (one sandbox per browser visitor):\ntradegate ui --host 0.0.0.0 --port 8790 --no-browser --multi-session\n```\n\nOr run the included non-root container (`Dockerfile`) on Render, Fly.io, Railway, or Docker:\n\n```\ndocker build -t tradegate .\ndocker run -p 8790:8790 tradegate\n```\n\nThe UI starts with an isolated `$100,000` paper sandbox (`AAPL`, `MSFT`, `NVDA`, `SPY`, 20% position/order cap, 5% price collar, 300s snapshot staleness cap, NYSE holidays, `allow_downsize=true`) and provides:\n\n- **8 live attack & failure triggers** (valid buy, duplicate retry block, oversized monotone binary-search downsize,**indirect prompt-injection hijack blocked by 5% price collar** , stale snapshot block, NYSE holiday block, rogue fill kill-switch latch, and 1-byte SHA-256 tamper check) plus an 8-step sequence runner.\n- **Live Risk Policy Editor (`Policy`)** : Edit position/order/gross caps, daily order limit,` allow_downsize` , and blocked symbols live — reloads`DefaultRiskEngine` against the same positions, kill switch, and SHA-256 hash chain.\n- **Self-Serve Verification & MCP Kit (`Export .jsonl` / `Connect MCP`)** : Download the raw on-disk` audit.jsonl` to run`tradegate verify-audit` locally, and copy ready-to-paste MCP configs for Claude Desktop, Cursor, or Copilot.\n- **Custom order ticket** , real-time exposure/weight gauges, operator kill-switch trip/release controls, non-allocating`/healthz` &`/api/metrics` telemetry endpoints, and one-click sandbox reset.\n\nStart the stdio MCP server backed by the local SQLite paper sandbox:\n\n```\ntradegate mcp --state-dir ./var/tradegate --broker local --initial-cash 100000\n```\n\nOr backed by Alpaca Paper Trading (strictly allowlisted to `https://paper-api.alpaca.markets`):\n\n```\nexport ALPACA_API_KEY=\"PK...\"\nexport ALPACA_SECRET_KEY=\"...\"\ntradegate mcp --state-dir ./var/tradegate --broker alpaca-paper\n```\n\n| Tool | Purpose | \n|---|---|\n| `check_order` | Dry-run pre-trade evaluation returning `approved` ,`adjusted_quantity` ,`reasons` ,`warnings` ,`audit_hash` without reserving cash or consuming`client_order_id` . | \n| `submit_guarded_order` | Idempotent `client_order_id` check under single-writer lock, risk evaluation, broker submission, and fill/rejection reconciliation. | \n| `get_portfolio_risk` | Current equity, cash, high-water mark, drawdown, gross exposure, daily return, positions, and kill-switch state. | \n| `verify_audit_chain` | Verifies SHA-256 hash chain integrity of `audit.jsonl` from genesis to latest sequence. | \n| `trip_kill_switch` | Latches the emergency kill switch active with `reason` and`actor` logged to the hash chain. | \n| `release_kill_switch` | Clears a latched kill switch with an explicit operator `reason` (>= 5 chars) and`actor` . | \n\n```\n{\n  \"mcpServers\": {\n    \"tradegate\": {\n      \"command\": \"tradegate-mcp\",\n      \"env\": {\n        \"TRADEGATE_STATE_DIR\": \"./var/tradegate\",\n        \"TRADEGATE_BROKER\": \"local\",\n        \"TRADEGATE_INITIAL_CASH\": \"100000\",\n        \"TRADEGATE_PRICES\": \"{\\\"AAPL\\\": \\\"200.00\\\", \\\"MSFT\\\": \\\"400.00\\\"}\"\n      }\n    }\n  }\n}\n```\n\nRisk configs are validated with Pydantic v2 (`extra=\"forbid\"`, frozen models) from TOML, JSON, or optional YAML (` tradegate[yaml]`):\n\n```\nversion = 1\nallowed_modes = [\"PAPER\"]\n\n[limits]\nmax_position_weight = \"0.20\"\nmax_gross_exposure = \"1.00\"\nmax_order_pct_equity = \"0.20\"\nmax_orders_per_day = 50\nprice_collar_pct = \"0.05\"\nallow_downsize = true\n\n[portfolio]\ntimezone = \"America/New_York\"\ndaily_loss_limit_pct = \"0.03\"\ndaily_loss_action = \"block_buys\"\n\n[paths]\nstate_path = \"var/risk_state.json\"\naudit_log_path = \"var/audit.jsonl\"\nkill_switch_state_path = \"var/kill_switch.json\"\nkill_switch_flag_path = \"var/KILL\"\nruff check src tests\npytest -v\ntradegate demo\n```\n\n- **Paper/sandbox only:** Not designed or authorized for live capital routing.`AlpacaPaperBroker` refuses any URL other than`https://paper-api.alpaca.markets` , and`LocalPaperBroker` refuses`TradingMode.LIVE` .\n- **Long-only cash model:** Short positions and margin borrowing are rejected by design.\n- **Single-host locking:** Single-writer exclusion uses OS advisory/byte-range file locks on a local filesystem; multi-host active-active deployments are out of scope.\n- **Market data:** TradeGate does not ship a live market-data feed. Callers supply reference prices (or configure marks on`LocalPaperBroker` ); missing prices for held positions fail closed on buys.\n\nMIT — see [LICENSE](https://github.com/hkedia08/tradegate/blob/main/LICENSE).", "url": "https://wpnews.pro/news/show-hn-tradegate-deterministic-pre-trade-firewall-for-ai-trading-agents", "canonical_source": "https://github.com/hkedia08/tradegate", "published_at": "2026-11-29 14:33:00+00:00", "updated_at": "2026-11-29 14:44:10.985421+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "agent-protocols", "ai-safety"], "entities": ["TradeGate", "DefaultRiskEngine", "LocalPaperBroker", "AlpacaPaperBroker", "TradeGateway", "Claude", "Copilot", "Cursor"], "also_reported_by": [], "takeaway": "TradeGate's DefaultRiskEngine applies 17 fail-closed gate rules and 8 monotone sizing rules, using binary search to downsize an order to the largest quantity satisfying all limits, with every decision fsynced into a SHA-256 hash-chained audit.jsonl that fails closed on edits or truncation.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/show-hn-tradegate-deterministic-pre-trade-firewall-for-ai-trading-agents", "markdown": "https://wpnews.pro/news/show-hn-tradegate-deterministic-pre-trade-firewall-for-ai-trading-agents.md", "text": "https://wpnews.pro/news/show-hn-tradegate-deterministic-pre-trade-firewall-for-ai-trading-agents.txt", "jsonld": "https://wpnews.pro/news/show-hn-tradegate-deterministic-pre-trade-firewall-for-ai-trading-agents.jsonld"}}