Skip to main content

Source: StockMock Backtest form (observed logged in, 17 Oct 2026). Status: draft, not started. More sources will be added to enhance this plan.

Update 17 Oct 2026: scope superseded by the combined TBS engine spec (StockMock + AlgoTest + Stoxxo). Architecture, milestones and risks below still apply.

TBS Backtester - Phase 1 Plan (17 Oct 2026)

Context​

EOD and 1-min IEOD data (NSE + BSE) are loaded. Next is the strategy layer. Phase 1 is a StockMock-style backtester for time-based options strategies: enter at a time, exit at a time, with leg-level SL/TP and day-level SL/TP. It runs on our own data, so there are no credits and no date limits (NIFTY from 2007+, vs StockMock's Feb 2019 start). Decisions made: NSE + BSE (SENSEX/BANKEX) in Phase 1; engine + API first, UI second.

What StockMock's Backtest form has (observed, logged in)​

  • Leg: index (nifty, banknifty, finnifty, midcpnifty, sensex, bankex), Futures/Options, CE/PE, Buy/Sell, lots, expiry (weekly / next weekly / monthly).
  • Strike selection: ATM +/- N points (50 steps), ATM %, Straddle Width, Closest Premium (+/-100 pts), CP as % of straddle premium. ATM from Spot or from Futures.
  • Per leg: Target Profit, Stop Loss, Trail SL, Wait & Trade, Re-Entry / Re-Execute, Journey, Move SL to Cost, Associated Hedge, Range Breakout.
  • Strategy: entry/exit time (same day or next day BTST/STBT), Strategy TP, Strategy SL, Protect The Profits, "square off one leg / all legs", Intraday vs Positional, date range, All Days / Budget / RBI-policy days.
  • Rules baked in: day starts 09:16, 0.5% slippage, variable lot sizes per date.
  • Results: P&L, max drawdown, success rate, day-wise trades, saved/default strategies (straddle, strangle, iron condor, spreads...).

Phase 1 scope (MVP engine)​

  1. Legs: option CE/PE and futures, buy/sell, lots, expiry weekly/next weekly/monthly.
  2. Strike selection: ATM +/- points, ATM %, Closest Premium, CP as % of straddle, Straddle Width. ATM from spot (futures option later).
  3. Per-leg SL and TP (% and points), Trail SL. Strategy-level SL/TP. Square off one leg vs all legs. Move SL to Cost.
  4. Entry/exit time on 1-min bars, intraday (same day) and positional (next-day exit). Day filters: All days, weekdays, expiry day, DTE.
  5. Costs: slippage % (default 0.5%), brokerage per lot/order, STT/charges (effective-dated), all configurable.
  6. Variable lot sizes by date (from fo_store lotsize).
  7. Results: trade list, daily P&L, equity curve, max drawdown, win rate, avg win/loss, profit factor, monthly table, per-leg detail.
  8. Deferred to Phase 2: Wait & Trade, Re-Entry/Re-Execute, Journey, Range Breakout, Protect The Profits, Associated Hedge, Budget/RBI day filters, optimizer.

Architecture​

New package backend/tbs/ (mirrors backend/carry/ layout):

  • spec.py - dataclasses/pydantic for strategy JSON (legs, rules, costs, date range). One JSON = one strategy; hashable so it can be saved to st_master (source='tradeentry', param_values, canonical_json).
  • data.py - thin adapter over existing readers: NSE via nseieod/nseIEOD.py Con_Price_Getter and the chain-pivot pattern in nseieod/oi_analysis.py (_contracts, _day, lru_cache); BSE via bseieod/reader.py (expiries, strikes, resolve_contract, get_bars). Expiries/strikes from scr_master; lot size from nseeod/fo_store.get_fo; trading days from nseieod/helpers.get_nse_working_days. Returns one standard day frame: minute grid x contract (open/high/low/close), spot, futures.
  • strikes.py - strike selectors (ATM pts/%, CP, CP-of-SP, straddle width).
  • engine.py - per-day simulator: resolve legs at entry minute, walk 1-min bars checking SL/TP/trail (conservative rule: if SL and TP both touched in a bar, SL first; configurable), apply slippage, square off at exit time. Pure function run_day(spec, day_data) -> trades.
  • runner.py - loops days (group by expiry to reuse loaded chains), parallel with a process pool for long ranges, progress reporting.
  • costs.py - effective-dated brokerage/STT/exchange charges, like carry/costs.py.
  • metrics.py - P&L, drawdown, win rate, profit factor, streaks, monthly/weekday tables.
  • Persistence: add bt_run, bt_trade (+ optional bt_leg) tables to StrategyBase in strategies/models.py, new Alembic revision. Summary + daily P&L stored as JSON on bt_run; trades in bt_trade.
  • API backend/app/api/tbs.py (/api/tbs/*): POST /run (BackgroundTasks, state + GET /status polling, same pattern as bhav_downloader.py / eodieod_upload.py), GET /runs, GET /runs/{id} (summary, equity, trades), POST /strategies save/list, GET /templates (straddle, strangle, iron condor, spreads). Register in app/main.py.
  • Docs: docs/docs/developer/knowledge-base/tbs-backtester.md (autogenerated sidebar, no edit needed).

Phase 1b - UI (after engine is validated)​

  • frontend/src/pages/TbsBacktest.jsx (+ tbsUi.jsx): leg builder, rules form, date range, run button with polling (hasSeenRunning guard), results tabs (summary, equity/drawdown via TEChart/LightweightChart, day-wise table, trades). Route in App.jsx, link in Sidebar.jsx, calls only via new api.tbs in services/api.js.

Milestones​

  1. Spec + data adapter + one-day simulator; unit tests on hand-built bars.
  2. Full runner + metrics + costs; CLI python -m tbs.run --spec x.json from backend/.
  3. Validation against StockMock: run the same short straddle (e.g. 09:20-15:15, SL 25%, 1 year) in both and compare daily P&L; expect small gaps from the 0.5% slippage and 09:16 start, and document them.
  4. API + persistence + templates.
  5. UI.

Risks / notes​

  • Data quality: missing minute bars in far-OTM options; need a rule (carry last price, skip leg, flag the day). Reuse the liquid-scripts / bse_quality checks to flag bad days.
  • Weekly expiry history is not uniform (NIFTY weekly from 2019, BANKNIFTY from 2016-17); expiry resolution must handle weekly vs monthly-only eras and holiday-shifted expiries.
  • Performance: load one day's chain in one DuckDB scan, cache per expiry; budget about 1 s/day or better.
  • Parquet of last-bar timestamps HH:MM:59 must be floored to the minute (existing rule).
  • ASCII-only log messages (Windows cp1252) and run modules from backend/ (repo hard rules).

Verification​

  • cd backend; python -m pytest tbs/tests for selectors and the day simulator.
  • CLI run on 1 month, then 1 year, compared with StockMock for the same settings.
  • API: start uvicorn, POST /api/tbs/run, poll /status, fetch the run. Stop any preview servers when done (repo rule 9).
  • UI (phase 1b): run via the preview tool and check the results page.