# Building a Real-Time F&O Fair Value Engine for Indian Markets

- URL: https://www.dhruvvakharwala.dev/blogs/fo-fair-value-engine-dhan-saras
- Author: Dhruv Vakharwala (https://www.dhruvvakharwala.dev/about)
- Published: April 11, 2026
- Category: Engineering
- Keywords: fair value engine, black-scholes, options pricing, implied volatility, nse f&o, fastapi websocket

> How we built a production fair-value calculator on top of Dhan - Black-Scholes, cost of carry, live depth, and mispricing signals - for Saras and NSE F&O.

**TL;DR:** Built a real-time F&O fair value engine for Saras: multi-feed WebSocket ingest, thread-safe Black-Scholes + cost-of-carry core, Newton-Raphson IV solver, 20-level depth rotation, and a liquidity-scored mispricing signal. Live via Dhan data, FastAPI REST + `/ws/fair` out, cross-validated against the broker's option chain.


## Introduction

At [Saras](https://www.saras.market/) - 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](https://dhan.co/)** 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](https://github.com/vakharwalad23/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](https://www.saras.market/disclaimer). Fair value and "mispricing" are model outputs, not guarantees of future P&amp;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.

```mermaid
flowchart TB
    subgraph Data["Dhan data plane"]
      WS["WebSocket: ticks (Full mode)"]
      DWS["WebSocket: 20-level depth"]
      REST["REST: option chain / scrip master"]
    end

    subgraph Pool["Connection pool"]
      F0["Feed client 0"]
      F1["Feed client 1"]
      F2["Feed client 2"]
    end

    WS --> F0
    WS --> F1
    WS --> F2

    Depth["Depth client<br/>max 50 names, rotate ~30s"]
    DWS --> Depth

    Engine["FairEngine<br/>BS + CoC, IV solver, Greeks"]
    F0 --> Engine
    F1 --> Engine
    F2 --> Engine
    Depth --> Engine

    REST --> Scrip["Scrip master + resolution"]
    Scrip --> Engine
    Engine --> API["FastAPI: REST + /ws/fair"]
    UI["Dashboard + integrators"]
    API --> UI

    style Engine fill:#74b9ff,stroke:#0984e3,color:#fff
    style API fill:#55efc4,stroke:#00b894,color:#fff
    style Data fill:#fdcb6e,stroke:#e17055,color:#fff
```

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

```mermaid
sequenceDiagram
    participant Dhan as Dhan WebSocket
    participant Feed as Feed client (per-thread loop)
    participant Engine as FairEngine (locked)
    participant API as FastAPI / asyncio
    participant Client as Dashboard / API clients

    Dhan->>Feed: Tick + liquidity fields
    Feed->>Engine: Normalize tick
    Engine->>Engine: Reverse index + IV (Newton-Raphson)
    Engine->>Engine: BS price + Greeks + liquidity score
    Engine->>Engine: Mispricing % (clamped)
    Engine->>API: Schedule broadcast (thread-safe)
    API->>Client: JSON FairResult
```

---

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

```mermaid
graph LR
    S["Spot S"] --> BS["Black-Scholes"]
    K["Strike K"] --> BS
    T["Time T"] --> BS
    r["Rate r"] --> BS
    sig["Vol σ"] --> BS
    BS --> P["Theoretical price"]
    BS --> G["Greeks: Δ Γ ν ..."]
    BS --> X["Higher-order sensitivities"]

    style BS fill:#a29bfe,stroke:#6c5ce7,color:#fff
    style P fill:#74b9ff,stroke:#0984e3,color:#fff
```

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

```mermaid
flowchart TD
    M["|mispricing %|"]
    M -->|"< 1%"| Fair["FAIR - no directional label"]
    M -->|"≥ 1%, > 0"| Over["OVERVALUED - short bias (model vs market)"]
    M -->|"≥ 1%, < 0"| Under["UNDERVALUED - long bias (model vs market)"]

    style Fair fill:#dfe6e9,stroke:#636e72,color:#000
    style Over fill:#fab1a0,stroke:#e17055,color:#000
    style Under fill:#55efc4,stroke:#00b894,color:#fff
```

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.

```mermaid
flowchart LR
    Engine["Engine: IV + Greeks"] --> CV["Cross-validator"]
    Chain["Dhan option chain"] --> CV
    CV --> R["Per-field report"]

    style CV fill:#fdcb6e,stroke:#e17055,color:#fff
```

---

## 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/fair` for live `FairResult` JSON
- 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

[Post on X](https://x.com/i/status/2042720514112929977)

---

## Lessons learned

1. **Separate "tick scale" from "depth scale".** Depth is expensive; rotation toward high-signal names is non-negotiable.  
2. **Lock discipline beats clever sharing.** A single engine lock and careful snapshots make reasoning tractable.  
3. **Market calendar is a first-class dependency.** Holiday handling belongs in the feed layer, not in ad-hoc cron.  
4. **Validate against the broker.** Option chain cross-checks catch subtle rounding and calendar bugs early.  
5. **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.

---

**Takeaway:** Separate tick-scale from depth-scale, lock discipline beats clever sharing, and cross-validate against the broker's option chain. Liquidity is part of the signal - fair value on a thin book is noise, not alpha.


---

## References

- [Saras](https://www.saras.market/) - platform home  
- [Dhan](https://dhan.co/) - broker APIs and market data used by this engine  
- [fair-value-engine (GitHub)](https://github.com/vakharwalad23/fair-value-engine) - source, README, and `docs/architecture.md` / `docs/usage.md`