TBS Basket (several strategies, one result)
A basket is StockMock's "Basket / Multiple Backtest": a saved list of TBS strategies run together over one date range and shown as one result. Page /tbs-basket (sidebar "TBS Basket", DEVELOPER rank). Code: backend/tbs/basket.py, API backend/app/api/baskets.py, page frontend/src/pages/TbsBasket.jsx. Written 7 Nov 2026 after reading StockMock's own basket page.
What a basket stores
A saved item of the user's library (teudb usr_strategy, category tbs_basket, engine basket), so folders, rename, favorite, duplicate and delete are the ordinary /api/library calls. Its JSON lists the members:
| Field | Meaning |
|---|---|
strategy_id | link to a TBS strategy of the library (the member's settings are NOT copied) |
multiplier | whole number, multiplies every leg's lots (1 to 100) |
slippage | % for this member, empty = the strategy's own |
weekdays | days to trade, empty = the strategy's own |
dte | keep only days whose days-to-expiry is listed, empty = every day |
on | switched off = not part of Run all |
Linked, not copied. A run resolves every member to the library strategy's current settings (edit a strategy and every basket uses the change at its next run). A run keeps a copy of what it ran with (bt_run.spec_json: {basket: true, members: [{idx, name, source_id, multiplier, dte, strategy}]}), so a finished run or a saved report never changes. A member whose library strategy was deleted is shown as "Missing", skipped at run time and named in the run's notes.
The run
POST /api/baskets/run (basket_id or the page's current members, optional only = positions of the selected rows, date_from, date_to, workers) queues ONE job like any backtest (same queue, same caps). Each member runs through the ordinary engine over the dates its index has data for (a Sensex member starts at the Sensex data, a note says so), one after another; progress counts the trades of all members together. The days are merged per entry date, every trade is tagged member / member_name (new bt_trade columns, alembic b7c3d9e2f410), and the summary is computed on the merged legs (margin and drawdown net across members). Up to 20 members are switched on per run. Nifty, Banknifty, Sensex etc. can be mixed; each member uses its own underlying's lot table.
The result
It is a normal run (mode = 'basket', underlying = 'BASKET'): the usual Summary, Equity, Day-wise, Trades tabs, the period filter, the hover contract chart and the day detail work on it (the Trades table gets a Strategy column; leg numbers repeat across members, so the chart and day detail look a leg up by member). New:
- By strategy tab: each member's net, win days, max profit / loss, max drawdown, return / MDD, streaks and expectancy next to the combined figures, an Include tick and a weight per member, and the correlation matrix of the members' daily profit.
- Re-weighting without a run:
GET /api/tbs/runs/{id}/view?weights=0:1,1:0.5,2:0(member:factor, 0 = out). The stored legs of a member are scaled (rupees and quantities) and everything is summarised again. A member keeps its own figures shown at weight 1 while it is out so it can be switched back on. The weight is on top of the multiplier the run used. - The day detail of a basket day sums the members' minute by minute curves (events carry the member name); with weights other than 1 it still shows the run as it was.
More features
- Export / report / estimate / order. Excel and PDF of a result as filtered on the page (
/api/tbs/runs/{id}/xlsx|pdf,tbs/export.py); Save report keeps a basket result in the Reports library (it reopens in the same basket result view);POST /api/baskets/estimategives trades and seconds for a run (median speed of recent runs); rows are re-ordered by drag (and sorted). - Basket stop loss / target (rupees, saved with the basket, overridable per run):
tbs/basket.apply_limitsscans the combined minute by minute net profit of the day (same curve as the Day detail); at the first minute at or beyond the SL / target every open leg is squared off at that minute's bar close (exit one minute later, reasonbasket_sl/basket_target, charges recomputed with the member's costs), legs that would have entered later are dropped. Intraday days only: a day holding a leg overnight is left alone (counted in the run notes). Whether StockMock squares off on the bar close or the next bar is not verified. .testfile (tbs/basketfile.py,GET /api/baskets/{id}/export,POST /api/baskets/import): Fernet-encrypted JSON of the basket and the full spec of every strategy. This is obfuscation plus tamper detection (key fromBASKET_FILE_KEYor a built-in secret), not protection against someone with the source. Import matches strategies by name with the user's TBS library: same content = linked, same name but different content = linked and left as it is unless the name is listed inupdate(use the file's version), no such name = created in "No folder"; a taken basket name becomes "x (2)" or replaces (on_name_clash).apply=falseis a dry run the dialog shows first.- Edit a member in the basket: the pencil opens the ordinary builder (
/tbs?strategy=ID&embed=1, Layout hides header and sidebar) in a dialog; saving updates the library strategy, so the Save dialog warns which baskets use it (GET /api/baskets/usage?strategy_id=), and the basket page refreshes the row and names the other baskets affected (builder poststbs-strategy-savedto the page). - Exact margin (
tbs/spanmargin.py,POST|GET /api/tbs/runs/{id}/margin): brokers' margin is the exchange SPAN (worst of 16 price / volatility scenarios, hedges netted) plus exposure on short options. The job puts the legs held together after every entry / exit of each day through that day's NSE SPAN file (marginism; archived files in<NSEFO>/_raw_margin/marginism, missing days downloaded politely 2 s apart), keeps the day's largest margin insummary.margin_daysand every view/export of the run then uses the largest day withmargin_source = span(the % figures are measured on it). Limits: end-of-day SPAN file (brokers use intraday files), bought premium is not margin, SENSEX / BANKEX are not in NSE's file and keep the 10.5 % estimate, a re-weighted basket view still uses the margin computed at weight 1. About 4 s per day plus downloads. Verified on a real file: a short straddle needs more margin than the same straddle with bought wings.
Not built yet
Share basket (a link for other users), "Import basket" from StockMock, saved row presets, BSE SPAN. See todolist/tbs/queue-capacity.md for the queue limits a large basket meets (a run costs about the sum of its members).
Tests
backend/tests/test_tbs_basket.py (member overrides, linking, merged run with progress and cancel, DTE filter, weights, correlation, the API), test_tbs_dayview.py, test_tbs_spanmargin.py, test_tbs_export.py.