Skip to main content
Glama
TradeGate MCP Server

TradeGate MCP Server

by hkedia08
README.md
# 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 (`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](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, 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.

## Installation

Requires Python 3.12+.

```bash
# 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):

```bash
tradegate demo
```

Sample output captured directly from `tradegate demo` on Windows (Python 3.12.10):

```text
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):

```bash
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`):

```bash
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:

```bash
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.

## MCP Server

Start the stdio MCP server backed by the local SQLite paper sandbox:

```bash
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`):

```bash
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)

```json
{
  "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]`):

```toml
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

```bash
ruff check src tests
pytest -v
tradegate demo
```

## Limitations

- **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.

## License

MIT — see [LICENSE](LICENSE).