Skip to main content

Option Strategy Simulator

Replay one trading day of an index option chain, add buy / sell legs by hand and watch P&L, payoff, Greeks and open interest as the clock moves. Modelled on StockMock's Simulator (walked on 2026-11-07), built on our own 1-minute IEOD store. TBS answers what would a rule have done over two years; the Simulator answers I am at 11:20 on 12 March, let me trade it.

Page Option Simulator (/option-simulator, developer rank like TBS). Plan, StockMock feature notes and a dated progress log: developer/todolist/option-simulator-plan.md.

Modules​

FileRole
backend/optsim/service.pyrun() builds the whole state for (underlying, date, expiry, cursor, orders); load() (day via the TBS loaders, small LRU on top of the TBS disk cache); chain_context() for the finder; to_tbs()
optsim/greeks.pyBlack-76 price, implied vol (bisection), delta / gamma / theta (per day) / vega (per vol point); forward from put-call parity at the strike nearest spot
optsim/payoff.pyExpiry payoff, target-time (T+0) curve, exact max profit / loss (piecewise linear), breakevens, probability of profit (lognormal), sigma bands, net Greeks. A {"cash": x} pseudo-leg carries the realised P&L of legs already exited
optsim/exits.pyPer-leg stop-loss / target on 1-minute bars: level fill, stop first when both hit in one bar
optsim/margin.pyExchange SPAN margin when the day's file is archived (tbs/spanmargin.NseSpan, never downloads), else the flat TBS estimate (MARGIN_PCT of the net sold notional)
optsim/oi.pyOI per strike at the cursor, PCR, max pain, OI series of the legs; reuses nseieod/oi_analysis._day (NIFTY / BANKNIFTY only)
optsim/finder.pyStrategy Finder: 1-4 leg combinations around ATM, numpy at the payoff kinks
optsim/to_tbs.pyBasket -> TBS strategy spec
optsim/live.pyToday's nseieod/oi_live snapshots -> a DayData
backend/app/api/optsim.py/api/optsim/*
frontend/src/pages/OptionSimulator.jsx, optsimTemplates.jsThe page, strategy tiles and the share-link codec

Underlyings (picker)​

Index / MCX / Stock picker as StockMock's. optsim/universe.py lists them (GET /underlyings): the 6 NSE / BSE indices, MCX symbols that have option files (code MCX:CRUDEOIL), and F&O stocks (equity rows of scr_master with stock options in the last 400 days). Stocks load through tbs/data.py (root_of() finds the stock's root masid) and have OI like NIFTY (oi_analysis._root falls back to the same lookup). MCX loads through optsim/mcx.py: no 1-minute spot exists, so the near-month continuous future (series I) is spot and fut; session 09:00 to the last bar (23:30 / 23:55), options expire 23:30 (dd.expiry_close), lot from scr_mcxfo_eod. MCX option files exist from 2025-07 and are on the VPS only (not tested locally); OI and Live are not available for MCX / BSE; "Backtest in TBS" is index-only.

Design: stateless​

The page owns the orders and the cursor. Every change posts the whole book to /state and the server rebuilds chain, positions, payoff, Greeks and the day series from the bars, so scrubbing the clock, replay and refresh need no server session. An order is {side B|S, opt CE|PE, strike, expiry, lots, time HH:MM, sl %, tp %}; the entry price is the bar close of the minute the leg was added (what the chain showed). Legs added after the cursor are not in the book yet; a leg whose contract has no bars is flagged error instead of failing the page.

API​

CallPurpose
GET /meta?underlying=Underlyings, data range (cached 10 minutes: the availability scan is slow)
GET /day?date=&step=Neighbouring NSE trading day (<< Day, Day >>)
POST /stateEverything for the cursor (target, iv_shift, lot_mode, live optional)
POST /marginMargin of the open legs (can take seconds: SPAN file), separate from /state
POST /oiOI per strike, PCR, max pain, leg OI series
POST /finderRanked combinations
POST /to-tbsTBS spec + warnings
GET /live-statusIs a live snapshot day available
GET / POST /basketsSaved baskets (library category optsim, delete through /api/library/strategies/{id})

What the page shows​

  • Clock: the OI page's navigator (<< Day, SOD, -2h ... -1m, hour / minute, 1m+ ... 2h+, EOD, Day >>) and Auto Run (move 1 / 5 / 15 / 30 min, 2 hours or a Day, every 1-5 s, till EOD or a time).
  • Chain: LTP with delta and OI per strike, ATM IV, straddle, DTE, PCR, max pain, total OI. ATM row centred (blue), ITM cells shaded yellow, ATM measured from Spot, Fut or Synth Fut (parity forward), hover a row for ATM +/- distance. B / S buttons per row; a contract that already has a leg shows the lots as a badge and the button opens + Buy|Sell / Remove. A strike that did not trade at the clock minute is greyed with at HH:MM of its last trade (Bars.real, the trade mask the loaders now keep; old cache files without it fall back to a carry-pattern guess). Hide collapses the chain: statistics and positions move to the left half, the payoff chart takes the right half.
  • Positions: lots stepper per leg and Qty in shares (lots x lot size).
  • Summary: P&L, max profit / loss, POP, net credit, margin (SPAN or estimate), breakevens.
  • Charts: Payoff (expiry line filled green above zero and red below, drag across it to zoom with a Reset zoom button, hover shows P&L at that spot, dashed target-time curve, spot and +/-1 / 2 sigma lines; Change IV, Target on, Change spot), MTM, Premium, OI (with OI change), Spot; the OI checkbox on the payoff draws CE / PE open interest bars per strike behind it; 1 / 2 / 3 / 5 / 15 minute timeframes on the day charts.
  • Positions table: per-leg expiry, entry, LTP, IV, delta, theta, gamma, vega, P&L, SL / target and exit marks; Open legs only.
  • Toolbar: Strategies (16 tiles at ATM with a wing width), Strategy Finder (popup), Save / Saved, Import (link or JSON), Backtest in TBS.

Numbers and their limits​

  • IV and Greeks are solved from 1-minute bar closes (Black-76, flat 6.5 % rate, forward from put-call parity); deep ITM options with no time value show no IV. Expiry is 15:30 IST.
  • Theta is per calendar day, vega per vol point, delta / gamma / theta / vega in units (lots x lot size).
  • Entry price = bar close of the cursor minute, no slippage or charges. P&L is gross.
  • Margin is exchange SPAN only when the file for that day is archived (margin/); otherwise a flat estimate, labelled as such.
  • The TBS loader reads the weekly and monthly expiries only, so only those expiries have chains.
  • OI exists for NIFTY, BANKNIFTY and F&O stocks (oi_analysis replay); FINNIFTY, MIDCPNIFTY, BSE and MCX show an empty OI chart. SENSEX / BANKEX and MCX option data is on the VPS only.
  • A strike with no trade yet today shows no price (the previous day's close is not looked up).

Strategy Finder​

Enumerates 1-4 leg combinations of the CE / PE strikes around ATM (calls from ATM - ITM to ATM + OTM strikes, puts the mirror), each bought or sold. The expiry payoff is piecewise linear, so every combination is evaluated exactly at its kinks (0, the strikes and the +/-2 sigma edges) with numpy: about 2.7 million combinations in 4-5 seconds.

  • Keeps risk-defined structures only (net long calls >= net short calls and net long puts >= net short puts) and drops "free lunch" results (no loss anywhere), which are price-rounding artefacts.
  • Reward = best payoff inside +/- 2 standard deviations of the time left (a far OTM long wing earns nothing there); risk = true worst case. Filters: min reward : risk, min POP, max loss (rupees), bias (net delta), leg count.
  • Ranked by POP x min(R:R, 20). Names are recognised for the common shapes, otherwise "Custom N-leg".

Backtest in TBS​

to_tbs.convert() makes an intraday spec: strikes as ATM steps (ATM of the cursor minute), expiry as the weekly / next weekly / monthly / next monthly rule it was on that day, SL / target as premium_pct, entry = first leg minute + 1 (TBS enters at the next bar open), later legs get a per-leg start time, exit 15:15, square off partial. The page stores {spec, warnings} in sessionStorage['optsimToTbs'] and goes to /tbs, where TbsBacktest.jsx loads it once.

Live mode (button hidden for now)​

live.load_live() reads today's oi_live snapshots (every 3 minutes in market hours, OI_LIVE_COLLECT), carries each value to 1-minute bars (open = high = low = close = last traded price) and attaches OI as dd.oi_live. Everything else runs unchanged; the page polls /live-status every 30 s and follows the newest snapshot. NIFTY / BANKNIFTY only; a contract that has not traded today has no price. The collector keeps the current day only.

Tests​

cd backend
venv\Scripts\python -m pytest tests -k optsim

test_optsim_core.py (Black-76, IV, Greeks, payoff extremes, exits, margin estimate, finder), test_optsim_api.py (the API with a stubbed day, an in-memory library, a made-up live snapshot file). No test touches the database or the Parquet store. UI checks were done in the browser with a temporary no-login page; there is no automated UI test.

Open items​

  • Rolling Straddle tab, OI for FINNIFTY / MIDCPNIFTY / SENSEX / BANKEX.
  • Real in-session Live mode on the VPS, SENSEX / BANKEX on the VPS, and the real login flow are untested.
  • Phase 3 margin shows the estimate locally (no SPAN files for most days).