TradeGate
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 (
LocalPaperBrokerandAlpacaPaperBroker) refuseLIVEmode 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.
Architecture
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 |
+------------------+
Key controls
- Fail-closed pre-trade engine (
DefaultRiskEngine): 17 gate rules (mode, order sanity, restricted lists, exchange hours & holiday calendar, order/account snapshot staleness, duplicateclient_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=Truefinds the exact largest tradeable increment (lot size or fractionalqty_step) that satisfies all sizing limits simultaneously. - OS single-writer lock: Holds a non-blocking OS file lock (
msvcrton Windows,fcntl.flockon POSIX) onrisk_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.jsonlwithseq,prev_hash, andhash = SHA-256(canonical_json(record)), flushed and fsynced. Startup verifies the chain and fails closed on edits, deletions, reordering, or truncation.
Installation
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]"
Quickstart
Create a starter tradegate.toml policy and run the 6-point diagnostic check:
tradegate init
tradegate doctor --config tradegate.toml
Run the reproducible local demo (zero credentials, zero network calls):
tradegate demo
For drop-in wrappers with TradingAgents, LangGraph, OpenAI Agents SDK, and CrewAI, see examples/. Set TRADEGATE_WEBHOOK_URL (HTTPS Slack, Discord, Telegram, or JSON webhook) to receive real-time kill-switch and blocked-order alerts.
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
Interactive Web UI
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 — reloadsDefaultRiskEngineagainst the same positions, kill switch, and SHA-256 hash chain. - Self-Serve Verification & MCP Kit (
Export .jsonl/Connect MCP): Download the raw on-diskaudit.jsonlto runtradegate verify-auditlocally, 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/metricstelemetry endpoints, and one-click sandbox reset.
MCP Server
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
Exposed MCP tools
| 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. |
Client configuration (Claude Desktop / GitHub Copilot / Cursor)
{
"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\"}"
}
}
}
}
Configuration
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"
Development
ruff check src tests
pytest -v
tradegate demo
Limitations
- Paper/sandbox only: Not designed or authorized for live capital routing.
AlpacaPaperBrokerrefuses any URL other thanhttps://paper-api.alpaca.markets, andLocalPaperBrokerrefusesTradingMode.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.
License
MIT — see LICENSE.
Metadata
Release files for tradegate-firewall 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tradegate_firewall-0.1.0.tar.gz | 120.2 kB | With provenance | Details for tradegate_firewall-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tradegate_firewall-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for tradegate_firewall-0.1.0-py3-none-any.whl |
Total release size: 235.8 kB
Release files / tradegate_firewall-0.1.0.tar.gz
| Download URL | tradegate_firewall-0.1.0.tar.gz |
|---|---|
| Size | 120.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2184557f361c656253fd0f9264eb90ee4a6712c4f3d028f968a407470d453e6e
|
|
BLAKE2b-256 checksum How to use checksums |
5fdeecd9ae6c37cbf1d059edc429835f43468272120832a3c0f3edc767bcf3b7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / tradegate_firewall-0.1.0-py3-none-any.whl
| Download URL | tradegate_firewall-0.1.0-py3-none-any.whl |
|---|---|
| Size | 115.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7c7584a64f8145fc9fb165148a4c7a886fddcfe1c2bbf7a1328e2055c3118440
|
|
BLAKE2b-256 checksum How to use checksums |
6bc43304e4826512ebcebef73a8c9d6d09a1e987f17775c9239d7af4a7acee9d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logSecurity for tradegate-firewall 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for tradegate_firewall-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.