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
@@ -0,0 +1,172 @@
1
+ {
2
+ "_doc": "US regulatory transaction fees on listed equity option sales, any broker. ORF and OCC clearing are broker pass-throughs (brokers/*.json); since 2026-07-01 ORF is assessed per executing exchange, so no venue-neutral rate exists.",
3
+ "schedule": "us_opt",
4
+ "omitted": ["rounding to the cent"],
5
+ "country": "US",
6
+ "segment": "OPT",
7
+ "currency": "USD",
8
+ "broker": null,
9
+ "exchanges": [
10
+ "CBOE",
11
+ "OPRA"
12
+ ],
13
+ "rate_sets": [
14
+ {
15
+ "effective_from": "2024-05-22",
16
+ "source": "SEC Section 31 $27.80/M from 2024-05-22 (https://www.sec.gov/rules-regulations/fee-rate-advisories/2024-2) ; FINRA TAF 2024-2025 schedule, SR-FINRA-2024-019 (https://www.finra.org/rules-guidance/rule-filings/sr-finra-2024-019/fee-adjustment-schedule)",
17
+ "charges": [
18
+ {
19
+ "name": "sec_fee",
20
+ "basis": "premium",
21
+ "side": "sell",
22
+ "product": "any",
23
+ "rate": 0.0000278,
24
+ "min": null,
25
+ "max": null,
26
+ "on": null
27
+ },
28
+ {
29
+ "name": "finra_taf",
30
+ "basis": "per_contract",
31
+ "side": "sell",
32
+ "product": "any",
33
+ "rate": 0.00279,
34
+ "min": null,
35
+ "max": null,
36
+ "on": null
37
+ }
38
+ ]
39
+ },
40
+ {
41
+ "effective_from": "2025-05-14",
42
+ "source": "SEC Section 31 $0.00/M from 2025-05-14 (https://www.sec.gov/rules-regulations/fee-rate-advisories/2025-2) ; FINRA TAF 2024-2025 schedule, SR-FINRA-2024-019 (https://www.finra.org/rules-guidance/rule-filings/sr-finra-2024-019/fee-adjustment-schedule)",
43
+ "charges": [
44
+ {
45
+ "name": "sec_fee",
46
+ "basis": "premium",
47
+ "side": "sell",
48
+ "product": "any",
49
+ "rate": 0,
50
+ "min": null,
51
+ "max": null,
52
+ "on": null
53
+ },
54
+ {
55
+ "name": "finra_taf",
56
+ "basis": "per_contract",
57
+ "side": "sell",
58
+ "product": "any",
59
+ "rate": 0.00279,
60
+ "min": null,
61
+ "max": null,
62
+ "on": null
63
+ }
64
+ ]
65
+ },
66
+ {
67
+ "effective_from": "2026-01-01",
68
+ "source": "FINRA TAF 2026 schedule, SR-FINRA-2024-019 (https://www.finra.org/rules-guidance/rule-filings/sr-finra-2024-019/fee-adjustment-schedule) ; SEC Section 31 $0.00/M from 2025-05-14 (https://www.sec.gov/rules-regulations/fee-rate-advisories/2025-2)",
69
+ "charges": [
70
+ {
71
+ "name": "sec_fee",
72
+ "basis": "premium",
73
+ "side": "sell",
74
+ "product": "any",
75
+ "rate": 0,
76
+ "min": null,
77
+ "max": null,
78
+ "on": null
79
+ },
80
+ {
81
+ "name": "finra_taf",
82
+ "basis": "per_contract",
83
+ "side": "sell",
84
+ "product": "any",
85
+ "rate": 0.00329,
86
+ "min": null,
87
+ "max": null,
88
+ "on": null
89
+ }
90
+ ]
91
+ },
92
+ {
93
+ "effective_from": "2026-04-04",
94
+ "source": "SEC Section 31 $20.60/M from 2026-04-04 (https://www.sec.gov/rules-regulations/fee-rate-advisories/2026-2) ; FINRA TAF 2026 schedule, SR-FINRA-2024-019 (https://www.finra.org/rules-guidance/rule-filings/sr-finra-2024-019/fee-adjustment-schedule)",
95
+ "charges": [
96
+ {
97
+ "name": "sec_fee",
98
+ "basis": "premium",
99
+ "side": "sell",
100
+ "product": "any",
101
+ "rate": 0.0000206,
102
+ "min": null,
103
+ "max": null,
104
+ "on": null
105
+ },
106
+ {
107
+ "name": "finra_taf",
108
+ "basis": "per_contract",
109
+ "side": "sell",
110
+ "product": "any",
111
+ "rate": 0.00329,
112
+ "min": null,
113
+ "max": null,
114
+ "on": null
115
+ }
116
+ ]
117
+ },
118
+ {
119
+ "effective_from": "2026-10-01",
120
+ "until": "2026-12-31",
121
+ "source": "FINRA TAF paused 2026-10-01..2026-12-31, SR-FINRA-2026-021 (https://www.finra.org/sites/default/files/2026-09/SR-FINRA-2026-021.pdf) ; SEC Section 31 $20.60/M from 2026-04-04 (https://www.sec.gov/rules-regulations/fee-rate-advisories/2026-2)",
122
+ "charges": [
123
+ {
124
+ "name": "sec_fee",
125
+ "basis": "premium",
126
+ "side": "sell",
127
+ "product": "any",
128
+ "rate": 0.0000206,
129
+ "min": null,
130
+ "max": null,
131
+ "on": null
132
+ },
133
+ {
134
+ "name": "finra_taf",
135
+ "basis": "per_contract",
136
+ "side": "sell",
137
+ "product": "any",
138
+ "rate": 0,
139
+ "min": null,
140
+ "max": null,
141
+ "on": null
142
+ }
143
+ ]
144
+ },
145
+ {
146
+ "effective_from": "2027-01-01",
147
+ "source": "FINRA TAF resumes 2027-01-01 at 2026 rates, held through 2028-12-31: SR-FINRA-2026-021 Exhibit 5B (https://www.finra.org/sites/default/files/2026-09/SR-FINRA-2026-021.pdf) and SR-FINRA-2026-020 (https://www.finra.org/sites/default/files/2026-09/SR-FINRA-2026-020.pdf), which postpones the 2027 increase to 2029 ; SEC Section 31 $20.60/M from 2026-04-04 (https://www.sec.gov/rules-regulations/fee-rate-advisories/2026-2)",
148
+ "charges": [
149
+ {
150
+ "name": "sec_fee",
151
+ "basis": "premium",
152
+ "side": "sell",
153
+ "product": "any",
154
+ "rate": 0.0000206,
155
+ "min": null,
156
+ "max": null,
157
+ "on": null
158
+ },
159
+ {
160
+ "name": "finra_taf",
161
+ "basis": "per_contract",
162
+ "side": "sell",
163
+ "product": "any",
164
+ "rate": 0.00329,
165
+ "min": null,
166
+ "max": null,
167
+ "on": null
168
+ }
169
+ ]
170
+ }
171
+ ]
172
+ }
while25/_days.py ADDED
@@ -0,0 +1,123 @@
1
+ """Which trading day a bar belongs to: the one rule the runtime's coverage check
2
+ (missing days) and while25.backtest.sessions (grouping) share, so the two can never
3
+ date a bar differently. Stdlib only.
4
+
5
+ No session hours ride the wire, so an intraday series is split into trading
6
+ days by its own daily pauses (a CME evening belongs to the next day's session),
7
+ each dated by its close on the exchange's own clock; a round-the-clock market
8
+ ("24/7") by UTC days; a daily bar carries its trading date (the engine stamps
9
+ it at UTC midnight of that date).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from collections import deque, namedtuple
14
+ from datetime import date, datetime, timedelta, timezone
15
+ from zoneinfo import ZoneInfo
16
+
17
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
18
+ _Unit = namedtuple("_Unit", "t_open t_close")
19
+
20
+ DAY_MS = 86_400_000
21
+ # A gap between two bars is a daily pause when it is at least DAY_PAUSE_MS
22
+ # long and no LONGER gap starts within DAY_PAUSE_LOOK_MS after it.
23
+ DAY_PAUSE_MS = 30 * 60_000
24
+ DAY_PAUSE_LOOK_MS = 12 * 3_600_000
25
+
26
+ #: The bar length of each interval history_span() checks. Weekly and monthly
27
+ #: bars are folded from daily ones by the engine: nothing of their own to check.
28
+ STEP_MS = {"1m": 60_000, "5m": 300_000, "15m": 900_000, "30m": 1_800_000,
29
+ "1h": 3_600_000, "1D": DAY_MS}
30
+
31
+ #: Every spelling the engine's interval parser takes,
32
+ #: to the one name bars are dated and gap-checked by. Case-sensitive like the
33
+ #: parser: "1m" is a minute, "1M" a month. A span asked as "1d" or "1440" was
34
+ #: served undated and every fill on it was refused CALENDAR_UNKNOWN.
35
+ _SPELLINGS = {"1m": ("1", "MINUTE_1"), "5m": ("5", "MINUTE_5"), "15m": ("15", "MINUTE_15"),
36
+ "30m": ("30", "MINUTE_30"), "1h": ("1H", "60", "MINUTE_60", "HOUR_1"),
37
+ "1D": ("1d", "1440", "DAY_1", "DAILY"), "1W": ("1w", "10080", "WEEK_1"),
38
+ "1M": ("43200", "MONTH_1")}
39
+ NAMES = {s: name for name, spellings in _SPELLINGS.items() for s in (name, *spellings)}
40
+
41
+
42
+ def interval_name(interval: str) -> str:
43
+ """The one name of an interval spelling; an unknown one as it is (the
44
+ engine refuses it UNKNOWN_INTERVAL)."""
45
+ return NAMES.get(interval, interval)
46
+
47
+
48
+ def utc_date(t_ms: int) -> date:
49
+ """The UTC calendar date of an instant."""
50
+ return (_EPOCH + timedelta(milliseconds=int(t_ms))).date()
51
+
52
+
53
+ def local_date(t_ms: int, tz: str) -> date:
54
+ """The calendar date of an instant on clock `tz` (an IANA name)."""
55
+ return (_EPOCH + timedelta(milliseconds=int(t_ms))).astimezone(ZoneInfo(tz)).date()
56
+
57
+
58
+ def _pauses(units: list) -> "tuple[list, list]":
59
+ """What an instrument's bars show of its trading days:
60
+ each unit's close, and the end of the trading day each unit belongs to —
61
+ the close of the last unit before the next daily pause, 0 when none comes
62
+ before the data ends.
63
+
64
+ A gap between two units is a daily pause when it is at least
65
+ DAY_PAUSE_MS long and no LONGER gap starts within DAY_PAUSE_LOOK_MS after
66
+ it: MNQ's bars stop at 16:00 Central and start again at 17:00, a holiday's
67
+ bars are not there, an early close's stop early, and a midday pause gives
68
+ way to the day's close later the same day. A thinly traded contract's quiet
69
+ hour can read as a pause, as it does on its chart."""
70
+ n = len(units)
71
+ closes = [u.t_close for u in units]
72
+ gaps = [units[j + 1].t_open - closes[j] for j in range(n - 1)]
73
+ pause = [False] * len(gaps)
74
+ # The longest gap starting within the look-ahead after each gap, by a
75
+ # sliding maximum walked from the end: the deque holds the window's
76
+ # indices left to right with gaps rising, so its right end is the
77
+ # longest; an index is dropped once a longer-or-equal gap starts before
78
+ # it (it leaves the window first and can never be the longest).
79
+ window: deque = deque()
80
+ for j in range(len(gaps) - 1, -1, -1):
81
+ k = j + 1
82
+ if k < len(gaps):
83
+ while window and gaps[window[0]] <= gaps[k]:
84
+ window.popleft()
85
+ window.appendleft(k)
86
+ while window and closes[window[-1]] > closes[j] + DAY_PAUSE_LOOK_MS:
87
+ window.pop()
88
+ longer_ahead = bool(window) and gaps[window[-1]] > gaps[j]
89
+ pause[j] = gaps[j] >= DAY_PAUSE_MS and not longer_ahead
90
+ ends = [0] * n
91
+ end = 0
92
+ for i in range(n - 1, -1, -1):
93
+ if i < len(pause) and pause[i]:
94
+ end = closes[i]
95
+ ends[i] = end
96
+ return closes, ends
97
+
98
+
99
+ def bar_days(times: list, interval_ms: int, round_the_clock: bool, tz: str) -> list:
100
+ """The trading day of each bar of an intraday series (bar open times,
101
+ ascending), in order: by UTC day on a round-the-clock market, else by the
102
+ series' own daily pauses, each day the date of its close on clock `tz`."""
103
+ if not times:
104
+ return []
105
+ if round_the_clock:
106
+ return [utc_date(t) for t in times]
107
+ units = [_Unit(t, t + int(interval_ms)) for t in times]
108
+ _closes, ends = _pauses(units)
109
+ last = units[-1].t_close
110
+ return [local_date((end or last) - 1, tz) for end in ends]
111
+
112
+
113
+ #: Bars that carry their trading date (the engine stamps it at UTC midnight).
114
+ DAILY = ("1D", "1W", "1M")
115
+
116
+
117
+ def trading_dates(times: list, interval: str, round_the_clock: bool, tz: str) -> list:
118
+ """The exchange trading date of each bar (open times, ascending), in
119
+ order: a daily, weekly or monthly bar its own UTC date, an intraday bar by
120
+ bar_days(). KeyError for an interval with no known bar length."""
121
+ if interval in DAILY:
122
+ return [utc_date(t) for t in times]
123
+ return bar_days(times, STEP_MS[interval], round_the_clock, tz)
while25/_figures.py ADDED
@@ -0,0 +1,233 @@
1
+ """Exact decimal figures, at the one boundary that touches the wire.
2
+
3
+ Everything the engine calls a quantity, a price or an amount rides the wire as
4
+ a CANONICAL decimal string (the engine's decimal-quantity
5
+ contract): optional leading '-', digits, an optional '.' followed by
6
+ digits, no exponent, no trailing zeros, "0" not "-0", at most nine fraction
7
+ digits. Money adds a currency.
8
+
9
+ Lives in `while25`, not the runtime: this is the SDK's own figure policy — what
10
+ a script may pass in and what it reads back — and `while25` has to enforce it
11
+ even when a script drives it directly through `ctx._call`, past the
12
+ runtime's own use of these same functions. The runtime imports this module (the way they already import `while25._runtime`)
13
+ rather than duplicating it, so the runtime and the standalone package can
14
+ never disagree about what a figure means.
15
+
16
+ Three functions do the whole conversion:
17
+
18
+ _canon(x, what) USER CODE -> wire text. Runs before a figure ever becomes
19
+ a JSON dict key crossing the worker -> parent pipe — a
20
+ Decimal is not JSON-safe, so this is also where a figure
21
+ stops being "whatever the author handed us" and starts
22
+ being the one string the engine's own parser accepts.
23
+ _dec(text) wire text -> Decimal | None. "" is not a number; it is
24
+ what an absent optional string reads back as, so it
25
+ decodes to None rather than Decimal("0") — a strategy
26
+ must never read "the broker did not say" as "zero".
27
+ _money(m) a wire Money submessage -> Money | None. Presence lives
28
+ on the CONTAINING optional field (Money itself has no
29
+ presence bit), so the call site passes `None` for
30
+ absence: `_money(r.day_pnl if r.HasField("day_pnl") else
31
+ None)`.
32
+
33
+ WHY A FLOAT NEEDS EXTRA SCRUTINY: `0.1 + 0.2` is `0.30000000000000004` in
34
+ binary floating point — a real value, not a typo, and rounding it to "fix" it
35
+ would make a wrong number look like a right one, exactly the failure mode this
36
+ whole design exists to close. So a float is accepted only when ITS OWN
37
+ shortest repr is already exact to nine fraction digits or fewer; anything
38
+ noisier is refused, with a hint at the value the author probably meant when
39
+ the excess is float noise and nothing else.
40
+
41
+ A float's shortest repr is read through float.__repr__, never repr(): NumPy 2
42
+ prints a float64 (a float subclass, and what pandas hands a script) as
43
+ "np.float64(0.1)". The repr's exponent form ("5e-05", "1e+16") is only how
44
+ Python prints a number under 1e-4 or from 1e16 up: notation, not noise, so it
45
+ is read as the value it is (0.00005) and never refused for its spelling.
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import math
50
+ import numbers
51
+ import re
52
+ from decimal import Decimal, InvalidOperation
53
+
54
+ #: The wire's own limit (money.proto): "at most nine fraction digits".
55
+ MAX_FRACTION_DIGITS = 9
56
+
57
+ #: The engine's decimal parser takes at most 27 digits
58
+ #: before the point; a larger figure is no figure the wire carries.
59
+ MAX_WHOLE_DIGITS = 27
60
+
61
+ #: How far, in units in the last place, a float may sit from its 9-digit
62
+ #: rounding for the difference to count as binary noise (0.1 + 0.2 is one).
63
+ _NOISE_ULPS = 4
64
+
65
+ #: A refused float's plain digits are shown beside its exponent repr only up
66
+ #: to this length ("1e-10 (0.0000000001)"); 5e-324 would be 326 characters.
67
+ _PLAIN_SHOWN_MAX = 30
68
+
69
+ #: What "str (plain decimal text)" means: an optional single leading '-',
70
+ #: then digits, an optional '.', more digits — a leading or trailing '.' is
71
+ #: fine ("...5" is not, ".5" and "5." are), but there must be at least one
72
+ #: digit somewhere. No exponent, no '+', no whitespace inside, no "nan" / "inf".
73
+ _PLAIN_DECIMAL = re.compile(r"^-?(\d+\.\d*|\.\d+|\d+)$")
74
+
75
+
76
+ def _float_hint(x: float) -> "str | None":
77
+ """The value a noisy float probably MEANT, for the refusal message only.
78
+
79
+ Rounding to the wire's own 9-fraction-digit limit collapses binary noise
80
+ like 0.1 + 0.2's trailing ...004 back to the float the author actually
81
+ typed (0.3) — but only when the excess IS noise: the rounded value must
82
+ sit within a few units in the last place of the float. Real digits past
83
+ the ninth (0.1234567891, or 1.5e-9 below the grid) are not noise, and a
84
+ rounded "suggestion" would be a different number, so none is offered;
85
+ nor is one when the rounding reaches zero. Written in plain digits
86
+ ("0.00003", never "3e-05", which a str figure refuses). A HINT, never a
87
+ fallback: the caller still refuses the original value.
88
+ """
89
+ f = float(x)
90
+ try:
91
+ rounded = round(f, MAX_FRACTION_DIGITS)
92
+ except (OverflowError, ValueError):
93
+ return None
94
+ if not math.isfinite(rounded) or rounded == 0:
95
+ return None
96
+ if abs(rounded - f) > _NOISE_ULPS * math.ulp(f):
97
+ return None
98
+ return _normalise(Decimal(float.__repr__(rounded)))
99
+
100
+
101
+ def _fraction_digits(d: Decimal) -> int:
102
+ """How many digits after the point d's VALUE needs. Trailing zeros do
103
+ not count, as the engine's parser does not count them ("1.0000000000"
104
+ is 1). Read off the digit tuple, never by writing the number out, so an
105
+ absurd exponent costs nothing to refuse."""
106
+ if d == 0:
107
+ return 0
108
+ _, digits, exponent = d.as_tuple()
109
+ if exponent >= 0:
110
+ return 0
111
+ trailing = 0
112
+ for digit in reversed(digits):
113
+ if digit != 0:
114
+ break
115
+ trailing += 1
116
+ return max(0, -exponent - trailing)
117
+
118
+
119
+ def _shown(x, d: Decimal) -> str:
120
+ """The refused figure as the author passed it, for the message: a
121
+ float's repr, plus its plain digits when the repr hid them behind an
122
+ exponent and they are short enough to read ("1e-10 (0.0000000001)").
123
+ Only a float's digits are written out; its exponent is bounded."""
124
+ if not isinstance(x, float):
125
+ return str(d)
126
+ text = float.__repr__(x)
127
+ if "e" in text or "E" in text:
128
+ plain = _normalise(d)
129
+ if len(plain) <= _PLAIN_SHOWN_MAX:
130
+ return f"{x!r} ({plain})"
131
+ return repr(x)
132
+
133
+
134
+ def _canon(x, what: str) -> str:
135
+ """One user-supplied figure, as the engine's canonical wire text.
136
+
137
+ Accepts a Decimal, an int (a NumPy integer too), a str of plain decimal
138
+ text, or a float, read by its own shortest repr in whatever notation
139
+ Python prints it (5e-05 is 0.00005). Refuses (ValueError, naming `what` and the value) a bool, NaN,
140
+ an infinity, a str in exponent notation, a value needing more than nine
141
+ fraction digits (trailing zeros do not count: "1.0000000000" is 1) or
142
+ more than 27 whole digits, or any other type — never by rounding: a
143
+ figure this cannot represent exactly is a figure it will not guess at.
144
+ """
145
+ # bool is an int subclass; caught first or `True` would silently become 1.
146
+ if isinstance(x, bool):
147
+ raise ValueError(f"{what} must be a number, not a bool ({x!r})")
148
+
149
+ if isinstance(x, Decimal):
150
+ d = x
151
+ elif isinstance(x, numbers.Integral):
152
+ # Python's int, or a NumPy integer (np.int64 is what a pandas integer
153
+ # column hands a script): a whole number, exact through int(). A bool
154
+ # is Integral too and was refused above; a NumPy bool is not Integral
155
+ # at all, and is refused below as the wrong type.
156
+ d = Decimal(int(x))
157
+ elif isinstance(x, str):
158
+ text = x.strip()
159
+ if not _PLAIN_DECIMAL.match(text):
160
+ raise ValueError(
161
+ f"{what} is not a plain decimal number: {x!r} — no exponent, "
162
+ f"no currency symbol, no thousands separator, at most one "
163
+ f"leading '-'")
164
+ try:
165
+ d = Decimal(text)
166
+ except InvalidOperation:
167
+ raise ValueError(f"{what} is not a valid decimal: {x!r}") from None
168
+ elif isinstance(x, float):
169
+ if not math.isfinite(x):
170
+ raise ValueError(f"{what} must be a finite number, not {x!r}")
171
+ # float.__repr__, not repr(): NumPy 2 prints a float64 (a float) as
172
+ # "np.float64(0.1)". An exponent in the shortest repr ("5e-05") is
173
+ # notation, and Decimal reads it exactly; the digit bounds below judge
174
+ # the value, as they do for every other type.
175
+ d = Decimal(float.__repr__(x))
176
+ else:
177
+ raise ValueError(
178
+ f"{what} must be a Decimal, int, str or float, not "
179
+ f"{type(x).__name__} ({x!r})")
180
+
181
+ if not d.is_finite():
182
+ raise ValueError(f"{what} must be a finite number, not {x!r}")
183
+ # Both bounds are read off the Decimal's digits and exponent, never by
184
+ # writing the number out: Decimal("1E-999999999") is refused at once, not
185
+ # spelled to a billion characters first.
186
+ if d != 0 and d.adjusted() >= MAX_WHOLE_DIGITS:
187
+ raise ValueError(
188
+ f"{what}={_shown(x, d)} has more than {MAX_WHOLE_DIGITS} whole "
189
+ f"digits — larger than any figure the wire carries")
190
+ if _fraction_digits(d) > MAX_FRACTION_DIGITS:
191
+ hint = _float_hint(x) if isinstance(x, float) else None
192
+ suggestion = (f" — pass Decimal({hint!r}) or {hint!r} instead"
193
+ if hint is not None else "")
194
+ raise ValueError(
195
+ f"{what}={_shown(x, d)} has more than {MAX_FRACTION_DIGITS} "
196
+ f"fraction digits{suggestion}")
197
+ return _normalise(d)
198
+
199
+
200
+ def _normalise(d: Decimal) -> str:
201
+ """A finite Decimal as canonical text: no exponent, no trailing zeros or
202
+ trailing dot, "-0" reads as "0"."""
203
+ if d == 0:
204
+ return "0"
205
+ sign = "-" if d < 0 else ""
206
+ text = format(d.copy_abs(), "f") # fixed-point, never an exponent
207
+ if "." in text:
208
+ text = text.rstrip("0").rstrip(".")
209
+ return sign + text
210
+
211
+
212
+ def _dec(text: "str | None"):
213
+ """Wire text as a Decimal, or None for an absent optional figure (an
214
+ empty string is never a zero — it is the proto3 default an unset
215
+ optional/required-in-name-only string field reads back as)."""
216
+ if not text:
217
+ return None
218
+ return Decimal(text)
219
+
220
+
221
+ def _money(m):
222
+ """A wire Money submessage as a while25.Money, or None when there is
223
+ none. Money carries no presence of its own — `optional Money` presence
224
+ lives on the field that holds it — so the call site resolves that first:
225
+ `_money(resp.day_pnl if resp.HasField("day_pnl") else None)`.
226
+ A Money whose value is empty is no figure either: it is what an unset
227
+ submessage reads back as, never a zero, and Decimal("") would raise and
228
+ take the whole call that carried it (portfolio(), say) down with it.
229
+ """
230
+ if m is None or not m.value:
231
+ return None
232
+ from .money import Money
233
+ return Money(Decimal(m.value), m.currency)
while25/_runtime.py ADDED
@@ -0,0 +1,49 @@
1
+ """The module context behind the package-level API.
2
+
3
+ `while25.log(...)`, `while25.subscribe(...)`, `while25.orders.buy(...)` all act
4
+ on the module that is running. Each module runs in its own worker process,
5
+ so "the module that is running" is one object per process — installed by the
6
+ worker when the module starts. An indicator computed in-process for a caller
7
+ (`while25.indicator(cls)`) gets its own view for the duration of that call,
8
+ on the calling thread only, so a schedule firing on another thread keeps
9
+ seeing the module's own context.
10
+
11
+ Tests bind a fake with `use(ctx)`; user code never touches this module.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import threading
16
+ from contextlib import contextmanager
17
+ from typing import Any, Iterator
18
+
19
+ _process_ctx: Any = None
20
+ _thread = threading.local()
21
+
22
+
23
+ def bind(ctx: Any) -> None:
24
+ """Install the module's context for this process (the worker does this)."""
25
+ global _process_ctx
26
+ _process_ctx = ctx
27
+
28
+
29
+ def current() -> Any:
30
+ ctx = getattr(_thread, "override", None)
31
+ if ctx is None:
32
+ ctx = _process_ctx
33
+ if ctx is None:
34
+ raise RuntimeError(
35
+ "while25.* called outside a running module. The package-level API acts on "
36
+ "the module the terminal is running; in a test, wrap the call in "
37
+ "`with while25.use(fake_ctx):`.")
38
+ return ctx
39
+
40
+
41
+ @contextmanager
42
+ def use(ctx: Any) -> Iterator[Any]:
43
+ """Make `ctx` the current context on THIS thread for the block."""
44
+ prev = getattr(_thread, "override", None)
45
+ _thread.override = ctx
46
+ try:
47
+ yield ctx
48
+ finally:
49
+ _thread.override = prev
@@ -0,0 +1,80 @@
1
+ {
2
+ "index": "banknifty",
3
+ "name": "NIFTY BANK",
4
+ "country": "IN",
5
+ "as_of": "2026-09-11",
6
+ "source": "https://archives.nseindia.com/content/indices/ind_niftybanklist.csv",
7
+ "count": 14,
8
+ "rows": [
9
+ {
10
+ "symbol": "AUBANK",
11
+ "name": "AU Small Finance Bank Ltd.",
12
+ "canonical_id": "EQ:IN:AUBANK"
13
+ },
14
+ {
15
+ "symbol": "AXISBANK",
16
+ "name": "Axis Bank Ltd.",
17
+ "canonical_id": "EQ:IN:AXISBANK"
18
+ },
19
+ {
20
+ "symbol": "BANKBARODA",
21
+ "name": "Bank of Baroda",
22
+ "canonical_id": "EQ:IN:BANKBARODA"
23
+ },
24
+ {
25
+ "symbol": "CANBK",
26
+ "name": "Canara Bank",
27
+ "canonical_id": "EQ:IN:CANBK"
28
+ },
29
+ {
30
+ "symbol": "FEDERALBNK",
31
+ "name": "Federal Bank Ltd.",
32
+ "canonical_id": "EQ:IN:FEDERALBNK"
33
+ },
34
+ {
35
+ "symbol": "HDFCBANK",
36
+ "name": "HDFC Bank Ltd.",
37
+ "canonical_id": "EQ:IN:HDFCBANK"
38
+ },
39
+ {
40
+ "symbol": "ICICIBANK",
41
+ "name": "ICICI Bank Ltd.",
42
+ "canonical_id": "EQ:IN:ICICIBANK"
43
+ },
44
+ {
45
+ "symbol": "IDFCFIRSTB",
46
+ "name": "IDFC First Bank Ltd.",
47
+ "canonical_id": "EQ:IN:IDFCFIRSTB"
48
+ },
49
+ {
50
+ "symbol": "INDUSINDBK",
51
+ "name": "IndusInd Bank Ltd.",
52
+ "canonical_id": "EQ:IN:INDUSINDBK"
53
+ },
54
+ {
55
+ "symbol": "KOTAKBANK",
56
+ "name": "Kotak Mahindra Bank Ltd.",
57
+ "canonical_id": "EQ:IN:KOTAKBANK"
58
+ },
59
+ {
60
+ "symbol": "PNB",
61
+ "name": "Punjab National Bank",
62
+ "canonical_id": "EQ:IN:PNB"
63
+ },
64
+ {
65
+ "symbol": "SBIN",
66
+ "name": "State Bank of India",
67
+ "canonical_id": "EQ:IN:SBIN"
68
+ },
69
+ {
70
+ "symbol": "UNIONBANK",
71
+ "name": "Union Bank of India",
72
+ "canonical_id": "EQ:IN:UNIONBANK"
73
+ },
74
+ {
75
+ "symbol": "YESBANK",
76
+ "name": "Yes Bank Ltd.",
77
+ "canonical_id": "EQ:IN:YESBANK"
78
+ }
79
+ ]
80
+ }