while25 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. while25/__init__.py +341 -0
  2. while25/_costs/brokers/alpaca.json +96 -0
  3. while25/_costs/brokers/binance.json +34 -0
  4. while25/_costs/brokers/coinbase.json +34 -0
  5. while25/_costs/brokers/ibkr.json +39 -0
  6. while25/_costs/brokers/upstox.json +175 -0
  7. while25/_costs/brokers/zerodha.json +175 -0
  8. while25/_costs/crypto_alpaca.json +27 -0
  9. while25/_costs/global_crypto.json +18 -0
  10. while25/_costs/in_nse_equity.json +238 -0
  11. while25/_costs/in_nse_etf.json +352 -0
  12. while25/_costs/in_nse_fo.json +450 -0
  13. while25/_costs/us_crypto.json +18 -0
  14. while25/_costs/us_equity.json +175 -0
  15. while25/_costs/us_options.json +172 -0
  16. while25/_days.py +123 -0
  17. while25/_figures.py +233 -0
  18. while25/_runtime.py +49 -0
  19. while25/_universes/banknifty.json +80 -0
  20. while25/_universes/ndx100.json +520 -0
  21. while25/_universes/nifty50.json +260 -0
  22. while25/_universes/nifty500.json +2505 -0
  23. while25/_universes/sp500.json +2525 -0
  24. while25/assume.py +263 -0
  25. while25/backtest.py +881 -0
  26. while25/barline.py +160 -0
  27. while25/combo_legs.py +238 -0
  28. while25/errors.py +77 -0
  29. while25/fonts/IBMPlexMono-Regular.ttf +0 -0
  30. while25/fonts/IBMPlexMono-SemiBold.ttf +0 -0
  31. while25/fonts/Inter-Bold.ttf +0 -0
  32. while25/fonts/Inter-Regular.ttf +0 -0
  33. while25/fonts/Inter-SemiBold.ttf +0 -0
  34. while25/fonts/OFL-IBMPlexMono.txt +93 -0
  35. while25/fonts/OFL-Inter.txt +93 -0
  36. while25/future_pick.py +77 -0
  37. while25/inputs.py +215 -0
  38. while25/instruments.py +488 -0
  39. while25/modules.py +397 -0
  40. while25/money.py +24 -0
  41. while25/option_pick.py +221 -0
  42. while25/plots.py +147 -0
  43. while25/report.py +644 -0
  44. while25/ui.py +680 -0
  45. while25/universes.py +70 -0
  46. while25-0.1.0.dist-info/METADATA +3194 -0
  47. while25-0.1.0.dist-info/RECORD +50 -0
  48. while25-0.1.0.dist-info/WHEEL +5 -0
  49. while25-0.1.0.dist-info/licenses/LICENSE +201 -0
  50. while25-0.1.0.dist-info/top_level.txt +1 -0
while25/backtest.py ADDED
@@ -0,0 +1,881 @@
1
+ """Calculators a backtest script calls, one trade at a time.
2
+
3
+ None of these loops over bars, holds a position or decides when a trade
4
+ happens: the script decides, and asks here what a fill on THIS bar costs and
5
+ returns. Each answer is exact Decimal, computed under a fixed Decimal context
6
+ (never the script's), with no clock and no randomness, and carries what it was
7
+ derived from, so the terminal can recompute every trade a script reports
8
+ and refuse one that does not match.
9
+
10
+ f_in = backtest.fill(bar, "buy", "limit", instrument=inst, price=100,
11
+ slippage=backtest.Slippage.bps(5))
12
+ f_out = backtest.exit_fill(bar2, "buy", instrument=inst, stop=95, target=110)
13
+ t = backtest.trade(inst, "buy", 10, f_in, f_out, product="intraday")
14
+
15
+ exit_fill (not first_exit then fill) records the bracket, so the parent
16
+ re-checks which level a bar touching both reached first; a plain fill() exit
17
+ is not checked, and the sealed block says how many such exits it holds.
18
+
19
+ A block of trades built here is sealed by the terminal or refused with
20
+ a rule id (R-SHAPE, R-DATA, R-WINDOW, R-TRADE-DERIVED, R-PRICE, R-FACTS,
21
+ R-CURRENCY, R-FLAT, R-TIME; see while25.ui.backtest_block).
22
+
23
+ Real costs come only from the dated cost registry (bundled as
24
+ while25/_costs): a missing schedule or rate is refused
25
+ (COSTS_UNKNOWN), never zero. Zero or custom costs are an assumption the
26
+ backtest states (backtest.assume / the user's defaults), recorded on every trade.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import functools
31
+ import json
32
+ import math
33
+ import numbers
34
+ import re
35
+ import unicodedata
36
+ from dataclasses import asdict, dataclass, field, is_dataclass, replace
37
+ from datetime import date, datetime
38
+ from decimal import (ROUND_HALF_EVEN, Context, Decimal, DivisionByZero, InvalidOperation,
39
+ Overflow, localcontext)
40
+ from pathlib import Path
41
+ from types import MappingProxyType
42
+ from zoneinfo import ZoneInfo
43
+
44
+ from . import _days
45
+ from .errors import While25Error
46
+ from .instruments import Instrument, _as_decimal
47
+ from .universes import _registry
48
+
49
+ # Wide enough that every product here (price x qty x multiplier x rate) is
50
+ # exact; fixed so a script's own decimal.getcontext() changes nothing.
51
+ _CTX = Context(prec=60, rounding=ROUND_HALF_EVEN, traps=[InvalidOperation, DivisionByZero, Overflow])
52
+
53
+ _SIDES = ("buy", "sell")
54
+ _HOWS = ("open", "close", "limit", "stop")
55
+ _PRODUCTS = ("intraday", "delivery")
56
+ _RULES = ("stop_first", "target_first")
57
+ # Inside one bar an open comes first, a limit / stop somewhere inside it, the
58
+ # close last; a close is known only at the bar's end.
59
+ _RANK = {"open": 0, "limit": 1, "stop": 1, "close": 2}
60
+ # A daily bar's length; intraday lengths are _days.STEP_MS.
61
+ _DAY_MS = 86_400_000
62
+
63
+
64
+ def _side(side) -> str:
65
+ if side not in _SIDES:
66
+ raise While25Error(f"side must be 'buy' or 'sell', not {side!r}", "BAD_SIDE")
67
+ return side
68
+
69
+
70
+ def _positive(x, what: str, code: str) -> Decimal:
71
+ """A finite, positive figure as an exact Decimal, or the refusal `code`."""
72
+ # ponytail: a price at or below 0 is refused, which also refuses a real
73
+ # negative futures price (WTI, 2020-04-20); a per-instrument "may go
74
+ # negative" venue fact is the upgrade path if such a contract is traded.
75
+ try:
76
+ d = _as_decimal(x, what)
77
+ except (ValueError, TypeError) as exc:
78
+ raise While25Error(str(exc), code) from None
79
+ if not d.is_finite() or d <= 0:
80
+ raise While25Error(f"{what} must be a finite number above 0, not {x!r}", code)
81
+ return d
82
+
83
+
84
+ def _bar(bar: dict) -> tuple:
85
+ """(time, open, high, low, close) of one bar, exact, or BAD_BAR."""
86
+ if not isinstance(bar, dict):
87
+ raise While25Error(f"a bar is a dict, not {type(bar).__name__}", "BAD_BAR")
88
+ t = bar.get("time")
89
+ if isinstance(t, bool) or not isinstance(t, numbers.Integral):
90
+ raise While25Error(f"bar time must be integer epoch ms, not {t!r}", "BAD_BAR")
91
+ o, h, l, c = (_positive(bar.get(k), f"bar {k}", "BAD_BAR") for k in ("open", "high", "low", "close"))
92
+ if not (l <= min(o, c) and max(o, c) <= h):
93
+ raise While25Error(f"bar is inconsistent: open {o} high {h} low {l} close {c}", "BAD_BAR")
94
+ return int(t), o, h, l, c
95
+
96
+
97
+ def _iso_date(d) -> date:
98
+ """A stamped trading date. None or "": CALENDAR_UNKNOWN (no clock, so no
99
+ date to cost on); not YYYY-MM-DD: BAD_BAR."""
100
+ if d is None or d == "":
101
+ raise While25Error("no exchange trading date (the answer named no exchange clock); "
102
+ "it cannot be costed", "CALENDAR_UNKNOWN")
103
+ try:
104
+ if isinstance(d, str) and len(d) == 10:
105
+ return date.fromisoformat(d)
106
+ except ValueError:
107
+ pass
108
+ raise While25Error(f"bar date must be YYYY-MM-DD, not {d!r}", "BAD_BAR")
109
+
110
+
111
+ def _bar_date(bar: dict) -> str:
112
+ """The bar's exchange trading date as the terminal stamped it."""
113
+ if bar.get("interval") in ("1W", "1M"):
114
+ raise While25Error(f"a {bar['interval']} bar spans many trading days and cannot date a "
115
+ f"fill; use daily or intraday bars", "BAD_BAR")
116
+ return _iso_date(bar.get("date")).isoformat()
117
+
118
+
119
+ def _bar_end(bar: dict, t: int) -> int:
120
+ """When the bar ends: its time plus its interval's length. A bar naming
121
+ no known interval has no end, so no fill on it can be ordered: BAD_BAR."""
122
+ iv = bar.get("interval")
123
+ period = _days.STEP_MS.get(iv) if isinstance(iv, str) else None
124
+ if iv == "1D":
125
+ period = _DAY_MS
126
+ if period is None:
127
+ raise While25Error(f"the bar names no interval of known length ({iv!r}); a fill on it "
128
+ f"cannot be put in time order", "BAD_BAR")
129
+ return t + period
130
+
131
+
132
+ def _trade_date(f: "Fill") -> date:
133
+ """The date a fill is costed on: its bar's exchange trading date."""
134
+ return _iso_date(f.date)
135
+
136
+
137
+ def _tick_or_refuse(inst: Instrument, p: Decimal) -> Decimal:
138
+ tick = inst.tick_for(p)
139
+ if tick is None:
140
+ raise While25Error(f"the venue states no tick for {inst.instrument_key or inst.symbol}; "
141
+ f"a fill cannot be put on its price grid", "RULES_UNKNOWN")
142
+ return tick
143
+
144
+
145
+ def _jsonable(o):
146
+ """json.dumps(default=) for what a backtest hands the view: a Fill or
147
+ Costs as its fields, a Decimal as its exact string. ctx.ui.push encodes
148
+ with it, and the terminal compares a re-derived trade in the same
149
+ form."""
150
+ if is_dataclass(o) and not isinstance(o, type):
151
+ return asdict(o)
152
+ return str(o)
153
+
154
+
155
+ # ---- slippage ---------------------------------------------------------------------
156
+
157
+ @dataclass(frozen=True)
158
+ class Slippage:
159
+ """Always against the trader: a buy pays more, a sell gets less. ticks:
160
+ n x the tick at the price; on a ladder (price_steps), n prices along its
161
+ grid from the price put on it against the trader, as Instrument.offset
162
+ walks them."""
163
+ kind: str = "none" # "none" | "bps" | "ticks"
164
+ n: Decimal = Decimal(0)
165
+
166
+ @staticmethod
167
+ def none() -> "Slippage":
168
+ return Slippage()
169
+
170
+ @staticmethod
171
+ def bps(n: float) -> "Slippage":
172
+ try:
173
+ d = _as_decimal(n, "bps")
174
+ except (ValueError, TypeError) as exc:
175
+ raise While25Error(str(exc), "BAD_SLIPPAGE") from None
176
+ if not d.is_finite() or d < 0:
177
+ raise While25Error(f"slippage bps must be finite and 0 or more, not {n!r}", "BAD_SLIPPAGE")
178
+ return Slippage("bps", d)
179
+
180
+ @staticmethod
181
+ def ticks(n: int) -> "Slippage":
182
+ if isinstance(n, bool) or not isinstance(n, numbers.Integral) or n < 0:
183
+ raise While25Error(f"slippage ticks must be a whole number 0 or more, not {n!r}", "BAD_SLIPPAGE")
184
+ return Slippage("ticks", Decimal(int(n)))
185
+
186
+ @staticmethod
187
+ def parse(text: str) -> "Slippage":
188
+ """describe()'s text back into the slippage (what a verifier re-applies)."""
189
+ if text == "none":
190
+ return Slippage.none()
191
+ kind, _, n = str(text).partition(":")
192
+ try:
193
+ if kind == "bps" and n:
194
+ return Slippage.bps(Decimal(n))
195
+ if kind == "ticks" and n.isascii() and n.isdigit():
196
+ return Slippage.ticks(int(n))
197
+ except InvalidOperation:
198
+ pass
199
+ raise While25Error(f"unreadable slippage {text!r} (none, bps:<n> or ticks:<n>)", "BAD_SLIPPAGE")
200
+
201
+ def describe(self) -> str:
202
+ # Plain, never an exponent: a recorded assumption parses back as is.
203
+ return "none" if self.kind == "none" else f"{self.kind}:{format(self.n, 'f')}"
204
+
205
+ def apply(self, price: Decimal, side: str, inst: Instrument) -> Decimal:
206
+ sign = 1 if _side(side) == "buy" else -1
207
+ with localcontext(_CTX):
208
+ if self.kind == "bps":
209
+ return price + sign * price * self.n / 10000
210
+ if self.kind == "ticks":
211
+ tick = _tick_or_refuse(inst, price)
212
+ if inst.price_steps:
213
+ # n x one tick would cross a step edge on the wrong
214
+ # increment (a sell from 3.10 three ticks down a 0.05 /
215
+ # 0.10 ladder is 2.90, not 2.80).
216
+ start = inst.snap(price, mode="up" if sign > 0 else "down")
217
+ return inst.offset(start, sign * int(self.n))
218
+ return price + sign * self.n * tick
219
+ return price
220
+
221
+
222
+ # ---- fills ------------------------------------------------------------------------
223
+
224
+ @dataclass(frozen=True)
225
+ class Fill:
226
+ time: int # the bar's time
227
+ how: str # open | close | limit | stop
228
+ raw: Decimal # the price before slippage and rounding
229
+ slippage: str # Slippage.describe()
230
+ price: Decimal # after slippage, on the tick against the trader
231
+ side: str
232
+ instrument_key: str = "" # whose bar; trade() refuses a mixed pair
233
+ level: "Decimal | None" = None # the limit / stop price asked; None for open / close
234
+ date: str = "" # the bar's exchange trading date: the cost date
235
+ end: "int | None" = None # the bar's end (time + interval): a close is known then
236
+ slippage_stated: bool = True # False: the assumption's default slippage applied
237
+ fills: str = "touch" # the fill style: touch | through
238
+ bracket: "dict | None" = None # exit_fill: {"stop", "target", "rule"} as strings
239
+ assume: str = "" # Assumptions.fingerprint() the fill was made under
240
+
241
+
242
+ def _assumed(assume) -> "Assumptions":
243
+ """assume= or, when None, the run's defaults(); anything else BAD_INPUT."""
244
+ a = defaults() if assume is None else assume
245
+ if not isinstance(a, Assumptions):
246
+ raise While25Error(f"assume must be a backtest.Assumptions (backtest.defaults() or "
247
+ f"backtest.assume(...)), not {type(assume).__name__}", "BAD_INPUT")
248
+ return a
249
+
250
+
251
+ def fill(bar: dict, side: str, how: str, *, instrument: Instrument, price=None,
252
+ slippage: "Slippage | None" = None, assume: "Assumptions | None" = None) -> "Fill | None":
253
+ """The fill of one order on one bar, or None when the bar never reaches it.
254
+
255
+ open / close: at that price (no `price`). limit: a buy fills iff
256
+ low <= price, at min(open, price); a sell iff high >= price, at
257
+ max(open, price). stop: a buy iff high >= price, at max(open, price); a
258
+ sell iff low <= price, at min(open, price) — a gap fills at the open,
259
+ worse than the stop. Under fills "through" a limit / stop must trade
260
+ past its price (strict <, >), not just touch it. Then slippage (None:
261
+ the assumption's default, recorded as not stated), then the venue's tick
262
+ against the trader (a buy up, a sell down). No tick stated: RULES_UNKNOWN.
263
+ `assume` None reads the run's defaults()."""
264
+ _side(side)
265
+ a = _assumed(assume)
266
+ stated = slippage is not None
267
+ if not stated:
268
+ slippage = a.slippage
269
+ elif not isinstance(slippage, Slippage):
270
+ raise While25Error(f"slippage must be a backtest.Slippage (Slippage.none(), "
271
+ f"Slippage.bps(n) or Slippage.ticks(n)), not {slippage!r}", "BAD_SLIPPAGE")
272
+ through = a.fills == "through"
273
+ if how not in _HOWS:
274
+ raise While25Error(f"how must be one of {', '.join(_HOWS)}, not {how!r}", "BAD_HOW")
275
+ t, o, h, l, c = _bar(bar)
276
+ day = _bar_date(bar)
277
+ end = _bar_end(bar, t)
278
+ with localcontext(_CTX):
279
+ if how in ("open", "close"):
280
+ if price is not None:
281
+ raise While25Error(f"a {how} fill takes no price", "BAD_PRICE")
282
+ raw = o if how == "open" else c
283
+ level = None
284
+ else:
285
+ if price is None:
286
+ raise While25Error(f"a {how} fill needs its price", "BAD_PRICE")
287
+ p = level = _positive(price, f"{how} price", "BAD_PRICE")
288
+ # A buy limit and a sell stop are reached from above, the others from below.
289
+ from_above = (how == "limit") == (side == "buy")
290
+ if from_above:
291
+ if l > p or (through and l == p):
292
+ return None
293
+ raw = min(o, p)
294
+ else:
295
+ if h < p or (through and h == p):
296
+ return None
297
+ raw = max(o, p)
298
+ slipped = slippage.apply(raw, side, instrument)
299
+ final = instrument.snap(slipped, mode="up" if side == "buy" else "down")
300
+ if final is None:
301
+ _tick_or_refuse(instrument, slipped)
302
+ if final <= 0:
303
+ raise While25Error(f"slippage {slippage.describe()} takes a {side} at {raw} to {final}, "
304
+ f"which is no price", "BAD_SLIPPAGE")
305
+ return Fill(time=t, how=how, raw=raw, slippage=slippage.describe(), price=final,
306
+ side=side, instrument_key=instrument.instrument_key, level=level,
307
+ date=day, end=end, slippage_stated=stated, fills=a.fills,
308
+ assume=a.fingerprint())
309
+
310
+
311
+ def first_exit(bar: dict, side: str, *, stop, target, rule: "str | None" = None,
312
+ assume: "Assumptions | None" = None) -> "str | None":
313
+ """Which of a position's exits this bar reaches first: "stop", "target" or
314
+ None. `side` is the position's entry side ("buy" = long). A bar that opens
315
+ through a level reached it first, whatever the rule; when both are touched
316
+ inside the bar, the order within it is unknowable and `rule` says which
317
+ to assume ("stop_first", the conservative default, or "target_first";
318
+ None: the assumption's same_bar). Under fills "through" a level is
319
+ reached only when traded past (strict <, >)."""
320
+ _side(side)
321
+ a = _assumed(assume)
322
+ if rule is None:
323
+ rule = a.same_bar
324
+ if rule not in _RULES:
325
+ raise While25Error(f"rule must be 'stop_first' or 'target_first', not {rule!r}", "BAD_RULE")
326
+ _t, o, h, l, _c = _bar(bar)
327
+ s = None if stop is None else _positive(stop, "stop", "BAD_PRICE")
328
+ g = None if target is None else _positive(target, "target", "BAD_PRICE")
329
+ long = side == "buy"
330
+ if s is not None and g is not None and (s >= g if long else s <= g):
331
+ raise While25Error(f"a {'long' if long else 'short'} position's stop {s} is on the wrong "
332
+ f"side of its target {g}", "BAD_PRICE")
333
+
334
+ def past(x, lvl, below): # x reached lvl from above (below=True) or from below
335
+ if lvl is None:
336
+ return False
337
+ if a.fills == "through":
338
+ return x < lvl if below else x > lvl
339
+ return x <= lvl if below else x >= lvl
340
+
341
+ at_open = "stop" if past(o, s, long) else "target" if past(o, g, not long) else None
342
+ hit_s, hit_g = past(l if long else h, s, long), past(h if long else l, g, not long)
343
+ if at_open:
344
+ return at_open
345
+ if hit_s and hit_g:
346
+ return "stop" if rule == "stop_first" else "target"
347
+ return "stop" if hit_s else "target" if hit_g else None
348
+
349
+
350
+ def exit_fill(bar: dict, side: str, *, instrument: Instrument, stop, target,
351
+ slippage: "Slippage | None" = None,
352
+ assume: "Assumptions | None" = None) -> "Fill | None":
353
+ """A position's bracket exit on this bar, or None when neither level is
354
+ reached. `side` is the POSITION's entry side; first_exit (under the
355
+ assumption's same_bar rule and fill style) picks the level, and the
356
+ opposite side fills there: the stop as a stop, the target as a limit.
357
+ The Fill records `bracket` {"stop", "target", "rule"} (strings; an absent
358
+ level None)."""
359
+ a = _assumed(assume)
360
+ which = first_exit(bar, side, stop=stop, target=target, assume=a)
361
+ if which is None:
362
+ return None
363
+ lvl = stop if which == "stop" else target
364
+ f = fill(bar, "sell" if side == "buy" else "buy", "stop" if which == "stop" else "limit",
365
+ instrument=instrument, price=lvl, slippage=slippage, assume=a)
366
+ plain = {k: None if v is None else format(_positive(v, k, "BAD_PRICE"), "f")
367
+ for k, v in (("stop", stop), ("target", target))}
368
+ return replace(f, bracket={**plain, "rule": a.same_bar})
369
+
370
+
371
+ # ---- costs ------------------------------------------------------------------------
372
+
373
+ _BUNDLED = Path(__file__).resolve().parent / "_costs"
374
+ _IN_TREE = None # a test may point this at a directory; else $WHILE25_REGISTRY/costs
375
+
376
+
377
+ def _dir() -> Path:
378
+ """The bundled registry first (staged into the package), else a source
379
+ checkout's, named by $WHILE25_REGISTRY."""
380
+ for d in (_BUNDLED, _IN_TREE or _registry("costs")):
381
+ if d and d.is_dir():
382
+ return d
383
+ raise While25Error(f"no cost registry found: expected {_BUNDLED} (bundled) or "
384
+ f"$WHILE25_REGISTRY/costs (source checkout)", "COSTS_UNKNOWN")
385
+
386
+
387
+ @functools.lru_cache(maxsize=1)
388
+ def _schedules() -> tuple:
389
+ """Every schedule in the registry, rates as exact Decimals. Read once."""
390
+ out = []
391
+ for path in sorted(_dir().rglob("*.json")):
392
+ doc = json.loads(path.read_text(), parse_float=Decimal, parse_int=Decimal)
393
+ out.extend(doc if isinstance(doc, list) else [doc])
394
+ for s in out:
395
+ if isinstance(s.get("non_equity"), dict):
396
+ s["non_equity"]["symbols"] = {k: frozenset(v) for k, v in s["non_equity"]["symbols"].items()}
397
+ # Frozen: a script holding a schedule cannot change what a later cost_for reads.
398
+ return tuple(_freeze(s) for s in out)
399
+
400
+
401
+ def _freeze(x):
402
+ if isinstance(x, dict):
403
+ return MappingProxyType({k: _freeze(v) for k, v in x.items()})
404
+ if isinstance(x, list):
405
+ return tuple(_freeze(v) for v in x)
406
+ return x
407
+
408
+
409
+ @dataclass(frozen=True)
410
+ class CostKey:
411
+ """What identifies a fill to the cost registry (README "Lookup")."""
412
+ country: str # the market profile's country_code
413
+ exchange: str # the instrument's exchange code: NSE, NFO, NYSE, ...
414
+ segment: str # EQ | FUT | OPT | CRYPTO
415
+ broker: str # the execution broker id
416
+ symbol: str = "" # the exchange's symbol: a listed non-equity uses its class's schedules
417
+
418
+
419
+ @dataclass
420
+ class Costs:
421
+ lines: "dict[str, Decimal]" # "<schedule>.<charge>" -> amount, unrounded
422
+ total: Decimal
423
+ currency: str
424
+ schedule: str # "<statutory>+<broker>"
425
+ rate_set: str # "<statutory effective_from>+<broker effective_from>"
426
+ backdated: bool = False # the broker's first rate set used before its date
427
+ derivation: dict = field(default_factory=dict)
428
+
429
+
430
+ def _one(matches: list, what: str) -> dict:
431
+ if not matches:
432
+ raise While25Error(f"no {what} cost schedule; refused rather than costed as zero", "COSTS_UNKNOWN")
433
+ if len(matches) > 1:
434
+ raise While25Error(f"{len(matches)} {what} cost schedules match: "
435
+ f"{', '.join(m['schedule'] for m in matches)}", "COSTS_UNKNOWN")
436
+ return matches[0]
437
+
438
+
439
+ def _rate_set(sched: dict, on: date, *, may_backdate: bool) -> "tuple[dict, bool]":
440
+ """The last rate set in force on `on`, and whether it was backdated.
441
+ Only a broker tariff (undated pages) may be backdated to its first set."""
442
+ sets = sched["rate_sets"]
443
+ picked = [rs for rs in sets if date.fromisoformat(rs["effective_from"]) <= on]
444
+ if not picked:
445
+ if may_backdate:
446
+ return sets[0], True
447
+ raise While25Error(f"{sched['schedule']} has no rate in force on {on.isoformat()} (first: "
448
+ f"{sets[0]['effective_from']}); refused, never zero", "COSTS_UNKNOWN")
449
+ rs = picked[-1]
450
+ if rs.get("until") and on > date.fromisoformat(rs["until"]):
451
+ raise While25Error(f"{sched['schedule']}'s temporary rate set ended {rs['until']} and no "
452
+ f"later one is on file", "COSTS_UNKNOWN")
453
+ return rs, False
454
+
455
+
456
+ def _charges(sched: dict, rs: dict, side: str, product: str, price: Decimal, qty: Decimal,
457
+ mult: Decimal) -> "dict[str, Decimal]":
458
+ """Every charge of one rate set that applies to this fill. No rounding:
459
+ the registry states none."""
460
+ value = price * qty * mult
461
+ applies = [c for c in rs["charges"] if c["side"] in (side, "both") and c["product"] in (product, "any")]
462
+ amounts: dict = {}
463
+
464
+ def clamp(c, amount):
465
+ if c["min"] is not None:
466
+ amount = max(amount, c["min"])
467
+ if c["max"] is not None:
468
+ amount = min(amount, c["max"])
469
+ return amount
470
+
471
+ for c in applies:
472
+ if c["basis"] == "tax":
473
+ continue
474
+ # Quantity convention: a contract instrument (multiplier > 1, a US option's
475
+ # 100) counts qty in contracts; a unit instrument (multiplier 1) in
476
+ # shares or units. A charge whose unit the instrument cannot state is refused.
477
+ if c["basis"] == "per_contract" and not mult > 1:
478
+ raise While25Error(f"{sched['schedule']}.{c['name']} is charged per contract and the "
479
+ f"venue states a multiplier of {mult}: contracts cannot be told from "
480
+ f"units", "RULES_UNKNOWN")
481
+ if c["basis"] == "per_share" and mult != 1:
482
+ raise While25Error(f"{sched['schedule']}.{c['name']} is charged per share and the venue "
483
+ f"states a multiplier of {mult}: shares cannot be told from "
484
+ f"contracts", "RULES_UNKNOWN")
485
+ base = {"turnover": value, "premium": value, "per_contract": qty, "per_share": qty,
486
+ "per_order": Decimal(1)}.get(c["basis"])
487
+ if base is None:
488
+ raise While25Error(f"{sched['schedule']}: unknown basis {c['basis']!r}", "COSTS_UNKNOWN")
489
+ amounts[c["name"]] = amounts.get(c["name"], Decimal(0)) + clamp(c, c["rate"] * base)
490
+ for c in applies:
491
+ if c["basis"] == "tax":
492
+ base = sum((amounts.get(n, Decimal(0)) for n in c["on"]), Decimal(0))
493
+ amounts[c["name"]] = amounts.get(c["name"], Decimal(0)) + clamp(c, c["rate"] * base)
494
+ return {f"{sched['schedule']}.{n}": a for n, a in amounts.items()}
495
+
496
+
497
+ #: (country, segment) whose statutory schedule must carry `non_equity` (the
498
+ #: validator's NON_EQUITY_REQUIRED): its cash segment lists ETFs, SGBs and
499
+ #: G-secs typed as equity. Without the list, or without a symbol to look up,
500
+ #: a cost there is refused, never costed as equity (fails closed).
501
+ _NON_EQUITY_REQUIRED = {("IN", "EQ")}
502
+
503
+
504
+ def _norm_symbol(symbol: str) -> str:
505
+ """The exchange's own spelling: NFKC (full-width letters), no format
506
+ characters (zero-width, BOM), no whitespace anywhere, no "NSE:"-style
507
+ prefix, no " EQ" / "-EQ" series word, no ".NSE" / ".NS" / ".BO" suffix,
508
+ upper case."""
509
+ s = "".join(ch for ch in unicodedata.normalize("NFKC", symbol or "")
510
+ if unicodedata.category(ch) != "Cf").strip().upper()
511
+ s = re.sub(r"[\s-]+EQ$", "", s.rsplit(":", 1)[-1].strip()) # a separated EQ only: EQUITAS stays
512
+ s = "".join(s.split())
513
+ for suffix in (".NSE", ".NS", ".BO"):
514
+ if s.endswith(suffix):
515
+ s = s[:-len(suffix)]
516
+ return s
517
+
518
+
519
+ def _class_of(stat, key: CostKey) -> "str | None":
520
+ """The kind the statutory schedule's `non_equity` list gives the symbol
521
+ (equity_etf, other_etf, SGB, ...), or None for an equity. COSTS_UNKNOWN
522
+ where the list is required and missing, or there is no symbol."""
523
+ ne = stat.get("non_equity")
524
+ norm = _norm_symbol(key.symbol)
525
+ if (stat["country"], stat["segment"]) in _NON_EQUITY_REQUIRED:
526
+ if not ne:
527
+ raise While25Error(f"{stat['schedule']}: the non-equity list is missing, so an ETF "
528
+ f"cannot be told from an equity; refused", "COSTS_UNKNOWN")
529
+ if not norm:
530
+ raise While25Error(f"no symbol to look up on {stat['schedule']}'s non-equity list; "
531
+ f"refused rather than costed as equity", "COSTS_UNKNOWN")
532
+ if not ne or not norm:
533
+ return None
534
+ # ponytail: a broker's series suffix ("SGBAUG28V-GB") is cut at the last
535
+ # "-"; only a listed symbol can match, so "BAJAJ-AUTO" is never refused.
536
+ for sym in dict.fromkeys((norm, norm.rsplit("-", 1)[0])):
537
+ for kind, listed in ne["symbols"].items():
538
+ if sym in listed:
539
+ return kind
540
+ return None
541
+
542
+
543
+ #: Said with every COSTS_UNKNOWN from the real-costs path:
544
+ #: zero and custom costs read no cost registry, so a run the registry cannot
545
+ #: cost runs once its costs are stated. The default is real costs, and the
546
+ #: refusal alone did not say so.
547
+ # backtest.assume() only RETURNS the choice: a script that called it and passed
548
+ # it nowhere (2026-11-25, a BITO run read this hint and did just that, twice)
549
+ # was still costed under real costs, so the hint names where it goes.
550
+ _COSTS_WAY_OUT = ("; zero or custom costs need no cost schedule: choose them in Settings, "
551
+ "Backtest, Costs, or in the script with a = backtest.assume(costs=\"zero\") "
552
+ "(or costs=\"custom\", custom_flat=..., custom_pct=...) passed as assume=a to "
553
+ "every backtest.fill(), exit_fill() and trade() call and to ui.backtest_block(); "
554
+ "calling backtest.assume() alone changes nothing. The backtest records the "
555
+ "choice on every trade")
556
+
557
+
558
+ def _says_the_way_out(fn):
559
+ """A COSTS_UNKNOWN leaving `fn` carries _COSTS_WAY_OUT, once (costs()
560
+ calls cost_for()). The same error, its code and traceback kept."""
561
+ @functools.wraps(fn)
562
+ def wrapped(*args, **kwargs):
563
+ try:
564
+ return fn(*args, **kwargs)
565
+ except While25Error as e:
566
+ if e.code == "COSTS_UNKNOWN" and _COSTS_WAY_OUT not in (e.message or ""):
567
+ e.message = (e.message or "") + _COSTS_WAY_OUT
568
+ e.args = (e.message,)
569
+ raise
570
+ return wrapped
571
+
572
+
573
+ @_says_the_way_out
574
+ def cost_for(key: CostKey, side: str, price, qty, *, product: str, on: date, multiplier) -> Costs:
575
+ """What one fill costs: the statutory schedule for (country, segment,
576
+ exchange) plus the broker's for (country, segment, broker), each at the
577
+ rate set in force on `on` (the fill's exchange-local trade date). Either
578
+ missing, or no statutory rate on `on`: COSTS_UNKNOWN. A test_only schedule
579
+ serves only broker "test_broker". A symbol on the statutory schedule's
580
+ non_equity list is costed from the schedules naming its class instead."""
581
+ _side(side)
582
+ if product not in _PRODUCTS:
583
+ raise While25Error(f"product must be 'intraday' or 'delivery', not {product!r}", "BAD_PRODUCT")
584
+ if isinstance(on, datetime) or not isinstance(on, date):
585
+ raise While25Error(f"on must be a date (the exchange-local trade date), not {on!r}", "BAD_DATE")
586
+ p = _positive(price, "price", "BAD_PRICE")
587
+ q = _positive(qty, "qty", "BAD_QTY")
588
+ if multiplier is None:
589
+ raise While25Error("the venue states no multiplier; a turnover cannot be computed", "RULES_UNKNOWN")
590
+ m = _positive(multiplier, "multiplier", "RULES_UNKNOWN")
591
+
592
+ pool = [s for s in _schedules() if s["country"] == key.country and s["segment"] == key.segment]
593
+
594
+ def usable(s: dict) -> dict:
595
+ if s.get("test_only") and key.broker != "test_broker":
596
+ raise While25Error(f"{s['schedule']} is test_only and serves only test_broker, not "
597
+ f"{key.broker!r}", "COSTS_UNKNOWN")
598
+ return s
599
+
600
+ def of(cls) -> list:
601
+ return [s for s in pool if cls in (s.get("classes") or (None,))]
602
+
603
+ stat = usable(_one([s for s in of(None) if s["broker"] is None
604
+ and key.exchange in (s.get("exchanges") or ())],
605
+ f"statutory {key.country} {key.segment} {key.exchange}"))
606
+ cls = _class_of(stat, key)
607
+ if cls is not None:
608
+ # A listed non-equity is costed only from its class's own schedules.
609
+ listed = (f"{key.symbol} is listed as {cls} on {key.exchange} ({stat['schedule']}, as of "
610
+ f"{stat['non_equity']['as_of']}): its charges are not equity charges")
611
+ stat = [s for s in of(cls) if s["broker"] is None and key.exchange in (s.get("exchanges") or ())]
612
+ if not stat:
613
+ raise While25Error(f"{listed}, and no schedule for {cls} is in the registry",
614
+ "COSTS_UNKNOWN")
615
+ stat = usable(_one(stat, f"statutory {key.country} {key.segment} {key.exchange} {cls}"))
616
+ brk = [s for s in of(cls) if s["broker"] is not None and s["broker"] == key.broker]
617
+ if not brk:
618
+ raise While25Error(f"{listed}, and broker {key.broker!r} has no {cls} schedule (its "
619
+ f"published tariff states none)", "COSTS_UNKNOWN")
620
+ brk = usable(_one(brk, f"broker {key.broker!r} {key.country} {key.segment} {cls}"))
621
+ else:
622
+ brk = usable(_one([s for s in of(None) if s["broker"] is not None and s["broker"] == key.broker],
623
+ f"broker {key.broker!r} {key.country} {key.segment}"))
624
+ if stat["currency"] != brk["currency"]:
625
+ raise While25Error(f"{stat['schedule']} is in {stat['currency']} and {brk['schedule']} in "
626
+ f"{brk['currency']}", "COSTS_UNKNOWN")
627
+ with localcontext(_CTX):
628
+ rs_s, _ = _rate_set(stat, on, may_backdate=False)
629
+ rs_b, backdated = _rate_set(brk, on, may_backdate=True)
630
+ lines = {**_charges(stat, rs_s, side, product, p, q, m), **_charges(brk, rs_b, side, product, p, q, m)}
631
+ total = sum(lines.values(), Decimal(0))
632
+ return Costs(
633
+ lines=lines, total=total, currency=stat["currency"],
634
+ schedule=f"{stat['schedule']}+{brk['schedule']}",
635
+ rate_set=f"{rs_s['effective_from']}+{rs_b['effective_from']}", backdated=backdated,
636
+ derivation={"key": asdict(key), "side": side, "price": p, "qty": q, "multiplier": m,
637
+ "product": product, "on": on.isoformat(),
638
+ "schedules": [stat["schedule"], brk["schedule"]],
639
+ "rate_sets": {stat["schedule"]: rs_s["effective_from"],
640
+ brk["schedule"]: rs_b["effective_from"]},
641
+ "backdated": backdated})
642
+
643
+
644
+ #: The catalog's instrument type -> cost segment (registry/costs README
645
+ #: "Lookup"). Both spellings the engine uses: canonical ids (EQ/FUT/OPT/
646
+ #: CRYPTO) and the catalog's (EQUITY/FUTURE/OPTION). Anything else has no
647
+ #: segment and is refused, never costed as its nearest neighbour.
648
+ _SEGMENTS = {"EQ": "EQ", "EQUITY": "EQ", "FUT": "FUT", "FUTURE": "FUT",
649
+ "OPT": "OPT", "OPTION": "OPT", "CRYPTO": "CRYPTO"}
650
+
651
+
652
+ def _broker(instrument: Instrument, broker) -> str:
653
+ """The broker given, else the account's ("" when not stated)."""
654
+ if broker is not None and (not isinstance(broker, str) or not broker):
655
+ raise While25Error(f"broker must be a broker id or None (the account's), not {broker!r}",
656
+ "BAD_BROKER")
657
+ return broker if broker is not None else instrument.broker_id
658
+
659
+
660
+ def _cost_key(instrument: Instrument, broker) -> CostKey:
661
+ """The registry key, from what the engine states; never from the key."""
662
+ brk = _broker(instrument, broker)
663
+ missing = [name for name, v in (("exchange", instrument.exchange),
664
+ ("instrument type", instrument.instrument_type),
665
+ ("country", instrument.country_code),
666
+ ("broker", brk)) if not v]
667
+ if missing:
668
+ raise While25Error(f"cannot cost {instrument.instrument_key or instrument.symbol}: "
669
+ f"While25 states no {', '.join(missing)}", "RULES_UNKNOWN")
670
+ t = instrument.instrument_type
671
+ # The US CRYPTO venue's catalog types its pairs as currency (README).
672
+ seg = _SEGMENTS.get(t) or ("CRYPTO" if t == "CURRENCY" and instrument.exchange == "CRYPTO" else None)
673
+ if seg is None:
674
+ raise While25Error(f"no cost segment for a {t} on {instrument.exchange}", "COSTS_UNKNOWN")
675
+ return CostKey(instrument.country_code, instrument.exchange, seg, brk, instrument.symbol)
676
+
677
+
678
+ @_says_the_way_out
679
+ def costs(instrument: Instrument, side: str, price, qty, *, product: str, on: date,
680
+ broker=None) -> Costs:
681
+ """cost_for() with the key read from the instrument and the account
682
+ (broker None = the account's broker)."""
683
+ return cost_for(_cost_key(instrument, broker), side, price, qty, product=product, on=on,
684
+ multiplier=instrument.multiplier)
685
+
686
+
687
+ # ---- trades -----------------------------------------------------------------------
688
+
689
+ def _in_order(entry: Fill, exit: Fill) -> None:
690
+ """BAD_FILL unless the exit can follow the entry. An entry known only at
691
+ its bar's end (limit, stop, close) allows no exit on a bar starting before
692
+ that end, whatever its interval; only the very same bar is judged by the
693
+ one-bar order: open before limit / stop before close (never a close, then
694
+ anything)."""
695
+ same_bar = exit.time == entry.time and exit.end == entry.end
696
+ if entry.how != "open" and exit.time < entry.end and not (same_bar and entry.how != "close"):
697
+ raise While25Error(f"the {exit.how} exit at {exit.time} comes before the {entry.how} entry "
698
+ f"is known (its bar ends at {entry.end})", "BAD_FILL")
699
+ if same_bar and _RANK.get(entry.how) == _RANK.get(exit.how) == 1:
700
+ raise While25Error(f"a {entry.how} entry and a {exit.how} exit on one bar: the order of "
701
+ f"the high and low inside one bar is unknowable; use a finer interval",
702
+ "BAD_FILL")
703
+ if exit.time == entry.time and _RANK.get(exit.how, -1) < _RANK.get(entry.how, 3):
704
+ raise While25Error(f"on one bar a {exit.how} exit comes before a {entry.how} entry "
705
+ f"(open, then limit / stop, then close)", "BAD_FILL")
706
+
707
+
708
+ def _venue_qty(inst: Instrument, q: Decimal) -> None:
709
+ """BAD_QTY for a quantity off the venue's stated step (lot, else
710
+ increment) or under its stated minimum; a rule not stated is not judged."""
711
+ step = inst.step
712
+ with localcontext(_CTX):
713
+ if step is not None and step.is_finite() and q % step != 0:
714
+ raise While25Error(f"qty {q} is not a multiple of the venue's size step {step}", "BAD_QTY")
715
+ if inst.min_qty is not None and q < inst.min_qty:
716
+ raise While25Error(f"qty {q} is under the venue's minimum {inst.min_qty}", "BAD_QTY")
717
+
718
+
719
+ def _stated_costs(a: "Assumptions", instrument: Instrument, side: str, price: Decimal, q: Decimal,
720
+ m: Decimal, product: str, on: date) -> Costs:
721
+ """One fill's zero or custom costs: no registry, no broker. Custom is
722
+ flat + pct/100 x price x qty x multiplier, one line named `custom`."""
723
+ if product not in _PRODUCTS:
724
+ raise While25Error(f"product must be 'intraday' or 'delivery', not {product!r}", "BAD_PRODUCT")
725
+ if not instrument.quote_currency:
726
+ raise While25Error(f"the venue states no currency for {instrument.instrument_key}; its "
727
+ f"costs cannot be stated", "RULES_UNKNOWN")
728
+ if a.costs == "zero":
729
+ name, lines = "zero", {}
730
+ else:
731
+ name = f"custom: {_plain(a.custom_flat)} per order + {_plain(a.custom_pct)}% of turnover"
732
+ with localcontext(_CTX):
733
+ lines = {"custom": a.custom_flat + a.custom_pct / 100 * price * q * m}
734
+ with localcontext(_CTX):
735
+ total = sum(lines.values(), Decimal(0))
736
+ return Costs(lines=lines, total=total, currency=instrument.quote_currency, schedule=name,
737
+ rate_set="", derivation={"side": side, "price": price, "qty": q, "multiplier": m,
738
+ "product": product, "on": on.isoformat(),
739
+ "schedules": [name], "rate_sets": {}, "backdated": False})
740
+
741
+
742
+ def _trade(key: "CostKey | None", instrument: Instrument, side: str, qty, entry: Fill, exit: Fill, *,
743
+ product: str, a: "Assumptions | None" = None, broker: "str | None" = None) -> dict:
744
+ """trade()'s arithmetic on an explicit cost key (None: costs `a` states,
745
+ recorded on `broker`); each side costed on its fill's exchange trading date.
746
+ `a` None reads the run's defaults()."""
747
+ a = _assumed(a)
748
+ _side(side)
749
+ out_side = "sell" if side == "buy" else "buy"
750
+ mine = a.fingerprint()
751
+ for f, want, what in ((entry, side, "entry"), (exit, out_side, "exit")):
752
+ if not isinstance(f, Fill):
753
+ raise While25Error(f"{what} must be a Fill, not {type(f).__name__}", "BAD_FILL")
754
+ if f.assume != mine:
755
+ raise While25Error(f"the {what} fill was built under different assumptions than the "
756
+ f"trade; make both fills and the trade under one", "BAD_FILL")
757
+ if f.side != want:
758
+ raise While25Error(f"a {side} trade's {what} is a {want} fill, not {f.side}", "BAD_FILL")
759
+ if f.instrument_key != instrument.instrument_key:
760
+ raise While25Error(f"the {what} fill is on {f.instrument_key!r}, not "
761
+ f"{instrument.instrument_key!r}", "BAD_FILL")
762
+ if isinstance(f.end, bool) or not isinstance(f.end, int) or f.end <= f.time:
763
+ raise While25Error(f"the {what} fill names no bar end after its time "
764
+ f"({f.end!r}); make it with fill()", "BAD_FILL")
765
+ on_entry, on_exit = _trade_date(entry), _trade_date(exit)
766
+ if exit.time < entry.time or on_exit < on_entry:
767
+ raise While25Error("the exit is before the entry", "BAD_FILL")
768
+ _in_order(entry, exit)
769
+ if product == "intraday" and on_entry != on_exit:
770
+ raise While25Error(f"an intraday trade closes on its own trading date: entry "
771
+ f"{on_entry.isoformat()}, exit {on_exit.isoformat()}; a position held "
772
+ f"overnight is product 'delivery'", "BAD_PRODUCT")
773
+ q = _positive(qty, "qty", "BAD_QTY")
774
+ _venue_qty(instrument, q)
775
+ if instrument.multiplier is None:
776
+ raise While25Error(f"the venue states no multiplier for {instrument.instrument_key}", "RULES_UNKNOWN")
777
+ m = _positive(instrument.multiplier, "multiplier", "RULES_UNKNOWN")
778
+ if key is None:
779
+ c_in = _stated_costs(a, instrument, side, entry.price, q, m, product, on_entry)
780
+ c_out = _stated_costs(a, instrument, out_side, exit.price, q, m, product, on_exit)
781
+ else:
782
+ c_in = cost_for(key, side, entry.price, q, product=product, on=on_entry, multiplier=m)
783
+ c_out = cost_for(key, out_side, exit.price, q, product=product, on=on_exit, multiplier=m)
784
+ with localcontext(_CTX):
785
+ gross = (exit.price - entry.price) * q * m * (1 if side == "buy" else -1)
786
+ pnl = gross - c_in.total - c_out.total
787
+ return {
788
+ "instrument": instrument.instrument_key, "side": side, "qty": q,
789
+ "entry_time": entry.time, "exit_time": exit.time, "entry": entry.price, "exit": exit.price,
790
+ "multiplier": m, "gross": gross, "costs_in": c_in, "costs_out": c_out, "pnl": pnl,
791
+ "derivation": {
792
+ "entry": asdict(entry), "exit": asdict(exit),
793
+ "slippage": {"entry": entry.slippage, "exit": exit.slippage},
794
+ "product": product, "broker": key.broker if key is not None else broker,
795
+ "on": {"entry": on_entry.isoformat(), "exit": on_exit.isoformat()},
796
+ "schedules": {"entry": c_in.derivation["schedules"], "exit": c_out.derivation["schedules"]},
797
+ "rate_sets": {"entry": c_in.derivation["rate_sets"], "exit": c_out.derivation["rate_sets"]},
798
+ "backdated": {"entry": c_in.backdated, "exit": c_out.backdated},
799
+ "costs_mode": a.costs, "assume": a.as_dict(),
800
+ },
801
+ }
802
+
803
+
804
+ @_says_the_way_out
805
+ def trade(instrument: Instrument, side: str, qty, entry: Fill, exit: Fill, *, product: str,
806
+ broker=None, assume: "Assumptions | None" = None) -> dict:
807
+ """One round trip: gross = (exit - entry) x qty x multiplier (negated for
808
+ a short), pnl = gross - both sides' costs.
809
+
810
+ Refused (BAD_FILL) when the exit cannot follow the entry: on one bar an
811
+ open comes first, a limit / stop inside, the close last; after a limit,
812
+ stop or close entry no other bar starting before the entry bar's end may
813
+ exit (any interval), and a close entry never exits on its own bar; a
814
+ limit / stop entry and a limit / stop exit on one bar are refused (the
815
+ order of its high and low is unknowable). COSTS_UNKNOWN also for an IN
816
+ equity cost with no symbol or no non-equity list to check it against.
817
+ BAD_PRODUCT: "intraday" with entry and exit on different trading dates.
818
+ BAD_QTY: qty off the venue's stated step (lot, else increment) or under
819
+ its stated minimum. A symbol the registry lists as a non-equity (ETF,
820
+ SGB, G-sec, InvIT, REIT) is costed from its class's own statutory and
821
+ broker schedules; COSTS_UNKNOWN when either is not in the registry.
822
+
823
+ Costs follow `assume` (None: the run's defaults()): "real" as above;
824
+ "zero" charges nothing and "custom" each fill flat + pct/100 x price x
825
+ qty x multiplier (one line, `custom`), neither reading the registry nor
826
+ needing a broker. Every other check stands; the venue's multiplier and
827
+ currency are still required (RULES_UNKNOWN). BAD_FILL: a fill made under
828
+ other assumptions than the trade's."""
829
+ a = _assumed(assume)
830
+ if a.costs == "real":
831
+ return _trade(_cost_key(instrument, broker), instrument, side, qty, entry, exit,
832
+ product=product, a=a)
833
+ return _trade(None, instrument, side, qty, entry, exit, product=product, a=a,
834
+ broker=_broker(instrument, broker) or None)
835
+
836
+
837
+ # ---- sessions ---------------------------------------------------------------------
838
+
839
+ @dataclass(frozen=True)
840
+ class Session:
841
+ date: date
842
+ bars: list
843
+ regular: "list | None" # the regular-session bars; None when a flag is unknown
844
+
845
+
846
+ def sessions(answer: dict) -> "list[Session]":
847
+ """A history_span() answer's bars grouped by exchange trading day, on the
848
+ clock the answer names (calendar_tz) and by the same rule its
849
+ missing_days uses: an intraday series by its own daily pauses (a CME
850
+ evening bar is the next day's), round-the-clock by UTC day, daily bars by
851
+ their date. No clock stated: CALENDAR_UNKNOWN, never UTC."""
852
+ tz = answer.get("calendar_tz")
853
+ if not tz:
854
+ raise While25Error("the answer names no exchange clock (calendar_tz); its bars cannot be "
855
+ "put on trading days", "CALENDAR_UNKNOWN")
856
+ try:
857
+ ZoneInfo(tz)
858
+ except Exception: # noqa: BLE001 — an unknown name or no tz database
859
+ raise While25Error(f"unknown exchange clock {tz!r}", "CALENDAR_UNKNOWN") from None
860
+ interval = answer.get("interval")
861
+ if interval not in _days.DAILY and interval not in _days.STEP_MS:
862
+ raise While25Error(f"unknown interval {interval!r}", "UNKNOWN_INTERVAL")
863
+ bars = [dict(b) for b in answer.get("bars") or ()]
864
+ for b in bars:
865
+ t = b.get("time")
866
+ if isinstance(t, bool) or not isinstance(t, numbers.Integral):
867
+ raise While25Error(f"bar time must be integer epoch ms, not {t!r}", "BAD_BAR")
868
+ bars.sort(key=lambda b: b["time"])
869
+ times = [int(b["time"]) for b in bars]
870
+ days = _days.trading_dates(times, interval, answer.get("calendar") == "24/7", tz)
871
+ grouped: dict = {}
872
+ for d, b in zip(days, bars):
873
+ grouped.setdefault(d, []).append(b)
874
+ return [Session(date=d, bars=bs,
875
+ regular=None if any(b.get("regular") is None for b in bs)
876
+ else [b for b in bs if b["regular"]])
877
+ for d, bs in sorted(grouped.items())]
878
+
879
+
880
+ # What a backtest assumes (defined in while25.assume, which needs Slippage).
881
+ from .assume import Assumptions, _plain, assume, defaults # noqa: E402,F401