Building a Real-Time F&O Fair Value Engine for Indian Markets
Introduction
At Saras—where we bring structured analytics and transparency to India’s trading ecosystem—one of the problems I wanted to solve in depth was options and futures fair value. Not a one-off spreadsheet: a real-time engine that could ingest live NSE F&O data, price contracts with standard models, score liquidity, and surface actionable mispricing alongside a live dashboard and APIs.
This post is a technical walkthrough of that system: architecture, pricing models, how we use Dhan for market data and reference checks, and what it took to keep the path smooth and fast in production. The implementation is open on GitHub as fair-value-engine.
Disclaimer: This article describes engineering and models for research and platform tooling. It is not investment advice. Saras is not a SEBI-registered advisor; see the platform disclaimer. Fair value and “mispricing” are model outputs, not guarantees of future P&L.
Why Fair Value for F&O?
Retail and professional participants often compare market price to a theoretical price derived from spot, time to expiry, rates, and volatility. For options, that is typically Black–Scholes (with implied volatility solved from the market). For index/stock futures, cost of carry links futures price to spot.
If you can compute that continuously and combine it with liquidity (spread, depth, volume, OI), you get:
- A theoretical fair price and Greeks for each contract
- A mispricing percentage vs. last traded price (with sensible clamps)
- A quality flag when the book is too thin to trust the signal
That is the core product loop we implemented end-to-end.
High-level architecture
The engine is a Python service: multiple WebSocket feeds for ticks and depth, a thread-safe pricing core, and FastAPI exposing REST + a live WebSocket stream to a small dashboard.
Capacity sketch: we shard subscriptions across three tick connections (thousands of instruments each per Dhan limits) and a separate depth connection capped at 50 instruments, auto-rotated toward the strongest current signals so the scarce depth budget tracks what matters.
End-to-end tick path
When a tick arrives, the engine resolves the contract in O(1), updates state under a lock, solves IV where needed, reprices, and optionally notifies the async layer for WebSocket broadcast.
Pricing models
Options: Black–Scholes + Newton–Raphson IV
We use standard Black–Scholes inputs: spot S, strike K, time to expiry T, risk-free r, and volatility σ. Implied volatility is backed out with Newton–Raphson so the model reprices the observed market as vol moves.
Futures: cost of carry
Futures fair value follows the cost-of-carry relation F = S · exp((r − d)·T) (dividend yield d where applicable). This keeps index and single-stock futures on the same conceptual footing as options in the same engine.
From fair price to “signal”
We classify mispricing in a simple, auditable way: small deviations are noise; beyond a threshold, direction matters.
Outputs are clamped (e.g. extreme percentages capped) and low-liquidity contracts are flagged so the UI and downstream consumers can deprioritize junk books.
Liquidity and 20-level depth
Dhan’s tick stream in Full mode gives rich top-of-book and activity fields. We also maintain a separate binary depth feed (20 levels per side) for a subset of names. That feeds:
- Spread and spread percentage
- Composite liquidity score
- Depth imbalance and stacked book snapshots
In practice, data quality from Dhan has been solid for this use case—ticks and depth line up well enough that cross-checks against their option chain API are meaningful.
Cross-validation: trusting the math
We can pull Dhan option chain Greeks/IV and compare them to the engine’s numbers, bucketed into OK / WARN / ALERT style deviation bands. That is invaluable when you are iterating on calendars, rates, or edge cases around expiries.
Threading, market hours, and “boring” reliability
Feeds run on dedicated threads with their own event loops; the engine mutates shared state under threading.Lock; WebSocket broadcast uses run_coroutine_threadsafe into the main asyncio loop. NSE hours and a cached holiday calendar mean clients sleep cleanly after the close instead of hammering reconnect loops—something you feel immediately in ops noise and CPU.
The result day-to-day: infra stays smooth—predictable CPU, stable connections, and a UI that can show MARKET CLOSED with a countdown instead of pretending the world is live.
What ships outward
- REST endpoints for fair results, signals, contracts, scrip resolution, option chain overlays, and validation reports
- WebSocket
/ws/fairfor liveFairResultJSON - A small static dashboard for monitoring signals and subscription tiers
That surface area lets product teams iterate without forking the core pricing code.
Post on X
Made real-time F&O fair value engine for Indian markets @DhanHQ ticks → Black-Scholes / Cost of Carry → mispricing signals Multiple instrument slots, enhanced Greeks , live dashboard Experimental. DYOR. github.com/vakharwalad23/…
Lessons learned
- Separate “tick scale” from “depth scale”. Depth is expensive; rotation toward high-signal names is non-negotiable.
- Lock discipline beats clever sharing. A single engine lock and careful snapshots make reasoning tractable.
- Market calendar is a first-class dependency. Holiday handling belongs in the feed layer, not in ad-hoc cron.
- Validate against the broker. Option chain cross-checks catch subtle rounding and calendar bugs early.
- Liquidity is part of the signal. Fair value without book quality is easy to misread.
Conclusion
Building this fair value engine meant wiring solid market data (via Dhan), classical pricing, and operational realism—sessions, holidays, connection budgets, and honest liquidity flags. At Saras, that kind of infrastructure turns raw feeds into consistent quantitative context traders can reason about, not just another chart overlay.
If you are exploring similar systems, start with a thin vertical slice: one index chain, full tick + depth, IV solver, and a single validation endpoint. Scale the subscription tiers once the numbers match the vendor chain within tolerance.
References
- Saras — platform home
- Dhan — broker APIs and market data used by this engine
- fair-value-engine (GitHub) — source, README, and
docs/architecture.md/docs/usage.md