Skip to main content

Option Strategy Simulator - initial plan (2026-11-07)

Status (2026-11-07): phases 1-8 done and committed locally, not pushed or deployed. Reference doc: developer/knowledge-base/option-simulator.md. Left open: Rolling Straddle tab, OI for FINNIFTY / MIDCPNIFTY / SENSEX / BANKEX, in-session Live mode on the VPS, VPS / login-flow testing (see section 5a). Section 2 was written from a walk of the logged-in StockMock Simulator (Nifty, one test leg); only Saved Strategies, Import, Rolling Straddle, Add Alert, Exit and Share were not opened.

1. What it is​

TBS (backend/tbs) answers "what would a rule have done over 2 years?". The Simulator answers "I am standing at 11:20 on 2025-03-12. Let me trade it by hand, minute by minute, and see P&L, payoff and Greeks." A practice / replay tool on our own 1-minute data (NSE + BSE SENSEX / BANKEX).

2. StockMock Simulator - features to confirm on the logged-in page​

AreaExpected (confirm)
Setupindex, date, expiry (weekly / monthly)
Replaystart time, play / pause, step 1 bar, speed 1x..N, jump to time, slider
Option chain at the cursor timestrikes around ATM, LTP, OI, IV, delta, buy / sell buttons per CE / PE
Positionslegs with qty (lots), entry, LTP, P&L, close leg, close all, per leg SL / target
Payoffexpiry payoff + "today" (T+0) curve, breakevens, max profit / loss, margin
Greeksnet delta, gamma, theta, vega of the basket
Chartsspot / futures chart, premium chart of selected legs, combined premium
Miscsave / load basket, day navigation, results summary

Needed from the user: log in in the Browser pane, then I walk each tab and screenshot the controls (read only). I will not type credentials.

Terms of service: StockMock bans scripts, bots, automation and bulk sweeps on the site. Our walk-through should be manual-paced and a handful of clicks, no crawling or API calls. We copy ideas and layout, not their data or code.

Observed on the logged-in page (2026-11-07, landing view only)​

  • Header: index / stock radio, underlying dropdown (NIFTY, BANKNIFTY, FINNIFTY, SENSEX, MIDCPNIFTY, BANKEX, F&O stocks from Oct 2024), date box with << Day / Day >>, SOD, EOD, back -2h -30m -15m -5m -1m, forward 1m+ 5m+ 15m+ 30m+ 2h+, hour and minute dropdowns. So the clock is jump buttons and dropdowns, not a play button; replay = repeated 1m+.
  • Market strip: Day Open (with change), Spot, Fut, Synth Fut, VIX, Add Futures (futures leg), Strategy Finder, Saved Strategies, Import, Add ons, Snapshot.
  • Option chain (left): expiry tabs with tags (CW current week 3 DTE, NW, CM, NM, then monthlies out to ~417 DTE); ATM IV, Straddle premium, PCR, Max Pain, total CE / PE OI bars; ATM basis toggle Spot / Fut / Synth Fut; rows = Call B S | Call LTP (delta) | Call OI | Strike | Put OI | Put LTP (delta) | B S Put; ATM row highlighted, ITM shaded; stale prices show "at 09:15:59" (last trade time) and - where no trade.
  • Right panel before any leg: Pre Built Strategies grouped Neutral / Bearish / Bullish, filter All / Risk Defined / Undefined Risk, expiry pick; tiles: Short / Long Straddle, Short / Long Strangle, Long / Short Iron Condor, Short / Long Iron Butterfly, Double Plateau, Jade Lizard, Reverse Jade Lizard, Call / Put Ratio Spread, Batman. Second tab Rolling Straddle (chart).
  • Credits: "46 days analytics left, 23 paid credits" - some actions cost credits (unknown which).
  • After one Buy click (B on the 24450 CE; credits stayed 23, so adding legs is free; the leg stays in the user's session, Clear / trash removes it):
    • B / S buttons appear on hover of a chain row; toast "Position added". Lot size 65, 1 lot default.
    • Right panel tabs: Payoff Chart | MTM | Strategy | OI | Rolling Straddle.
    • Metric strip: Est. Margin, P&L (Rs and %), Max Profit, Max Loss (Rs and %), POP (probability of profit), Net Credit, Breakevens (with % from spot).
    • Payoff chart: expiry line (red loss / green profit fill) plus blue dashed target-date (T+0) curve, vertical spot line, shaded +/-1 and +/-2 sigma bands (-1s, +1s, +2s), a probability axis on the right.
    • Controls under the chart: Change IV (- 0% +), Change Spot (- value +), Target On date + hour + minute dropdowns, "Target P&L" readout.
    • Bottom tabs: Positions | Greeks | Target P&L | Notes | Add ons.
    • Positions table: checkbox per leg, B/S, lots, qty, date-time, strike + type, expiry dropdown (per leg), entry price, LTP, P&L, lots-exit, delete; Multiplier (x lots), lot size, Add Alert, Save, Share, Exit, Clear.
    • Greeks tab: per leg IV, Delta, Theta, Gamma, Vega, plus a total row; toggles "Greeks in Rs" and "multiply by lot size".
    • Entry price is the LTP at the cursor minute; a leg shows its entry time.
  • Chart tabs (all share a 1m / 2m / 3m / 5m / 15m timeframe picker and a "Scroll zoom" checkbox, with a range navigator under the chart):
    • Strategy: the combined premium of the whole basket over the day (empty until legs have traded bars).
    • MTM: the basket's mark-to-market P&L over the day ("No data to display" when the cursor is at the first minute).
    • OI: open interest of the selected leg (orange) against spot (grey dotted) over the day, with an "Open Interest Change" toggle.
    • Charts show the whole day up to the cursor, so replay reveals the day as the clock moves.
  • Add ons menu (in the positions panel) is only display options: Entry/Exit Date, Entry/Exit Date Time, Delta, Multiply Greeks by Lot Size, Show Full P&L, Merge CE PE Legs together, View only open positions. No SL / target here (those may be Add Alert or the Exit action).
  • Auto Run (header, so there IS a replay): pick Move 1 min / 5 min / 15 min / 30 min / 2 hours / Day, Every 1-5 sec, Till EOD or Custom time; shows a chip such as "1m/1s, 6 Nov" with go and cancel. Client side timer stepping the cursor, as designed. Also a Snapshot (camera) button.
  • Strategy Finder (dialog, not run to avoid spending credits): inputs Min Reward Ratio (2), Min POP (40), Max Loss, Expiry, OTM Range (20 strikes), ITM Range (2), Leg Count (up to 4), Bias filter (Any / ...), Reset, Find Strategies; result table columns: #, Strategy, R:R, POP, Net Credit, Max Profit, Max Loss, Delta, Bias, Action (load into basket). Header line shows the context: index, ATM, strike range, total strikes. So it is a brute-force search over 1-4 leg combinations near ATM ranked by the filters.
  • Layout note: the page is wider than the 800 px pane; a full desktop width shows top nav (Dashboard, Backtest, Analytics > Simulator, Education), then the clock row, strip, chain left and chart tabs right.
  • Still unseen: Saved Strategies list, Import, Rolling Straddle tab, Add Alert, Exit, Share.

Design additions: finder.py enumerates 1-4 leg combinations (calls / puts, buy / sell, +/- N strikes of ATM) and ranks by reward:risk and POP using the payoff module; capped for runtime (4 legs x 22 strikes x 2 sides is large, so prune: defined-risk first, spread widths, sorted strikes).

Extra design points: three time-series endpoints behind the chart tabs (basket premium, basket MTM, leg OI vs spot), all cut at the cursor minute; the positions table gets the same display toggles (merge CE/PE legs, open positions only).

Design additions from this: POP and sigma bands need an IV-based lognormal distribution (we have Black-76); Change IV / Change Spot / Target On are plain recomputes of the payoff function, so the stateless state API gets iv_shift, spot_override, target_time inputs; per-leg expiry changes (calendar / diagonal) must be supported in the order model; share = a link to a saved basket.

Takeaways for our design: (a) the chain is the centre of the UI, (b) the time cursor with jump buttons is simple and cheap to build, (c) pre-built strategy tiles = our templates.py, (d) expiry tags (CW / NW / CM / NM + DTE) and Synth Fut ATM basis are worth copying, (e) delta shown inline with LTP.

3. What we already have (reuse)​

NeedExisting piece
1-min bars of index, futures, options (NSE, BSE)tbs/loaders.py, daydata.py (Bars), data.py, data_bse.py, day cache cache.py
Chain replay from 1-min Parquet (OI, PCR, max pain, premium decay)nseieod/oi_analysis.py (_day, build_result), UI OIAnalysis.jsx, OITimeNav.jsx
Strike selection, lots, lot size by date, expiry rulestbs/strikes.py, lots.py, templates.py
Fill model, slippage, charges, margintbs/engine.py, costs.py, spanmargin.py
Black-76 pricer, IVsilveropt/black76.py (adapt for index options; IV solve is new)
Candle chartcomponents/TEChart.jsx; day charts tbsDayCharts.jsx
Save strategies / reports per userbackend/library, /api/library, tbsLibrary.jsx
Live OInseieod/oi_live.py (later: simulator on today's live data)

4. Design​

Backend backend/optsim/​

  • session.py - a simulation session: (symbol, date, expiry, cursor_minute); loads the day once through the TBS loaders and day cache into memory.
  • chain.py - chain_at(session, minute): strikes, CE / PE LTP (bar close at the cursor), OI (if the store has it), IV and Greeks computed (Black-76 on futures price, time to expiry in IST market minutes).
  • book.py - positions and fills: place(order, minute), close(leg, minute), per-leg SL / target checked bar by bar while the clock advances (high / low of the bar, gap_fill like TBS), slippage and charges from tbs.costs.
  • payoff.py - basket expiry payoff and T+0 curve from IV, breakevens, max P / L; SPAN margin via tbs.spanmargin.
  • Stateless API: the client holds the order list and the cursor; the server recomputes (chain, positions, payoff, greeks, pnl curve) for any (date, cursor, orders). No server session state, so replay, scrubbing and refresh all work.
  • Endpoints /api/optsim/: meta (dates, expiries, availability), state (POST: date, expiry, cursor, orders), series (day spot / selected legs 1-min series for charts), baskets (save / load via library).
  • Public-tier gate decided with the user (see open questions).

Frontend pages/OptionSimulator.jsx​

  • Top bar: index, date picker (available days from availability.py), expiry, clock with play / pause / step / speed / slider.
  • Left: option chain around ATM with B / S buttons and lots; centre: spot chart + premium of selected legs (TEChart, cursor line); right: positions table, net Greeks, P&L, margin; bottom: payoff chart (expiry + T+0), breakevens.
  • Playback is client side (timer advances the cursor, fetches state; prefetch the whole day's chain grid once to keep it smooth - see risks).
  • Save / load basket, "send to TBS" (turn the hand-built basket into a TBS spec to backtest it over many days).

5. Phases​

  1. Discovery: done (section 2).
  2. MVP: NIFTY + SENSEX, date + expiry pick, time cursor (jump buttons, hour / minute, SOD / EOD, day prev / next), chain with LTP, delta, OI, ATM IV, straddle premium, PCR, max pain; B / S legs; positions table with live P&L; expiry payoff chart with breakevens, max P / L.
  3. Risk view: Black-76 IV + Greeks (per leg and total), T+0 curve, Change IV / Change Spot / Target On, POP + sigma bands, SPAN margin.
  4. Charts + replay: Strategy (basket premium), MTM, OI tabs with 1 / 2 / 3 / 5 / 15 m timeframe; Auto Run (move step, every N sec, till EOD / time).
  5. Convenience: pre-built strategy tiles (templates.py), save / load baskets (library) + Share link, Import, display toggles (merge CE/PE, open only), per-leg expiry.
  6. Strategy Finder (finder.py) and extra underlyings (BANKNIFTY, FINNIFTY, MIDCPNIFTY, BANKEX).
  7. Bridge: simulator basket -> TBS spec; live mode on today's data via oi_live.
  8. Docs + tests per phase: knowledge-base/option-simulator.md; tests for chain, fills, payoff, Greeks (known Black-76 values), finder pruning.

Order of work inside the MVP: backend session + chain + book + payoff with tests -> /api/optsim/state -> page.

5a. Progress log​

  • 2026-11-07 phase 2 done (backend/optsim + /api/optsim + pages/OptionSimulator.jsx, route /option-simulator): chain with LTP / IV / delta, B / S legs, positions, P&L, expiry payoff, MTM / premium / spot charts, replay jump + Auto Run.

  • 2026-11-07 phase 3 done except OI: Black-76 IV and Greeks (per leg and total), target-time (T+0) curve with Change IV and Target on, Change spot readout, POP and +/-1, 2 sigma bands, per-leg SL / target % exits (level fill, stop first, realised P&L kept as a cash pseudo-leg), margin (optsim/margin.py, /api/optsim/margin: SPAN file when archived locally, else flat estimate; no SPAN file locally for 2026-07-14, so the estimate shows).

  • 2026-11-07 phase 4 done: OI via optsim/oi.py + /api/optsim/oi (reuses oi_analysis._day, NIFTY / BANKNIFTY only): OI per strike in the chain, PCR, max pain, total OI strip, OI chart of the legs (with OI change toggle); 1 / 2 / 3 / 5 / 15 m timeframes on MTM / Premium / OI / Spot; Auto Run adds 2 hours, Day and a till time. OI for FINNIFTY / MIDCPNIFTY / SENSEX / BANKEX is still missing (their loaders have no OI replay).

  • Tested in the browser with a temporary no-login page (deleted). Real login flow, SENSEX / BANKEX and the VPS are untested.

  • 2026-11-07 phase 5 done except Rolling Straddle / Strategy Finder / extra underlyings: strategy tiles (16: straddles, strangles, iron condor / butterfly, jade lizards, ratio and vertical spreads) built at ATM with a wing width; Save / Saved (library category optsim, /api/optsim/baskets, delete via /api/library/strategies/{id}), Share (link #b=..., no server), Import (link or JSON), per-leg expiry select (only expiries with loaded bars; the TBS loader reads weekly / monthly ones), Open legs only toggle. A leg whose contract has no bars (basket loaded on another day) is flagged "no bars" instead of failing the page. /meta is cached 10 minutes (the availability scan is slow).

  • 2026-11-07 phase 6 done except Rolling Straddle: Strategy Finder (optsim/finder.py, /api/optsim/finder, Finder panel): 1-4 leg combinations of the CE / PE strikes around ATM (OTM / ITM ranges), exact payoff at the kinks with numpy (about 2.7 million combinations in 4-5 s), filters min reward:risk, min POP, max loss, bias, leg count; risk-defined only (no net naked short calls or puts); reward = best payoff inside +/- 2 standard deviations (so a far OTM long wing earns nothing), risk = true worst case; ranked by POP x min(R:R, 20); "Add" puts the legs into the basket. All six underlyings load a day and a chain locally (BANKNIFTY, FINNIFTY, MIDCPNIFTY, SENSEX, BANKEX checked with no legs); OI exists for NIFTY / BANKNIFTY only.

  • 2026-11-07 phase 7 done: (a) Backtest in TBS (optsim/to_tbs.py, /api/optsim/to-tbs): the basket becomes an intraday TBS spec (strikes as ATM steps of the cursor minute, expiry as weekly / next weekly / monthly / next monthly rule, SL / target % of premium, entry = first leg minute + 1, later legs get a start time, square off partial) and opens in the TBS builder (sessionStorage hand-over, TbsBacktest.jsx loads it once); warnings are shown in its error strip. (b) Live (optsim/live.py, /api/optsim/live-status, live flag on state / margin / oi / finder): today's oi_live snapshots become a DayData (3-minute prices carried to 1-minute bars, OI per strike), so chain, legs, payoff, Greeks, OI and the finder run on today's session; the page polls every 30 s and follows the newest snapshot; NIFTY / BANKNIFTY only. Verified locally with the 2026-10-16 snapshot file (market closed); the real in-session behaviour (collector running on the VPS) is untested.

  • 2026-11-07 phase 8 done: knowledge-base doc option-simulator.md, plan reconciled, final test run (see the commit).

6. Risks / decisions​

  • Data weight: a full day of every strike is large. Plan: load once per day, hold in the TBS day cache, send the client only the strikes within +/- N around ATM at the cursor.
  • IV for index options needs a robust solver and the right forward (futures vs spot + carry); expiry-day IV explodes, cap and flag.
  • OI at 1-minute exists in the IEOD bars (oi column) - confirm it is populated for options on all years.
  • BSE data is on the VPS only, so BSE simulation can only be tested there.
  • Fill model: reuse TBS locked model (slippage 0.5 on entry, gap_fill) so Simulator and TBS agree on the same trade.

7. Open questions for the user​

Defaults used unless the user says otherwise:

  1. Access tier: registered users (like aa_plans); power tier later if load is a problem.
  2. Underlyings for MVP: NIFTY + SENSEX (data we already validate in TBS); the rest in phase 6.
  3. Practice mode that hides the future: not in MVP; the stateless API already supports it (cursor-limited series), so it is a UI switch later.
  4. Priority: replay + chain + fills first (phase 2), Greeks / payoff risk view right after (phase 3).
  5. Not copying StockMock's credit system; free for our users.