Skip to content

SomuTech/realtime-options-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

Trading MCP Server

License: MIT Python 3.13+ MCP SDK

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.

🎯 Overview

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.

Key Characteristics

  • 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_snapshot also 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

📊 System Architecture

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
Loading

✨ Features

Core MCP Tools

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

Architecture Highlights

  • 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)

🚀 Quick Start

Prerequisites

  • Python 3.13+
  • Angel One trading account with SmartAPI enabled
  • TradingView account (optional, for fallback candle data)

1. Clone & Setup

# 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

2. Configure Credentials

# 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_password

3. Start Server

python -m src.mcp_server

Server starts on stdio transport (MCP standard). Output:

Started MCP server on stdio
Tools registered: market_snapshot, candle_analysis, option_analysis, option_ltp, indicators

4. Validate Setup

python smoke_test.py

Expected output:

✅ market_snapshot: PASS
✅ candle_analysis: PASS
✅ option_analysis: PASS
✅ option_ltp: PASS
✅ indicators: PASS
═══════════════════════════════════════
All 5 tools verified ✓

📡 Tool API Reference

1. market_snapshot

Get real-time market snapshot for an index.

market_snapshot(symbol: str) -> str

Parameters:

  • 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
  }
}

2. candle_analysis

Fetch OHLCV candles with technical indicators.

candle_analysis(symbol: str, count: int = 25, interval: str | None = None) -> str

Parameters:

  • 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
    }
  }
}

3. option_analysis

Analyze options chain for strategies.

option_analysis(symbol: str, direction: str | None = None, strike: int | None = None) -> str

Parameters:

  • symbol (str): Index symbol
  • direction (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
    }
  }
}

4. option_ltp

Get LTP and Greeks for specific option strike.

option_ltp(symbol: str, strike: int, option_type: str, expiry: str | None = None) -> str

Parameters:

  • symbol (str): Index symbol
  • strike (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
    }
  }
}

5. indicators

Get technical indicators for an index.

indicators(symbol: str, interval: str | None = None) -> str

Parameters:

  • symbol (str): Index symbol
  • interval (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
    }
  }
}

🔄 Tool Invocation Flows

Market Snapshot Flow

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
Loading

Option LTP Flow

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
Loading

🏗️ Project Structure

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

🔧 Configuration

Environment Variables

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_MINUTE

🧪 Testing & Validation

Run Smoke Tests

python smoke_test.py

Tests all 5 tools against live data during market hours.


🛡️ Security

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

About

Claude-powered realtime trading agent for SENSEX/Nifty 50 options using Model Context Protocol (MCP)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages