QuantRisk
This server provides paper-trading and risk-control capabilities via MCP tools, with no live order routing.
Generate mock GNN alpha signals for informational purposes only.
Read normalized synthetic market-data quotes.
Run deterministic pre-trade risk validation without submitting an order.
Submit paper-only orders after mandatory pre-trade risk checks.
Trip an irreversible risk circuit breaker to block new order attempts during incidents.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@QuantRisk Compute portfolio risk and show limit utilization"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Safety-First MCP Quant Risk Orchestration Engine
This project is a production-like paper-trading and risk orchestration platform designed around deterministic pre-trade validation, auditability, and fail-closed operational controls. It includes a browser dashboard, REST API, MCP tools, PostgreSQL persistence, Redis controls, and Docker deployment.
Safety posture: live order routing is disabled by default and hard-coded to paper mode. This repository is designed to support controlled paper trading and operational validation, not live broker execution.
Architecture Overview
MCP Client / Agent
|
v
FastMCP Server
|
+--> Risk Engine (VaR, drawdown, max position)
+--> Order State Machine (QUEUED -> VALIDATED -> APPROVED -> PAPER_FILLED)
+--> PostgreSQL persistence (orders, positions, audit_logs)
+--> Redis cache and token-bucket rate limiter
+--> FastAPI gateway (dashboard, REST API, /healthz, /metrics)
+--> Prometheus + Grafana observabilityRelated MCP server: Guardian MCP
Portfolio Application
The FastAPI gateway serves the dashboard at http://localhost:8000/. The dashboard provides:
synthetic market state and order-book depth
risk evaluation before execution
paper-order submission
open positions and recent orders
immutable audit events
portfolio and circuit-breaker status
explicit
PAPER MODEandFAIL-CLOSEDsafety indicators
The dashboard is intentionally a live paper-trading console, not a real-money trading interface.
Is the website hard-coded?
The UI does not fabricate order results. It calls the FastAPI endpoints, which execute the risk engine and persist orders, positions, and audit events in PostgreSQL. Redis supplies rate limiting and alert publishing.
The market feed is intentionally synthetic and deterministic. A ticker produces a repeatable demonstration quote, depth, spread, and feature vector instead of connecting to an exchange. This keeps the demo safe and reproducible. Replacing _market_state() with a validated market-data adapter is the production integration boundary.
Browser-only workflow
You can use the complete paper-trading application from the website without an MCP client:
Enter a ticker to inspect its market state.
Evaluate a BUY or SELL order against the risk controls.
Submit the order through guarded paper execution.
View the persisted order, position, and audit records.
Run a portfolio risk report.
Run a deterministic stress scenario.
Monitor the circuit breaker and system status.
MCP clients and the website are two interfaces over the same workflow skills. The website is the easiest human interface; MCP is the automation interface for agents.
REST API
The dashboard uses these HTTP endpoints:
Method | Endpoint | Purpose |
|
| Paper mode, portfolio, and breaker status |
|
| Synthetic market state |
|
| Evaluate ticker, side, and quantity |
|
| Validate and fill a paper order; requires |
|
| Recent persisted orders |
|
| Persisted paper positions |
|
| Recent risk and execution events |
|
| Operator-triggered trading pause |
|
| Discover available workflow skills |
|
| Run the portfolio risk-report skill |
|
| Run the portfolio stress-test skill |
Example PowerShell request:
$body = @{ ticker = "AAPL"; side = "BUY"; qty = 10 } | ConvertTo-Json
Invoke-RestMethod http://localhost:8000/api/orders/paper -Method Post `
-Headers @{ "X-Idempotency-Key" = "demo-aapl-order-001" } `
-ContentType "application/json" -Body $bodyEach order key is cached in Redis for 24 hours. Repeating the same key returns the original completed payload without re-running risk or filling another order. Execution also acquires lock:position:{ticker} with a 500ms deadline; if another worker holds that ticker lock, the API returns 409 Conflict and records distributed_lock_timeout in the audit log.
MCP Tools and Skills
MCP tools are the machine-callable skills of this application. An MCP client or agent can discover and invoke them through the FastMCP server. They all use the same risk and order-control concepts as the dashboard API:
MCP tool | Skill |
| Inspect synthetic quote, depth, spread, and GNN features |
| Validate an order against position, VaR, drawdown, and rate limits |
| Create a queued order, apply controls, and paper-fill approved orders; accepts optional |
| Discover the available quant workflow skills |
| Summarize positions, exposure, limits, and breaker state |
| Project portfolio P&L under a deterministic price shock |
The same catalog is available to browser and API clients at:
GET /api/skillsExample skill-oriented agent flow:
1. list_skills
2. get_market_state("AAPL")
3. evaluate_risk("AAPL", "BUY", 10)
4. execute_trade("AAPL", "BUY", 10)
5. portfolio_risk_report()
6. stress_test_portfolio(-5)Skills are intentionally workflow-level capabilities, while tools remain the individual callable operations. Both entry points use the same fail-closed risk engine, order state machine, PostgreSQL records, Redis controls, and audit events.
The reusable skill pattern is:
request -> rate limit -> risk evaluation -> state transition -> persistence -> audit + alertYou can add future skills as new @mcp.tool() functions and corresponding REST routes, but they should call shared domain services rather than duplicate risk logic. Current higher-level skills include portfolio-risk reporting and scenario stress testing. Appropriate future skills include reconciliation checks, operator health summaries, and model-drift checks.
Order State Machine
The order lifecycle is deliberately strict and fail-closed:
QUEUED -> VALIDATED -> APPROVED -> PAPER_FILLED
\-> REJECTED
VALIDATED -> REJECTED
APPROVED -> REJECTED
REJECTED -> * (terminal)
PAPER_FILLED -> * (terminal)Any invalid transition raises an explicit domain exception via OrderStateTransitionError.
Risk Architecture
The risk engine enforces:
max position size per asset
account-level VaR threshold
dynamic daily drawdown circuit breaker
audit-log immutability for rejected trades
Redis pub/sub alerting on risk breaches
If any limit is breached, the system writes the rejection event to audit_logs, rejects the order, and triggers the alert channel.
Database Layout
The project uses PostgreSQL + SQLAlchemy Async ORM. Core schema:
orders: id, ticker, side, qty, price, status, created_at, updated_atpositions: ticker, qty, avg_entry_price, unrealized_pnlaudit_logs: id, order_id, event_type, details (JSONB), timestamp
A SQL migration script is provided in migrations/001_init_schema.sql.
Runtime Components
mcp_server.py: MCP tools and higher-level skills for market state, risk, execution, reporting, and stress testingcore/risk.py: deterministic risk engine and fail-closed breakercore/cache.py: Redis-backed state and token-bucket limitercore/db.py: Async SQLAlchemy session and table definitionscore/state_machine.py: order lifecycle enforcementapi/gateway.py: FastAPI dashboard, REST API, health, and Prometheus metrics endpointsfrontend/: responsive browser dashboard served by FastAPImigrations/001_init_schema.sql: PostgreSQL schema migration.github/workflows/ci.yml: automated tests, formatting, and lint checks
Quick Start
python -m venv .venv
source .venv/bin/activate # or .\.venv\Scripts\Activate.ps1 on Windows
python -m pip install -e .[dev]
cp .env.example .env
python -m uvicorn api.gateway:app --host 0.0.0.0 --port 8000Open the dashboard at http://localhost:8000/.
Local MCP runner:
python mcp_server.pyTesting and Quality Gates
pytest -q
black --check .
flake8 .The verified local integration flow is:
healthz -> market state -> paper order -> PostgreSQL order/position/audit recordsThe test suite covers state transitions, risk rejection, drawdown/VaR controls, Redis rate limiting, and database initialization.
Deployment Stack
The repository includes container health checks and a full local observability stack:
PostgreSQL
Redis
Prometheus
Grafana
trading-engine service
Run the full stack:
docker compose up --buildIf port 8000 is already used on your machine, choose another host port in PowerShell:
$env:APP_PORT = "8001"
docker compose up -d --buildThen open http://localhost:8001/.
For a detached deployment:
docker compose up -d --buildThen visit:
http://localhost:3000 (Grafana)
http://localhost:9090 (Prometheus)
Check the running stack:
Invoke-RestMethod http://localhost:8000/healthz | ConvertTo-JsonExpected health response includes:
{"status":"ok","database":true,"redis":true,"paper_mode":true}Operational Safety Guarantees
This design intentionally enforces the following:
paper-only execution by default
explicit validation before execution
immutable audit records for every risk decision
fail-closed circuit breaker for drawdown and VaR violations
Redis-backed rate limiting for order spam mitigation
structured telemetry for trade execution and risk rejection events
Production Hardening Path
This project is production-oriented but still intentionally constrained to paper trading. It is resume-ready as a deployed portfolio application, but it is not a live brokerage system. Before any real-money integration, the next milestones are:
migrate from synthetic market data to a validated feed provider
add durable approvals and secrets management
enforce multi-party sign-off for live execution
replace process-local risk state with fully shared transactional state
add authentication, authorization, HTTPS, restricted CORS, and managed secrets
add broker execution, idempotency, reconciliation, and exchange-level controls
Never set a public demo to live mode. The intended public deployment is a paper-trading demonstration with protected infrastructure dependencies.
See docs/architecture.md, docs/operational-controls.md, and docs/threat-model.md.
Available Tools
5 toolsgenerate_alpha_signalA
Run the mock PyTorch GNN and return an alpha score. Informational only; never places an order.
Inputs: symbol (required), features (required). Returns: object
market_snapshotB
Read a normalized mock market-data quote.
Inputs: symbol (required). Returns: object
submit_paper_orderA
Submit a paper-only order after mandatory pre-trade risk validation.
Inputs: side (required), symbol (required), quantity (required), limit_price (required), +1 more. Returns: object
trip_risk_circuit_breakerA
Irreversibly block new order attempts in this process; use for an incident or anomaly.
Inputs: reason (required). Returns: object
validate_orderA
Run deterministic pre-trade risk checks without submitting an order.
Inputs: side (required), symbol (required), quantity (required), limit_price (required), +1 more. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool maps to a clearly distinct concern: signal generation, market data, pre-trade validation, paper order submission, and circuit breaking. There is no meaningful overlap or ambiguity between the tools.
Most tools follow a clear verb_noun pattern like generate_alpha_signal, validate_order, and submit_paper_order. The exception is market_snapshot, which is noun-only and breaks the otherwise consistent convention.
Five tools is a well-scoped size for a focused quant risk and paper trading server. Each tool serves a distinct step in the intended workflow without redundancy or bloat.
The core flow of generating a signal, validating an order, submitting a paper order, and tripping a breaker is covered. However, there is no way to query or cancel submitted paper orders, and no visibility into the circuit breaker state, leaving notable lifecycle gaps.
Maintenance
Related MCP Connectors
Guardrails for trading agents. Built-in risk management, 100+ tools for strategy R&D, 12+ venues.
Honest backtests and paper trading for US options and equities, driven by your agent.
Unified financial infrastructure connecting AI agents directly to trade live/demo brokerage accounts, Web3 non-custodial wallets, real-time market data across equities, ETFs, crypto, forex, options, DeFi swaps, and prediction markets, institutional research feeds, and algorithmic strategy backtesters.
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to execute stock trading operations with built-in risk controls and human approval workflows. Supports paper trading simulation, real brokerage integration (Alpaca, Tradier), backtesting, sentiment analysis, and portfolio management while maintaining strict separation between AI intelligence and trade execution.MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to propose stock, ETF, and crypto trades through Alpaca paper trading while enforcing deterministic policy rules and recording every decision in an audit trail.13 npmMIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to run a full quant research workflow over MCP: pulling data, authoring and backtesting strategies, running statistical validation and risk checks, and recording findings for future sessions.1MIT
- AlicenseAqualityBmaintenanceEnables AI agents to paper-trade on Polymarket against live order books with realistic fees and fill mechanics, including market search, portfolio tracking, and strategy backtesting.33226 PyPI495MIT