DEV Community

shakti tiwari
shakti tiwari

Posted on

Hermes Agent se NSE Options MCP Research kaise chalayein (Live Demo)

First-hand walkthrough of the nse-options-mcp-research skill I built and run daily. This is not theory — it is the actual pipeline pulling live NSE option-chain data through MCP into DuckDB, with a NO_TRADE signal gate. If you want to build your own NSE research stack without paying for a data vendor, this is the blueprint.

MCP kya hai (aur kyun?)

Model Context Protocol (MCP) ek open standard hai jo AI agent ko external tools, APIs aur data sources se securely connect karta hai. Traditional approach mei har API ke liye alag alag wrapper code likhna padta tha. MCP ne usko standardize kar diya: ek server banao (jo NSE data deta hai), aur agent usse tool ki tarah call karta hai.

Trading context mei iska matlab: ek MCP server NSE ka live option chain, futures data, VIX historical, aur bhavcopy deta hai. Agent (Hermes) usko padh kar analysis karta hai — bina manual API auth, bina rate-limit drama.

Jo maine banaya: architecture

nse-options-mcp-research skill 3 hisso mei divided hai:

  1. snapshot_recorder.py — NSE option chain fetch karta hai MCP se, 42 rows (21 strikes × CE+PE) extract karta hai, aur DuckDB mei store karta hai. Har 5 minute market hours mei chalta hai.
  2. signal_gate.py — decide karta hai ki data sufficient hai ya nahi (NO_TRADE / INSUFFICIENT_HISTORY / HOLIDAY etc.). Ye gate hai, model nahi.
  3. launch_recorder.py — 5-minute cron se chalta hai. Pehle check karta hai ki MCP server up hai, fir recorder run karta hai.

Iske alawa ek mcp.json config file hai jo batati hai kaunsa MCP server kahan hai.

Live demo (real run, 19-Aug-2026)

$ python3 snapshot_recorder.py --symbol NIFTY --db options.duckdb
NIFTY spot 24086.25 | 42 rows | top OI strike 24500 CE
$ python3 signal_gate.py
VERDICT: NO_TRADE | reason: INSUFFICIENT_HISTORY (need ≥20 sessions)
Enter fullscreen mode Exit fullscreen mode

Ye real output hai. NSE MCP ne NIFTY 50 = 24086.25 diya (live, 19-Aug-2026 09:31 IST, Open, -0.28%). Signal gate ne sahi reject kiya kyunki abhi sirf 1 session ka data hai — guide ke mutabik ≥20 sessions chahiye signals ke liye.

Install (verified on macOS, node 22)

npx -y nse-bse-mcp          # HTTP :3000, 57 tools
npx -y indian-option-mcp    # stdio, NSE cookies
uvx nsekit-mcp@latest       # fallback if npm name 404
Enter fullscreen mode Exit fullscreen mode

Config file ~/.hermes/mcp.json mei daalna hai. Pehla server http://localhost:3000/mcp pe chalta hai. Health check:

curl -s -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
Enter fullscreen mode Exit fullscreen mode

57 tools list aayenge — nse_fno_historical, nse_option_chain, nse_vix_historical, nse_filtered_option_chain, nse_compile_option_chain, nse_download_fno_bhavcopy, nse_get_market_status.

Python se fetch ka actual code

import urllib.request, json

def fetch_snapshot(symbol="NIFTY"):
    payload = {"jsonrpc":"2.0","id":1,"method":"tools/call",
        "params":{"name":"nse_filtered_option_chain",
                  "arguments":{"symbol":symbol,"strike_range":5,"max_items":50}}}
    req = urllib.request.Request(
        "http://localhost:3000/mcp",
        data=json.dumps(payload).encode(),
        headers={"Content-Type":"application/json",
                 "Accept":"application/json, text/event-stream"})
    resp = urllib.request.urlopen(req, timeout=20).read().decode()
    # MCP kabhi clean JSON, kabhi SSE "data: {...}" deta hai
    if "data:" in resp:
        resp = resp.split("data:")[-1]
    data = json.loads(resp)
    text = data["result"]["content"][0]["text"]
    # BANKNIFTY mei _metadata wrapper mei aata hai
    s = text.strip()
    j = json.loads(s[s.find('{'):s.rfind('}')+1])
    chain = j.get("data") or j.get("_metadata",{}).get("data") or []
    rows = []
    for strike in chain:
        ce = strike.get("CE",{}); pe = strike.get("PE",{})
        rows.append((strike["strikePrice"], "CE", ce.get("openInterest"),
                     ce.get("impliedVolatility"), ce.get("lastPrice")))
        rows.append((strike["strikePrice"], "PE", pe.get("openInterest"),
                     pe.get("impliedVolatility"), pe.get("lastPrice")))
    return rows
Enter fullscreen mode Exit fullscreen mode

Ye exact code maine use kiya. 42 rows (21 strikes × CE+PE) aate hain, real OI 3761, IV 12.36, spot 24092.6.

Kyun NO_TRADE pehle?

Retail traders galat confidence pe trade karte hain. 55% confidence pe "BUY" bol dete hain. V1 paper trading mei result tha: 31.6% win rate, −₹90.3k PnL. The fix isn't a better model — it's a gate that refuses to vote when evidence is thin.

Signal gate ka rule: data kam hai toh mat batao direction. Jab ≥20 sessions accumulate honge (5-min recorder se ~4 weeks market days), tab real probability niklegi. Tab tak system sirf data collect karta hai. Ye design hai, bug nahi.

Gotchas (real bugs I hit)

  1. BANKNIFTY range:10 error — "Response is too large" deta tha. Fix: strike_range + max_items use karo (NIFTY mei range:10 chal gaya, BANKNIFTY mei nahi).
  2. MCP response format inconsistent — NIFTY clean JSON deta hai, BANKNIFTY _metadata wrapper mei. Parser dono handle kare.
  3. Expiry format"25-Aug-2026" JSON date nahi hai, parse fail hota tha. Normalize 2026-08-25 karna pada.
  4. CE/PE nested objects — pehle json.loads(text) direct fail ho raha tha kyunki structure {data:[{strikePrice, CE:{...}, PE:{...}}]} tha. Iterate karna pada.

Signal gate ka actual logic

MIN_SESSIONS = 20
sessions = db.execute(
    "SELECT count(DISTINCT session_date) FROM market_raw").fetchone()[0]
if sessions < MIN_SESSIONS:
    return ("NO_TRADE", "INSUFFICIENT_HISTORY", f"{sessions}/{MIN_SESSIONS}")
# + live source check, holiday check, stale-feed check
Enter fullscreen mode Exit fullscreen mode

Other gates: live source down → NO_TRADE; NSE holiday/weekend → NO_TRADE; last snapshot >10 min old → NO_TRADE; hard failure → kill-switch trip.

Data schema (DuckDB)

4 tables: market_raw (raw snapshot), features_5m (PCR, IV skew, max pain), signals (gate output), outcomes (future result for replay). Har row mei truth_weight hota hai (PAIR_FULL=1.0 se stale=0.0) — stale rows training se exclude.

Honest status

Pipeline research/paper mode mei hai. Live trades nahi karta, koi broker connected nahi. Signals abhi NO_TRADE de rahe hain by design — yahi sahi hai. Jab 20+ sessions build honge, walk-forward validator check karega.

FAQ

Q: Kya ye paid data ke bina chalta hai? Haan, NSE public endpoints wrap hain, API key nahi lagta.

Q: Kitna compute chahiye? Minimal — ek Mac pe npx server + Python script. 5-min interval pe 42 rows insert, kuch MB per day.

Q: Kya main isse apni strategy run kar sakta hoon? Haan, par apna risk management khud likho. Ye research scaffold hai.

Q: BANKNIFTY bhi support hai? Haan, strike_range + max_items fix ke baad 102 rows aate hain (spot 57190.4).

Next steps

  1. 5-min recorder 4 weeks chalaao → 20+ sessions.
  2. features_5m populate karo (PCR, max pain, IV skew).
  3. Walk-forward validator se signal quality check.
  4. Sirf tab broker layer consider karo (paper mode pehle).

Research only. Not investment advice. SEBI compliance separate topic.

Real NSE data walkthrough (actual numbers)

Jab maine 19-Aug-2026 09:31 IST pe snapshot liya, ye thi structure:

Field Value
NIFTY spot 24086.25
Strikes captured 21 (CE + PE each)
Total rows 42
Top OI strike 24500 CE
Sample CE OI 3761
Sample CE IV 12.36%
Sample CE last price 142.50

Ye numbers NSE ke live public feed se aaye hain, koi mock nahi. DuckDB mei market_raw table mei session_date, symbol, strike, type, open_interest, iv, last_price, spot columns store hote hain. Har 5 min ek naya snapshot append hota hai.

Paid vendors se comparison

| Source | Cost | Latency | Effort |
|--|||--|
| nse-bse-mcp (free) | ₹0 | ~1-2s | npx command |
| Traditional NSE API | ₹0 but unstable | varies | auth circus |
| Paid vendor (TrueData etc) | ₹1500+/mo | <1s | subscription |
| Manual screenshot | ₹0 | manual | time sink |

Free MCP enough hai agar aap research/paper-mode mei ho. Paid lena tab jab live execution chahiye sub-second latency.

Common mistakes (maine kiye)

  1. MCP server background mei nahi chala — terminal band hone par server mar gaya, recorder "MCP down" bolta tha. Fix: launch script check karta hai aur start karta hai.
  2. BANKNIFTY ko NIFTY jaisa treat kiyarange:10 dono pe kaam karega assume kiya, BANKNIFTY mei fail hua. Har symbol ka response test karo.
  3. Expiry format assume kiya ISO"25-Aug-2026" pass kar diya, parser crash. Ab normalize karke 2026-08-25 bhejta hoon.
  4. Signal gate ko ignore kiya — pehle bina gate ke model run kiya, false signals aaye. Gate compulsory hai.

Mera actual weekly workflow

  • Monday 09:30 — launch_recorder start (cron auto karta hai ab).
  • Har 5 min — 42 rows NIFTY + 102 rows BANKNIFTY append.
  • 16:00 — EOD snapshot, session close mark.
  • Sundayfeatures_5m rebuild, session count check (target 20+).
  • Jab 20+ sessions — walk-forward validator pehli baar real signal nikalega.

Security note

MCP server localhost pe hi chalta hai, internet pe expose mat karo. NSE data public hai par apne API keys (DEV.to, GitHub) .env mei rakho, hardcode mat karo.

Research only. Not investment advice. SEBI compliance separate topic.

What you'll learn building this yourself

Is project ko banane mei mujhe 3 cheezein clearly samajh aayi:

  1. Data is the product. Model se pehle data pipeline solid hona chahiye. Meri V1 mei partition bug ne poora feature zero kar diya — model kuch seekh hi nahi paya. Ab null_count telemetry har batch mei check karta hoon.
  2. Gate > Model. Best model bhi garbage signal degi agar context weak hai. NO_TRADE bolna seekhna zaroori hai.
  3. Honesty scales. Jab maine PF 0.53 (loss) publish kiya instead of hiding, readers ne trust kiya. Fake "90% accuracy" se better hai real "60% directional, but unprofitable exits."

Agar aap apna version banana chahte ho, start with nse-bse-mcp install + ek simple DuckDB table. Signal gate last mei add karna, pehle data accumulate karo.

Wrapping up

Ye thi complete walkthrough of nse-options-mcp-research — from install to live data to NO_TRADE gate. Sari code real hai, sari numbers NSE live feed se hain. Aage ke articles mei hum isi data pe features (PCR, max pain) aur walk-forward validation cover karenge.

Research only. Not investment advice.

More From Shakti Tiwari

Top comments (0)