TradeGate MCP Server
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
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.
Related MCP server: QuantRisk
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
Run the reproducible local demo (zero credentials, zero network calls):
tradegate demoSample 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.jsonlInteractive 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-sessionOr run the included non-root container (Dockerfile) on Render, Fly.io, Railway, or Docker:
docker build -t tradegate .
docker run -p 8790:8790 tradegateThe 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 100000Or 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-paperExposed MCP tools
Tool | Purpose |
| Dry-run pre-trade evaluation returning |
| Idempotent |
| Current equity, cash, high-water mark, drawdown, gross exposure, daily return, positions, and kill-switch state. |
| Verifies SHA-256 hash chain integrity of |
| Latches the emergency kill switch active with |
| Clears a latched kill switch with an explicit operator |
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 demoLimitations
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.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Pre-trade risk gating and verifiable decision evidence for AI trading agents. Oracle-backed price/safety checks across Base, Solana, Hyperliquid and BNB, plus signed receipts and portable evidence bundles for any agent action.
Deterministic pre-trade risk firewall and portfolio MCP server for AI agents (IBKR, Alpaca).
Guardrails for trading agents. Built-in risk management, 100+ tools for strategy R&D, 12+ venues.
Pre-execution governance for AI agents. Deterministic PASS/FAIL/REVIEW verdicts, replayable proof.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceEnables AI agents to execute prediction-market trades through a risk-control gateway that enforces signed mandates and generates proof trails for accountability.0MIT
- FlicenseAqualityDmaintenanceEnables agents to generate alpha signals, retrieve market snapshots, compute portfolio risk, validate and submit paper orders, and trigger a kill switch, all under deterministic pre-trade risk controls and audit logging.5-

Collar Guardrailofficial
AlicenseNot gradedqualityBmaintenanceEnables AI trading agents to submit proposed trades for deterministic pre-execution risk evaluation, returning allow/warn/deny decisions, risk scores, and tamper-evident audit hashes. It also supports token safety checks, balance simulation, asset registry lookup, and audit trail verification.MIT- AlicenseNot gradedqualityBmaintenanceLocal, advisory-only pre-trade risk gate for AI trading agents. 12 deterministic fail-closed rules return PASS/WARN/BLOCK with reasons and a local hash-chained audit log. Never places orders and needs no broker credentials. Early-stage open source (MIT).MIT