Skip to main content
Glama
avnijainnn

QuantRisk

by avnijainnn

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 observability

Related MCP server: trading-mcp-server

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 MODE and FAIL-CLOSED safety 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:

  1. Enter a ticker to inspect its market state.

  2. Evaluate a BUY or SELL order against the risk controls.

  3. Submit the order through guarded paper execution.

  4. View the persisted order, position, and audit records.

  5. Run a portfolio risk report.

  6. Run a deterministic stress scenario.

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

GET

/api/status

Paper mode, portfolio, and breaker status

GET

/api/market/{ticker}

Synthetic market state

POST

/api/risk/evaluate

Evaluate ticker, side, and quantity

POST

/api/orders/paper

Validate and fill a paper order; requires X-Idempotency-Key

GET

/api/orders

Recent persisted orders

GET

/api/positions

Persisted paper positions

GET

/api/audit-events

Recent risk and execution events

POST

/api/circuit-breaker

Operator-triggered trading pause

GET

/api/skills

Discover available workflow skills

GET

/api/portfolio/risk-report

Run the portfolio risk-report skill

POST

/api/portfolio/stress-test?shock_percent=-5

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 $body

Each 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

get_market_state

Inspect synthetic quote, depth, spread, and GNN features

evaluate_risk

Validate an order against position, VaR, drawdown, and rate limits

execute_trade

Create a queued order, apply controls, and paper-fill approved orders; accepts optional idempotency_key

list_skills

Discover the available quant workflow skills

portfolio_risk_report

Summarize positions, exposure, limits, and breaker state

stress_test_portfolio

Project portfolio P&L under a deterministic price shock

The same catalog is available to browser and API clients at:

GET /api/skills

Example 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 + alert

You 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_at

  • positions: ticker, qty, avg_entry_price, unrealized_pnl

  • audit_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 testing

  • core/risk.py: deterministic risk engine and fail-closed breaker

  • core/cache.py: Redis-backed state and token-bucket limiter

  • core/db.py: Async SQLAlchemy session and table definitions

  • core/state_machine.py: order lifecycle enforcement

  • api/gateway.py: FastAPI dashboard, REST API, health, and Prometheus metrics endpoints

  • frontend/: responsive browser dashboard served by FastAPI

  • migrations/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 8000

Open the dashboard at http://localhost:8000/.

Local MCP runner:

python mcp_server.py

Testing and Quality Gates

pytest -q
black --check .
flake8 .

The verified local integration flow is:

healthz -> market state -> paper order -> PostgreSQL order/position/audit records

The 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 --build

If port 8000 is already used on your machine, choose another host port in PowerShell:

$env:APP_PORT = "8001"
docker compose up -d --build

Then open http://localhost:8001/.

For a detached deployment:

docker compose up -d --build

Then visit:

Check the running stack:

Invoke-RestMethod http://localhost:8000/healthz | ConvertTo-Json

Expected health response includes:

{"status":"ok","database":true,"redis":true,"paper_mode":true}

Operational Safety Guarantees

This design intentionally enforces the following:

  1. paper-only execution by default

  2. explicit validation before execution

  3. immutable audit records for every risk decision

  4. fail-closed circuit breaker for drawdown and VaR violations

  5. Redis-backed rate limiting for order spam mitigation

  6. 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:

  1. migrate from synthetic market data to a validated feed provider

  2. add durable approvals and secrets management

  3. enforce multi-party sign-off for live execution

  4. replace process-local risk state with fully shared transactional state

  5. add authentication, authorization, HTTPS, restricted CORS, and managed secrets

  6. 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 tools
generate_alpha_signalA

Run the mock PyTorch GNN and return an alpha score. Informational only; never places an order.

ParametersJSON Schema
NameRequiredDescriptionDefault
symbolYes
featuresYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A3.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full behavioral burden. It discloses two key traits: the model is a mock and the call has no order side effects. However, it omits details about return shape, errors, or feature-vector requirements, so disclosure is partial.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two short sentences with no filler. The core action and output are front-loaded, and the crucial safety clarification 'never places an order' is included without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple two-parameter mock tool, the purpose and side-effect profile are clear, and an output schema exists so return-value details are not required. The only notable gap is the unexplained 'features' parameter, but overall the description is sufficiently complete for the tool's complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, and the description adds no meaning for either parameter. 'symbol' is weakly inferable from the name, but 'features' is entirely unexplained—no length, ordering, or normalization context. The description fails to compensate for the schema gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description names a specific action ('Run'), the resource ('mock PyTorch GNN'), and the output ('alpha score'). It also explicitly distinguishes itself from order-placing siblings with 'never places an order', making its purpose unmistakable.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The phrase 'Informational only; never places an order' gives a clear context and an explicit when-not-to-use boundary. It does not name alternative siblings like market_snapshot or specify when to prefer this one, but the informational intent is clearly conveyed.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

market_snapshotB

Read a normalized mock market-data quote.

ParametersJSON Schema
NameRequiredDescriptionDefault
symbolYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

B3.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must carry the disclosure burden. 'Read' and 'mock' convey that this is a non-destructive, non-production data operation, which is useful. However, it does not explain normalization rules, whether the quote is current/last available, error behavior, or any other operational trait, and no annotations compensate.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence with no filler; every word contributes. It is appropriately short for a one-parameter read operation, though terse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a one-parameter read tool with an output schema, the core call shape is clear, but there is no usage guidance, no caveats, and no explanation of the 'normalized' aspect. The missing usage context and parameter semantics leave the agent to guess when and how to invoke this over alternatives.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has one required parameter, 'symbol', with 0% description coverage, and the description adds no explicit parameter explanation. The phrase 'market-data quote' only weakly implies that symbol identifies the instrument. A format or example would be needed to reach the low-coverage compensation bar.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description names a specific verb ('Read') and a specific resource ('normalized mock market-data quote'), so an agent can tell this is the market-data retrieval tool. Among siblings (generate_alpha_signal, validate_order, submit_paper_order, trip_risk_circuit_breaker), it uniquely reads a quote rather than generating, validating, submitting, or tripping something.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives no explicit condition for use, no exclusions, and no pointer to an alternative sibling. It only states what the tool does; the agent must infer when to pick it. No prerequisites or context are provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

submit_paper_orderA

Submit a paper-only order after mandatory pre-trade risk validation.

ParametersJSON Schema
NameRequiredDescriptionDefault
sideYes
symbolYes
quantityYes
limit_priceYes
client_order_idYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must carry behavioral weight. It discloses that the order is paper-only and that prior risk validation is mandatory, which are useful traits. However, it does not explain failure behavior, required permissions, or side effects, so it only partially satisfies the burden.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence with no filler. Every part contributes meaning: 'submit', 'paper-only order', and the pre-trade validation requirement.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Despite having an output schema, the tool is missing essential usage context: parameter semantics are completely undocumented and there are no annotations. The description provides a high-level workflow hint but is not sufficient for an agent to construct valid calls reliably.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, and the description provides no meaning for any of the five required parameters. It does not compensate for the schema's lack of documentation, leaving the agent to guess valid values for side, quantity, limit_price, and client_order_id.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb ('submit') and resource ('paper-only order'), and adds a key ordering constraint ('after mandatory pre-trade risk validation') that distinguishes it from sibling validation tools. This is a clear, non-tautological purpose statement.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The phrase 'after mandatory pre-trade risk validation' gives the agent explicit context about when to invoke this tool relative to the validation workflow. It does not name alternatives or state when not to use it, but the precondition is clear enough for correct sequencing.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

trip_risk_circuit_breakerA

Irreversibly block new order attempts in this process; use for an incident or anomaly.

ParametersJSON Schema
NameRequiredDescriptionDefault
reasonYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.1/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the burden and it discloses three key traits: irreversibility, scope ('in this process'), and what it affects ('new order attempts'). It does not cover operational details like idempotency or whether pending orders are affected, hence not a 5.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

One tightly written sentence with no filler; the core action and trigger are front-loaded. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a one-parameter tool with an output schema, the description covers the essential what, scope, and when. The 'reason' parameter semantics and a bit more operational context are absent, but the tool is simple enough that the missing detail is minor.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has one required string 'reason' with 0% description coverage, and the description adds no parameter-level meaning. The name alone gives some clue, but the description was required to compensate for the schema gap and does not.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb ('block'), resource ('new order attempts'), and a critical modifier ('irreversibly'), plus the emergency context ('incident or anomaly'). This is clearly distinct from sibling tools like submit_paper_order or validate_order.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives a clear trigger condition: 'use for an incident or anomaly.' It does not explicitly name when-not-to-use or alternatives, but the emergency context is sufficient to guide selection against the normal-flow siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

validate_orderA

Run deterministic pre-trade risk checks without submitting an order.

ParametersJSON Schema
NameRequiredDescriptionDefault
sideYes
symbolYes
quantityYes
limit_priceYes
client_order_idYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the behavioral transparency burden. It does add meaningful traits: 'deterministic' and 'without submitting an order,' which rule out randomness and order placement side effects. It doesn't disclose input requirements or failure behavior, but the core safety property is stated.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence with no filler. It front-loads the action and the key safety distinction, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

A tool with five required parameters, no annotations, and 0% schema coverage needs more than a one-line description for correct invocation. While an output schema exists, it does not compensate for missing parameter semantics and unclear boundaries versus sibling risk tools.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, and the description does not explain any of the five required parameters. The agent is left with only parameter names and no guidance on formats, allowed values, or meaning, so the description adds no parameter-level value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Run') with a clear resource ('pre-trade risk checks') and adds the key distinction 'without submitting an order.' This makes it easy to distinguish from order-submission siblings like submit_paper_order.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The phrase 'without submitting an order' gives a clear context for when to use this tool: when validation is needed but execution is not. However, it does not explicitly name alternatives or state when not to use it, especially relative to trip_risk_circuit_breaker.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 5 tool updatesv0.1.0
    • First observedgenerate_alpha_signal
    • First observedmarket_snapshot
    • First observedsubmit_paper_order
    • First observedtrip_risk_circuit_breaker
    • First observedvalidate_order

TDQS

A3.7/5.0
Disambiguation5/5

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.

Naming Consistency4/5

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.

Tool Count5/5

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.

Completeness3/5

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

ActivityMaintained
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables 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
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to interact with Kalshi event contracts and perpetual markets via a safety-focused MCP interface, with paper trading by default, strict schemas, and fail-closed behavior.
    Apache 2.0

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/avnijainnn/QuantRisk'

If you have feedback or need assistance with the MCP directory API, please join our Discord server