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/ui.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
"""Panel declaration.
|
|
2
|
+
|
|
3
|
+
A plugin declares its layout ONCE, at import, and afterwards only pushes values
|
|
4
|
+
into named slots (`ctx.ui.push`).
|
|
5
|
+
|
|
6
|
+
Display-only. `html` is the default: the app's own page, author-owned markup
|
|
7
|
+
and CSS rendered as written in a sandboxed frame on the terminal's brand theme
|
|
8
|
+
(scripts never run). `view` is a whole panel described as WHAT to show (a block
|
|
9
|
+
tree the terminal renders in its own components — the backtest view among
|
|
10
|
+
them); `metric` / `chart` / `table` / `text` show single values. None of them
|
|
11
|
+
accept input or call back into Python. The interaction model is a separate design pass (open question 4), and
|
|
12
|
+
adding a half-considered one now would freeze a callback contract that has to
|
|
13
|
+
hold for third parties.
|
|
14
|
+
|
|
15
|
+
Declaration is module-level and happens at import, exactly like the `@on.*`
|
|
16
|
+
decorators — so a panel exists as soon as its file is run, before the module is
|
|
17
|
+
ever started. That is what lets the terminal show a plugin's panel in the
|
|
18
|
+
picker without running its code on a cadence.
|
|
19
|
+
"""
|
|
20
|
+
import math
|
|
21
|
+
import numbers
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
from decimal import Decimal
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
|
|
27
|
+
CONTAINER_KINDS = frozenset({"row"})
|
|
28
|
+
LEAF_KINDS = frozenset({"metric", "chart", "table", "text", "html"})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DeclarationError(Exception):
|
|
32
|
+
"""A layout that cannot be rendered as written."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Widget:
|
|
37
|
+
kind: str
|
|
38
|
+
slot: str = ""
|
|
39
|
+
label: str = ""
|
|
40
|
+
children: list = field(default_factory=list)
|
|
41
|
+
# chart only: True promises data-rate redraws and buys the lightweight SVG
|
|
42
|
+
# fast path; False (default) renders the interactive Wiz chart with hover.
|
|
43
|
+
live: bool = False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Panel:
|
|
48
|
+
panel_id: str
|
|
49
|
+
label: str
|
|
50
|
+
root: Widget | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Keyed by thread: runs execute on a pool, so two files can be executing at
|
|
54
|
+
# once. A single global would let one file's ui.layout() land in another's
|
|
55
|
+
# declaration — a panel silently belonging to the wrong plugin.
|
|
56
|
+
_declared: dict[int, Panel] = {}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _key() -> int:
|
|
60
|
+
return threading.get_ident()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def panel(panel_id: str, label: str = "") -> None:
|
|
64
|
+
"""Name the panel this file declares."""
|
|
65
|
+
pid = str(panel_id).strip()
|
|
66
|
+
if not pid:
|
|
67
|
+
raise DeclarationError("a panel needs an id")
|
|
68
|
+
_declared[_key()] = Panel(panel_id=pid, label=str(label or pid))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def layout(*widgets: Widget) -> None:
|
|
72
|
+
"""Set the panel's contents. Multiple widgets stack vertically."""
|
|
73
|
+
current = _declared.get(_key())
|
|
74
|
+
if current is None:
|
|
75
|
+
# Inventing a panel id here would produce a panel the author never named
|
|
76
|
+
# and therefore cannot target from ctx.ui.push().
|
|
77
|
+
raise DeclarationError("call ui.panel(...) before ui.layout(...)")
|
|
78
|
+
|
|
79
|
+
root = Widget(kind="column", children=list(widgets))
|
|
80
|
+
_check_slots(root)
|
|
81
|
+
current.root = root
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def row(*children: Widget) -> Widget:
|
|
85
|
+
return Widget(kind="row", children=list(children))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def metric(slot: str, label: str = "") -> Widget:
|
|
89
|
+
return _leaf("metric", slot, label)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def chart(slot: str, label: str = "", *, live: bool = False) -> Widget:
|
|
93
|
+
"""A chart slot.
|
|
94
|
+
|
|
95
|
+
`live=False` (the default) renders an INTERACTIVE chart — hover, tooltips,
|
|
96
|
+
legend — right for anything a person reads. `live=True` promises data-rate
|
|
97
|
+
redraws (every tick / every second) and buys the lightweight SVG fast path
|
|
98
|
+
with axis min/max labels instead; use it only when the chart genuinely
|
|
99
|
+
streams.
|
|
100
|
+
|
|
101
|
+
Push EITHER a bare list of numbers (a sparkline) or a Wiz-shaped spec:
|
|
102
|
+
|
|
103
|
+
ctx.ui.push("profile", {
|
|
104
|
+
"kind": "grouped_bar", # 11 kinds — see below
|
|
105
|
+
"rows": [{"price": 30190, "mnq": 412, "nq": 980}, ...],
|
|
106
|
+
"x": "price", "y": ["mnq", "nq"],
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
A slot REPLACES its value, so the chart redraws on every push. This is
|
|
110
|
+
where a chart belongs: nothing in the terminal displays `while25.viz`
|
|
111
|
+
(the console says so when a script calls it).
|
|
112
|
+
|
|
113
|
+
Long form works too — `"series": "contract"` with a single `y` splits one
|
|
114
|
+
measure column into a series per distinct value.
|
|
115
|
+
|
|
116
|
+
Kinds: line, area, bar, grouped_bar, stacked_bar, scatter, bubble, pie,
|
|
117
|
+
donut, histogram, heatmap. pie/donut take one measure and drop
|
|
118
|
+
non-positives (a negative has no share of a whole); histogram bins one
|
|
119
|
+
measure; heatmap is long form (series = rows, x = columns, y = value).
|
|
120
|
+
"""
|
|
121
|
+
w = _leaf("chart", slot, label)
|
|
122
|
+
w.live = bool(live)
|
|
123
|
+
return w
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def table(slot: str, label: str = "") -> Widget:
|
|
127
|
+
return _leaf("table", slot, label)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def text(slot: str, label: str = "") -> Widget:
|
|
131
|
+
return _leaf("text", slot, label)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def view(slot: str, label: str = "") -> Widget:
|
|
135
|
+
"""A whole panel described as WHAT to show — reach for this first.
|
|
136
|
+
|
|
137
|
+
Push a dict with a `blocks` list and the terminal renders it in its own
|
|
138
|
+
components: the same tiles, tables and badges every built-in panel uses.
|
|
139
|
+
You name TONES, never colours; the terminal formats every number, shows
|
|
140
|
+
the absent marker for a missing value, and applies its type scale. There
|
|
141
|
+
is no HTML and no CSS to get wrong, so every app looks like the terminal.
|
|
142
|
+
|
|
143
|
+
ui.layout(ui.view("main"))
|
|
144
|
+
...
|
|
145
|
+
while25.ui.push("main", {"blocks": [
|
|
146
|
+
{"kind": "header", "title": "Desk", "stamp": "every 10s",
|
|
147
|
+
"badges": [{"text": "live", "tone": "active"}]},
|
|
148
|
+
{"kind": "tiles", "items": [
|
|
149
|
+
{"label": "Open positions", "value": len(positions)},
|
|
150
|
+
]},
|
|
151
|
+
{"kind": "table", "title": "Positions", "rows": positions,
|
|
152
|
+
"columns": ["symbol", "quantity",
|
|
153
|
+
{"key": "pnl", "label": "P&L", "tone": "money"}]},
|
|
154
|
+
]})
|
|
155
|
+
|
|
156
|
+
Blocks (v1): `header` {title, subtitle?, stamp?, badges?}, `tiles`
|
|
157
|
+
{items: [{label, value, tone?, sub?}], columns?}, `kv` {title?, items:
|
|
158
|
+
[{label, value, tone?}]}, `table` {title?, rows, columns?: [name or {key,
|
|
159
|
+
label?, tone?, align?}]}, `badges` {items: [{text, tone?}]}, `text` {text,
|
|
160
|
+
tone?}, `progress` {label?, value, max?, text?, tone?}, `chart` {title?,
|
|
161
|
+
spec or points, live?} — interactive Wiz unless `live` is true, which
|
|
162
|
+
promises data-rate redraws and buys the SVG fast path — `backtest` (a
|
|
163
|
+
whole results view — build it with `backtest_block`, never by hand),
|
|
164
|
+
`html` {title?, html} for one sandboxed section of your own markup,
|
|
165
|
+
`section` {title, blocks}, `row` {blocks}, `divider`. An unknown kind
|
|
166
|
+
renders visibly as unsupported.
|
|
167
|
+
|
|
168
|
+
Tones: `money` (coloured by SIGN — the only tone that reads the value),
|
|
169
|
+
`profit`, `loss`, `active`, `attention`, `error`, `muted`, `neutral`.
|
|
170
|
+
Pass raw numbers, not pre-formatted strings; pass None for "not known
|
|
171
|
+
yet", never 0. Limits: 400 blocks, nesting depth 5, 500 table rows.
|
|
172
|
+
|
|
173
|
+
`label` is optional, as for `html`: the tree usually carries its own
|
|
174
|
+
header. Declared as the layout's ONLY widget, the view becomes the WHOLE
|
|
175
|
+
PANEL; mixed with other widgets it is one section among them.
|
|
176
|
+
|
|
177
|
+
On the wire this is the same widget kind as `html` — the payload decides
|
|
178
|
+
how it renders — so an older terminal shows the dict as text rather than
|
|
179
|
+
nothing.
|
|
180
|
+
"""
|
|
181
|
+
s = str(slot).strip()
|
|
182
|
+
if not s:
|
|
183
|
+
raise DeclarationError("view needs a slot name")
|
|
184
|
+
return Widget(kind="html", slot=s, label=str(label))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def html(slot: str, label: str = "") -> Widget:
|
|
188
|
+
"""The app's page, in HTML — the default for an app's panel.
|
|
189
|
+
|
|
190
|
+
Push a markup string. You own the page, structure AND look; your CSS
|
|
191
|
+
renders as written:
|
|
192
|
+
|
|
193
|
+
ui.layout(ui.html("view"))
|
|
194
|
+
...
|
|
195
|
+
ctx.ui.push("view",
|
|
196
|
+
"<div class='page stack'>"
|
|
197
|
+
" <div class='header'><h3>Ladder</h3><span class='stamp'>1s</span></div>"
|
|
198
|
+
" <div class='tiles'><div class='tile'>"
|
|
199
|
+
" <div class='k'>Day P&L</div><div class='v profit'>1,234.50</div>"
|
|
200
|
+
" </div></div>"
|
|
201
|
+
"</div>")
|
|
202
|
+
|
|
203
|
+
Build on the brand theme: the terminal's live tokens resolve inside
|
|
204
|
+
(`var(--color-amber)`, `--color-profit`, `--color-loss`, `--color-text-dim`,
|
|
205
|
+
`--color-surface-2`, ...) and follow its light/dark switch; bare <h1>-<h4>,
|
|
206
|
+
<table>, <p>, <small>, <pre>, <hr> and <a> are already styled; and the
|
|
207
|
+
class catalog (`.page`, `.stack`, `.tiles` > `.tile` > `.k` / `.v`, `.card`,
|
|
208
|
+
`.badge-*`, `.c-profit` / `.c-loss`, ... — SDK_README.md "HTML") is there to
|
|
209
|
+
compose from. The brand sheet sits in a lower cascade layer, so any CSS you
|
|
210
|
+
write wins over it; nothing is snapped or stripped. Charts are yours to
|
|
211
|
+
draw — inline <svg> built in Python, or CSS bars; a `chart` block beside an
|
|
212
|
+
`html` block in a `view` adds hover, and is optional.
|
|
213
|
+
|
|
214
|
+
`label` is OPTIONAL here, unlike the other widgets: pass one to get the
|
|
215
|
+
terminal's small caption above the view, omit it and the markup stands on
|
|
216
|
+
its own. Declare `ui.html` as the layout's ONLY widget and the view
|
|
217
|
+
becomes the WHOLE PANEL — full height, no caption, no padding. Mix it
|
|
218
|
+
with other widgets and each html leaf is one section among them.
|
|
219
|
+
|
|
220
|
+
The terminal renders it in a sandboxed frame: scripts NEVER run —
|
|
221
|
+
`<script>`, `on*` handlers and `javascript:` URLs are all inert. HTML and
|
|
222
|
+
CSS only; compute in Python and push new markup. Links are opened by the
|
|
223
|
+
terminal in the system browser (https only).
|
|
224
|
+
"""
|
|
225
|
+
s = str(slot).strip()
|
|
226
|
+
if not s:
|
|
227
|
+
raise DeclarationError("html needs a slot name")
|
|
228
|
+
return Widget(kind="html", slot=s, label=str(label))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
_RETIRED = ("equity", "stats", "drawdown", "benchmark", "currency")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
#: backtest_block(logic=) limits: sections, lines per section, chars per name and per line.
|
|
235
|
+
LOGIC_SECTIONS, LOGIC_LINES, LOGIC_NAME, LOGIC_LINE = 10, 12, 40, 240
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def check_logic(sections, fn: str = "") -> None:
|
|
239
|
+
"""Raises TypeError / ValueError naming the field unless `sections` is the
|
|
240
|
+
`logic` backtest_block records: [{"name": str, "lines": [str, ...]}]
|
|
241
|
+
within the limits. The parent's seal runs this same check (R-SHAPE)."""
|
|
242
|
+
if not isinstance(sections, list):
|
|
243
|
+
raise TypeError(f"{fn}logic must be a list of {{name, lines}} sections")
|
|
244
|
+
if len(sections) > LOGIC_SECTIONS:
|
|
245
|
+
raise ValueError(f"{fn}logic has {len(sections)} sections; at most {LOGIC_SECTIONS}")
|
|
246
|
+
for n, sec in enumerate(sections):
|
|
247
|
+
w = f"{fn}logic[{n}]"
|
|
248
|
+
if not isinstance(sec, dict) or set(sec) != {"name", "lines"}:
|
|
249
|
+
raise TypeError(f"{w} must be {{name, lines}}")
|
|
250
|
+
name, lines = sec["name"], sec["lines"]
|
|
251
|
+
if not isinstance(name, str):
|
|
252
|
+
raise TypeError(f"{w}.name must be a str")
|
|
253
|
+
if len(name) > LOGIC_NAME:
|
|
254
|
+
raise ValueError(f"{w}.name is {len(name)} characters; at most {LOGIC_NAME}")
|
|
255
|
+
if not isinstance(lines, list):
|
|
256
|
+
raise TypeError(f"{w}.lines must be a str or a list of str")
|
|
257
|
+
if not 1 <= len(lines) <= LOGIC_LINES:
|
|
258
|
+
raise ValueError(f"{w}.lines holds {len(lines)} lines; 1 to {LOGIC_LINES}")
|
|
259
|
+
for j, line in enumerate(lines):
|
|
260
|
+
if not isinstance(line, str):
|
|
261
|
+
raise TypeError(f"{w}.lines[{j}] must be a str")
|
|
262
|
+
if not line.strip():
|
|
263
|
+
raise ValueError(f"{w}.lines[{j}] must be a non-empty str")
|
|
264
|
+
if len(line) > LOGIC_LINE:
|
|
265
|
+
raise ValueError(f"{w}.lines[{j}] is {len(line)} characters; at most {LOGIC_LINE}")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _logic(logic) -> "list | None":
|
|
269
|
+
"""backtest_block's `logic` as [{"name", "lines"}]: a dict (its order the
|
|
270
|
+
display order) or (name, lines) pairs; a line value one str or a list."""
|
|
271
|
+
if logic is None:
|
|
272
|
+
return None
|
|
273
|
+
if isinstance(logic, dict):
|
|
274
|
+
pairs = list(logic.items())
|
|
275
|
+
elif isinstance(logic, (list, tuple)):
|
|
276
|
+
pairs = list(logic)
|
|
277
|
+
else:
|
|
278
|
+
raise TypeError("backtest_block() logic must be a dict {name: lines} or a list of "
|
|
279
|
+
"(name, lines) pairs")
|
|
280
|
+
out = []
|
|
281
|
+
for n, pair in enumerate(pairs):
|
|
282
|
+
if not isinstance(pair, (list, tuple)) or len(pair) != 2:
|
|
283
|
+
raise TypeError(f"backtest_block() logic[{n}] must be a (name, lines) pair")
|
|
284
|
+
name, lines = pair
|
|
285
|
+
out.append({"name": name, "lines": [lines] if isinstance(lines, str)
|
|
286
|
+
else list(lines) if isinstance(lines, (list, tuple)) else lines})
|
|
287
|
+
check_logic(out, "backtest_block() ")
|
|
288
|
+
return out
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def backtest_block(trades, *retired, data=None, start_equity=0.0, capital=None, title=None,
|
|
292
|
+
subtitle=None, notes=None, assume=None, logic=None, **unknown) -> dict:
|
|
293
|
+
"""The results of a backtest as ONE block — the terminal draws the whole view.
|
|
294
|
+
|
|
295
|
+
You hand over the trades and the history you built them on; the terminal
|
|
296
|
+
computes everything else and seals it, or refuses it with the rule it broke.
|
|
297
|
+
|
|
298
|
+
span = while25.data.history_span("EQ:US:AAPL", "15m", "2025-01-01", "2025-06-30")
|
|
299
|
+
... # your logic decides every trade
|
|
300
|
+
f_in = backtest.fill(bar, "buy", "open", instrument=inst)
|
|
301
|
+
f_out = backtest.fill(later, "sell", "stop", instrument=inst, price=stop)
|
|
302
|
+
if f_out is not None:
|
|
303
|
+
product = "intraday" if f_in.date == f_out.date else "delivery"
|
|
304
|
+
trades.append(backtest.trade(inst, "buy", 10, f_in, f_out, product=product))
|
|
305
|
+
...
|
|
306
|
+
while25.ui.push("main", {"blocks": [
|
|
307
|
+
while25.ui.backtest_block(trades, data=[span["id"]], capital=100_000,
|
|
308
|
+
title="RSI(14) mean reversion")]})
|
|
309
|
+
|
|
310
|
+
`trades`: what `while25.backtest.trade()` returned, every position closed
|
|
311
|
+
(close what is still open at the end as a last trade). `data`: the id (or
|
|
312
|
+
ids) of the `history_span` answers the trades were filled on.
|
|
313
|
+
`start_equity`: where the curve starts (0 = cumulative P&L). `capital`:
|
|
314
|
+
switches on the percentage figures (None: your default capital, if set).
|
|
315
|
+
`assume`: the assumptions every trade was built under (None: the run's
|
|
316
|
+
backtest.defaults(); else backtest.assume(...)). Declare them once for the
|
|
317
|
+
whole backtest: a trade built under others is refused (R-TRADE-DERIVED),
|
|
318
|
+
and the sealed block states each assumption with its source (built-in,
|
|
319
|
+
your default, this backtest).
|
|
320
|
+
`logic`: the strategy's rules in your words, shown above the figures as
|
|
321
|
+
"from the script": a dict {"Entry": ["RSI(14) < 30", ...], "Exit": "..."}
|
|
322
|
+
(its order is the display order) or a list of (name, lines) pairs; a
|
|
323
|
+
line value is one str or a list of str. Any section name (Universe,
|
|
324
|
+
Model, Legs, Hedge ratio, ...). At most 10 sections and 12 lines per
|
|
325
|
+
section, a name at most 40 characters and a line at most 240, every line
|
|
326
|
+
a non-empty str: else TypeError or ValueError naming the field (the seal
|
|
327
|
+
refuses a malformed one, R-SHAPE). The seal never interprets the words.
|
|
328
|
+
|
|
329
|
+
The terminal re-derives every trade from the bars it delivered and
|
|
330
|
+
the venue's own facts, and computes the per-bar marked-to-market equity
|
|
331
|
+
curve, drawdown, statistics and monthly table itself. A trade that does
|
|
332
|
+
not re-derive, a price outside its bar, an id this module was never given
|
|
333
|
+
or an open position refuses the whole block, naming the rule.
|
|
334
|
+
|
|
335
|
+
The rules (a refused block names one; none is drawn): R-SHAPE (not a block
|
|
336
|
+
this function builds), R-DATA (a data id never given, or a trade on an
|
|
337
|
+
instrument no answer covers), R-WINDOW (a trade outside the covered
|
|
338
|
+
window), R-TRADE-DERIVED (not what backtest.trade() gives on the recorded
|
|
339
|
+
bars, or what trade() refuses: an impossible fill order, intraday held
|
|
340
|
+
overnight, a quantity off the venue's step, a symbol listed as not
|
|
341
|
+
equity; a trade built under other assumptions than the block declares,
|
|
342
|
+
a bracketed exit against its same-bar rule, a `your default` your
|
|
343
|
+
defaults do not hold), R-PRICE (at or below 0, or outside its bar), R-FACTS (the venue
|
|
344
|
+
states no multiplier, tick or currency, or the trade is costed on another
|
|
345
|
+
broker than the account's), R-CURRENCY (more than one),
|
|
346
|
+
R-FLAT (an open trade), R-TIME (not epoch ms). Real costs come from the
|
|
347
|
+
dated registry or the trade is refused (COSTS_UNKNOWN), never zero; zero
|
|
348
|
+
or custom costs are an assumption the block states.
|
|
349
|
+
|
|
350
|
+
`equity`, `stats`, `drawdown`, `benchmark` and `currency` are no longer
|
|
351
|
+
accepted: passing one raises TypeError naming it, because nothing the
|
|
352
|
+
script computes reaches the view. The seal cannot see look-ahead in your
|
|
353
|
+
own logic or a best-of-many parameter sweep.
|
|
354
|
+
"""
|
|
355
|
+
if retired:
|
|
356
|
+
raise TypeError("backtest_block() takes the trades only: the equity curve (and stats, "
|
|
357
|
+
"drawdown, benchmark, currency) is computed by the terminal; build each "
|
|
358
|
+
"trade with while25.backtest.trade() and pass data=[answer ids]")
|
|
359
|
+
for k in unknown:
|
|
360
|
+
if k in _RETIRED:
|
|
361
|
+
raise TypeError(f"backtest_block() no longer accepts {k!r}: the terminal computes it "
|
|
362
|
+
f"from the trades; build each trade with while25.backtest.trade()")
|
|
363
|
+
raise TypeError(f"backtest_block() got an unexpected keyword argument {k!r}")
|
|
364
|
+
if data is None:
|
|
365
|
+
raise TypeError("backtest_block() needs data=: the id(s) of the history_span answers "
|
|
366
|
+
"the trades were built on (answer['id'])")
|
|
367
|
+
from .backtest import _assumed
|
|
368
|
+
return {"kind": "backtest", "trades": [] if trades is None else list(trades),
|
|
369
|
+
"data": [data] if isinstance(data, str) else list(data),
|
|
370
|
+
"start_equity": start_equity, "capital": capital, "title": title,
|
|
371
|
+
"subtitle": subtitle, "notes": notes, "assume": _assumed(assume).as_dict(),
|
|
372
|
+
"logic": _logic(logic)}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
# ---- desk blocks (2026-10-27) ----
|
|
376
|
+
|
|
377
|
+
_OPEN = ("auto", "holds", "working", "combos", "log")
|
|
378
|
+
_SECTIONS = ("holds", "working", "combos", "log")
|
|
379
|
+
_OPS = frozenset({"<", "<=", ">", ">=", "==", "between", "crosses_above", "crosses_below"})
|
|
380
|
+
_TONES = frozenset({"money", "profit", "loss", "active", "attention", "error", "muted", "neutral"})
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def strategy_block(strategy=None, *, open="auto", sections=None, title=None, capital=None,
|
|
384
|
+
**unknown) -> dict:
|
|
385
|
+
"""A live strategy's reconciled figures as ONE block, drawn by the terminal.
|
|
386
|
+
|
|
387
|
+
The terminal fills it from the same data as the Live Strategies panel
|
|
388
|
+
(holdings, working orders, combos, log, Open / Closed / Total P&L), so the
|
|
389
|
+
two never disagree. The script says WHERE it goes and nothing else.
|
|
390
|
+
|
|
391
|
+
while25.ui.push("main", {"blocks": [while25.ui.strategy_block()]})
|
|
392
|
+
|
|
393
|
+
`strategy`: a module id; None is the module doing the push (the terminal stamps
|
|
394
|
+
it). `open`: which tab the details open on ("auto" | "holds" | "working" |
|
|
395
|
+
"combos" | "log"), or False for folded. `sections`: a subset of
|
|
396
|
+
["holds", "working", "combos", "log"]; the terminal fixes their order.
|
|
397
|
+
`title`: the display name (None: the module's label).
|
|
398
|
+
`capital`: what the strategy was given to trade, in the currency it trades
|
|
399
|
+
in (e.g. 5000). The terminal draws its equity curve from it: capital plus
|
|
400
|
+
the terminal's own Total P&L, the % read against it, the capital shown as
|
|
401
|
+
declared by the script. A positive number; None: no curve baseline.
|
|
402
|
+
|
|
403
|
+
No figure may be passed: any other keyword raises TypeError naming it, and
|
|
404
|
+
The terminal drops every other key from a hand-built {"kind": "strategy"}.
|
|
405
|
+
Capital is the one stated INPUT, never a result the terminal shows as its own.
|
|
406
|
+
"""
|
|
407
|
+
for k in unknown:
|
|
408
|
+
raise TypeError(f"strategy_block() got an unexpected keyword argument {k!r}: its figures "
|
|
409
|
+
f"come from the terminal, never the script")
|
|
410
|
+
if strategy is not None:
|
|
411
|
+
if not isinstance(strategy, str):
|
|
412
|
+
raise TypeError("strategy_block() strategy must be a module id (str) or None")
|
|
413
|
+
if not strategy.strip():
|
|
414
|
+
raise ValueError("strategy_block() strategy must not be blank (None: this module)")
|
|
415
|
+
if sections is not None:
|
|
416
|
+
if isinstance(sections, (str, bytes, dict)) or not isinstance(sections, (list, tuple)):
|
|
417
|
+
raise TypeError("strategy_block() sections must be a list")
|
|
418
|
+
sections = list(sections)
|
|
419
|
+
if any(s not in _SECTIONS for s in sections) or len(set(sections)) != len(sections):
|
|
420
|
+
raise ValueError(f"strategy_block() sections must be distinct names from {list(_SECTIONS)}")
|
|
421
|
+
if not (open is False or (isinstance(open, str) and open in _OPEN)):
|
|
422
|
+
raise ValueError(f"strategy_block() open must be one of {list(_OPEN)} or False")
|
|
423
|
+
if sections is not None and open not in (False, "auto") and open not in sections:
|
|
424
|
+
raise ValueError(f"strategy_block() open={open!r} is not among the sections")
|
|
425
|
+
_str_or_none("strategy_block", "title", title)
|
|
426
|
+
if capital is not None:
|
|
427
|
+
if isinstance(capital, bool) or not isinstance(capital, (int, float)):
|
|
428
|
+
raise TypeError("strategy_block() capital must be a number")
|
|
429
|
+
if not math.isfinite(capital) or capital <= 0:
|
|
430
|
+
raise ValueError("strategy_block() capital must be a positive, finite number")
|
|
431
|
+
return {"kind": "strategy", "strategy": strategy, "open": open, "sections": sections,
|
|
432
|
+
"title": title, "capital": capital}
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def rule(label, value, op, target, *, prev=None, near=None, unit=None, fmt=None) -> dict:
|
|
436
|
+
"""One rule of a `conditions` block. The terminal judges it, never the script.
|
|
437
|
+
|
|
438
|
+
`op`: < <= > >= == between crosses_above crosses_below. `between` takes
|
|
439
|
+
`target=[lo, hi]` with lo <= hi; a crossing needs `prev` (the value one step
|
|
440
|
+
earlier): crosses_above is met when prev <= target < value. `near`: an
|
|
441
|
+
absolute amount in the value's units, the band the progress bar fills
|
|
442
|
+
across. `unit`: a word after the distance ("+32 pts"). `fmt`: a suffix the
|
|
443
|
+
terminal glues onto every figure of the rule, its value, target and
|
|
444
|
+
distance (fmt="x" shows "1.8x"); not a number format. `value=None` is "not
|
|
445
|
+
known yet" (shown as the absent marker and not met), never 0.
|
|
446
|
+
|
|
447
|
+
Any real number works, numpy and Decimal included; a NaN, pd.NA or
|
|
448
|
+
infinite value, target, prev or near (an indicator still warming up) becomes None,
|
|
449
|
+
"not known yet", so a draw never halts on one. A wrong `op`, a `between`
|
|
450
|
+
target that is not [lo, hi], or a crossing with no `prev` still raises.
|
|
451
|
+
"""
|
|
452
|
+
_label("rule", label)
|
|
453
|
+
if op not in _OPS:
|
|
454
|
+
raise ValueError(f"rule() op must be one of {sorted(_OPS)}, not {op!r}")
|
|
455
|
+
value = _num("rule", "value", value, none_ok=True)
|
|
456
|
+
if op == "between":
|
|
457
|
+
if (not isinstance(target, (list, tuple)) or len(target) != 2
|
|
458
|
+
or any(t is None or not _is_num(t) for t in target)):
|
|
459
|
+
raise ValueError("rule() target for 'between' must be [lo, hi]")
|
|
460
|
+
target = [_num("rule", "target", t) for t in target]
|
|
461
|
+
if None not in target and target[0] > target[1]:
|
|
462
|
+
raise ValueError("rule() target for 'between' needs lo <= hi")
|
|
463
|
+
else:
|
|
464
|
+
target = _num("rule", "target", target)
|
|
465
|
+
if op.startswith("crosses_") and prev is None:
|
|
466
|
+
raise ValueError(f"rule() op {op!r} needs prev, the value one step earlier")
|
|
467
|
+
prev = _num("rule", "prev", prev, none_ok=True)
|
|
468
|
+
near = _num("rule", "near", near, none_ok=True)
|
|
469
|
+
if near is not None and near <= 0:
|
|
470
|
+
raise ValueError("rule() near must be greater than 0")
|
|
471
|
+
_str_or_none("rule", "unit", unit)
|
|
472
|
+
_str_or_none("rule", "fmt", fmt)
|
|
473
|
+
out = {"label": label, "value": value, "op": op, "target": target}
|
|
474
|
+
out.update({k: v for k, v in (("prev", prev), ("near", near), ("unit", unit), ("fmt", fmt))
|
|
475
|
+
if v is not None})
|
|
476
|
+
return out
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def conditions(title, rules, *, need="all") -> dict:
|
|
480
|
+
"""How close the strategy is to its signal: rules built with `rule()`.
|
|
481
|
+
|
|
482
|
+
`need`: "all", "any", or how many must be met (an int of 1 or more; more
|
|
483
|
+
than the rules is simply never met, so leaving an unknown rule out never
|
|
484
|
+
raises). The terminal shows each rule met or not yet, its distance, and
|
|
485
|
+
"k of n met".
|
|
486
|
+
"""
|
|
487
|
+
_str_or_none("conditions", "title", title, none_ok=False)
|
|
488
|
+
if not isinstance(rules, (list, tuple)) or not all(isinstance(r, dict) for r in rules):
|
|
489
|
+
raise TypeError("conditions() rules must be a list of rule() results")
|
|
490
|
+
ok = need in ("all", "any") if isinstance(need, str) else (
|
|
491
|
+
isinstance(need, numbers.Integral) and not isinstance(need, bool) and need >= 1)
|
|
492
|
+
if not ok:
|
|
493
|
+
raise ValueError("conditions() need must be 'all', 'any' or an int of 1 or more")
|
|
494
|
+
need = need if isinstance(need, str) else int(need)
|
|
495
|
+
return {"kind": "conditions", "title": title, "need": need, "rules": list(rules)}
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def level(label, value, *, tone=None) -> dict:
|
|
499
|
+
"""One level of a `levels` block. Tone a stop `loss` and a target `profit`
|
|
500
|
+
and the terminal shows reward/risk. `value=None` (or a NaN): not placed
|
|
501
|
+
yet, e.g. a stop computed from a price that has not arrived. A display
|
|
502
|
+
helper never halts the strategy over a level it cannot place yet."""
|
|
503
|
+
_label("level", label)
|
|
504
|
+
out = {"label": label, "value": _num("level", "value", value, none_ok=True)}
|
|
505
|
+
if tone is not None:
|
|
506
|
+
out["tone"] = _tone("level", tone)
|
|
507
|
+
return out
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def levels(*, price, levels, title=None) -> dict:
|
|
511
|
+
"""The price against the strategy's own levels (built with `level()`), on
|
|
512
|
+
one line with each distance in points and %. `price=None` (or a NaN):
|
|
513
|
+
not known yet."""
|
|
514
|
+
if not isinstance(levels, (list, tuple)) or not all(isinstance(x, dict) for x in levels):
|
|
515
|
+
raise TypeError("levels() levels must be a list of level() results")
|
|
516
|
+
_str_or_none("levels", "title", title)
|
|
517
|
+
out = {"kind": "levels", "price": _num("levels", "price", price, none_ok=True),
|
|
518
|
+
"levels": list(levels)}
|
|
519
|
+
if title is not None:
|
|
520
|
+
out["title"] = title
|
|
521
|
+
return out
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def timeline(events, *, title=None) -> dict:
|
|
525
|
+
"""What the strategy did and why. `events`: (t_ms, text) or
|
|
526
|
+
(t_ms, text, tone) with `t_ms` an int (numpy's too) of epoch milliseconds;
|
|
527
|
+
the terminal shows them newest first in the app's own time format."""
|
|
528
|
+
if not isinstance(events, (list, tuple)):
|
|
529
|
+
raise TypeError("timeline() events must be a list of (t_ms, text[, tone])")
|
|
530
|
+
_str_or_none("timeline", "title", title)
|
|
531
|
+
out_events = []
|
|
532
|
+
for ev in events:
|
|
533
|
+
if not isinstance(ev, (list, tuple)) or len(ev) not in (2, 3):
|
|
534
|
+
raise ValueError(f"timeline() events must be (t_ms, text[, tone]), not {ev!r}")
|
|
535
|
+
t, text, tone = (*ev, None)[:3]
|
|
536
|
+
if not isinstance(t, numbers.Integral) or isinstance(t, bool):
|
|
537
|
+
raise TypeError(f"timeline() t must be an int of epoch ms, not {type(t).__name__}")
|
|
538
|
+
t = int(t)
|
|
539
|
+
if t < 0:
|
|
540
|
+
raise ValueError("timeline() t must be epoch ms, not negative")
|
|
541
|
+
if not isinstance(text, str):
|
|
542
|
+
raise TypeError("timeline() text must be a str")
|
|
543
|
+
e = {"t": t, "text": text}
|
|
544
|
+
if tone is not None:
|
|
545
|
+
e["tone"] = _tone("timeline", tone)
|
|
546
|
+
out_events.append(e)
|
|
547
|
+
head = {"kind": "timeline"} if title is None else {"kind": "timeline", "title": title}
|
|
548
|
+
return {**head, "events": out_events}
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def chart_block(spec, *, title=None, live=False) -> dict:
|
|
552
|
+
"""The `chart` block: a Wiz-shaped spec dict (see `ui.chart`), or a bare
|
|
553
|
+
list of numbers for a sparkline. `live=True` buys the SVG fast path."""
|
|
554
|
+
if isinstance(spec, dict):
|
|
555
|
+
out = {"kind": "chart", "spec": spec}
|
|
556
|
+
elif isinstance(spec, (list, tuple)):
|
|
557
|
+
out = {"kind": "chart", "points": list(spec)}
|
|
558
|
+
else:
|
|
559
|
+
raise TypeError("chart_block() spec must be a Wiz spec dict or a list of numbers")
|
|
560
|
+
if not isinstance(live, bool):
|
|
561
|
+
raise TypeError("chart_block() live must be True or False")
|
|
562
|
+
_str_or_none("chart_block", "title", title)
|
|
563
|
+
out["live"] = live
|
|
564
|
+
if title is not None:
|
|
565
|
+
out["title"] = title
|
|
566
|
+
return out
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def custom(title, *, html) -> dict:
|
|
570
|
+
"""Your own markup as one block, framed and labelled "From the script ·
|
|
571
|
+
custom". Sandboxed, scripts never run. Text claiming "Reconciled by
|
|
572
|
+
While25" or "Sealed by While25" is refused (R-IMPERSONATE)."""
|
|
573
|
+
_str_or_none("custom", "title", title, none_ok=False)
|
|
574
|
+
_str_or_none("custom", "html", html, none_ok=False)
|
|
575
|
+
return {"kind": "custom", "title": title, "html": html}
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _is_num(v) -> bool:
|
|
579
|
+
"""A real number: int, float, Decimal, numpy's, or pandas' missing value
|
|
580
|
+
(pd.NA, a nullable column's NaN); never a bool (numpy's bool_ is no
|
|
581
|
+
numbers.Real either)."""
|
|
582
|
+
return (isinstance(v, (numbers.Real, Decimal)) and not isinstance(v, bool)) or _is_na(v)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _is_na(v) -> bool:
|
|
586
|
+
"""pd.NA, read without importing pandas: only a script that already
|
|
587
|
+
imported it can hold one."""
|
|
588
|
+
na = getattr(sys.modules.get("pandas"), "NA", None)
|
|
589
|
+
return na is not None and v is na
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _num(fn, field, v, *, none_ok=False):
|
|
593
|
+
"""A plain int or float for the JSON (a Decimal or numpy number becomes
|
|
594
|
+
one: a display figure), or None when allowed. A NaN or infinite number is
|
|
595
|
+
None too, "not known yet": a pandas indicator is NaN while it warms up, and
|
|
596
|
+
a display helper must never halt the strategy over it. Absent stays None,
|
|
597
|
+
never 0."""
|
|
598
|
+
if v is None and none_ok:
|
|
599
|
+
return None
|
|
600
|
+
if not _is_num(v):
|
|
601
|
+
raise TypeError(f"{fn}() {field} must be a number, not {type(v).__name__}")
|
|
602
|
+
if _is_na(v) or (isinstance(v, Decimal) and not v.is_finite()):
|
|
603
|
+
return None # pd.NA, Decimal NaN / sNaN / Infinity (float() raises on sNaN)
|
|
604
|
+
if isinstance(v, numbers.Integral):
|
|
605
|
+
return int(v)
|
|
606
|
+
f = float(v)
|
|
607
|
+
return f if math.isfinite(f) else None
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _str_or_none(fn, field, v, *, none_ok=True):
|
|
611
|
+
if not (isinstance(v, str) or (none_ok and v is None)):
|
|
612
|
+
raise TypeError(f"{fn}() {field} must be a str")
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _label(fn, label):
|
|
616
|
+
_str_or_none(fn, "label", label, none_ok=False)
|
|
617
|
+
if not label.strip():
|
|
618
|
+
raise ValueError(f"{fn}() label must not be blank")
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _tone(fn, tone):
|
|
622
|
+
if tone not in _TONES:
|
|
623
|
+
raise ValueError(f"{fn}() tone must be one of {sorted(_TONES)}")
|
|
624
|
+
return tone
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
# ---- internals ----
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _leaf(kind: str, slot: str, label: str) -> Widget:
|
|
631
|
+
s = str(slot).strip()
|
|
632
|
+
if not s:
|
|
633
|
+
raise DeclarationError(f"{kind} needs a slot name")
|
|
634
|
+
return Widget(kind=kind, slot=s, label=str(label or s))
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def _check_slots(root: Widget) -> None:
|
|
638
|
+
"""Reject a duplicate slot: two widgets bound to one name would both update
|
|
639
|
+
on every push, and the author could not tell which one they meant."""
|
|
640
|
+
seen: set[str] = set()
|
|
641
|
+
stack = [root]
|
|
642
|
+
while stack:
|
|
643
|
+
w = stack.pop()
|
|
644
|
+
if w.slot:
|
|
645
|
+
if w.slot in seen:
|
|
646
|
+
raise DeclarationError(f"slot {w.slot!r} is used more than once")
|
|
647
|
+
seen.add(w.slot)
|
|
648
|
+
stack.extend(w.children)
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def push(slot: str, value) -> None:
|
|
652
|
+
"""Push a value into a declared slot of the running module's panel.
|
|
653
|
+
|
|
654
|
+
The declaration (`ui.panel`, `ui.layout`) and the runtime push live under
|
|
655
|
+
one name on purpose: `while25.ui` is the whole panel story."""
|
|
656
|
+
from . import _runtime
|
|
657
|
+
return _runtime.current().ui.push(slot, value)
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def declared_slots(p: Panel) -> set[str]:
|
|
661
|
+
if p.root is None:
|
|
662
|
+
return set()
|
|
663
|
+
out: set[str] = set()
|
|
664
|
+
stack = [p.root]
|
|
665
|
+
while stack:
|
|
666
|
+
w = stack.pop()
|
|
667
|
+
if w.slot:
|
|
668
|
+
out.add(w.slot)
|
|
669
|
+
stack.extend(w.children)
|
|
670
|
+
return out
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def take_declaration() -> Panel | None:
|
|
674
|
+
"""Read and clear THIS thread's declaration. Called by the runtime after a
|
|
675
|
+
run, on the same thread that executed the file."""
|
|
676
|
+
return _declared.pop(_key(), None)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def reset() -> None:
|
|
680
|
+
_declared.pop(_key(), None)
|