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)
- Legs: option CE/PE and futures, buy/sell, lots, expiry weekly/next weekly/monthly.
- Strike selection: ATM +/- points, ATM %, Closest Premium, CP as % of straddle, Straddle Width. ATM from spot (futures option later).
- Per-leg SL and TP (% and points), Trail SL. Strategy-level SL/TP. Square off one leg vs all legs. Move SL to Cost.
- Entry/exit time on 1-min bars, intraday (same day) and positional (next-day exit). Day filters: All days, weekdays, expiry day, DTE.
- Costs: slippage % (default 0.5%), brokerage per lot/order, STT/charges (effective-dated), all configurable.
- Variable lot sizes by date (from
fo_storelotsize). - Results: trade list, daily P&L, equity curve, max drawdown, win rate, avg win/loss, profit factor, monthly table, per-leg detail.
- 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 tost_master(source='tradeentry',param_values,canonical_json).data.py- thin adapter over existing readers: NSE vianseieod/nseIEOD.pyCon_Price_Getterand the chain-pivot pattern innseieod/oi_analysis.py(_contracts,_day, lru_cache); BSE viabseieod/reader.py(expiries,strikes,resolve_contract,get_bars). Expiries/strikes fromscr_master; lot size fromnseeod/fo_store.get_fo; trading days fromnseieod/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 functionrun_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, likecarry/costs.py.metrics.py- P&L, drawdown, win rate, profit factor, streaks, monthly/weekday tables.- Persistence: add
bt_run,bt_trade(+ optionalbt_leg) tables toStrategyBaseinstrategies/models.py, new Alembic revision. Summary + daily P&L stored as JSON onbt_run; trades inbt_trade. - API
backend/app/api/tbs.py(/api/tbs/*):POST /run(BackgroundTasks, state +GET /statuspolling, same pattern asbhav_downloader.py/eodieod_upload.py),GET /runs,GET /runs/{id}(summary, equity, trades),POST /strategiessave/list,GET /templates(straddle, strangle, iron condor, spreads). Register inapp/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 (hasSeenRunningguard), results tabs (summary, equity/drawdown viaTEChart/LightweightChart, day-wise table, trades). Route inApp.jsx, link inSidebar.jsx, calls only via newapi.tbsinservices/api.js.
Milestones
- Spec + data adapter + one-day simulator; unit tests on hand-built bars.
- Full runner + metrics + costs; CLI
python -m tbs.run --spec x.jsonfrombackend/. - 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.
- API + persistence + templates.
- 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_qualitychecks 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:59must 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/testsfor 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.