Show HN: TradeGate – Deterministic pre-trade firewall for AI trading agents 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. Deterministic pre-trade execution firewall, tamper-evident audit log, and MCP server for AI trading agents. TradeGate 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 . 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. For 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 . AI Agent / MCP Client Claude, Copilot, Cursor | | MCP over stdio tradegate mcp / tradegate-mcp v +--------------+ | TradeGateway | +--------------+ | | v v +------------------+ +------------------------------------+ | DefaultRiskEngine| | BrokerAdapter Paper/Sandbox only | |------------------| |------------------------------------| | 17 gate rules | | - LocalPaperBroker SQLite | | 8 sizing rules | | - AlpacaPaperBroker HTTPS paper | | Monotone bsearch | | allowlist only; refuses live | | OS writer lock | +------------------------------------+ | Latching KillSw | | SHA-256 audit | +------------------+ - 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 . - 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. - 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. - 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. - 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. Requires Python 3.12+. Core risk engine + local SQLite paper broker + CLI pip install -e . With MCP server and Alpaca Paper adapter pip install -e ". all " Development & test suite pytest, hypothesis, ruff pip install -e ". dev " Run the reproducible local demo zero credentials, zero network calls : tradegate demo Sample output captured directly from tradegate demo on Windows Python 3.12.10 : TradeGate Execution Firewall - Reproducible Local Demo ==================================================================== 1 valid guarded buy - APPROVED AND FILLED 51.742 ms, hash=a67b6d724b0c BUY 50 AAPL filled @ $200.04 fees $5.00 2 duplicate client order id - BLOCKED 15.927 ms, hash=254f3ebe4cdb duplicate: client order id 'demo-ord-001' was already approved 3 oversized monotone downsize - DOWNSIZED AND FILLED 35.749 ms, hash=e55e4d5fc87b 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% 4 stale account snapshot - BLOCKED 13.992 ms, hash=bf8cdfcecaaa account snapshot: 720s old max 300s 5 unpriced holding valuation - BLOCKED 14.951 ms, hash=36581126ea30 valuation: no price for held US:UNPRICED; buys blocked until all holdings are priced 6 exchange holiday rejection - BLOCKED 4.082 ms, hash=d5ddaf51f202 market hours: US is closed on 2026-07-03 non-trading day 7 unapproved fill latches kill switch - LATCHED AND BLOCKED 28.237 ms, hash=7e8a08aa7514 kill switch active: reconciliation failure on rogue-unapproved-999: fill for an order this engine never approved; reconcile with the broker before resetting 8 sha256 audit tamper detection - VERIFIED AND TAMPER CAUGHT 13.682 ms, hash=7e8a08aa7514 Intact chain: 14 records OK tail 7e8a08aa7514... ; tampered copy caught: record 14: content hash mismatch edited? -------------------------------------------------------------------- Measured wall-clock latency 8 scenarios : median=15.439 ms | p95=51.742 ms | max=51.742 ms 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. Verify any audit log independently exits 0 if intact, 1 on any tamper or missing file : tradegate verify-audit path/to/audit.jsonl Launch 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 : tradegate ui Persistent local state dir: tradegate ui --host 127.0.0.1 --port 8790 --state-dir ./var/ui-sandbox --no-browser Multi-visitor isolated hosted mode one sandbox per browser visitor : tradegate ui --host 0.0.0.0 --port 8790 --no-browser --multi-session Or run the included non-root container Dockerfile on Render, Fly.io, Railway, or Docker: docker build -t tradegate . docker run -p 8790:8790 tradegate The 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: - 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. - 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. - 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. - 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. Start the stdio MCP server backed by the local SQLite paper sandbox: tradegate mcp --state-dir ./var/tradegate --broker local --initial-cash 100000 Or backed by Alpaca Paper Trading strictly allowlisted to https://paper-api.alpaca.markets : export ALPACA API KEY="PK..." export ALPACA SECRET KEY="..." tradegate mcp --state-dir ./var/tradegate --broker alpaca-paper | Tool | Purpose | |---|---| | check order | Dry-run pre-trade evaluation returning approved , adjusted quantity , reasons , warnings , audit hash without reserving cash or consuming client order id . | | submit guarded order | Idempotent client order id check under single-writer lock, risk evaluation, broker submission, and fill/rejection reconciliation. | | get portfolio risk | Current equity, cash, high-water mark, drawdown, gross exposure, daily return, positions, and kill-switch state. | | verify audit chain | Verifies SHA-256 hash chain integrity of audit.jsonl from genesis to latest sequence. | | trip kill switch | Latches the emergency kill switch active with reason and actor logged to the hash chain. | | release kill switch | Clears a latched kill switch with an explicit operator reason = 5 chars and actor . | { "mcpServers": { "tradegate": { "command": "tradegate-mcp", "env": { "TRADEGATE STATE DIR": "./var/tradegate", "TRADEGATE BROKER": "local", "TRADEGATE INITIAL CASH": "100000", "TRADEGATE PRICES": "{\"AAPL\": \"200.00\", \"MSFT\": \"400.00\"}" } } } } Risk configs are validated with Pydantic v2 extra="forbid" , frozen models from TOML, JSON, or optional YAML tradegate yaml : version = 1 allowed modes = "PAPER" limits max position weight = "0.20" max gross exposure = "1.00" max order pct equity = "0.20" max orders per day = 50 price collar pct = "0.05" allow downsize = true portfolio timezone = "America/New York" daily loss limit pct = "0.03" daily loss action = "block buys" paths state path = "var/risk state.json" audit log path = "var/audit.jsonl" kill switch state path = "var/kill switch.json" kill switch flag path = "var/KILL" ruff check src tests pytest -v tradegate demo - 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 . - Long-only cash model: Short positions and margin borrowing are rejected by design. - 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. - 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. MIT — see LICENSE https://github.com/hkedia08/tradegate/blob/main/LICENSE .