A production-grade Model Context Protocol (MCP) server that provides real-time market analysis tools for Indian index derivatives trading. Designed for AI agent integration with clean separation of concerns, robust error handling, and enterprise-grade reliability.
Trading MCP bridges AI agents and live market data, enabling algorithmic analysis of NIFTY and SENSEX instruments. The server exposes five core tools with multi-provider data resilience and graceful fallback strategies.
- Protocol: Model Context Protocol (MCP) for universal AI integration
- Data Sources: Angel One SmartAPI + NSE Public APIs with intelligent fallback
- Response Format: Structured JSON with explicit status codes and diagnostic metadata
- Macro Context:
market_snapshotalso includes GIFT Nifty, FII/DII footprint, USD/INR, and Brent crude - Error Handling: Retry logic, partial response support, and market-closure awareness
- Logging: Per-session structured logs for audit and debugging
graph TB
subgraph "Client Layer"
AI["AI Agent / Client"]
end
subgraph "MCP Server"
FastMCP["FastMCP Server<br/>src/mcp_server.py"]
subgraph "Tool Handlers"
MS["market_snapshot()"]
CA["candle_analysis()"]
OA["option_analysis()"]
OL["option_ltp()"]
IND["indicators()"]
end
end
subgraph "Business Logic Layer"
VA["Input Validators<br/>validators.py"]
METRICS["Metrics Processor<br/>metrics.py"]
RESPONSE["Response Formatter<br/>response.py"]
end
subgraph "Integration Layer"
ANGEL["Angel One SmartAPI<br/>angel_one.py"]
NSE["NSE Public APIs<br/>via nsepython"]
TVDF["TradingView Datafeed<br/>tvDatafeed"]
end
subgraph "External Services"
ANGEL_SVC["Angel One<br/>Live Streaming API"]
NSE_SVC["NSE<br/>Option Chain API"]
TVDF_SVC["TradingView"]
end
AI -->|"Tool Invocation"| FastMCP
FastMCP -->|"Route"| MS
FastMCP -->|"Route"| CA
FastMCP -->|"Route"| OA
FastMCP -->|"Route"| OL
FastMCP -->|"Route"| IND
MS --> VA
CA --> VA
OA --> VA
OL --> VA
IND --> VA
VA --> METRICS
METRICS --> RESPONSE
VA --> ANGEL
VA --> NSE
VA --> TVDF
ANGEL --> ANGEL_SVC
NSE --> NSE_SVC
TVDF --> TVDF_SVC
RESPONSE -->|"JSON Response"| FastMCP
FastMCP -->|"MCP Protocol"| AI
| Tool | Purpose | Data Source | Fallback |
|---|---|---|---|
| market_snapshot | Real-time index LTP + macro context (GIFT Nifty, FII/DII, USD/INR, Brent) | Angel One + public macro APIs | Historical candles |
| candle_analysis | OHLCV bars with RSI & volume SMA | Angel One | TradingView |
| option_analysis | Options chain analysis (IV, Greeks) | NSE API | Cached data |
| option_ltp | Specific strike LTP & Greeks | NSE chain | Last candle |
| indicators | Technical indicators (EMA, VWAP) | Angel One | Computed from candles |
- ✅ Multi-provider resilience with intelligent fallback strategies
- ✅ Structured error handling with explicit status codes
- ✅ Market-aware (handles pre-market, trading hours, and closure)
- ✅ Stateless design for horizontal scalability
- ✅ Audit logging with per-session structured JSON logs
- ✅ Type-safe with Python 3.13+ dataclass validation
- ✅ Environment-only credentials (zero hardcoded secrets)
- Python 3.13+
- Angel One trading account with SmartAPI enabled
- TradingView account (optional, for fallback candle data)
# Clone repository
git clone https://github.com/SomuTech/realtime-options-agent.git
cd realtime-options-agent
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt# Copy template
cp .env.example .env
# Edit .env with your credentials
# ANGEL_API_KEY=your_api_key
# ANGEL_CLIENT_ID=your_client_id
# ANGEL_PASSWORD=your_trading_password
# ANGEL_TOTP_SECRET=your_totp_seed (base32)
# TVDATAFEED_USERNAME=your_email
# TVDATAFEED_PASSWORD=your_passwordpython -m src.mcp_serverServer starts on stdio transport (MCP standard). Output:
Started MCP server on stdio
Tools registered: market_snapshot, candle_analysis, option_analysis, option_ltp, indicators
python smoke_test.pyExpected output:
✅ market_snapshot: PASS
✅ candle_analysis: PASS
✅ option_analysis: PASS
✅ option_ltp: PASS
✅ indicators: PASS
═══════════════════════════════════════
All 5 tools verified ✓
Get real-time market snapshot for an index.
market_snapshot(symbol: str) -> strParameters:
symbol(str): Index symbol ("NIFTY"or"SENSEX")
Response:
{
"symbol": "NIFTY",
"status": "ok",
"timestamp": "2026-04-12T09:45:30.123456+05:30",
"data": {
"ltp": 23170.50,
"prev_close": 23150.25,
"day_high": 23250.00,
"day_low": 23100.00,
"volume": 15234500,
"oi": 5450000,
"change": 20.25,
"change_percent": 0.0874,
"bid": 23169.50,
"ask": 23171.50
}
}Fetch OHLCV candles with technical indicators.
candle_analysis(symbol: str, count: int = 25, interval: str | None = None) -> strParameters:
symbol(str):"NIFTY"or"SENSEX"count(int): Number of candles (default: 25)interval(str, optional):"ONE_MINUTE","FIVE_MINUTE","FIFTEEN_MINUTE","HOURLY","DAILY"
Response:
{
"symbol": "NIFTY",
"status": "ok",
"timestamp": "2026-04-12T09:45:30.123456+05:30",
"data": {
"interval": "FIVE_MINUTE",
"candles": [
{
"time": "2026-04-12T09:40:00+05:30",
"open": 23160.00,
"high": 23180.50,
"low": 23150.25,
"close": 23170.50,
"volume": 125000
}
],
"indicators": {
"rsi_14": 65.42,
"volume_sma_20": 118500,
"ema_9": 23172.30,
"vwap": 23168.75
}
}
}Analyze options chain for strategies.
option_analysis(symbol: str, direction: str | None = None, strike: int | None = None) -> strParameters:
symbol(str): Index symboldirection(str, optional):"CE"(Call) or"PE"(Put)strike(int, optional): Strike price filter
Response:
{
"symbol": "NIFTY",
"status": "ok",
"data": {
"index_ltp": 23170.50,
"expiry": "19-Mar-2026",
"chain_summary": {
"total_calls": 125,
"total_puts": 125,
"atm_strike": 23200
},
"iv_analysis": {
"call_iv_mean": 18.5,
"put_iv_mean": 19.2,
"iv_skew": 0.7
}
}
}Get LTP and Greeks for specific option strike.
option_ltp(symbol: str, strike: int, option_type: str, expiry: str | None = None) -> strParameters:
symbol(str): Index symbolstrike(int): Strike price (e.g., 23150)option_type(str):"CE"or"PE"expiry(str, optional): Expiry date (default: nearest expiry)
Response:
{
"symbol": "NIFTY",
"strike": 23150,
"option_type": "CE",
"status": "ok",
"data": {
"index_ltp": 23170.50,
"option": {
"ltp": 135.50,
"oi": 450000,
"volume": 89500,
"iv": 18.5
},
"greeks": {
"delta": 0.62,
"theta": -0.35,
"vega": 0.42,
"intrinsic_value": 20.50
}
}
}Get technical indicators for an index.
indicators(symbol: str, interval: str | None = None) -> strParameters:
symbol(str): Index symbolinterval(str, optional): Candle interval (default:FIVE_MINUTE)
Response:
{
"symbol": "NIFTY",
"status": "ok",
"data": {
"interval": "FIVE_MINUTE",
"indicators": {
"rsi_14": 65.42,
"ema_9": 23172.30,
"vwap": 23168.75,
"volume_sma_20": 118500,
"atr_14": 45.25
}
}
}sequenceDiagram
participant Client
participant MCP as MCP Server
participant Validator as Input Validator
participant Angel as Angel One API
participant Logger as Session Logger
Client->>MCP: market_snapshot("NIFTY")
MCP->>Validator: Validate symbol
Validator-->>MCP: ✓ Valid
MCP->>Angel: Query NIFTY LTP
alt Market Open
Angel-->>MCP: Live LTP + Volume
else Market Closed
Angel-->>MCP: Last candle data
end
MCP->>Logger: Write audit log
MCP-->>Client: JSON Response
sequenceDiagram
participant Client
participant MCP
participant NSE as NSE API
participant Compute as Greeks Calculator
Client->>MCP: option_ltp("NIFTY", 23150, "CE")
MCP->>NSE: Fetch option chain
NSE-->>MCP: Full chain with all strikes
MCP->>MCP: Extract strike 23150 from chain
MCP->>Compute: Calculate Greeks (delta, theta, vega)
Compute-->>MCP: Greeks data
MCP-->>Client: Complete option data + Greeks
trading-mcp/
├── src/
│ ├── __init__.py
│ ├── mcp_server.py # MCP tool registration & routing
│ ├── runtime.py # Runtime configuration & context
│ │
│ ├── config/
│ │ ├── trading_rules.py # Trading constants & expirations
│ │ └── symbols.py # Supported symbols metadata
│ │
│ ├── integrations/
│ │ ├── angel_one.py # Angel SmartAPI wrapper
│ │ ├── nse_api.py # NSE option chain API
│ │ └── tvdatafeed_client.py # TradingView fallback
│ │
│ └── tools/
│ ├── response.py # Response envelope formatter
│ ├── validators.py # Input validation rules
│ ├── metrics.py # Technical indicator computation
│ ├── market_snapshot.py # market_snapshot tool
│ ├── candle_analysis.py # candle_analysis tool
│ ├── options_analysis.py # option_analysis & option_ltp tools
│ └── indicators.py # indicators tool
│
├── docs/
│ ├── ARCHITECTURE.md
│ ├── API_REFERENCE.md
│ └── DEPLOYMENT.md
│
├── server.py # Entrypoint (delegates to src.mcp_server)
├── smoke_test.py # Integration test suite
├── requirements.txt # Python dependencies
├── .env.example # Credential template
├── .gitignore
└── LICENSE
Create .env file (copy from .env.example):
# ===== REQUIRED: Angel One Credentials =====
ANGEL_API_KEY=your_smartapi_key_here
ANGEL_CLIENT_ID=your_client_id_here
ANGEL_PASSWORD=your_trading_password_here
ANGEL_TOTP_SECRET=your_base32_totp_seed_here
# ===== OPTIONAL: TradingView Fallback =====
TVDATAFEED_USERNAME=your_email@gmail.com
TVDATAFEED_PASSWORD=your_tv_password_here
# ===== OPTIONAL: Trading Configuration =====
DEFAULT_SYMBOL=NIFTY
CANDLE_INTERVAL=FIVE_MINUTEpython smoke_test.pyTests all 5 tools against live data during market hours.
✅ No hardcoded secrets - All credentials from environment
✅ Trace audit logs - JSON logs for regulatory compliance
✅ .gitignore configured - .env never committed
✅ Input validation - All parameters sanitized
Built with ❤️ By SomuTech