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.
- while25/__init__.py +341 -0
- while25/_costs/brokers/alpaca.json +96 -0
- while25/_costs/brokers/binance.json +34 -0
- while25/_costs/brokers/coinbase.json +34 -0
- while25/_costs/brokers/ibkr.json +39 -0
- while25/_costs/brokers/upstox.json +175 -0
- while25/_costs/brokers/zerodha.json +175 -0
- while25/_costs/crypto_alpaca.json +27 -0
- while25/_costs/global_crypto.json +18 -0
- while25/_costs/in_nse_equity.json +238 -0
- while25/_costs/in_nse_etf.json +352 -0
- while25/_costs/in_nse_fo.json +450 -0
- while25/_costs/us_crypto.json +18 -0
- while25/_costs/us_equity.json +175 -0
- while25/_costs/us_options.json +172 -0
- while25/_days.py +123 -0
- while25/_figures.py +233 -0
- while25/_runtime.py +49 -0
- while25/_universes/banknifty.json +80 -0
- while25/_universes/ndx100.json +520 -0
- while25/_universes/nifty50.json +260 -0
- while25/_universes/nifty500.json +2505 -0
- while25/_universes/sp500.json +2525 -0
- while25/assume.py +263 -0
- while25/backtest.py +881 -0
- while25/barline.py +160 -0
- while25/combo_legs.py +238 -0
- while25/errors.py +77 -0
- while25/fonts/IBMPlexMono-Regular.ttf +0 -0
- while25/fonts/IBMPlexMono-SemiBold.ttf +0 -0
- while25/fonts/Inter-Bold.ttf +0 -0
- while25/fonts/Inter-Regular.ttf +0 -0
- while25/fonts/Inter-SemiBold.ttf +0 -0
- while25/fonts/OFL-IBMPlexMono.txt +93 -0
- while25/fonts/OFL-Inter.txt +93 -0
- while25/future_pick.py +77 -0
- while25/inputs.py +215 -0
- while25/instruments.py +488 -0
- while25/modules.py +397 -0
- while25/money.py +24 -0
- while25/option_pick.py +221 -0
- while25/plots.py +147 -0
- while25/report.py +644 -0
- while25/ui.py +680 -0
- while25/universes.py +70 -0
- while25-0.1.0.dist-info/METADATA +3194 -0
- while25-0.1.0.dist-info/RECORD +50 -0
- while25-0.1.0.dist-info/WHEEL +5 -0
- while25-0.1.0.dist-info/licenses/LICENSE +201 -0
- while25-0.1.0.dist-info/top_level.txt +1 -0
while25/modules.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Module base classes and the subscription decorators.
|
|
2
|
+
|
|
3
|
+
A strategy IS a class, so it is declared as one: typed contracts, IDE
|
|
4
|
+
completion, real inheritance for shared logic, and metadata visible as class
|
|
5
|
+
attributes rather than hidden in a dict.
|
|
6
|
+
|
|
7
|
+
Kinds differ ONLY in what they may emit and how the terminal presents them.
|
|
8
|
+
They do NOT differ in what wakes them — that is declared per-module, and market
|
|
9
|
+
data is one source among several rather than a requirement.
|
|
10
|
+
"""
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any, Callable
|
|
13
|
+
|
|
14
|
+
from .barline import Bars, bar_args
|
|
15
|
+
from .inputs import InputSpec
|
|
16
|
+
|
|
17
|
+
_SUBS_ATTR = "__while25_subs__"
|
|
18
|
+
#: The handler a `Bars` line is subscribed under: Module._w25_bars, which does
|
|
19
|
+
#: nothing. The runtime adds the bar to the line before any handler runs.
|
|
20
|
+
BARS_HANDLER = "_w25_bars"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Subscription:
|
|
25
|
+
source: str # bar|tick|schedule|signal|order|fill|position
|
|
26
|
+
args: dict = field(default_factory=dict)
|
|
27
|
+
handler: str = "" # method name on the class
|
|
28
|
+
#: The `Bars` line an `@on.bar(line)` handler was tagged with. The class's
|
|
29
|
+
#: CURRENT line of that name decides the symbol and interval
|
|
30
|
+
#: (Module.subscriptions), so it is no part of what is declared or sent.
|
|
31
|
+
line: Any = field(default=None, repr=False, compare=False)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _attach(source: str, _line: Any = None, **args) -> Callable:
|
|
35
|
+
def deco(fn: Callable) -> Callable:
|
|
36
|
+
subs = list(getattr(fn, _SUBS_ATTR, []))
|
|
37
|
+
subs.append(Subscription(source=source, args=args, handler=fn.__name__, line=_line))
|
|
38
|
+
setattr(fn, _SUBS_ATTR, subs)
|
|
39
|
+
return fn
|
|
40
|
+
return deco
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _required(fn: Callable) -> Callable:
|
|
44
|
+
"""Marks a method every module of a kind must write itself: the base's
|
|
45
|
+
version is a placeholder, and a class still holding it is refused when its
|
|
46
|
+
file is saved (Module.missing)."""
|
|
47
|
+
fn.__w25_required__ = True
|
|
48
|
+
return fn
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class on:
|
|
52
|
+
"""Subscription decorators. A module declares what wakes it; the runtime
|
|
53
|
+
delivers. `signal` is the extension point — a new source is a publisher,
|
|
54
|
+
not an SDK revision."""
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def bar(symbol, interval: "str | None" = None, *, hours: "str | None" = None) -> Callable:
|
|
58
|
+
"""Wake on each closed bar of `symbol` at `interval`, or of a `Bars`
|
|
59
|
+
line declared on the class: `@on.bar(tsla)`. A handler on a line
|
|
60
|
+
follows the LINE: a subclass that declares `tsla` again, on another
|
|
61
|
+
symbol or interval, moves the handler with it.
|
|
62
|
+
|
|
63
|
+
`hours` — the session the bars come from, in the word an order uses:
|
|
64
|
+
left out = the venue's regular session, for every instrument (futures
|
|
65
|
+
included); "eth" = the full session, pre and post market included.
|
|
66
|
+
"rth" is not a choice: leave hours out for regular hours. A regular
|
|
67
|
+
and an "eth" subscription on one symbol and interval are two series,
|
|
68
|
+
each delivered only to its own subscribers."""
|
|
69
|
+
if isinstance(symbol, Bars):
|
|
70
|
+
# The line says its own interval and session.
|
|
71
|
+
if interval is not None or hours:
|
|
72
|
+
raise TypeError("@on.bar(line): a Bars line already says its interval "
|
|
73
|
+
"and hours")
|
|
74
|
+
return _attach("bar", _line=symbol, **dict(symbol.args))
|
|
75
|
+
if interval is None:
|
|
76
|
+
raise TypeError("@on.bar(symbol, interval): the interval is missing")
|
|
77
|
+
return _attach("bar", **bar_args(symbol, interval, hours))
|
|
78
|
+
|
|
79
|
+
@staticmethod
|
|
80
|
+
def tick(symbol: str) -> Callable:
|
|
81
|
+
return _attach("tick", symbol=symbol)
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def news(symbol: str) -> Callable:
|
|
85
|
+
"""Wake on a live news article for `symbol`. The handler receives the
|
|
86
|
+
article as a plain dict (CompanyNewsData fields; absent fields are
|
|
87
|
+
absent keys). Requires a news provider on the engine — without one the
|
|
88
|
+
subscription is accepted and simply never fires."""
|
|
89
|
+
return _attach("news", symbol=symbol)
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def schedule(cron: str = "", *, every: str = "", tz: str = "") -> Callable:
|
|
93
|
+
return _attach("schedule", cron=cron, every=every, tz=tz)
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def signal(name: str, *, sender=None, **filters) -> Callable:
|
|
97
|
+
"""Wake on another module's `while25.emit(name, payload)`.
|
|
98
|
+
|
|
99
|
+
`sender` names the ONE module this handler listens to: its class
|
|
100
|
+
(`sender=DipWatch`) or its id. A signal of that name from any other
|
|
101
|
+
module does not reach it. Left out, the name alone decides, among the
|
|
102
|
+
senders the runtime lets through (see `while25.emit` in the guide)."""
|
|
103
|
+
args = {"name": name, "filters": filters}
|
|
104
|
+
if sender is not None:
|
|
105
|
+
sid = sender if isinstance(sender, str) else getattr(sender, "id", "")
|
|
106
|
+
if not isinstance(sid, str) or not sid.strip():
|
|
107
|
+
raise TypeError("@on.signal(sender=): a module's class, or its id")
|
|
108
|
+
args["sender"] = sid.strip()
|
|
109
|
+
return _attach("signal", **args)
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def order(**filters) -> Callable:
|
|
113
|
+
return _attach("order", filters=filters)
|
|
114
|
+
|
|
115
|
+
@staticmethod
|
|
116
|
+
def fill(**filters) -> Callable:
|
|
117
|
+
return _attach("fill", filters=filters)
|
|
118
|
+
|
|
119
|
+
@staticmethod
|
|
120
|
+
def position(**filters) -> Callable:
|
|
121
|
+
return _attach("position", filters=filters)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class Module:
|
|
125
|
+
"""Shared base. `kind` is set by each concrete base below."""
|
|
126
|
+
|
|
127
|
+
id: str = ""
|
|
128
|
+
label: str = ""
|
|
129
|
+
version: str = "0.0.0"
|
|
130
|
+
inputs: list[InputSpec] = []
|
|
131
|
+
kind: str = "module"
|
|
132
|
+
#: The monitors that are PART of a module that trades (2026-11-14): its
|
|
133
|
+
#: classes, `monitors = [DipWatch]`. Each starts when the module is
|
|
134
|
+
#: deployed and stops when it stops, and among the modules that trade its
|
|
135
|
+
#: signals reach this one alone. Said HERE, on the class, and not by which
|
|
136
|
+
#: file a Monitor happens to sit in: moving a class to another file
|
|
137
|
+
#: changes nothing, and a Monitor nobody lists is nobody's part. Only a
|
|
138
|
+
#: Strategy, or an App that trades, may list any.
|
|
139
|
+
monitors: list = []
|
|
140
|
+
|
|
141
|
+
# Lifecycle — run and stop, and nothing else (S18: no resume).
|
|
142
|
+
def on_start(self, ctx: Any) -> None: ...
|
|
143
|
+
|
|
144
|
+
def _w25_bars(self, ctx: Any, bar: dict) -> None:
|
|
145
|
+
"""What a `Bars` line is subscribed under (BARS_HANDLER). Nothing to
|
|
146
|
+
do here: the runtime has already added the bar to the line."""
|
|
147
|
+
|
|
148
|
+
def on_stop(self, ctx: Any) -> None:
|
|
149
|
+
"""Runs once when the module is stopped (2026-10-17): by its Stop, a
|
|
150
|
+
stop on its panel, a restart of its code, or the app closing
|
|
151
|
+
(the terminal ends the runtime the clean way). A crash or a
|
|
152
|
+
kill of the process runs none of it.
|
|
153
|
+
|
|
154
|
+
Handlers still waiting to run when the stop came are skipped, and
|
|
155
|
+
`while25.alive()` reads False from that moment. on_stop then has TWO
|
|
156
|
+
SECONDS before the process is ended, finished or not. It cannot trade: every order call (buy, sell, place,
|
|
157
|
+
bracket, cancel, modify) raises While25Error with code
|
|
158
|
+
MODULE_STOPPING, and is not to be retried — the trader's Stop decides
|
|
159
|
+
what happens to the module's orders. It may log, save its own files
|
|
160
|
+
and read what the module holds (`while25.portfolio.my_positions()`,
|
|
161
|
+
`while25.orders.mine()`). A raise in it is logged; it halts
|
|
162
|
+
nothing."""
|
|
163
|
+
|
|
164
|
+
@classmethod
|
|
165
|
+
def missing(cls) -> list:
|
|
166
|
+
"""The methods this module's kind requires that the class has not
|
|
167
|
+
written: it still holds the base's placeholder (`_required`). Empty
|
|
168
|
+
for a class that may be registered. Read from the classes' own
|
|
169
|
+
attributes, so no property or descriptor of the module is run."""
|
|
170
|
+
absent, seen = [], set()
|
|
171
|
+
for klass in cls.__mro__:
|
|
172
|
+
for name, attr in vars(klass).items():
|
|
173
|
+
if name in seen:
|
|
174
|
+
continue # a class nearer the module already decided it
|
|
175
|
+
seen.add(name)
|
|
176
|
+
if getattr(attr, "__w25_required__", False):
|
|
177
|
+
absent.append(name)
|
|
178
|
+
return sorted(absent)
|
|
179
|
+
|
|
180
|
+
@classmethod
|
|
181
|
+
def bar_lines(cls) -> list:
|
|
182
|
+
"""Every `Bars` line declared on this class and its bases, as
|
|
183
|
+
(attribute name, declaration), in definition order. A subclass that
|
|
184
|
+
declares the same name again replaces the base's line; one that puts
|
|
185
|
+
anything else under that name takes the line away."""
|
|
186
|
+
found: dict = {}
|
|
187
|
+
for klass in reversed(cls.__mro__):
|
|
188
|
+
for name, attr in vars(klass).items():
|
|
189
|
+
if isinstance(attr, Bars):
|
|
190
|
+
found.pop(name, None) # re-declared: its place is the subclass's
|
|
191
|
+
found[name] = attr
|
|
192
|
+
elif name in found:
|
|
193
|
+
del found[name]
|
|
194
|
+
return list(found.items())
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
def subscriptions(cls) -> list[Subscription]:
|
|
198
|
+
"""Every subscription declared on this class and its bases: its `Bars`
|
|
199
|
+
lines first, then its handlers in definition order. Discoverable
|
|
200
|
+
WITHOUT instantiating, so registration can validate a module before
|
|
201
|
+
its __init__ ever runs.
|
|
202
|
+
|
|
203
|
+
A SUBCLASS OVERRIDES BY NAME (2026-11-14). A method a subclass tags
|
|
204
|
+
again REPLACES what its bases declared for that method; one it
|
|
205
|
+
overrides without a tag keeps the base's declaration and is the
|
|
206
|
+
method that gets called. Before, both declarations were kept, and a
|
|
207
|
+
strategy that inherited from another and tagged its override was
|
|
208
|
+
called twice for every bar: two orders. Nothing is ever declared
|
|
209
|
+
twice: the same source, arguments and handler count once.
|
|
210
|
+
|
|
211
|
+
A HANDLER ON A LINE FOLLOWS THE LINE. `@on.bar(tsla)` means "the bars
|
|
212
|
+
of the line this class calls `tsla`", so a subclass that declares
|
|
213
|
+
`tsla` again moves the handler to its symbol and interval (_on_line)."""
|
|
214
|
+
by_handler: dict[str, list] = {}
|
|
215
|
+
for klass in reversed(cls.__mro__):
|
|
216
|
+
taken: set[int] = set()
|
|
217
|
+
for _name, attr in vars(klass).items():
|
|
218
|
+
subs = getattr(attr, _SUBS_ATTR, None)
|
|
219
|
+
if not subs or id(attr) in taken:
|
|
220
|
+
continue # untagged, or the same function under a second name
|
|
221
|
+
taken.add(id(attr))
|
|
222
|
+
handler = subs[0].handler
|
|
223
|
+
by_handler.pop(handler, None) # this class's word for the method stands
|
|
224
|
+
by_handler[handler] = list(subs)
|
|
225
|
+
lines = dict(cls.bar_lines())
|
|
226
|
+
found: list[Subscription] = [
|
|
227
|
+
Subscription(source="bar", args=dict(line.args), handler=BARS_HANDLER)
|
|
228
|
+
for line in lines.values()]
|
|
229
|
+
for subs in by_handler.values():
|
|
230
|
+
found.extend(sub if sub.line is None else cls._on_line(sub, lines) for sub in subs)
|
|
231
|
+
once: list[Subscription] = []
|
|
232
|
+
seen: set[str] = set()
|
|
233
|
+
for sub in found:
|
|
234
|
+
mark = repr((sub.source, sorted(sub.args.items(), key=lambda kv: kv[0]), sub.handler))
|
|
235
|
+
if mark not in seen:
|
|
236
|
+
seen.add(mark)
|
|
237
|
+
once.append(sub)
|
|
238
|
+
return once
|
|
239
|
+
|
|
240
|
+
@classmethod
|
|
241
|
+
def _on_line(cls, sub: Subscription, lines: dict) -> Subscription:
|
|
242
|
+
"""An `@on.bar(line)` handler's subscription as THIS class declares
|
|
243
|
+
the line (`lines`: its bar lines by name). The line the class holds
|
|
244
|
+
under that name now decides, which is the one `self.<name>` reads. A
|
|
245
|
+
class that took the line away while a handler is still on it is a
|
|
246
|
+
declaration error, said when its file is saved. A line that is not an
|
|
247
|
+
attribute of the class at all (written inline, or another class's) is
|
|
248
|
+
only a way of writing its symbol and interval."""
|
|
249
|
+
name = getattr(sub.line, "_name", "")
|
|
250
|
+
current = lines.get(name) if name else None
|
|
251
|
+
if current is None:
|
|
252
|
+
if name and any(vars(k).get(name) is sub.line for k in cls.__mro__):
|
|
253
|
+
raise TypeError(
|
|
254
|
+
f"{cls.__name__}.{sub.handler} is on the bar line `{name}`, which "
|
|
255
|
+
f"{cls.__name__} no longer declares. Declare the line, or give "
|
|
256
|
+
f"{sub.handler} its own @on.bar.")
|
|
257
|
+
return Subscription(source="bar", args=dict(sub.args), handler=sub.handler)
|
|
258
|
+
return Subscription(source="bar", args=dict(current.args), handler=sub.handler)
|
|
259
|
+
|
|
260
|
+
@classmethod
|
|
261
|
+
def has_run(cls) -> bool:
|
|
262
|
+
"""True when the module defines the run() escape hatch itself — the
|
|
263
|
+
base does not, so a bare subclass does not inherit invocability."""
|
|
264
|
+
return any("run" in vars(k) for k in cls.__mro__)
|
|
265
|
+
|
|
266
|
+
@classmethod
|
|
267
|
+
def has_on_start(cls) -> bool:
|
|
268
|
+
"""True when the module defines on_start itself.
|
|
269
|
+
|
|
270
|
+
on_start IS an entry point — it is the one the runtime has always
|
|
271
|
+
called. The base declares it as a no-op, so `in vars(k)` and not
|
|
272
|
+
hasattr: a subclass that never wrote one has nothing to invoke."""
|
|
273
|
+
return any("on_start" in vars(k) for k in cls.__mro__ if k is not Module)
|
|
274
|
+
|
|
275
|
+
@classmethod
|
|
276
|
+
def describe_inputs(cls) -> list[dict]:
|
|
277
|
+
return [i.describe() for i in cls.inputs]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class Strategy(Module):
|
|
281
|
+
"""May place orders, behind the human deploy-confirm.
|
|
282
|
+
|
|
283
|
+
THE STRATEGY IS WHAT IS DEPLOYED (2026-11-14). What belongs to it is said
|
|
284
|
+
on its class, and each part runs as its own kind with only its own rights:
|
|
285
|
+
`monitors = [AiGate]` watch and may ask the AI; `desk = BtcDesk` is its
|
|
286
|
+
panel, an App that shows and never trades. Deploying the strategy starts
|
|
287
|
+
them with it and opens the desk's panel; stopping it stops them."""
|
|
288
|
+
kind = "strategy"
|
|
289
|
+
#: Its panel: an App class. Its `ui.strategy_block()` shows this strategy,
|
|
290
|
+
#: and what it emits reaches this strategy (its buttons) when it was
|
|
291
|
+
#: started with it.
|
|
292
|
+
desk = None
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class Indicator(Module):
|
|
296
|
+
"""Produces one or more named series for the chart.
|
|
297
|
+
|
|
298
|
+
ONE indicator, ONE label, N lines. Declare the shape as class attributes and
|
|
299
|
+
return a dict of series from `compute()`:
|
|
300
|
+
|
|
301
|
+
class MyBollinger(Indicator):
|
|
302
|
+
id = "my_bb"
|
|
303
|
+
label = "My Bollinger"
|
|
304
|
+
overlay = True
|
|
305
|
+
inputs = [Int("length", default=20, minimum=2, maximum=500),
|
|
306
|
+
Float("mult", default=2.0, step=0.1)]
|
|
307
|
+
plots = [Plot("basis", color="#e0a34a"),
|
|
308
|
+
Plot("upper", color="#4aa3e0", style="dashed"),
|
|
309
|
+
Plot("lower", color="#4aa3e0", style="dashed")]
|
|
310
|
+
fills = [Fill("upper", "lower", color="#4aa3e0", opacity=0.08)]
|
|
311
|
+
|
|
312
|
+
def compute(self, ctx):
|
|
313
|
+
n = ctx.params["length"]
|
|
314
|
+
...
|
|
315
|
+
return {"basis": basis, "upper": up, "lower": lo}
|
|
316
|
+
|
|
317
|
+
Declared rather than drawn: the author says what the shape IS and While25
|
|
318
|
+
renders it, which is what stops a plugin breaking the chart's look or its
|
|
319
|
+
rendering performance. Every colour, width and line style declared here is
|
|
320
|
+
a DEFAULT — the user can override any of them in the chart's settings
|
|
321
|
+
dialog, exactly as for a built-in indicator.
|
|
322
|
+
"""
|
|
323
|
+
kind = "indicator"
|
|
324
|
+
|
|
325
|
+
# Appearance. Empty `plots` means the indicator has not declared its shape,
|
|
326
|
+
# which register-time validation refuses rather than drawing nothing.
|
|
327
|
+
plots: list = []
|
|
328
|
+
fills: list = []
|
|
329
|
+
levels: list = []
|
|
330
|
+
bands: list = []
|
|
331
|
+
overlay: bool = True
|
|
332
|
+
# Recompute as the bar FORMS, not only when it closes.
|
|
333
|
+
#
|
|
334
|
+
# The chart drives this from the candle it is already drawing, so it costs
|
|
335
|
+
# no subscription and lands on the chart that asked. Off by default: a full
|
|
336
|
+
# recompute per tick is real work, and most indicators say all they have to
|
|
337
|
+
# say once a bar is final.
|
|
338
|
+
intrabar: bool = False
|
|
339
|
+
y_min: float | None = None
|
|
340
|
+
y_max: float | None = None
|
|
341
|
+
precision: int | None = None
|
|
342
|
+
|
|
343
|
+
@_required
|
|
344
|
+
def compute(self, ctx):
|
|
345
|
+
"""Return {plot name: values} for the bars in `while25.bars`.
|
|
346
|
+
|
|
347
|
+
The one method every indicator must write itself. A class that leaves
|
|
348
|
+
it out is refused when its file is saved (Module.missing), where it
|
|
349
|
+
used to register, sit in the chart's list and fail on the first chart
|
|
350
|
+
that asked it for a line."""
|
|
351
|
+
raise NotImplementedError(
|
|
352
|
+
f"{type(self).__name__} has no compute(self, ctx): an indicator returns "
|
|
353
|
+
f"its plots from it")
|
|
354
|
+
|
|
355
|
+
@classmethod
|
|
356
|
+
def describe_style(cls) -> dict:
|
|
357
|
+
"""The declaration, flattened for the wire.
|
|
358
|
+
|
|
359
|
+
Serialized in the CHILD, because the parent never sees the class.
|
|
360
|
+
"""
|
|
361
|
+
return {
|
|
362
|
+
"plots": [{
|
|
363
|
+
"name": p.name, "color": p.color, "width": p.width,
|
|
364
|
+
"style": p.style, "plot_type": p.plot_type,
|
|
365
|
+
"color_down": p.color_down, "opacity": p.opacity,
|
|
366
|
+
"overlay": cls.overlay if p.overlay is None else p.overlay,
|
|
367
|
+
"visible": p.visible,
|
|
368
|
+
} for p in cls.plots],
|
|
369
|
+
"fills": [{"upper": f.upper, "lower": f.lower,
|
|
370
|
+
"color": f.color, "opacity": f.opacity}
|
|
371
|
+
for f in cls.fills],
|
|
372
|
+
"levels": [{"value": l.value, "color": l.color,
|
|
373
|
+
"width": l.width, "style": l.style}
|
|
374
|
+
for l in cls.levels],
|
|
375
|
+
"bands": [{"top": b.top, "bottom": b.bottom,
|
|
376
|
+
"color": b.color, "opacity": b.opacity}
|
|
377
|
+
for b in cls.bands],
|
|
378
|
+
"overlay": cls.overlay,
|
|
379
|
+
"y_min": cls.y_min,
|
|
380
|
+
"y_max": cls.y_max,
|
|
381
|
+
"precision": cls.precision,
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
@classmethod
|
|
385
|
+
def validate_style(cls) -> None:
|
|
386
|
+
from .plots import validate
|
|
387
|
+
validate(cls.plots, cls.fills, cls.levels, cls.bands)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
class Monitor(Module):
|
|
391
|
+
"""Produces verdicts / notifications. Cannot obtain order rights."""
|
|
392
|
+
kind = "monitor"
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class App(Module):
|
|
396
|
+
"""Drives a custom panel."""
|
|
397
|
+
kind = "app"
|
while25/money.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""An exact amount, in a currency.
|
|
2
|
+
|
|
3
|
+
Wire Money (money.proto) is a canonical decimal string plus a currency code.
|
|
4
|
+
This is the SDK's own view of it: a Decimal so arithmetic is exact, frozen so
|
|
5
|
+
a strategy cannot mutate a figure it read off a position. Nothing here adds
|
|
6
|
+
two Money values in different currencies by assumption — the runtime's
|
|
7
|
+
position() combiner is the one place that has to decide what
|
|
8
|
+
"cannot honestly be summed" means.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from decimal import Decimal
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Money:
|
|
18
|
+
"""value is exact; currency is the ISO or venue code it is stated in
|
|
19
|
+
("INR", "USD", "USDT", "BTC")."""
|
|
20
|
+
value: Decimal
|
|
21
|
+
currency: str
|
|
22
|
+
|
|
23
|
+
def __str__(self) -> str: # "1234.5 USD"
|
|
24
|
+
return f"{self.value} {self.currency}"
|
while25/option_pick.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Turning a description of an option into one listed contract (2026-10-24).
|
|
2
|
+
|
|
3
|
+
The pure half of `while25.option()`: reading what the author wrote ("26th",
|
|
4
|
+
"ATM+2", "CE"), and choosing the expiry and the strike from the lists the
|
|
5
|
+
terminal answers with. Nothing here talks to the terminal, so the rules are
|
|
6
|
+
tested on their own — and they are the Options Builder's:
|
|
7
|
+
|
|
8
|
+
- ATM is the listed strike nearest the money, a tie going to the HIGHER strike
|
|
9
|
+
(the same rule the app and the engine use).
|
|
10
|
+
- ATM+N is N strikes HIGHER and ATM-N is N strikes LOWER, for calls and puts
|
|
11
|
+
alike (the app's strikeIndexAtOffset). A step is one listed strike, not a
|
|
12
|
+
fixed price distance: a list can step 50 near the money and 100 further out.
|
|
13
|
+
- A money beyond the listed strikes is no ATM at all — the end strike is not
|
|
14
|
+
the money just because it is the nearest one listed.
|
|
15
|
+
|
|
16
|
+
Malformed input raises ValueError (the author's mistake, nothing was asked);
|
|
17
|
+
a lookup that cannot be answered raises While25Error with a code.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import calendar
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from datetime import date, datetime
|
|
25
|
+
from decimal import Decimal, InvalidOperation
|
|
26
|
+
|
|
27
|
+
from .errors import While25Error
|
|
28
|
+
|
|
29
|
+
# What a call or a put may be written as: the words, the letters, and the
|
|
30
|
+
# Indian venues' CE / PE.
|
|
31
|
+
_RIGHTS = {"CALL": "C", "C": "C", "CE": "C", "PUT": "P", "P": "P", "PE": "P"}
|
|
32
|
+
|
|
33
|
+
_ATM = re.compile(r"^ATM(?:([+-])(\d+))?$")
|
|
34
|
+
_DAY = re.compile(r"^(\d{1,2})(?:ST|ND|RD|TH)?$")
|
|
35
|
+
_ISO = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
|
|
36
|
+
_COMPACT = re.compile(r"^(\d{4})(\d{2})(\d{2})$")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_right(right) -> str:
|
|
40
|
+
"""'C' or 'P'. CALL / PUT, C / P, CE / PE, in any capitals."""
|
|
41
|
+
letter = _RIGHTS.get(str(right or "").strip().upper())
|
|
42
|
+
if letter is None:
|
|
43
|
+
raise ValueError(f"right must be CALL or PUT (C / P, CE / PE), not {right!r}")
|
|
44
|
+
return letter
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class StrikeSpec:
|
|
49
|
+
"""A listed strike by its price, or a count of strikes from the money."""
|
|
50
|
+
price: "Decimal | None" = None
|
|
51
|
+
offset: "int | None" = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse_strike(strike) -> StrikeSpec:
|
|
55
|
+
""""ATM", "ATM+2", "ATM-2" (spaces and capitals as you like), or a price —
|
|
56
|
+
a number or plain decimal text ("5000", 152.5, Decimal("24500"))."""
|
|
57
|
+
if isinstance(strike, bool):
|
|
58
|
+
raise ValueError(f"strike must be a price or ATM / ATM+N / ATM-N, not {strike!r}")
|
|
59
|
+
if isinstance(strike, str):
|
|
60
|
+
text = strike.replace(" ", "").upper()
|
|
61
|
+
m = _ATM.match(text)
|
|
62
|
+
if m:
|
|
63
|
+
n = int(m.group(2) or 0)
|
|
64
|
+
return StrikeSpec(offset=-n if m.group(1) == "-" else n)
|
|
65
|
+
try:
|
|
66
|
+
price = Decimal(text)
|
|
67
|
+
except InvalidOperation:
|
|
68
|
+
raise ValueError(
|
|
69
|
+
f"strike must be a price or ATM / ATM+N / ATM-N, not {strike!r}") from None
|
|
70
|
+
elif isinstance(strike, (int, Decimal)):
|
|
71
|
+
price = Decimal(strike)
|
|
72
|
+
elif isinstance(strike, float):
|
|
73
|
+
price = Decimal(repr(strike)) # its shortest form: 152.5, not 152.4999...
|
|
74
|
+
else:
|
|
75
|
+
raise ValueError(f"strike must be a price or ATM / ATM+N / ATM-N, not {strike!r}")
|
|
76
|
+
if not price.is_finite() or price <= 0:
|
|
77
|
+
raise ValueError(f"a strike must be a price above 0, not {strike!r}")
|
|
78
|
+
return StrikeSpec(price=price)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def parse_settlement(settlement) -> str:
|
|
82
|
+
"""'pm' (the default: settles at the close) or 'am' (settles on the
|
|
83
|
+
morning's opening prices — SPX monthlies)."""
|
|
84
|
+
if settlement is None or str(settlement).strip() == "":
|
|
85
|
+
return "pm"
|
|
86
|
+
word = str(settlement).strip().lower()
|
|
87
|
+
if word not in ("am", "pm"):
|
|
88
|
+
raise ValueError(f'settlement must be "am" or "pm", not {settlement!r}')
|
|
89
|
+
return word
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def parse_atm_from(atm_from) -> str:
|
|
93
|
+
"""'options' (the default — the forward the option prices place, as the
|
|
94
|
+
Options Builder centres on) or 'spot' (the underlying's own price, as the
|
|
95
|
+
Option Chain panel marks by default)."""
|
|
96
|
+
if atm_from is None or str(atm_from).strip() == "":
|
|
97
|
+
return "options"
|
|
98
|
+
word = str(atm_from).strip().lower()
|
|
99
|
+
if word not in ("options", "spot"):
|
|
100
|
+
raise ValueError(f'atm_from must be "options" or "spot", not {atm_from!r}')
|
|
101
|
+
return word
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def next_day_of_month(day: int, today: date) -> date:
|
|
105
|
+
"""The next calendar date on or after `today` whose day of the month is
|
|
106
|
+
`day` — a month without that day (the 31st in a 30-day month) is passed."""
|
|
107
|
+
if not 1 <= day <= 31:
|
|
108
|
+
raise ValueError(f"a day of the month is 1 to 31, not {day}")
|
|
109
|
+
year, month = today.year, today.month
|
|
110
|
+
for _ in range(13):
|
|
111
|
+
if day <= calendar.monthrange(year, month)[1]:
|
|
112
|
+
candidate = date(year, month, day)
|
|
113
|
+
if candidate >= today:
|
|
114
|
+
return candidate
|
|
115
|
+
month += 1
|
|
116
|
+
if month > 12:
|
|
117
|
+
month, year = 1, year + 1
|
|
118
|
+
raise ValueError(f"no date falls on day {day}") # unreachable: every year has a 31st
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def target_date(expiry, today: date) -> date:
|
|
122
|
+
"""The date an expiry spec names. A date ("2026-11-20", "20261120", a
|
|
123
|
+
`date` or `datetime`), or a day of the month ("26", "26th", 26): the next
|
|
124
|
+
date on or after today that falls on it."""
|
|
125
|
+
if isinstance(expiry, datetime):
|
|
126
|
+
return expiry.date()
|
|
127
|
+
if isinstance(expiry, date):
|
|
128
|
+
return expiry
|
|
129
|
+
if isinstance(expiry, bool):
|
|
130
|
+
raise ValueError(f"expiry must be a date or a day of the month, not {expiry!r}")
|
|
131
|
+
if isinstance(expiry, int):
|
|
132
|
+
return next_day_of_month(expiry, today)
|
|
133
|
+
text = str(expiry or "").strip().upper()
|
|
134
|
+
for pattern in (_ISO, _COMPACT):
|
|
135
|
+
m = pattern.match(text)
|
|
136
|
+
if m:
|
|
137
|
+
try:
|
|
138
|
+
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
|
139
|
+
except ValueError:
|
|
140
|
+
raise ValueError(f"{expiry!r} is not a real date") from None
|
|
141
|
+
m = _DAY.match(text)
|
|
142
|
+
if m:
|
|
143
|
+
return next_day_of_month(int(m.group(1)), today)
|
|
144
|
+
raise ValueError(
|
|
145
|
+
f'expiry must be a date ("2026-11-20") or a day of the month ("26", "26th"), '
|
|
146
|
+
f"not {expiry!r}")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def board_for(target: date, settlement: str, expiries, morning_expiries,
|
|
150
|
+
underlying: str) -> str:
|
|
151
|
+
"""The board to read for `target`: "YYYY-MM-DD AM" for the morning-settled
|
|
152
|
+
board of a date that lists both kinds, else the plain date. Refused
|
|
153
|
+
(NO_EXPIRY) when the date lists no expiry, naming the nearest that do."""
|
|
154
|
+
iso = target.isoformat()
|
|
155
|
+
if settlement == "am" and f"{iso} AM" in set(morning_expiries):
|
|
156
|
+
return f"{iso} AM"
|
|
157
|
+
if iso in set(expiries):
|
|
158
|
+
return iso
|
|
159
|
+
dates = sorted(set(expiries) | {e.split(" ")[0] for e in morning_expiries})
|
|
160
|
+
before = [d for d in dates if d < iso]
|
|
161
|
+
after = [d for d in dates if d > iso]
|
|
162
|
+
near = " and ".join(x for x in (before[-1] if before else "", after[0] if after else "") if x)
|
|
163
|
+
raise While25Error(
|
|
164
|
+
f"{underlying} has no expiry on {iso}" + (f" - the nearest are {near}" if near else ""),
|
|
165
|
+
"NO_EXPIRY")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def nearest_index(strikes, money: Decimal) -> int:
|
|
169
|
+
"""Index of the listed strike nearest `money`, a tie going to the higher
|
|
170
|
+
strike, whichever order the list is in. -1 for an empty list."""
|
|
171
|
+
best, gap, best_strike = -1, None, None
|
|
172
|
+
for i, k in enumerate(strikes):
|
|
173
|
+
g = abs(k - money)
|
|
174
|
+
if gap is None or g < gap or (g == gap and k > best_strike):
|
|
175
|
+
best, gap, best_strike = i, g, k
|
|
176
|
+
return best
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def within_list(strikes, money: Decimal) -> bool:
|
|
180
|
+
"""Whether `money` lies on the listed strikes, half a step past either end
|
|
181
|
+
included — the Options Builder's rule: past that, the end strike is not
|
|
182
|
+
the money."""
|
|
183
|
+
ks = sorted(strikes)
|
|
184
|
+
if len(ks) < 2:
|
|
185
|
+
return True
|
|
186
|
+
low_step = ks[1] - ks[0]
|
|
187
|
+
high_step = ks[-1] - ks[-2]
|
|
188
|
+
return ks[0] - low_step / 2 <= money <= ks[-1] + high_step / 2
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def pick_strike_index(strikes, spec: StrikeSpec, money: "Decimal | None") -> int:
|
|
192
|
+
"""Index into `strikes` (ascending) of the strike `spec` names.
|
|
193
|
+
|
|
194
|
+
A price must be one that is listed — never rounded onto a neighbour
|
|
195
|
+
(NO_STRIKE names the nearest listed). An ATM offset counts listed strikes
|
|
196
|
+
from the one nearest `money`; running off either end is OFF_THE_LIST."""
|
|
197
|
+
if spec.price is not None:
|
|
198
|
+
for i, k in enumerate(strikes):
|
|
199
|
+
if k == spec.price:
|
|
200
|
+
return i
|
|
201
|
+
below = [k for k in strikes if k < spec.price]
|
|
202
|
+
above = [k for k in strikes if k > spec.price]
|
|
203
|
+
near = " and ".join(str(x) for x in ([below[-1]] if below else []) + ([above[0]] if above else []))
|
|
204
|
+
raise While25Error(
|
|
205
|
+
f"{spec.price} is not a listed strike" + (f" - the nearest are {near}" if near else ""),
|
|
206
|
+
"NO_STRIKE")
|
|
207
|
+
if money is None:
|
|
208
|
+
raise While25Error("there is no price to count strikes from the money", "NO_PRICE")
|
|
209
|
+
if not strikes:
|
|
210
|
+
raise While25Error("the board lists no strikes", "NO_STRIKE")
|
|
211
|
+
if not within_list(strikes, money):
|
|
212
|
+
raise While25Error(
|
|
213
|
+
f"the money ({money}) is beyond the listed strikes ({strikes[0]} to "
|
|
214
|
+
f"{strikes[-1]}): there is no strike at the money", "OFF_THE_LIST")
|
|
215
|
+
atm = nearest_index(strikes, money)
|
|
216
|
+
i = atm + int(spec.offset or 0)
|
|
217
|
+
if not 0 <= i < len(strikes):
|
|
218
|
+
raise While25Error(
|
|
219
|
+
f"ATM{spec.offset:+d} runs off the strike list: ATM is {strikes[atm]}, and the "
|
|
220
|
+
f"list runs from {strikes[0]} to {strikes[-1]}", "OFF_THE_LIST")
|
|
221
|
+
return i
|