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,3194 @@
1
+ Metadata-Version: 2.4
2
+ Name: while25
3
+ Version: 0.1.0
4
+ Summary: The While25 Python SDK — write strategies, indicators, monitors and apps for the While25 terminal.
5
+ Author: While25
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://while25.com
8
+ Keywords: trading,quant,strategy,backtesting,while25
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Financial and Insurance Industry
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Topic :: Office/Business :: Financial :: Investment
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: report
18
+ Requires-Dist: reportlab>=4.2; extra == "report"
19
+ Requires-Dist: matplotlib>=3.9; extra == "report"
20
+ Requires-Dist: pandas>=2.0; extra == "report"
21
+ Dynamic: license-file
22
+
23
+ # while25
24
+
25
+ The Python SDK for the [While25](https://while25.com) trading terminal.
26
+
27
+ Write strategies, indicators, monitors and apps as **classes**. Declare what
28
+ wakes them; While25 runs them and renders what they produce.
29
+
30
+ ```bash
31
+ pip install while25
32
+ ```
33
+
34
+ The SDK has **no dependencies**. You can write and unit-test a strategy on a
35
+ plain Python install and run it in the terminal unchanged — which is the point:
36
+ until `pip install while25` worked, nobody could develop without a terminal.
37
+
38
+ ---
39
+
40
+ ## A strategy
41
+
42
+ ```python
43
+ import while25
44
+ from while25 import Strategy, on
45
+
46
+ class MeanReversion(Strategy):
47
+ id = "mean_reversion"
48
+ label = "Mean Reversion"
49
+ version = "1.0.0"
50
+
51
+ @on.tick("EQ:US:AAPL")
52
+ def on_tick(self, ctx, tick):
53
+ while25.log(f"last {tick['ltp']}")
54
+ ```
55
+
56
+ **The package is the API.** Inside a running module, `while25.log`,
57
+ `while25.candles`, `while25.buy`, `while25.subscribe`, `while25.ui.push` and
58
+ the rest act on the module the terminal is running — there is one module per
59
+ process, so nothing has to be passed around. The `ctx` a handler receives is
60
+ the same object, kept for the explicit style and for tests. Shorten the name
61
+ yourself if you like: `import while25 as w25`. While a module runs,
62
+ `dir(while25.orders)` (or `.data`, `.portfolio`, `.market`, `.chart`, `.viz`,
63
+ `.ai`) lists that name's calls.
64
+
65
+ A tick carries `symbol`, `ltp`, `bid`, `ask`, `timestamp_ms` and `as_of` (when
66
+ While25 last saw data for the instrument). `bid`, `ask`
67
+ and `timestamp_ms` are `None` when the venue has not sent them — never `0`.
68
+ IBKR delivers bid and ask as separate updates, so one side is routinely
69
+ absent on a given tick; test for `None` before comparing.
70
+
71
+ Four kinds, one shape. They differ only in what they may emit and how the
72
+ terminal presents them — **not** in what wakes them:
73
+
74
+ | Kind | For |
75
+ |---|---|
76
+ | `Strategy` | Something that trades |
77
+ | `Indicator` | Something drawn on the chart |
78
+ | `Monitor` | Something that watches and notifies |
79
+ | `App` | Something with its own panel: a strategy's desk is one |
80
+
81
+ ## What can wake a module
82
+
83
+ ```python
84
+ @on.tick("EQ:US:AAPL") # every tick, uncoalesced
85
+ @on.bar("EQ:US:AAPL", "5m") # each closed bar of that interval (hours="eth": the full session)
86
+ @on.bar(aapl) # the same, for a Bars line the class declares (see "Bars")
87
+ @on.schedule(every="10m") # a cadence — no market data needed
88
+ @on.signal("rebalance") # another module's while25.emit()
89
+ @on.signal("dip_ok", sender=DipWatch) # that signal from that one module only
90
+ @on.order(tag="mine") # order lifecycle events tagged "mine" (account-wide — see below)
91
+ @on.fill(tag="mine") # the same stream, narrowed to executions
92
+ @on.news("EQ:US:AAPL") # each live news article on that symbol (needs a news vendor)
93
+ ```
94
+
95
+ A symbol known only once the module runs — one picked in its settings, or an
96
+ option `while25.option()` named — cannot go in a decorator: the decorators are
97
+ read from the file when it is saved, before any setting has a value. Turn its
98
+ prices on while running and name the method its ticks call:
99
+
100
+ ```python
101
+ def on_start(self, ctx):
102
+ self.coin = while25.params["coin"] # a Symbol setting
103
+ while25.subscribe(self.coin, on_tick=self.on_coin)
104
+
105
+ def on_coin(self, ctx, tick): # every tick of that coin
106
+ ...
107
+ ```
108
+
109
+ Each tick of that symbol then calls `on_coin(ctx, tick)`, exactly as an
110
+ `@on.tick` line for it would. See "Live market data" below for the rules. Bars
111
+ have no such call: `@on.bar` takes a symbol written in the file. Where the
112
+ choice is a short list known in advance (NIFTY or BANKNIFTY), write a line for
113
+ each and read the setting inside the handler.
114
+
115
+ **What each handler receives.** `@on.tick`: `(ctx, tick)`, the tick dict
116
+ above. `@on.bar`: `(ctx, bar)` with `symbol`, `interval`, `hours` (`""` for
117
+ the regular session, `"eth"` for the full one), `time_ms` (the bar's start),
118
+ `open`, `high`, `low`, `close` and `volume` — closed bars only, never the one
119
+ still forming. `@on.schedule`: `(ctx)`. `@on.signal`: `(ctx, payload)`.
120
+ `@on.order` / `@on.fill`: `(ctx, ev)`, the event dict under Orders.
121
+ `@on.news`: `(ctx, article)`, a row as `news()` returns them.
122
+
123
+ `@on.bar(symbol, interval, hours=None)` takes the chart's intervals and the
124
+ session in an order's word: left out, the venue's regular session (futures
125
+ included); `"eth"`, the full session. `"rth"` is refused. A regular and an
126
+ `"eth"` line on one symbol are two series, each delivered to its own
127
+ handler. An interval or session While25 cannot serve for that
128
+ instrument is refused `BAD_INTERVAL` / `BAD_HOURS` as a warning on the
129
+ module, which runs on with the rest.
130
+
131
+ `@on.schedule(every=...)` takes `"250ms"`, `"5s"`, `"10m"`, `"2h"`. The check
132
+ runs once a second, so nothing fires finer than that; a handler held up past
133
+ a period (a long `history_span()`) runs once and resumes its cadence, not
134
+ once per missed period. `cron=` and `tz=` are not implemented: a schedule
135
+ with no `every=` is refused at registration, like `@on.position`.
136
+
137
+ `@on.order` and `@on.fill` take `tag=` and `symbol=`, each an exact match;
138
+ left out, every event on the account. `@on.signal(name, sender=None)` wakes
139
+ on `while25.emit(name, payload)` from another running module. `sender` names
140
+ the one module the handler listens to, by its class or its id
141
+ (`sender=DipWatch`, `sender="dip_watch"`): that signal from any other module
142
+ does not reach it. Which signals reach a module that trades at all is under
143
+ `while25.emit` in "Start and stop".
144
+
145
+ **Not deliverable:** `@on.position`. Nothing publishes position changes to
146
+ this runtime, so a module declaring one is **refused at registration** with a
147
+ message saying so. That is deliberate: it used to register, report `running`,
148
+ and never fire, which is indistinguishable from a strategy whose logic is
149
+ wrong. (Bar, order and fill delivery went the same way once: declarable before
150
+ they were deliverable. They are deliverable now; the refusal is the rule that
151
+ keeps a registered module one that will actually wake.)
152
+
153
+ A module may declare several, or none. A module with a `run()` method has it
154
+ called once, after `on_start`, on the module's one executor thread — the
155
+ escape hatch for anything the declarative surface does not cover. Nothing
156
+ else of the module runs while `run()` runs (no handler, no schedule), so a
157
+ `run()` that loops checks `while25.alive()` each pass and returns when it is
158
+ False: that is the moment the terminal asked the module to stop, and a loop
159
+ that goes on is ended with the process two seconds later. A module with
160
+ neither a subscription nor `run()` is refused at registration: nothing could
161
+ ever wake it.
162
+
163
+ **A class built on another.** A module may subclass one of your own, and a
164
+ method the child writes again replaces the parent's:
165
+
166
+ ```python
167
+ class Fast(MeanReversion):
168
+ id = "mean_reversion_fast"
169
+
170
+ @on.tick("EQ:US:AAPL") # tagged again: this tag is the one that counts
171
+ def on_tick(self, ctx, tick):
172
+ ...
173
+ ```
174
+
175
+ - Tagged again, the child's tag replaces the parent's for that method, so it
176
+ is called once per event, on what the child's tag says.
177
+ - Written again with no tag, it keeps the parent's tag and is the method that
178
+ runs.
179
+ - A method the child does not write is inherited as it is. So are `inputs`,
180
+ `monitors` and `Bars` lines; a child that declares a `Bars` line again
181
+ under the same name moves the handlers on that line with it.
182
+
183
+ ## Start and stop
184
+
185
+ `on_start(ctx)` runs first, on the module's own thread, before any handler:
186
+ the module reads `starting` until it returns, so a long fetch there (a
187
+ `warmup()`, see "Warm-up") delays nothing but the module's own first decision.
188
+ A raise in it puts the module in `error` with the message, and nothing of it
189
+ runs.
190
+
191
+ `on_stop(ctx)` runs once when the module is stopped: by its Stop, a stop on
192
+ its panel, a restart of its code, or the app closing. A crash or a kill of
193
+ the process runs none of it. From the moment the Stop arrives,
194
+ `while25.alive()` reads False, handlers still waiting are skipped (the log
195
+ says how many), and every order call — `buy`, `sell`, `place`, `bracket`,
196
+ `combo`, `cancel`, `modify`, `square_off` — raises `While25Error` with code
197
+ `MODULE_STOPPING` and is not to be retried: the trader's Stop decides what
198
+ happens to the module's orders. `on_stop` may log, save its own files and
199
+ read what the module holds (`while25.portfolio.my_positions()`,
200
+ `while25.orders.mine()`); it has two seconds before the process is ended,
201
+ finished or not, and a raise in it is logged, never a halt.
202
+
203
+ **When the computer sleeps, nothing runs.** No price or bar reaches a module,
204
+ no order goes out, and While25's held stops cannot act: a stop whose
205
+ level was crossed meanwhile fires late, on the first price after waking (a
206
+ stop the broker holds goes on working). On waking the module goes on with the
207
+ prices that come now; it is not stopped. Its log says how long the computer
208
+ was asleep ("The computer was asleep from 10:02 to 11:15 (73 min): no prices
209
+ or bars reached this strategy, ..."), the app shows the same notice, and the
210
+ bars it missed are not delivered after the fact.
211
+
212
+ `while25.emit("name", payload)` publishes a signal. Delivery is fire-and-forget to
213
+ **running** subscribers only: nothing queues, nothing replays, and a signal with
214
+ no listener is a no-op rather than an error. A publisher must not need to know
215
+ who is listening.
216
+
217
+ What reaches a module that trades (a `Strategy`, or an `App` that imports
218
+ one) depends on who sent it. A module that does not trade hears every signal.
219
+
220
+ | Sent by | Reaches a module that trades |
221
+ |---|---|
222
+ | a `Strategy` or a trading `App` you deployed from the app | yes |
223
+ | a `Monitor` | only when that module was deployed with the monitor box ticked |
224
+ | a strategy's own desk | its own strategy only (its buttons) |
225
+ | any other `App` that does not trade, an `Indicator` | never |
226
+ | anything else: a script started any other way than from the app, one that is not running | never |
227
+
228
+ A monitor a strategy lists as its own (`monitors = [DipWatch]`) signals that
229
+ strategy and no other module that trades (see "A monitor inside a strategy").
230
+ A signal that is held back is said once in the sender's log. A strategy that
231
+ acts on an indicator works it out itself, from its own bars (see "An
232
+ indicator's numbers in a strategy"). A handler with `sender=` hears only the
233
+ module it names, and only when the table lets that module through.
234
+
235
+ ## Typed inputs
236
+
237
+ ```python
238
+ import while25
239
+ from while25 import Strategy
240
+ from while25.inputs import Float, Int, Symbol
241
+
242
+ class Breakout(Strategy):
243
+ id = "breakout"
244
+ inputs = [
245
+ Int("length", default=20, minimum=2, maximum=200),
246
+ Float("threshold", default=1.5),
247
+ Symbol("instrument"),
248
+ ]
249
+
250
+ def on_start(self, ctx):
251
+ self.length = while25.params["length"]
252
+ ```
253
+
254
+ Import the types directly rather than `from while25 import inputs` — inside a
255
+ class body the `inputs` attribute shadows the module, so `inputs.Int` would
256
+ raise `NameError`.
257
+
258
+ The terminal renders these as a configuration form and validates before your
259
+ code runs. On a strategy the form is part of the "Deploy LIVE — real money"
260
+ window: one field per input, in the order declared, each filled with what was
261
+ last entered for it on this machine, else its default.
262
+
263
+ A `Symbol` input is a search box over the same instruments the terminal's own
264
+ search finds (a continuous futures series is left out: no order can be placed
265
+ on one); its value is the instrument key picked, and `while25.params[name]`
266
+ reads it once the module runs. Declare as many as you need — each is its own
267
+ field, read by its own name. Because the value only exists once the module
268
+ runs, a module that watches it turns its prices on with
269
+ `while25.subscribe(key, on_tick=...)`, never with `@on.tick` (see above).
270
+
271
+ Six types: `Int(name, default, minimum, maximum, step)`, `Float(...)` the
272
+ same, `Bool(name, default=False)`, `Str(name, default="")`, `Enum(name,
273
+ choices=[...], default)` and `Symbol(name)`. Every one takes `label=`, the
274
+ field's name on the form (the key when left out); `Int` and `Float` take
275
+ `step=`, the increment the form steps by. A default outside its own bounds, or
276
+ not among its choices, is refused when the class is declared. Values arrive
277
+ typed: `while25.params["length"]` is an `int`, and a value the form could not
278
+ coerce or that is out of range fails the start, naming the input, before your
279
+ code runs.
280
+
281
+ ## Market data
282
+
283
+ ```python
284
+ bars = while25.candles("EQ:US:AAPL", "5m", limit=200) # newest 200, LIVE series
285
+ old = while25.historical("EQ:US:AAPL", "1D", # a real vendor pull
286
+ start="2024-01-01")
287
+ today = while25.intraday("EQ:US:AAPL", "5m") # today, from the vendor
288
+ q = while25.quote("EQ:US:AAPL") # None if unknown
289
+ ```
290
+
291
+ `candles(..., source=)` picks **which store** the bars come from, and the three
292
+ are different questions rather than fallbacks for one another:
293
+
294
+ | `source` | Reads | Raises when |
295
+ |---|---|---|
296
+ | `"live"` (default) | the in-memory series a chart or `@on.bar` is filling — **never fetches** | `NO_SERIES`, when nothing is watching that symbol and interval yet |
297
+ | `"historical"` | a real vendor pull, cached; intraday intervals within a bar budget (below) | `NO_DATA` / `BAD_RANGE` |
298
+ | `"intraday"` | today's bars from the vendor, no cache | `UNSUPPORTED_INTERVAL` outside 1m/5m/15m/30m/1h |
299
+
300
+ An interval While25 does not know (`"7m"`) is refused `UNKNOWN_INTERVAL`
301
+ on every source, never read as another. An **indicator does not call
302
+ `candles()` at all**: it receives the chart's own series as `while25.bars`
303
+ (see Indicators), and `source="live"` inside `compute()` raises
304
+ `LIVE_IN_COMPUTE`, because a second series drifts from the one drawn under
305
+ the plot with nothing to notice. `"live"` is for a strategy or an app reading
306
+ the series a chart, or its own `@on.bar` line, is filling. An analysis script
307
+ with no chart open wants `"historical"`; a backtest wants `history_span()`
308
+ (below), which has no bar budget.
309
+
310
+ `start`/`end` are ISO dates and apply to `"historical"` only. `start` is
311
+ honoured: While25 walks as many vendor requests as the range takes, back
312
+ to the history floor (2012) and, for an intraday interval, within a budget of
313
+ 25,000 bars counted back from `end`. A start it could not reach is logged on
314
+ the module as a warning naming the date the answer really starts from, and
315
+ the rows carry it as `.effective_start` and why as `.note` ("" when the answer
316
+ covers the window). The budget is this call's limit, never the vendor's depth:
317
+ `history_span()` fetches every bar of the window. The rows also carry `.session`
318
+ (`"regular"` or `"full"`) and `.adjustment` (`"raw"`, `"split"`, or `None`
319
+ where the vendor states nothing — never read `None` as raw). A data call that
320
+ gets no answer within 30 seconds raises `TimeoutError`.
321
+
322
+ `while25.history(...)` still works and is exactly `candles(..., source="live")`.
323
+ (`while25.data.*` is the same surface under its namespace.)
324
+ It is deprecated: the name promised a fetch it never performed, which is what
325
+ made people expect vendor data from it.
326
+
327
+ `quote()` returns `None` when the terminal has no data for that symbol — `0.0`
328
+ is a real price, and a strategy that cannot tell "no data" from "worthless"
329
+ will act on the difference.
330
+
331
+ A quote carries `symbol`, `ltp`, `bid`, `ask`, `open`, `high`, `low`,
332
+ `prev_close`, `volume`, `time` (the venue's stamp), `as_of` (when While25
333
+ last saw data for it) and `market_open` (`True`, `False`, or `None` when it
334
+ cannot say); every figure is `None` until seen, never `0`. `ltp` is the last
335
+ TRADED price: `None` until the instrument has traded in what the terminal
336
+ holds, even when it already has a bid and an ask for it. `quotes([...])`
337
+ answers one entry per symbol asked, in that order, `None` where there is no
338
+ data.
339
+
340
+ A `candles(source="historical")` call whose vendor fetch fails raises
341
+ `IO_ERROR` with the vendor's failure, even when earlier bars are cached: they
342
+ are never handed back as the answer the vendor did not give. Ask again.
343
+
344
+ ### A whole span of history
345
+
346
+ `candles(source="historical")` reads what the vendor serves in one call. For a
347
+ whole span, every bar between two dates, use `history_span()`:
348
+
349
+ ```python
350
+ r = while25.history_span("EQ:US:AAPL", "5m", "2024-01-02", "2024-06-28")
351
+ bars = r["bars"] # the rows candles() returns, plus "regular"
352
+ r["missing_days"] # ["2024-03-11", ...]: trading days with no bar
353
+ ```
354
+
355
+ The interval is one of `1m`, `5m`, `15m`, `30m`, `1h`, `1D`, `1W`, `1M`; the
356
+ other spellings While25 takes (`1d`, `1440`, `DAILY`, `60`, ...) come back
357
+ under that name.
358
+
359
+ While25 fetches exactly that window on a worker of its own, request by
360
+ request at the vendor's pace (a chart always goes first), with no cap that cuts
361
+ it short. Nothing is cached on disk: a window that has fully closed (its end
362
+ before the exchange's today) is kept in memory for While25's session, and
363
+ the same span asked again comes back from it with `r["vendor_requests"] == 0`
364
+ and a line in `r["vendor_notes"]` that says "served from memory". A window
365
+ still open is fetched every time. A refusal comes back in the vendor's own
366
+ words, as a `While25Error` with While25's code (`TOO_WIDE`, `VENDOR_PACING`,
367
+ `PERMISSION`, `NOT_SUPPORTED`, ...). It BLOCKS until the span is in, which takes
368
+ minutes on a paced vendor: call it from `on_start`, a schedule or a one-shot
369
+ run, never from a tick handler. Each request shows in the module's log
370
+ (`history EQ:US:AAPL 5m: fetching history, part 3 of about 12`; `waiting, a chart
371
+ is loading its history first` while charts go first; `waiting its turn, 2 fetches
372
+ ahead` while another module's fetch or a backtest runs — While25 fetches
373
+ one span at a time), and a Stop of the module stops the fetch (`CANCELLED`).
374
+ One span at a time per module: a second call while one is under way is
375
+ refused `BUSY`. A span that reports nothing for 180 seconds is given up
376
+ (`TIMEOUT`), and so is one still running after 30 minutes. A walk the vendor
377
+ stopped short raises with the vendor's words; its partial bars are not
378
+ returned.
379
+
380
+ `hours="eth"` and `adjust="split"` work as on `candles()`; so does `price="mark"`
381
+ (a Binance USD-M futures contract's mark candles, no volume; `UNSUPPORTED_PRICE`
382
+ elsewhere; left out, the last trade). The answer also
383
+ says `session`, `adjustment`, `covered_from` / `covered_to` (the dates it
384
+ covers), `first_bar_ms` (the first bar's time; `None` with no bars),
385
+ `vendor`, `vendor_requests`, `vendor_notes` (stretches the vendor said
386
+ held nothing) and `calendar`, the exchange calendar the instrument trades on
387
+ (`"XNYS"`, `"XBOM"`, `"CMES"`, `"24/7"`; `""` when none is known).
388
+ `missing_days` lists the finished trading days of that calendar inside the
389
+ covered dates that have no bar: whole days only, `None` when no calendar is
390
+ known. Weekly and monthly series are not checked.
391
+
392
+ A span cut short (`TOO_WIDE` mid-walk, `VENDOR_PACING`, a vendor refusal) raises
393
+ `While25Error` whose `.answer` holds the partial answer: the bars it got, with
394
+ `covered_from` / `covered_to`, to inspect. It has no `id`, so a backtest can
395
+ never be sealed on it. If the call outlives its 30-minute wait it raises a plain
396
+ `TimeoutError` instead and the walk is cancelled at While25.
397
+
398
+ ### Bars: a bar line the module keeps
399
+
400
+ ```python
401
+ from while25 import Bars, Strategy, on
402
+
403
+ class Breakout(Strategy):
404
+ id = "breakout"
405
+ aapl = Bars("EQ:US:AAPL", "5m", keep=200)
406
+
407
+ @on.bar(aapl)
408
+ def on_bar(self, ctx, bar):
409
+ high = max(self.aapl.closes[:-1]) # the 199 closes before this bar
410
+ ...
411
+ ```
412
+
413
+ `Bars(symbol, interval, *, hours=None, keep=200)` declares a bar line on the
414
+ class and keeps its bars:
415
+
416
+ - It is the line's subscription: no separate `@on.bar(symbol, interval)`.
417
+ - At start it holds its last `keep` finished bars before `on_start` runs,
418
+ fetched by a warm-up with every check under "Warm-up" below. A refusal
419
+ fails the start with its reason.
420
+ - Each closed bar is added before any handler runs, and the oldest dropped
421
+ past `keep`.
422
+
423
+ `keep`: 1 to 10,000. `hours="eth"`: the full session. Intervals: 1m, 5m, 15m,
424
+ 30m, 1h, 1D, 1W, 1M; another is refused when the file is saved (use
425
+ `@on.bar(symbol, interval)` and keep the bars yourself). `@on.bar(line)`
426
+ wakes a handler on the line's bars; with no handler the line is still kept,
427
+ for a tick handler to read. Any kind of module may declare lines.
428
+
429
+ On the module, `self.aapl` is the line:
430
+
431
+ | | |
432
+ |---|---|
433
+ | `self.aapl.rows` | the bars, oldest first, each as an `@on.bar` handler receives it |
434
+ | `self.aapl.last` | the newest finished bar, `None` before there is one |
435
+ | `self.aapl.closes` | every bar's close, oldest first |
436
+ | `len(self.aapl)`, `self.aapl[-1]`, `for bar in self.aapl` | as on a list |
437
+ | `self.aapl.indicator(cls, *, forming=False, **params)` | an indicator worked out from these bars (see "An indicator's numbers in a strategy") |
438
+
439
+ Read `rows`; While25 writes it.
440
+
441
+ ### Warm-up: the history a strategy decides from
442
+
443
+ A `Bars` line does all of this for you. `warmup()` is the same fetch by hand,
444
+ for a module that keeps its bars in its own way:
445
+
446
+ ```python
447
+ class Breakout(Strategy):
448
+ id = "breakout"
449
+
450
+ def on_start(self, ctx):
451
+ bars = while25.warmup("EQ:US:AAPL", "5m", 200) # the 200 bars before now
452
+ self.closes = [b["close"] for b in bars]
453
+
454
+ @on.bar("EQ:US:AAPL", "5m")
455
+ def on_bar(self, ctx, bar):
456
+ self.closes.append(bar["close"]) # carries on from the warm-up
457
+ ...
458
+ ```
459
+
460
+ A strategy that computes on bars (a 20-bar average, an RSI) needs the bars
461
+ before its first one. `warmup(symbol, interval, bars, hours=None)` gives the
462
+ last `bars` finished bars of one of the strategy's **own `@on.bar` lines**,
463
+ written as the line writes them (`hours="eth"` for an `"eth"` line); with no
464
+ such line it raises `ValueError`. Intervals: 1m, 5m, 15m, 30m, 1h, 1D, 1W,
465
+ 1M; `bars` 1 to 10,000. To have an indicator do the computing, hand it these
466
+ bars: see "An indicator's numbers in a strategy".
467
+
468
+ It is fetched the way a backtest's history is — While25's history
469
+ service, no cache, the vendor's own refusal — back from now until it holds
470
+ the bars, and checked before it is handed on:
471
+
472
+ - **Every trading day is there.** A trading day of the instrument's exchange
473
+ calendar with no bar inside the warm-up refuses (`MISSING_DAYS`, naming the
474
+ days); a weekly or monthly line, a whole week or month. An instrument with
475
+ no exchange calendar known has days nobody can check, and refuses too
476
+ (`NO_CALENDAR`).
477
+ - **Nothing unfinished.** A bar still forming is left out.
478
+ - **Enough of it.** Fewer than `bars` finished bars refuses
479
+ (`NOT_ENOUGH_HISTORY`, saying how many there are) — after one wider fetch,
480
+ since how far back the first may go is worked out before the calendar is
481
+ known.
482
+ - **It joins the live bars.** Where the line's live series and the warm-up
483
+ both hold bars, they are the same bars (`WARMUP_JOIN` names the first live
484
+ bar the history lacks: another bar grid, or a bar the vendor lost), and no
485
+ bar that finished before the line was attached is missing from both
486
+ (`WARMUP_JOIN`: the vendor had not published it yet — deploy again in a
487
+ moment).
488
+
489
+ Call it in `on_start`: the strategy reads `starting` until it returns, and
490
+ nothing of it runs meanwhile. On an intraday line it first waits until 15
491
+ seconds after the line was attached, so the vendor has published the bar
492
+ that finished as the strategy started (that bar is never delivered live).
493
+ Each vendor request shows in the module's log,
494
+ and so in the last-log cell of its row in Live strategies; a Stop stops the
495
+ fetch, and the strategy ends stopped. Let a refusal raise: the start fails
496
+ with the reason, and the strategy never decides on history nobody checked.
497
+ The vendor's own codes come through as on `history_span()` (`TOO_WIDE`,
498
+ `VENDOR_PACING`, `PERMISSION`, `TIMEOUT`, `CANCELLED`, ...), and one span runs
499
+ at a time per module, a `history_span()` included (`BUSY`).
500
+
501
+ The rows have an `@on.bar` bar's keys — `symbol`, `interval`, `hours`,
502
+ `time_ms`, `open`, `high`, `low`, `close`, `volume` — so one piece of code can
503
+ read both, and the list carries `.session`, `.adjustment`, `.vendor` and
504
+ `.calendar`. A live bar the warm-up already gave (one that finished while it
505
+ fetched) is not delivered to the line's handlers again. The first live bar
506
+ after it is checked once more against the live series; a bar between the two
507
+ that reached the strategy neither way halts it with the reason (phase
508
+ `warmup`) before the handler runs.
509
+
510
+ ### News
511
+
512
+ ```python
513
+ rows = while25.news("EQ:US:AAPL", start="2026-08-01", limit=20) # oldest first
514
+ rows.truncated # True: the page cap was hit, older articles may exist
515
+ rows.errors # {instrument_key: "FAILED" | "PARTIAL"}: a vendor fetch that fell over
516
+ ```
517
+
518
+ `news(symbols, start=, end=, source=, limit=)` answers from the same news
519
+ path the terminal's news panel reads. `symbols` is one symbol or a list of up
520
+ to 10; `start` / `end` are ISO dates or epoch milliseconds, `end` inclusive to
521
+ the end of its day; `source` names one outlet; `limit` caps articles per
522
+ symbol (50 by default, 200 at most). Each row has `symbol`, `time_ms`,
523
+ `title` and `url` always, and `author`, `excerpt`, `body`, `source`,
524
+ `sentiment`, `sentiment_score`, ... only when the vendor sent them (an absent
525
+ field is an absent key), plus `in_market_hours` (`True` / `False` / `None`).
526
+ With no news vendor configured it raises `NO_PROVIDER` rather than returning
527
+ an empty list. `@on.news("EQ:US:AAPL")` delivers each live article the same
528
+ way, one handler call per article; with no news vendor the line is accepted
529
+ and never fires.
530
+
531
+ ### Index members
532
+
533
+ ```python
534
+ while25.universes() # ["banknifty", "ndx100", ...]
535
+ while25.universe("ndx100") # [{"symbol", "name", "canonical_id"}, ...]
536
+ while25.universe_info("ndx100") # index, name, country, as_of, source, count
537
+ ```
538
+
539
+ Dated reference data from the terminal's own constituent registry, read from
540
+ a file with no round trip. An index it does not hold raises `ValueError`
541
+ naming the ones it does — never an empty list.
542
+
543
+ ## Open data
544
+
545
+ Public filings and registers (SEC today), live from the source and never cached,
546
+ through the same registry the AI reads.
547
+
548
+ ```python
549
+ while25.data.catalog("filings") # [{"id", "category", "description", "markets"}]
550
+ while25.data.describe("sec.company_filings") # params with choices, result columns
551
+ df = while25.data.fetch("sec.company_filings", symbol="AAPL")
552
+ df.attrs["dataset_id"] # "ds_..."; the AI sees the same id
553
+ df.attrs["provenance"] # provider, command, params, hosts, fetched_at
554
+ while25.data.get("ds_...") # a dataset fetched earlier this session
555
+ ```
556
+
557
+ Dates come back as `datetime.date`. A refusal raises `While25Error` whose `.code`
558
+ says why: `AMBIGUOUS` (the symbol matches several companies; the message lists
559
+ them), `CONTACT_REQUIRED` (SEC needs a contact email, taken from your
560
+ While25 account, and none is available yet), `INVALID_PARAMS`, `NOT_FOUND`, `NOT_COVERED`, `UNKNOWN_COMMAND`,
561
+ `DATASET_EVICTED`, `FETCH_FAILED` (the message carries `retry_after_s` when the source said),
562
+ `TOO_LARGE` (the dataset is too big to hand over whole; it is kept: read it in pages
563
+ with `while25.data.get(id, offset=, limit=, columns=, filter=)`). Outside the
564
+ desktop app these calls raise `RuntimeError`.
565
+
566
+ ## Your own files and packages
567
+
568
+ The workspace is a real directory, and your module runs with it as the working
569
+ directory. Relative paths are relative to it:
570
+
571
+ ```
572
+ <workspace>/
573
+ ├── indicators/ strategies/ monitors/ apps/ your modules
574
+ ├── data/ files you drop in
575
+ ├── lib/ packages you pip install
576
+ └── requirements.txt
577
+ ```
578
+
579
+ ```python
580
+ import pandas as pd
581
+
582
+ df = pd.read_csv("data/straddles.csv") # a file you dropped in
583
+ df.to_parquet("data/straddles.parquet") # and one you write back
584
+ ```
585
+
586
+ Drop files onto the **workspace** drawer in the Code panel and they land in
587
+ `data/`. A name that already exists is suffixed rather than replaced — silently
588
+ overwriting a file a running script is reading would change its results with
589
+ nothing to notice.
590
+
591
+ **numpy and pandas ship with the terminal.** Anything else is yours to install,
592
+ from the same drawer or by listing it in `requirements.txt`. Packages go to
593
+ `lib/`, which is on `sys.path` ahead of the bundled ones — so a version you pin
594
+ wins, rather than your install quietly doing nothing. `lib/` belongs to the
595
+ installer: saving, deleting, moving or creating anything in it by hand is
596
+ refused ("lib/ is managed by the package installer — install or remove
597
+ packages instead"). Install before you deploy: while a strategy or trading App
598
+ runs, packages can't change.
599
+
600
+ The workspace is the unit that moves. On a cloud machine it is a mounted
601
+ volume, so every path above means the same thing there as it does locally.
602
+
603
+ ## Live market data: a module is its own subscriber
604
+
605
+ A module is its own subscriber, like a chart or a watchlist row. When it
606
+ starts, While25 takes a subscription per instrument it declared
607
+ (`@on.tick`, `@on.bar`) that lasts exactly as long as the module runs —
608
+ whoever else holds the same instrument — and stopping the module releases
609
+ them. What While25 cannot give (over the plan's limit on live
610
+ instruments, `SUB_CAP`; no vendor for the key, `NO_VENUE`; a bar interval or
611
+ session it cannot serve, `BAD_INTERVAL` / `BAD_HOURS`) does not stop the
612
+ module: it runs with the keys it did get, and the refusal shows as a warning
613
+ on it (Live strategies shows it as its last error).
614
+
615
+ ```python
616
+ while25.subscribe("IDX:IN:BANKNIFTY") # ask for one more at runtime; True, or
617
+ # SubscriptionError with the refusal code
618
+ while25.subscribe("IDX:IN:BANKNIFTY", on_tick=self.on_bank) # ...and call on_bank per tick
619
+ while25.unsubscribe("IDX:IN:BANKNIFTY") # its prices, and the calls, end together
620
+ while25.market.is_open("IDX:IN:NIFTY") # True / False / None (cannot be placed)
621
+ ```
622
+
623
+ A key turned on at runtime gets its live prices exactly as a declared one
624
+ does. Without `on_tick=` nothing is called for them — `quote(key)` reads the
625
+ latest. With it, every tick calls that method, as an `@on.tick` line would:
626
+
627
+ - `on_tick=` takes one of the strategy's **own methods** (`self.on_bank`). A
628
+ plain function, a lambda or another object's method raises `TypeError`, and
629
+ nothing is subscribed: the tick calls its handler by name on the strategy.
630
+ - Subscribing the same key again with another method replaces the first.
631
+ `unsubscribe(key)`, the strategy's stop or a halt ends the calls.
632
+ - A key both declared in an `@on.tick` line and named at runtime with the same
633
+ method is called once per tick, never twice.
634
+ - It works from `on_start` (the usual place for a symbol a setting named),
635
+ from any handler, and from `run()`.
636
+ - `SubscriptionError` is raised only for what While25 refuses at once:
637
+ code `NOT_RUNNING` (the module is stopping or stopped) or `BAD_REQUEST`
638
+ (not a key). While25's own refusals — over the plan's limit, no vendor
639
+ for the key — come back as a warning on the module (Live strategies shows
640
+ it as its last error) while it keeps running with the keys it did get; the
641
+ call itself returned True. False means the terminal could not be reached.
642
+
643
+ Every tick and quote carries `as_of` — While25's arrival time — so a
644
+ script can tell a fresh price from a stale one instead of guessing. A quote's
645
+ `open`, `high`, `low`, `prev_close` and `volume` are `None` until the
646
+ engine has actually seen them (a vendor that sends them as separate ticks
647
+ leaves each unknown until its own tick lands) — never a 0 standing in for a
648
+ price. `historical(..., start=)` is honoured back to the history floor
649
+ (2012); a clamped start is logged as a warning.
650
+
651
+ ## Orders
652
+
653
+ The full broker surface, not a curated subset:
654
+
655
+ ```python
656
+ while25.buy("EQ:US:AAPL", 10)
657
+ while25.sell("EQ:US:AAPL", 10, order_type="LMT", price=195.0)
658
+
659
+ while25.bracket("EQ:US:AAPL", "BUY", 10,
660
+ take_profit=210.0, stop_loss=190.0)
661
+
662
+ # entry plus a stop, no target: the stop is armed when the entry fills
663
+ while25.buy("EQ:US:AAPL", 10, stop_loss=190.0)
664
+
665
+ # a trailing stop: follows the price 2.50 below it, sells when price turns back
666
+ while25.sell("EQ:US:AAPL", 10, order_type="TRAIL",
667
+ trail_amount=2.5, reduce_only=True)
668
+
669
+ while25.place("EQ:US:AAPL", "BUY", 10, order_type="STP",
670
+ trigger_price=189.0, product="intraday", validity="ioc")
671
+
672
+ # a cash amount instead of a share count — sent to the broker as the amount,
673
+ # where its venue takes one (Alpaca: a stock it trades in fractions)
674
+ while25.buy("EQ:US:AAPL", amount=5000)
675
+
676
+ # the same calls live under while25.orders.* too
677
+ ```
678
+
679
+ Order types: `MKT · LMT · STP · STP LMT · MIT · LIT · TRAIL` — the order
680
+ ticket's own names, written exactly so (`STP` a stop that fires a market
681
+ order, `STP LMT` a stop-limit, `TRAIL` a trailing stop); no other spelling is
682
+ accepted. The auction types `MOO · MOC · LOO · LOC` are
683
+ refused at once (below). Groups: `simple` (a plain order) and `basket` (a
684
+ bracket) — passing `stop_loss=` makes it a bracket without you naming the
685
+ group; `oco` and `oto` are refused `UNSUPPORTED`.
686
+
687
+ `product=` is the pocket the order opens in: `"delivery"` (the default),
688
+ `"intraday"`, `"margin"` or `"normal"`, as the connected broker takes them for
689
+ that market; anything else is refused `BAD_PRODUCT`. A protective order states
690
+ the same product as the position it protects. The rest of `place()`'s
691
+ arguments ride through to the broker where it takes them: `tag=` (at most 20
692
+ characters, on every event of the order), `idempotency_key=`, `symbol=`,
693
+ `disclosed_quantity=`, `is_amo=` (an after-market order on an Indian broker),
694
+ `slice=`, and the group fields `group=`, `group_id=`, `parent_order_id=` and
695
+ `linked_order_id=`.
696
+
697
+ **A bracket is an entry with a stop, and optionally a take-profit.** While25
698
+ holds the stop and arms it the moment the entry fills, sized to what filled and
699
+ grown with every later fill, whether or not your script is still running. It
700
+ ends through its own exits only: its take-profit, its stop, or a square off of
701
+ it (`while25.orders.square_off()`, below, or Square off on its line in the
702
+ Positions tab). An order of your own beside it is a separate order: a plain
703
+ sell closes nothing of the bracket, its stop and take-profit keep working, and
704
+ the next of them to fill opens a position the other way. The one exception is a
705
+ coin at a venue that takes its fees out of the holding without reporting them
706
+ per fill (Alpaca today): there a bracket follows the holding, and ends when the
707
+ coin is gone, however that happens.
708
+
709
+ - `stop_loss=` alone is "enter with a stop, exit on my own signal".
710
+ - `stop_loss=` with `take_profit=` adds a resting limit order for the profit;
711
+ whichever exit closes the position, the other is withdrawn.
712
+ - `take_profit=` alone is refused: it protects nothing, so it is not a bracket.
713
+ Place the entry, then a limit order to take the profit.
714
+ - `trail_amount=` on a bracket makes its stop trail the price at that distance.
715
+ It must be above 0: a trail of 0 or below is refused (`ValueError`), never
716
+ sent as a fixed stop.
717
+
718
+ If the stop cannot be set when the entry fills (the price is already through
719
+ its level, after a fast fill or a gap), nothing is closed for you: `@on.order`
720
+ hears a `REJECT` under the stop's id (below), carrying your `tag=`, order type
721
+ `STP`, and a reason that starts `the bracket's stop could not be set`. The
722
+ position is open with no stop and what to do about it is your script's decision.
723
+
724
+ **The bracket's stop has an order id of its own: the bracket's id followed by
725
+ `-SL`.** It is the same for the bracket's whole life, so you can move the stop,
726
+ or take it off, while keeping the position:
727
+
728
+ ```python
729
+ entry = while25.buy("EQ:US:AAPL", 10, stop_loss=190.0)
730
+ stop_id = entry["order_id"] + "-SL"
731
+
732
+ while25.orders.modify(stop_id, trigger_price=195.0) # move it, say to break-even
733
+ while25.orders.cancel(stop_id) # take it off; the position stays
734
+ ```
735
+
736
+ It answers once the entry has filled. Before that there is no stop yet, and the
737
+ call is refused `NOT_WORKING`. `@on.order` hears the stop under that id, with
738
+ your `tag=`:
739
+
740
+ | `ev["event"]` | when |
741
+ |---|---|
742
+ | `HELD` | it is set, on the entry's first fill; `ev["trigger_price"]` and `ev["quantity"]` are its level and size |
743
+ | `MODIFY` | it was moved, by you or from the chart, or the bracket re-sized it after a later fill of the entry |
744
+ | `MODIFY_REJECT` | a change was refused and it waits as it was; `ev["reason"]` says why |
745
+ | `NOTICE` | the broker's word about a working order it keeps as it is (IBKR: an order marked ETH is worked in regular hours only, its message 2109); `ev["reason"]` says what |
746
+ | `CANCEL` | it ended without firing: you cancelled it, or the position is gone |
747
+ | `REJECT` | it could not be set at all (above) |
748
+
749
+ Only the level is yours to change. `quantity=` is refused, because the stop is
750
+ always the size of the position it protects, and `price=` is refused, because it
751
+ fires at market. A trailing bracket stop's level cannot be moved: it follows the
752
+ price. A stop you cancel stays off: the bracket does not put it back when a
753
+ later fill arrives, and its take-profit, if it has one, keeps working. To put
754
+ protection back, place a stop of your own with `reduce_only=True`. When the
755
+ stop fires, the exit order it places arrives as `NEW` and then `FILL` under that
756
+ order's own id, not the stop's, carrying your `tag=`.
757
+
758
+ **To leave a bracket at a time you pick, square it off.** A time exit is the
759
+ usual case:
760
+
761
+ ```python
762
+ entry = while25.buy("FUT:US:MNQ:202612", 1, stop_loss=20950, take_profit=21100)
763
+ # ... at 15:55:
764
+ while25.orders.square_off(entry["order_id"])
765
+ ```
766
+
767
+ It does what Square off does on the bracket's line in the Positions tab: the
768
+ bracket's take-profit and stop come off first, then what it holds is closed at
769
+ market, and the bracket ends. It squares off only your own bracket, and only
770
+ once its entry has filled. It answers as soon as While25 has taken it,
771
+ with `{"ok": True, "square_off_id": ..., "bracket_id": ...}`. What the square off
772
+ then does arrives at `@on.order` as `SQUARE_OFF` events under the bracket's id,
773
+ with the bracket's `tag=`:
774
+
775
+ | `ev["status"]` | when |
776
+ |---|---|
777
+ | `WITHDRAWING` | the take-profit and stop are being taken off; the close goes out once they are |
778
+ | `SENT` | the market close went out: `ev["close_order_id"]` is its id, `ev["quantity"]` its size |
779
+ | `DONE` | it finished: the bracket is closed, or it had already ended; `ev["reason"]` says which |
780
+ | `REFUSED` | nothing was closed: `ev["reason"]` says why (the kill switch is on, the broker link is down, or the close itself was refused) |
781
+ | `STOPPED` | it stopped short of closing (a withdrawal was not confirmed in time, or the broker was detached); `ev["reason"]` says what the bracket still has |
782
+ | `INTERRUPTED` | a restart of the app cut it short |
783
+
784
+ The close's own order also arrives as `NEW` and then `FILL` under
785
+ `ev["close_order_id"]`, with no `tag=`. Refused at once, with nothing sent:
786
+ `NO_BRACKET` (no open bracket has that id), `NOT_ORDER_OWNER` (it is another
787
+ module's), `NOTHING_HELD` (its entry has not filled: cancel the entry instead)
788
+ and `MARKET_CLOSED` (its market cannot take the close now). It also works for a
789
+ bracket the broker holds.
790
+
791
+ **`validity=` is how long the order lives** (`day · gtc · ioc · fok · opg · cls`,
792
+ whichever the connected broker takes for that kind of instrument, and `gtt` for
793
+ a stop-limit Zerodha or Upstox holds: below). `opg` and
794
+ `cls` name the opening and the closing auction, so they go only on an order
795
+ sent straight to the broker (`MKT`, `LMT`, or a stop the broker holds):
796
+ a stop, stop-limit or if-touched order held here fires mid-session, when its
797
+ level is crossed, and is refused with them, and so is a bracket's `STP LMT` /
798
+ `STP` entry held here. Leave it
799
+ out and While25 uses the broker's normal one for the instrument: day almost
800
+ everywhere, `gtc` where there is no day order (crypto on Alpaca), and `ioc`
801
+ for an `MKT` order where the broker takes no other (crypto on IBKR: "MKT
802
+ Orders only support IOC"). A validity you state is sent as stated, and the
803
+ broker answers.
804
+
805
+ On a bracket, `validity=` is the **entry's** (checked against the same list).
806
+ The take-profit always goes out `gtc` where the broker offers it, so it does
807
+ not end at the close while the position is open; where the broker has no `gtc`
808
+ (Zerodha, Upstox) it goes out with the normal one and ends at the close.
809
+ The stop is held by While25 and never ends by time.
810
+
811
+ **`hours="eth"` asks for extended hours too:** pre-market and after-hours on a
812
+ US stock or ETF, sent to the broker with its extended-hours flag (IBKR
813
+ outsideRth, Alpaca extended_hours) — and on IBKR, Cboe's overnight session
814
+ (8:15pm to 9:25am New York) and its 4:15 to 5pm curb for the index options
815
+ that trade them (SPX, SPXW, XSP), any order type, IBKR answering for it.
816
+ Leave it out for regular hours. That is
817
+ the only choice — `"rth"` is **refused**, because on a future it changes
818
+ nothing (a futures order works every session the exchange runs, and a held
819
+ stop on a future already reacts to every price) and crypto never closes. So
820
+ `"eth"` means something on a stock, an ETF or such an index option only (a
821
+ stock or ETF option has no extended session, and Alpaca trades every option
822
+ in regular hours only); stated elsewhere it goes through and the broker
823
+ answers. A broker with no extended session (Zerodha,
824
+ Upstox) refuses it. A **market or limit order is sent as asked and the
825
+ broker answers** for it: Alpaca refuses an `"eth"` market order, and IBKR
826
+ answers one on a stock with its message 2109 (the flag "is ignored based on
827
+ the order type and destination") and works it in regular hours only. An order
828
+ While25 **holds** — a stop (`"STP"`, `"STP LMT"`), an if-touched order
829
+ (`"MIT"`, `"LIT"`), a trailing stop, a bracket's stop — is judged **at
830
+ placement** (`BAD_HOURS`), never when it fires, by what the broker works
831
+ outside regular hours on that kind of instrument: on Alpaca (every kind) a
832
+ **limit with `"day"` or `"gtc"`**, on IBKR stocks and ETFs a **limit**. There
833
+ an `"eth"` stop that would fire a market order (`"STP"`, `"MIT"`,
834
+ `"TRAIL"`, a bracket's stop) is refused, and on Alpaca an `"eth"`
835
+ stop-limit stating `"ioc"` / `"fok"` too: use a stop-limit (`"STP LMT"`), or leave
836
+ hours out. On a bracket `hours=` is the **whole bracket's**: the entry, the
837
+ take-profit and the stop.
838
+
839
+ **`MOO · MOC · LOO · LOC` are refused at once.** No broker here is sent an
840
+ auction order type. Where the broker takes the auction as a validity, the
841
+ refusal says how: on Alpaca shares, `order_type="MKT"` (or `"LMT"`) with
842
+ `validity="opg"` for the open or `"cls"` for the close.
843
+
844
+ **A bracket's entry is `MKT`, `LMT`, `STP LMT` or `STP`,** with exactly the
845
+ prices that shape takes; anything else is refused instead of being placed as a
846
+ different order. Its `tag=` rides onto the entry, the take-profit and the stop,
847
+ so `@on.fill(tag=...)` hears every one of them, and its `idempotency_key=` is honoured
848
+ like a plain order's: a retried bracket is refused `DUPLICATE_ORDER`, not
849
+ placed twice.
850
+
851
+ **A stop or an if-touched order is held by While25, unless you ask the broker to hold it** (`held_by="broker"`, below).
852
+ `STP LMT` (stop-limit: `trigger_price` and `price`), `STP` (stop-market), `MIT` and
853
+ `LIT` (market / limit if touched) wait inside While25 and go out as a plain
854
+ market or limit order when price reaches `trigger_price`. A stop rests on the
855
+ far side of the market (a SELL stop below it); an if-touched order rests on the
856
+ near side (a SELL touch above it, a BUY touch below). A trailing stop
857
+ (`order_type="TRAIL", trail_amount=2.5`) is held the same way: it
858
+ follows the price at that distance and goes out as a market order when price
859
+ turns back by it. Held by While25, the distance is a price amount, never a
860
+ percentage, and a trailing stop takes no `trigger_price=` or `price=` of its
861
+ own; held by the broker (below) it takes the broker's own terms.
862
+
863
+ **On Binance (spot and futures) While25 holds no `STP LMT` or `LIT`:**
864
+ Binance judges a limit's price band when the order arrives, so the limit could
865
+ be refused when it fires. Refused `INVALID_PARAMETERS`, nothing placed: use
866
+ `STP`, or on spot a `STP LMT` with `held_by="broker"`. A bracket's `STP LMT`
867
+ entry is unchanged.
868
+
869
+ On its own such an order is an **entry**: it fires at its level whatever you
870
+ hold, so a stop left behind a position you have since closed opens a new
871
+ position the other way. Say it is protection and it behaves like protection:
872
+
873
+ ```python
874
+ # sell 10 if price falls to 189 — only while the long is still held
875
+ stop = while25.sell("EQ:US:AAPL", 10, order_type="STP",
876
+ trigger_price=189.0, reduce_only=True)
877
+ ```
878
+
879
+ With `reduce_only=True` the order is retired when the position is gone, fires
880
+ for no more than you hold, and places nothing if its side would add to the
881
+ position. Place it once the position exists (from your `@on.fill`), with the
882
+ same `product=` the position was opened with: a protective order that reaches
883
+ its level with nothing held is dropped, not placed. `reduce_only` is refused on
884
+ any other order type and on a bracket, whose own stop and target are protective
885
+ already.
886
+
887
+ **A limit order that must rest: `post_only=True`.** On a venue that takes the
888
+ flag (Coinbase, Binance) a post-only limit order is refused by the venue if it
889
+ would trade at once instead of resting on the book, so it only ever fills as
890
+ the resting side (the maker fee). Refused on anything but `order_type="LMT"`,
891
+ on a bracket, and where the connected broker takes no such flag on that kind
892
+ of instrument (`POST_ONLY_UNSUPPORTED`, naming the broker).
893
+
894
+ ```python
895
+ # rest at 100,000 and never take: Binance refuses it if it would fill at once
896
+ while25.buy("CRYPTO:GLOBAL:BTC-USDT", 0.01, order_type="LMT", price=100000,
897
+ post_only=True)
898
+ ```
899
+
900
+ **Or have the broker hold it: `held_by="broker"`.** Left out (or `"local"`),
901
+ While25 holds the order as above, which works only while the app is
902
+ running. With `held_by="broker"` it is sent at once as the broker's **own**
903
+ stop order, held and triggered at the broker, so it works with the app closed:
904
+
905
+ ```python
906
+ # the same protective stop, held by the broker itself
907
+ stop = while25.sell("EQ:US:AAPL", 10, order_type="STP", trigger_price=189.0,
908
+ reduce_only=True, held_by="broker", validity="gtc")
909
+ ```
910
+
911
+ Your script says it, order by order: the terminal's **STOPS HELD BY** setting is
912
+ for the terminal's own tickets and never applies to a script.
913
+
914
+ - **Where:** only where the connected broker can hold that order type on that
915
+ kind of instrument, on a live account: IBKR, a stop (`STP`), a stop-limit
916
+ (`STP LMT`) and a trailing stop (`TRAIL`, sent as IBKR's TRAIL LIMIT with a
917
+ limit offset), not on crypto; Alpaca, a stop, a
918
+ stop-limit and a trailing stop on US stocks and ETFs, a stop and a
919
+ stop-limit on options, a stop-limit on crypto (Alpaca starts a trailing
920
+ stop from the market and has no trailing stop-limit, so a start level or a
921
+ limit offset is refused with the reason); Zerodha, a stop (`STP`) and a
922
+ stop-limit (`STP LMT`) everywhere (Zerodha itself refuses the `STP` where the
923
+ exchanges stopped it: NSE options, BSE); Upstox, a stop-limit everywhere
924
+ and a stop (`STP`) except on option contracts. Anywhere else the order is refused `BROKER_HELD_UNSUPPORTED`
925
+ and nothing is placed: it is never held by While25 instead.
926
+ - **The broker's rules apply to it**, and the broker answers for them: IBKR
927
+ triggers most stops in regular trading hours only (a plain stop on a US stock
928
+ always), some outside them only when sent with `hours="eth"`.
929
+ - **It lives as long as its `validity=` at the broker.** Left out, that is the
930
+ broker's normal one for the instrument (DAY on IBKR, so it ends at the
931
+ close). State `validity="gtc"` for a stop that must last, as above.
932
+ - **Zerodha has no `gtc`: a stop-limit (`STP LMT`) that must last states
933
+ `validity="gtt"`.** Zerodha keeps it as its own GTT for up to a year and,
934
+ when the price crosses `trigger_price=`, places a LIMIT order at `price=`.
935
+ `gtt` is refused on anything else (an `STP` too: a GTT only places a limit
936
+ order), on a stop whose trigger is not on the stop side of the price now, and
937
+ when no live price is held; Zerodha itself refuses one on an intraday
938
+ position. Upstox takes `gtt` the same way, with `price=` equal to
939
+ `trigger_price=`.
940
+ - **It is an ordinary working order:** `@on.order` hears `NEW` when it goes to
941
+ the broker (not `HELD`) and `FILL` when it fills; `modify()` and
942
+ `cancel()` reach it at the broker.
943
+ - **With `reduce_only=True`** it is refused (a `REJECT` with the reason)
944
+ unless it reduces a position you hold and is no larger than it, because the
945
+ broker fires a stop whole. While the app runs, it is cancelled when that
946
+ position closes and cut, never grown, when the position shrinks.
947
+ - `held_by` is refused on a market or limit order, which goes to the broker
948
+ at once anyway. `"local"` and `"broker"` are read in any capitals, by the
949
+ same rule as the terminal's own orders.
950
+ - **Every order event says who holds the order:** `ev["held_by"]` is
951
+ `"broker"` for a stop resting at the broker as its own order, `"local"`
952
+ for one While25 holds (its `HELD`, `MODIFY`, `MODIFY_REJECT` and
953
+ `CANCEL`), and `None` for an order nobody holds (a market or limit order,
954
+ or the order a held stop placed when it fired). A script that restarts
955
+ reads from it where each of its stops is.
956
+ - **A trailing stop the broker holds takes the broker's own terms:**
957
+ `trail_amount=` (price points) or `trail_percent=` (0 to 100; one of the
958
+ two, never both), `trigger_price=` as the level it starts at (optional:
959
+ left out, the broker starts it from the market), and `trail_limit_offset=`
960
+ to fire a limit that far from the stop level instead of a market order (a
961
+ trailing stop-limit). Its level is the broker's to move: `ev["trigger_price"]`
962
+ is the level the broker last reported, and `modify(id, trigger_price=...)`
963
+ is refused — change its distance instead, in the terms it was placed with
964
+ (`modify(id, trail_amount=3)` or `trail_percent=2`), or its limit offset
965
+ (`modify(id, trail_limit_offset=0.75)`). A trailing stop While25 holds
966
+ trails by `trail_amount=` only and keeps it.
967
+ - **A bracket the broker holds: `held_by="broker"` on `bracket(...)`** (or on
968
+ a `buy` / `sell` with `stop_loss=`). The entry, the take-profit and the stop
969
+ go to the broker as its own linked orders, so the whole bracket works with
970
+ the app closed — where the connected broker holds brackets for that kind of
971
+ instrument: IBKR (not on crypto); Alpaca (US stocks and ETFs, never with a
972
+ trailing stop); Upstox (as a GTT: a limit entry, sent at once at its price,
973
+ or a `STP LMT` stop entry at its trigger — a market or `STP` entry is
974
+ refused; validity `gtt`). Anywhere else it is refused
975
+ `BROKER_HELD_UNSUPPORTED` and nothing is placed, never held by While25
976
+ instead. Its take-profit's id is the id the call returns followed by `-T`,
977
+ its stop's by `-S` (not `-SL`); each is an ordinary working order at the
978
+ broker (`NEW`, then `FILL`; `modify()` and `cancel()` reach it there), and
979
+ when one exit fills the broker cancels the other. The stop is a stop-market
980
+ order at the broker, or a trailing stop with `trail_amount=` (a percentage
981
+ is refused on a bracket; so is `trail_limit_offset=`, because a bracket's
982
+ stop fires at market). Left out (or `"local"`), While25 holds the
983
+ bracket's exits as above.
984
+
985
+ The id that call returns is the order's id for its whole life:
986
+ `while25.orders.modify(stop["order_id"], trigger_price=191.0)` moves it,
987
+ `while25.orders.cancel(stop["order_id"])` removes it, and when it fires, the
988
+ order it places arrives in `@on.order` / `@on.fill` under that same id.
989
+
990
+ `modify()` returning only means the change was handed over. Whether it was
991
+ made arrives as an event: `MODIFY` when the order was moved or resized,
992
+ `MODIFY_REJECT` with the reason when it was not, in which case the order waits
993
+ exactly as it was. The commonest refusal is a level on the wrong side of the
994
+ current price (a SELL stop moved above it would fire at once). A trailing
995
+ stop's level cannot be moved at all: it follows the price (one the broker
996
+ holds takes a new distance instead, above). The same two events
997
+ arrive when the trader drags the order's line on the chart, so a script always
998
+ knows where its stop is:
999
+
1000
+ ```python
1001
+ @on.order(tag="mine")
1002
+ def on_order(self, ctx, ev):
1003
+ if ev["event"] == "MODIFY":
1004
+ ctx.log(f"stop now at {ev['trigger_price']} for {ev['quantity']}")
1005
+ elif ev["event"] == "MODIFY_REJECT":
1006
+ ctx.log(f"stop not changed: {ev['reason']}")
1007
+ ```
1008
+
1009
+ `@on.order` hears a held order's whole life:
1010
+
1011
+ | `ev["event"]` | when | `ev["status"]` |
1012
+ |---|---|---|
1013
+ | `HELD` | While25 has accepted it and is holding it; `ev["trigger_price"]` is the level it waits at | `TRIGGER_PENDING` |
1014
+ | `MODIFY` | it was moved or resized, by your `modify()` or from the chart; `ev["trigger_price"]` and `ev["quantity"]` are what it has now | `TRIGGER_PENDING` |
1015
+ | `MODIFY_REJECT` | a change was refused and it waits as it was; `ev["reason"]` says why | still working |
1016
+ | `NOTICE` | the broker's word about a working order it keeps as it is (IBKR: an order marked ETH is worked in regular hours only, its message 2109); `ev["reason"]` says what | still working |
1017
+ | `CANCEL` | it ended without firing; `ev["reason"]` says why: `cancelled`, the position it protected is no longer held, `withdrawn at the close of the session: it was a DAY order`, `withdrawn at its end time: it was a GTD order`, or `dropped: ...` | `CANCELLED` |
1018
+ | `REJECT` | it could not be held at all; `ev["reason"]` is the real cause (for example the level is already on the wrong side of the price) | `REJECTED` |
1019
+ | `NEW`, then `FILL` | it fired: the order it placed went to the broker, under the same id | as for any order |
1020
+
1021
+ Match these on `ev["order_id"]`. A trailing stop is not announced each time its
1022
+ level follows the price; only a change somebody made is.
1023
+
1024
+ **How long a held order waits** (one While25 holds; a stop the broker holds
1025
+ lives for its `validity=` at the broker, above). `validity=` applies to the
1026
+ order it places when it fires. It also decides one more thing:
1027
+
1028
+ - **An entry that states `validity="day"` is withdrawn at the close of the
1029
+ session it trades in** (the regular close with `hours=` left out, the extended
1030
+ session's close for `"eth"`), as a DAY order is at a broker, and `@on.order` hears
1031
+ `CANCEL` with the reason `withdrawn at the close of the session: it was a DAY
1032
+ order`. Placed after the close, its day is the next trading day. Before this
1033
+ it waited until it fired, so a "day" stop placed on Monday could fire on
1034
+ Thursday.
1035
+ - **One that states `validity="gtd"` is withdrawn at its `good_till=`**, and
1036
+ `@on.order` hears `CANCEL` with the reason `withdrawn at its end time: it was a
1037
+ GTD order`. The order it places when it fires carries no end time: a limit
1038
+ goes `"gtc"`, a market order as the broker sends one.
1039
+ - **Leave `validity=` out, or state `"gtc"`, and it waits until it fires or is
1040
+ cancelled**, across days.
1041
+ - **A protective order (`reduce_only=True`) is never withdrawn by time**: a
1042
+ position must not lose its stop overnight, whatever `validity=` says, and one
1043
+ stated `"gtd"` is refused (`INVALID_PARAMETERS`). That
1044
+ is While25's rule: a protective stop the broker holds ends when its
1045
+ `validity=` does (left out, DAY on IBKR: at the close), so state `"gtc"`.
1046
+ - On a market that never closes (crypto) there is no close for the day to end
1047
+ at, so a `"day"` order waits too.
1048
+ - If the close cannot be read for the instrument, a `"day"` entry is refused
1049
+ (`INVALID_PARAMETERS`, the message says so) rather than held to a close that
1050
+ was guessed: place it `"gtc"`, or try again.
1051
+
1052
+ A bracket whose entry is a stop (`order_type="STP"` or `"STP LMT"`) follows the same
1053
+ rule: when its entry is `day` (stated, or left out where the broker's normal
1054
+ validity is `day`), the waiting entry is withdrawn at the close and the bracket
1055
+ ends (`CANCEL` on the bracket's id, reason `the bracket's stop entry was
1056
+ withdrawn at the close of the session: it was a DAY order`). State
1057
+ `validity="gtc"` and it waits until it fires.
1058
+
1059
+ **Which prices a held order looks at: those of its `hours=`.** With `hours=`
1060
+ left out, on a stock, an ETF or an option, **regular-session prices only**, a
1061
+ bracket's stop included. Outside them it waits, and the first price of the next
1062
+ session is judged against the session's last one, so a gap through its level
1063
+ fires at the open. The order it places is a regular-hours order, so a stop that
1064
+ fired on an after-hours price could only trade at the next open anyway, at
1065
+ whatever that open was. For `"eth"` — and always on a future or a crypto
1066
+ pair — every price, the extended session's included, and the order it places
1067
+ when it fires goes out for extended hours too.
1068
+
1069
+ **Figures are exact, never binary floating point.** `quantity`, `price`,
1070
+ `trigger_price`, `take_profit`, `stop_loss`, `trail_amount`, `trail_limit_offset` and `amount` each
1071
+ accept a `Decimal`, an `int` (a NumPy or pandas integer too), a plain decimal
1072
+ string (`"10.5"`, `".5"`, `"5."` all work), or a `float` (a NumPy or pandas
1073
+ float too) — but only when its value
1074
+ is exact to at most 9 fraction digits. `0.1` is fine (`Decimal("0.1")`), and so
1075
+ is `0.00005`, although Python prints it `5e-05`; `0.1 + 0.2` is refused,
1076
+ because it is `0.30000000000000004` in binary floating point and rounding it to
1077
+ "fix" it would be guessing at a number you did not write:
1078
+
1079
+ ```python
1080
+ from decimal import Decimal
1081
+
1082
+ while25.buy("EQ:US:AAPL", 10, price=100.5) # float, exact -> fine
1083
+ while25.buy("EQ:US:AAPL", Decimal("0.1") + Decimal("0.2")) # exact -> "0.3"
1084
+ while25.buy("EQ:US:AAPL", 0.1 + 0.2) # ValueError: use Decimal("0.3") or "0.3"
1085
+ ```
1086
+
1087
+ `bool`, `NaN`, an infinity, a string in exponent notation (`"1e10"`), more than
1088
+ 27 whole digits and more than 9 fraction digits are always refused
1089
+ (`ValueError`, naming the argument and the value) — never rounded, never
1090
+ truncated. Trailing zeros are not fraction digits: `"1.0000000000"` is 1.
1091
+
1092
+ **`quantity=` or `amount=` — exactly one, never both, never neither.**
1093
+ `quantity` is a share/contract count; `amount` is a cash amount in the
1094
+ instrument's own quote currency, sent to the broker AS the amount where its
1095
+ venue takes one, and the venue decides the units, so it spends exactly the
1096
+ amount: Coinbase (market or limit, buying or selling), Binance (market orders,
1097
+ buying or selling), Alpaca (crypto, and stocks it trades in fractions: market
1098
+ or limit, DAY on stocks) and IBKR (a crypto market buy, which IBKR takes in
1099
+ cash only: a crypto market buy by `quantity=` is refused). Nothing converts an
1100
+ amount into units (2026-11-08): on any other broker, shape or instrument it is
1101
+ refused in words (`AMOUNT_NOT_TAKEN`) and the order takes `quantity=`. An
1102
+ `amount` order is market or limit only — it cannot carry a bracket
1103
+ (`take_profit=`/`stop_loss=` need a quantity to size their own legs from); an
1104
+ order sized by amount cannot be changed; and a strategy's sell needs
1105
+ `quantity=` (its part sells no more than
1106
+ it holds). While such an order works, its `quantity` is what has filled so
1107
+ far and its `pending_quantity` is 0: the units are the venue's to decide. It
1108
+ has ended at its `COMPLETE` event (below), never when `pending_quantity`
1109
+ reads 0.
1110
+
1111
+ **Every price defaults to `None` — absent, meaning "no price".** `price`,
1112
+ `trigger_price`, `take_profit`, `stop_loss` all default to `None` (a market
1113
+ order has no price; an unset trigger or bracket leg is simply not there). A
1114
+ **stated** price must be greater than zero: passing `price=0` used to mean
1115
+ "no price" and now raises `ValueError("0 is not a price")`. If you mean
1116
+ "market order", leave `price` unset.
1117
+
1118
+ Every call blocks and returns the real answer, **including a risk rejection** —
1119
+ which raises, so a strategy can never mistake a refusal for a fill.
1120
+
1121
+ **An order call can time out** — 25 seconds with no answer from While25
1122
+ (a slow broker, a contract still being looked up). It raises `While25Error`
1123
+ with code `TIMEOUT`, and that is the one refusal that is not a refusal: the
1124
+ order may still have been placed. The error carries the idempotency key the
1125
+ order went out with (`e.idempotency_key`, also in its message). Pass it back
1126
+ to place the order again safely — if the first went through, While25
1127
+ answers `DUPLICATE_ORDER` instead of placing a second one — or wait for the
1128
+ order's events on `@on.order` / `orders.mine()`. Whatever While25
1129
+ answers after the wait is written to the module's console ("the order that
1130
+ timed out WAS accepted by the terminal: OID-7", or "was refused: ..."). The
1131
+ same holds for `combo()`; a `cancel()`, `modify()` or `square_off()` that
1132
+ times out may still have been applied.
1133
+
1134
+ ```python
1135
+ try:
1136
+ res = while25.buy("EQ:US:AAPL", 10)
1137
+ except while25.While25Error as e:
1138
+ if e.code != "TIMEOUT":
1139
+ raise
1140
+ res = while25.buy("EQ:US:AAPL", 10, idempotency_key=e.idempotency_key) # never twice
1141
+ ```
1142
+
1143
+ **There is no paper trading from Python.** An order needs a live grant — the
1144
+ confirmation a human completes in the panel before a strategy is deployed.
1145
+ Without one, every order is refused with `NO_LIVE_GRANT`; nothing is simulated,
1146
+ and nothing is quietly filled somewhere you were not looking.
1147
+
1148
+ That is deliberate. An ungranted order used to be redirected to the paper book,
1149
+ which made "deploy it and read the fills" a substitute for testing — against
1150
+ *live* market data, priced by a simulator with no contract multiplier, no F&O
1151
+ margin and no expiry. The fills looked real and the numbers were not.
1152
+
1153
+ **To evaluate a strategy, backtest it in the script.** Pull the history you want
1154
+ and run your logic over it. No orders are placed, so nothing needs granting:
1155
+
1156
+ ```python
1157
+ rows = while25.history("EQ:US:AAPL", "1D", limit=500)
1158
+ cash, pos = 100_000.0, 0
1159
+ for prev, bar in zip(rows, rows[1:]):
1160
+ if bar["close"] > prev["close"] and not pos:
1161
+ pos, cash = 1, cash - bar["close"]
1162
+ elif bar["close"] < prev["close"] and pos:
1163
+ pos, cash = 0, cash + bar["close"]
1164
+ while25.log(f"final equity {cash + pos * rows[-1]['close']:.2f}")
1165
+ ```
1166
+
1167
+ **A script may cancel or modify only its own orders.** Every place, cancel and
1168
+ modify leaves the order stamped with the module that sent it — read from the
1169
+ worker the call arrived on, never from your arguments, so a script cannot name
1170
+ another module. While25 refuses `NOT_ORDER_OWNER` for any order id your
1171
+ module did not place — another module's order (a strategy's take-profit leg
1172
+ included), or one worked by hand in the terminal — and `NO_LIVE_GRANT` once your
1173
+ module's grant is revoked or it stops, even for orders it placed earlier.
1174
+
1175
+ `modify(order_id, *, quantity=None, price=None, trigger_price=None,
1176
+ trail_amount=None, trail_percent=None, trail_limit_offset=None)` changes a
1177
+ working order. **Absent means unchanged** — pass only what you want to change,
1178
+ and at least one of them, or it raises (`ValueError`) rather than sending a
1179
+ no-op to While25. The three trail terms are for a trailing stop the broker
1180
+ holds: its new distance in the terms it was placed with (`trail_amount=` price
1181
+ points or `trail_percent=`, never both) and a trailing stop-limit's new limit
1182
+ offset; stated on an order that does not trail at the broker, or in the other
1183
+ terms than its own, they are refused `BAD_TRAIL`:
1184
+
1185
+ ```python
1186
+ while25.orders.modify("OID-123", price=196.0) # move the price only
1187
+ while25.orders.modify("OID-123", quantity=5) # resize only
1188
+ while25.orders.modify("TRAIL-1", trail_amount=3) # a broker trail: follow 3 points away
1189
+ while25.orders.modify("OID-123") # ValueError: nothing to change
1190
+ ```
1191
+
1192
+ One exception, for a held stop-limit: moving its `trigger_price` alone carries
1193
+ its limit `price` with it by the same amount, so the gap you set between them
1194
+ stays (a sell stop-limit at 95 / 94 moved to 90 becomes 90 / 89). Pass `price`
1195
+ as well to set the limit yourself. A limit-if-touched order's `price` is the
1196
+ price you deal at, so it stays where you put it when its `trigger_price` moves.
1197
+
1198
+ **Order events carry the same exact figures.** An `@on.order` / `@on.fill`
1199
+ handler's `ev` dict has `event` (`NEW`, `FILL`, `COMPLETE`, `CANCEL`, `REJECT`, `MODIFY`,
1200
+ `MODIFY_REJECT`, `CANCEL_REJECT` — a cancel the broker refused, the order
1201
+ still working — `HELD`, `NOTICE`, `SQUARE_OFF`, `POSITION_SQUARED_OFF`), `order_id`,
1202
+ `instrument_key`, `symbol`, `side`, `order_type`, `status`, `tag`, `reason`,
1203
+ `timestamp_ms`, `held_by`, `combo_id`, `square_off_id` and `close_order_id`,
1204
+ and the figures: `quantity`, `filled_quantity` and `pending_quantity` as
1205
+ `Decimal` (always stated), and `price`, `average_price`, `last_fill_quantity`,
1206
+ `last_fill_price` as `Decimal | None` — `None` on anything that is not a fill
1207
+ (a `NEW`, a `CANCEL`, a `REJECT` states no fill figures at all). The fill
1208
+ prices (`average_price`, `last_fill_price`) are what the order filled at, with
1209
+ no fee in them: fees are included where brokers send them, in a position's
1210
+ `average_price` (see Positions and funds).
1211
+ A `FILL` is one execution: it always states `last_fill_quantity` and
1212
+ `last_fill_price`, and it is all `@on.fill` hears. An order that ends on its
1213
+ last fill says so on that `FILL` (`status` `COMPLETE`). One that ends on the
1214
+ venue's word with nothing new filled is told a `COMPLETE` (`@on.order` only):
1215
+ `status` `COMPLETE`, the whole order's `filled_quantity` and `average_price`,
1216
+ and `None` for `last_fill_quantity` and `last_fill_price`. An order by
1217
+ `amount=` always ends this way, after its last `FILL`.
1218
+ A `SQUARE_OFF` event (a bracket's square off, see Orders) is not an order:
1219
+ it states only `quantity`, the close's size once the close is sent, and
1220
+ `None` for the other figures; its `square_off_id` and `close_order_id` are
1221
+ `None` on every other event.
1222
+ A `POSITION_SQUARED_OFF` event says that what YOUR module held on an
1223
+ instrument is no longer its own: the whole position was squared off (Square
1224
+ off on the position's row in the Positions tab, or the daily loss limit), or
1225
+ the broker squared it off itself. Only your module hears it, on its
1226
+ `@on.order` handlers whatever `tag=` they name (a `symbol=` still applies:
1227
+ a part of your own carries no tag), once per thing
1228
+ taken: its part (`order_id` is `""`), a bracket of its (the bracket's id and
1229
+ `tag`) or a combo's part (`combo_id`). It is not an order: `quantity` is what
1230
+ the module held there, `product` its pocket (as `my_position()` names it;
1231
+ `""` where a market keeps one position per instrument), `side` the side that
1232
+ closes it (`SELL` for a long), `reason` the words, and every other figure is
1233
+ `None`. `my_position()` reads the same from that moment. Read any count of
1234
+ your own again from it, never just drop it (another pocket may still be the
1235
+ module's), or the next exit sells units the module no longer has:
1236
+
1237
+ ```python
1238
+ @on.order
1239
+ def on_order(self, ctx, ev):
1240
+ if ev["event"] == "POSITION_SQUARED_OFF":
1241
+ mine = while25.portfolio.my_position(ev["instrument_key"])
1242
+ self.held[ev["instrument_key"]] = mine["quantity"] if mine else Decimal(0)
1243
+ ```
1244
+ `combo_id` names the combo an order is a leg of (see Combos): it is set on
1245
+ every event of the combo's legs, of the closes its square off sends, and on
1246
+ that square off's `SQUARE_OFF` events, and is `None` on an order of no combo.
1247
+ `trigger_price` is `Decimal | None` too: the level a held order waits at,
1248
+ `None` on an order that has none:
1249
+
1250
+ ```python
1251
+ @on.fill(tag="mine")
1252
+ def on_fill(self, ctx, ev):
1253
+ ctx.log(f"filled {ev['last_fill_quantity']} @ {ev['last_fill_price']}")
1254
+ ```
1255
+
1256
+ Two refusals the order core makes AFTER the call has returned arrive this way
1257
+ too, as a `REJECT` whose `reason` starts with the code. `SELL_EXCEEDS_PART:` —
1258
+ a coin held outright (crypto spot) cannot be sold short, and the sell was for
1259
+ more than this strategy's own part holds there, less its sells already
1260
+ working (a short bracket entry is refused the same way): size a sell from
1261
+ your own fills, never from the account's `position()`. `LONG_ONLY_ONE_STRATEGY:`
1262
+ — a coin at a venue that takes its fees from the holding without reporting
1263
+ them per fill (Alpaca today), while another strategy holds a part, a working
1264
+ order or a live bracket on it: nothing to retry; pick another instrument, or
1265
+ stop the other strategy first. See "Two strategies, one account".
1266
+
1267
+ You still cannot choose *how* a granted order executes — that is bound by the
1268
+ terminal, never by your script.
1269
+
1270
+ **What the SDK refuses before anything leaves your script, as `ValueError`:**
1271
+ `quantity=` / `amount=` neither or both, a quantity or amount that is not
1272
+ positive, `amount=` with a bracket or on anything but a market or limit
1273
+ order, `take_profit=` without `stop_loss=`, `group="simple"` with a bracket,
1274
+ `reduce_only=True` on anything but a stop / if-touched / trailing-stop order
1275
+ or on a bracket, `post_only=True` on anything but a limit order or on a
1276
+ bracket, `held_by=` that is not `"local"` / `"broker"` or stated on a
1277
+ market or limit order, a trail (`trail_amount=`, `trail_percent=`,
1278
+ `trail_limit_offset=`) on an order that does not trail or in terms its holder
1279
+ does not take, a trail or limit offset of 0 or below, `hours=` other than
1280
+ `"eth"` (`"rth"` included), and a stated price of 0 or below. While25
1281
+ makes the same checks again on anything that reaches it; the codes
1282
+ `BAD_REDUCE_ONLY`, `BAD_HELD_BY`, `BAD_TRAIL`, `BAD_GROUP`, `BAD_HOURS` and
1283
+ `BAD_NOTIONAL` below are its words for them.
1284
+
1285
+ **Refusal codes on `while25.orders.*` (and the `while25.buy` / `sell` / `place` / `bracket` shortcuts).** Every order call can come back refused;
1286
+ the code says why and what to do:
1287
+
1288
+ | code | meaning | what your script should do |
1289
+ |---|---|---|
1290
+ | `NO_LIVE_GRANT` | no human has granted this module live orders | deploy through the panel; nothing is simulated |
1291
+ | `BUSY` | the script-order lane (512 queued broker calls) or the order core's queue is full — nothing was sent | back off and retry; seeing this at all means you are sending far too fast |
1292
+ | `TIMEOUT` | While25 gave no answer within 25 seconds: the order MAY have been placed | place it again with `e.idempotency_key` (a duplicate is refused), or watch `@on.order`; the late answer lands on the console — never place it again under a fresh key |
1293
+ | `WRONG_LANE` | the order id belongs to a client-origin order | act only on orders your module placed |
1294
+ | `GRANT_STALE` | the code changed since live orders were granted | redeploy — the grant belongs to the code the human read |
1295
+ | `NOT_A_STRATEGY` | only `class X(Strategy)` may trade | declare the kind, or drop the order calls |
1296
+ | `NOT_ORDER_OWNER` | the order id is not yours | another module's order, or one worked by hand, is never yours to touch |
1297
+ | `ORDER_RIGHTS` | this module may not trade: not a Strategy or an App importing one, or started without a complete approval of its code (its log says which) | make it a Strategy, or keep its imports under 500 workspace files and deploy again |
1298
+ | `NOT_WORKING` | the order is not open (filled, cancelled, or unknown) | refresh your view of the book before acting |
1299
+ | `UNSUPPORTED` | the venue/engine cannot do this (e.g. `oco`/`oto` groups) | use `bracket(...)` — it is engine-managed |
1300
+ | `MODULE_NOT_RUNNING` | While25 last saw your module stopped or halted; its grant ended with that run | nothing — an order only comes from a running module, and a module started again needs a fresh Deploy |
1301
+ | `MODULE_STOPPING` | the module's Stop has begun (its `on_stop`, or a handler still running when the Stop came) | nothing — never retry; the trader's Stop decides what happens to its orders |
1302
+ | `MODULE_HALTED` | the module raised and halted; nothing from it is sent | fix the error and deploy again |
1303
+ | `GRANT_ENDED` | the grant ended: the module stopped or its Stop ran | deploy again |
1304
+ | `NOT_READY` | While25's order path, instrument catalog or options are not up yet | ask again in a moment — nothing was sent |
1305
+ | `NO_ENGINE` | While25 is not attached to Python | ask again; `my_position()` / `mine()` say `NOT_READY` for the same |
1306
+ | `BAD_ANSWER` | While25's answer could not be read (a figure that is not a number) | nothing to retry — report it |
1307
+ | `BAD_PRODUCT` | `product=` is not `delivery`, `intraday`, `margin` or `normal` | state one of them — nothing was placed |
1308
+ | `BAD_TAG` | `tag=` is over 20 characters | shorten it — nothing was placed |
1309
+ | `BAD_NOTIONAL` | `quantity=` and `amount=` both stated (the SDK refuses this first, as `ValueError`) | size the order one way |
1310
+ | `IMPORT_TIME_DATA` | the call ran while the file was being loaded (at import: on a save, a register or a restore), not in a running module | move it into `on_start()`, a handler or `compute()` |
1311
+ | `NOT_IN_RUN` | an order call — or anything but `candles`, `quotes`, `news`, `portfolio`, `instrument`, `history_span` and the chart tools — from a one-shot run, which has no grant and owns no orders | deploy it as a module |
1312
+ | `BAD_VALIDITY` | the `validity=` is not one the connected broker takes for this kind of instrument (`gtt` included, anywhere but a stop-limit Zerodha or Upstox holds, or a bracket Upstox holds; on Upstox only `gtt` on such a bracket); the message lists what it does take | pick one from the list — nothing was placed or armed |
1313
+ | `BAD_HOURS` | the `hours=` is not `"eth"` (`"rth"` included: it is not a choice); or `"eth"` on a broker with no extended session; or `"eth"` on an order While25 holds (a stop, an if-touched order, a trailing stop, a bracket's stop) whose fire the broker does not work outside regular hours on that instrument (Alpaca: a limit with `"day"` or `"gtc"` only; IBKR stocks and ETFs: a limit only) | state `"eth"`, or leave hours out for regular hours; for a held order use a stop-limit (`"STP LMT"`), or leave hours out — nothing was placed or armed. A market or limit order sent at once is never refused for this: the broker answers |
1314
+ | `BAD_REDUCE_ONLY` | `reduce_only=True` on an order it cannot apply to: anything but `STP`, `STP LMT`, `MIT`, `LIT`, `TRAIL`, or a bracket | drop the flag, or place a stop / if-touched / trailing-stop order |
1315
+ | `BAD_POST_ONLY` | `post_only=True` on anything but a limit order (`LMT`) | drop the flag, or place a limit order |
1316
+ | `POST_ONLY_UNSUPPORTED` | `post_only=True` where the connected broker takes no post-only order on that kind of instrument (the message names the broker), or no broker is connected | drop the flag — nothing was placed |
1317
+ | `AMOUNT_NOT_TAKEN` | `amount=` on an order the connected venue takes no amount on (Coinbase: a sell or a stop-limit; Binance: anything but a market order), or a strategy's sell by amount there | state `quantity=` instead — nothing was placed |
1318
+ | `GTD_NEEDS_END_TIME` | `validity="gtd"` without `good_till=`, or with an end time already past | state `good_till=` (an ISO 8601 time with its offset, or epoch milliseconds) in the future — nothing was placed |
1319
+ | `BAD_HELD_BY` | `held_by=` is not `"local"` or `"broker"` (in any capitals); or it is stated on a market or limit order (nobody holds one) | leave `held_by` out, or state it on a stop / if-touched / trailing-stop order or on a bracket — nothing was placed |
1320
+ | `BROKER_HELD_UNSUPPORTED` | `held_by="broker"` where the connected broker cannot hold that order type on that kind of instrument (the message names the broker and the type), or a bracket where the broker holds none, or the account is not live | hold it in While25 (leave `held_by` out); a `STP LMT` on Binance futures: use `STP` — nothing was placed |
1321
+ | `BAD_TRAIL` | a trailing stop with no distance; one While25 holds with `trail_percent=`, `trigger_price=`, `price=` or `trail_limit_offset=`; one the broker holds with both `trail_amount=` and `trail_percent=`, a percent outside 0 to 100, or a `price=`; `trail_limit_offset=` on a bracket; `trail_amount=` / `trail_percent=` / `trail_limit_offset=` on an order that does not trail; or `modify()` stating a trail on an order that does not trail at the broker, or in the other terms than its own | give a trailing stop While25 holds a price distance in `trail_amount=` and nothing else; give one the broker holds `trail_amount=` or `trail_percent=` (and `trigger_price=` / `trail_limit_offset=` if wanted); take the trail off a plain order; change a broker trail in the terms it was placed with |
1322
+ | `BAD_ORDER_TYPE` | an order type that is not `MKT`, `LMT`, `STP`, `STP LMT`, `MIT`, `LIT` or `TRAIL` written exactly so (`market`, `sl-m` and the other old spellings included), or `MOO` / `MOC` / `LOO` / `LOC` (no broker here is sent one) | the message says what to place instead where the broker takes the auction as a validity |
1323
+ | `BAD_GROUP` | a bracket with a take-profit and no stop, an entry type a bracket cannot place, a percentage trail on a bracket, or `group="simple"` together with `stop_loss=` / `take_profit=` (a plain order cannot carry them; it used to go out with no stop) | the message names which, and what works |
1324
+ | `DUPLICATE_ORDER` | a placement with this `idempotency_key=` was already accepted (plain order or bracket) | nothing was placed again — a corrected resubmit needs a fresh key |
1325
+ | `NO_BRACKET` | `square_off()` named no open bracket, and no open combo of your module: it has ended (its take-profit or stop closed it, or a square off did) or was never placed | nothing to close — nothing was sent |
1326
+ | `NOTHING_HELD` | `square_off()` on a bracket whose entry has not filled | cancel the entry instead — nothing was sent |
1327
+ | `MARKET_CLOSED` | `square_off()` while the bracket's market cannot take its market close; the message says why | square off again once it trades — nothing was sent |
1328
+ | `NOT_LIVE` | `square_off()` while the terminal is not on the live account | nothing was sent |
1329
+
1330
+ A trail applies in two places. Standalone it is `order_type="TRAIL",
1331
+ trail_amount=...` — held by While25 at that fixed price distance, or by
1332
+ the broker (`held_by="broker"`, where the broker holds trailing stops: IBKR,
1333
+ not on crypto) in the broker's own terms: `trail_amount=` or
1334
+ `trail_percent=`, a `trigger_price=` to start from, a `trail_limit_offset=`
1335
+ to fire a limit. On a bracket it is `bracket(..., stop_loss=...,
1336
+ trail_amount=...)`, a fixed price distance whoever holds the bracket (a
1337
+ percentage trail is refused there). `trail_amount=`, `trail_percent=` or
1338
+ `trail_limit_offset=` on any other order (a market, limit, stop or
1339
+ if-touched order) is refused in words rather than sent with no trailing stop
1340
+ behind it.
1341
+
1342
+ **Only a `Strategy` — or an `App` that imports one — may place orders.**
1343
+ Order rights go by kind: an `Indicator`, a `Monitor` or an ordinary `App`
1344
+ calling any of `buy / sell / place / bracket / combo / cancel / modify` gets
1345
+ `OrderRightsError("<kind> modules cannot place orders")` — raised in the worker
1346
+ before any request leaves for While25, so nothing reaches a broker. It is a
1347
+ `While25Error` (code `ORDER_RIGHTS`), so an existing `except While25Error`
1348
+ catches it. While25 checks again in its own process, for every order
1349
+ request whatever call sent it (the private `ctx._call(...)` included), and
1350
+ answers `ORDER_RIGHTS` without sending anything; While25 enforces the same
1351
+ rule on live grants. If something needs to trade, make it a
1352
+ `Strategy` — or have a `Monitor` `while25.emit()` a signal that a `Strategy`
1353
+ subscribes to, which keeps the trading decision behind the human
1354
+ deploy-confirm: a monitor's signals reach it only with the box ticked at its
1355
+ deploy. An ordinary `App`'s and an `Indicator`'s signals never reach a module
1356
+ that trades, except a strategy's own desk (see `while25.emit` in "Start and stop"); a strategy works an
1357
+ indicator out itself (see "An indicator's numbers in a strategy").
1358
+
1359
+ **A strategy's panel: its desk.** The strategy is what you deploy. Its panel
1360
+ is an `App` its class names, `desk = ...`, written above it in the same file:
1361
+
1362
+ ```python
1363
+ # strategies/breakout.py
1364
+ from types import SimpleNamespace
1365
+ import while25
1366
+ from while25 import App, Bars, Strategy, on, ui
1367
+
1368
+ ui.panel("breakout_desk", "Breakout")
1369
+ ui.layout(ui.view("main"))
1370
+
1371
+ class BreakoutDesk(App): # shows, never trades
1372
+ id = "breakout_desk"
1373
+
1374
+ @on.signal("breakout_state", sender="breakout")
1375
+ def state(self, ctx, payload):
1376
+ s = SimpleNamespace(**payload)
1377
+ while25.ui.push("main", {"blocks": [ui.strategy_block(), ui.timeline(s.events)]})
1378
+
1379
+ class Breakout(Strategy):
1380
+ id = "breakout"
1381
+ desk = BreakoutDesk
1382
+ aapl = Bars("EQ:US:AAPL", "5m", keep=200)
1383
+
1384
+ @on.bar(aapl)
1385
+ def bar(self, ctx, bar):
1386
+ ... # the logic, and its orders
1387
+ while25.emit("breakout_state", {"events": [...]})
1388
+ ```
1389
+
1390
+ - **Deploy starts both, Stop stops both.** Deploying the strategy starts its
1391
+ desk and opens the desk's panel; when the strategy stops or halts, the desk
1392
+ stops. On the panel, the button is Deploy while the strategy is not
1393
+ running, and Stop is the strategy's Stop window.
1394
+ - **The desk shows, it never trades.** Its `ui.strategy_block()` shows its
1395
+ strategy. It hears what the strategy sends with `@on.signal(name,
1396
+ sender="<strategy id>")` (the id, as text: the strategy's class comes below
1397
+ it), and what it sends reaches its strategy (its buttons). A bug in the desk
1398
+ halts the desk, never the strategy.
1399
+ - **Each part runs as its own kind**: the strategy, its desk and its monitors
1400
+ (`monitors = [...]`) are separate scripts with separate rights. Creating one
1401
+ inside another (`Breakout()` in an App) runs its code as the caller: its
1402
+ triggers and bar lines never run, and a Monitor's `ai.ask` is refused there.
1403
+
1404
+ **Trading Apps, the old way.** An App whose file imports a Strategy class by
1405
+ name still trades and deploys, for scripts written that way: the App runs, the
1406
+ strategy inside it is a plain object fed by hand, and every order is the App's.
1407
+ `import strategies.breakout` (the module, not the class) does NOT make an App
1408
+ trade, and neither does importing only the `Strategy` base; an Indicator, a
1409
+ Monitor or a strategy's desk never trades, whatever it imports. A Strategy with
1410
+ `Bars` lines held by a trading App is refused when the file is saved: those
1411
+ lines would never be filled there. While a strategy or trading App runs, its
1412
+ own file and every helper it imports are frozen (writes refused with
1413
+ `LIVE_STRATEGY`); stop it to edit them. Editing any of them while it is
1414
+ stopped changes the code the grant was confirmed for, so the grant has to be
1415
+ confirmed again. Neither is restarted automatically after a Python restart — a
1416
+ person starts it.
1417
+
1418
+ **What the approval covers is what you import by name.** The terminal reads
1419
+ your imports without running them — `import x`, `from x import y` (inside a
1420
+ function too), relative imports, `from pkg import *` when `pkg/__init__.py`
1421
+ lists a literal `__all__` — against your script's real `sys.path`, in its
1422
+ order: in the terminal that is a project's own folder, then `lib/`, then the
1423
+ bundled packages (numpy, pandas, while25), then the workspace, then Python's
1424
+ own library. So a package in `lib/`, or a bundled one, with the same name as
1425
+ a file of yours is the one that runs — name your files so they don't collide.
1426
+ The workspace files it finds are hashed
1427
+ into the revision the human confirms. The Strategy that makes an App trade
1428
+ must be defined in the App's file or in one of those files: a Strategy reached
1429
+ through `importlib`, `__import__`, a computed `__all__` or a `sys.path` you
1430
+ changed does not make it trade. A live strategy or trading App then loads only
1431
+ those files, byte for byte as confirmed: importing any other workspace file —
1432
+ or one changed since the confirm, or one outside the workspace that is not
1433
+ Python's own library or an installed package — raises `ImportError`
1434
+ (at start, or in the handler that imports it):
1435
+
1436
+ ```
1437
+ `helpers.late` is not part of the code approved for live trading — stop and redeploy to include it
1438
+ ```
1439
+
1440
+ A file edited since the confirm says "changed after it was approved" instead. Import it by name so it is covered, then deploy again. Packages you
1441
+ `pip install` into `lib/` are installed packages, not your code — so only
1442
+ the installer changes `lib/` (anything else is refused, see above), and while
1443
+ any strategy or trading App runs, installing a package is refused with
1444
+ "packages can't change while a strategy is running ('<id>') — stop it
1445
+ first"; starting a strategy or trading App while an install is under way is
1446
+ refused with "packages are changing — wait for the install to finish, then
1447
+ start '<id>'". Any spelling of a frozen file is the file: another case on a
1448
+ Mac's disk, a symlink or a hard link is refused the same. Not covered:
1449
+ code you load yourself from a path — `exec()` of a file you read,
1450
+ `importlib.util.spec_from_file_location` — and data files; they are yours to
1451
+ keep stable. A live module whose imports run past 500 workspace files is not
1452
+ covered at all: it runs, may not place orders, and says so in its log.
1453
+
1454
+ ## Positions and funds
1455
+
1456
+ ```python
1457
+ p = while25.portfolio.position("EQ:US:AAPL") # None when flat
1458
+ f = while25.portfolio.funds() # margin_used, margin_available, assets, figures — or None
1459
+ if f is None:
1460
+ why = while25.portfolio.funds_unavailable_reason() # the broker's own words
1461
+ d = while25.portfolio.day_pnl() # today's ACCOUNT P&L (a Money) — or None
1462
+ ```
1463
+
1464
+ **Figures are exact.** `position()`'s `quantity` is a `Decimal`; its
1465
+ `average_price` and `last_price` are `Decimal | None`; its `pnl` is a
1466
+ `while25.Money | None` — a frozen `(value: Decimal, currency: str)` pair
1467
+ that reads as `"1234.5 USD"`. A position's `last_price` and `pnl` are `None`
1468
+ until its instrument has ticked since the broker snapshot.
1469
+
1470
+ **Binance futures P&L follows the account's "P&L on" choice** (risk policy: Last price, the
1471
+ default, or Mark price; the loss limits follow it): every row states `pnl_price` (`"mark"` |
1472
+ `"last"`) and `mark_price` (`Decimal | None`); a stop held there keeps the price the choice named
1473
+ when it was placed (`mine()["held_stops"][i]["triggers_on"]`: `"mark"` | `"last"`); a trailing
1474
+ stop on the mark placed before the contract's first mark waits for it (its `trigger_price` is
1475
+ `None` until then);
1476
+ `average_price` there is the fills' average (fees and funding are outside positions on Binance and
1477
+ Coinbase futures); `funds()["contract_settings"]` is `[{"instrument_key", "symbol", "margin_type":
1478
+ "cross" | "isolated", "leverage"}]`, as the tickets show them.
1479
+
1480
+ **Fees are included where brokers send them.** A position's `average_price`
1481
+ takes each fill's fee when the broker reports one (IBKR's commissions), raising a long's average and lowering a short's; where the broker
1482
+ reports none (Alpaca, Zerodha and Upstox today) it stays at the fill prices.
1483
+ Don't add a fee the broker sent to it again yourself.
1484
+
1485
+ A symbol held under more than one product (intraday and delivery, say) comes
1486
+ back as ONE combined position: `quantity` summed; `pnl` summed only when
1487
+ *every* row states one *and* they are all in the same currency (a long in INR
1488
+ and a short in USD cannot be honestly added, so it is `None`); `average_price`
1489
+ is the quantity-weighted average, quantized to 9 decimal places, and *only*
1490
+ across rows on the same side (a long averaged against a short is `None`,
1491
+ never a guess). `position()["rows"]` keeps each broker row exactly as
1492
+ reported, and `["products"]` names them, so nothing is lost by combining.
1493
+
1494
+ `day_pnl()`, `realised_pnl()` and `unrealised_pnl()` are account-level
1495
+ `Money | None` figures from the broker's own account line (day P&L falls back
1496
+ to the terminal's portfolio summary when it holds rows); each is `None` when
1497
+ nobody stated it — never a sum over positions, which vanish when a position
1498
+ closes.
1499
+
1500
+ Never cached: a stale position feeding a sizing decision is a money bug.
1501
+
1502
+ When one of the combined rows states no quantity, the whole `quantity` is
1503
+ `None` (never summed as 0), and then there is no side and no `average_price`
1504
+ either.
1505
+
1506
+ ### What this module holds: `my_position()`, `my_positions()`, `orders.mine()`
1507
+
1508
+ ```python
1509
+ mine = while25.portfolio.my_position("EQ:US:AAPL") # None when it has nothing there
1510
+ every = while25.portfolio.my_positions() # one dict per instrument, [] for none
1511
+ working = while25.orders.mine() # its working orders and held stops
1512
+ ```
1513
+
1514
+ `position()` is the account's; this is the module's own, changed by its own
1515
+ orders and ended by a square off of the whole position (a
1516
+ `POSITION_SQUARED_OFF` event says so), and kept across a Stop and a restart of the app, so a strategy
1517
+ deployed again (the same `id`) reads where it left off. `my_position(key)`
1518
+ takes the instrument key, or its symbol when that names one instrument the
1519
+ module has (two: `ValueError`), and returns:
1520
+
1521
+ | Key | |
1522
+ |---|---|
1523
+ | `instrument_key`, `symbol` | the instrument |
1524
+ | `quantity` | its PART, a signed `Decimal`: what its orders bought and sold outside any bracket or combo; `Decimal(0)` when all it has there is in brackets or combos |
1525
+ | `product` | the part's pocket (`"DELIVERY"`, `"INTRADAY"`, `"MARGIN"`; `""` where a market keeps one per instrument); `None` across several pockets (each is in `rows`) |
1526
+ | `average_price`, `last_price` | `Decimal`, or `None` when not known |
1527
+ | `pnl` | While25's unrealised P&L on the part, a `Money`; `None` when the price or the multiplier is not known |
1528
+ | `closed_pnl`, `closed_pnl_beside` | on each of `rows` (as on each `mine()` part): what the part closed, a `Money` or `None`, and beside it the fees its fills paid in another asset (Binance's BNB), a list of `Money`, one per asset, never converted; a BNB-paid fee is never in `average_price` or `pnl` |
1529
+ | `account_quantity` | the pocket's whole net on the account beside it, a signed `Decimal`; `None` until the broker's first position report of the session (never `0`), and `None` across several pockets |
1530
+ | `rows`, `products` | each part as stated, one per pocket, and their pockets |
1531
+ | `brackets` | its brackets there: `bracket_id`, `group_label`, `side`, `product`, `quantity_held`, `entry_average`, `last_price`, `pnl`, `broker_held`, `waiting_for_entry` |
1532
+ | `combos` | its combos' legs there (see Combos) |
1533
+
1534
+ Parts in several pockets combine by `position()`'s rules. `my_positions()`
1535
+ lists every instrument the module has a part, a bracket or a combo leg on.
1536
+ `orders.mine(instrument_key=None)` lists its working orders and the stops
1537
+ While25 holds for it, one dict each: `order_id`, `instrument_key`,
1538
+ `symbol`, `side`, `order_type` (`MKT`, `LMT`, `STP`, `STP LMT`, `MIT`, `LIT`,
1539
+ `TRAIL`), `product`, `validity`, `hours`, `quantity`,
1540
+ `filled_quantity`, `price`, `trigger_price`, `status` (`PENDING`, `OPEN`, or
1541
+ `TRIGGER_PENDING` for a stop held by While25), `held_by`, `tag`,
1542
+ `bracket_id`, `group_label` and `role` (`ENTRY`, `EXIT`, `TAKE_PROFIT`,
1543
+ `PROTECTIVE_STOP`, `ENTRY_STOP`, `BRACKET_ENTRY`, `BRACKET_TAKE_PROFIT`,
1544
+ `BRACKET_STOP`, `COMBO_LEG`). All three are reads: they need no order
1545
+ rights, `on_stop` may call them, and they are answered from what While25
1546
+ already holds, so a strategy may ask every tick. `NOT_READY` while
1547
+ While25 cannot tell yet (its order path is not up, or it is not attached
1548
+ to Python): ask again, never read it as flat.
1549
+
1550
+ **`funds()` returns `{"margin_used": Money | None, "margin_available": Money |
1551
+ None, "assets": [...]}`, or `None`** when the broker has not stated the
1552
+ account's funds at all — a panel must render that as unavailable rather than as
1553
+ a number. Each figure is `None` where the venue does not state it: Alpaca
1554
+ states no available margin, so its `margin_available` is `None` on a funded
1555
+ account; render that as "not stated", never as 0, and never gate an order on it. It is not a rare path: Upstox refuses the funds route outside its
1556
+ service hours, and a broker that has told you nothing has not told you the
1557
+ account is empty. Write `if f is None:`, never `f = while25.portfolio.funds()
1558
+ or {}` and never `.get("margin_available", 0)` — a fabricated zero is
1559
+ indistinguishable from a drained account, which is the one mistake this API
1560
+ is shaped to prevent. `assets` is `[]`, never absent, when the venue states no
1561
+ per-asset breakdown — each entry is `{"asset": str, "free": Decimal | None,
1562
+ "locked": Decimal | None, "total": Decimal | None}`, for the crypto venues
1563
+ that report balances per coin.
1564
+
1565
+ `figures` is every figure the broker states, under its own names and in its
1566
+ own order (the Funds tab's rows); `[]` from a While25 that sends none.
1567
+ Each is `{"section": str, "label": str, "column": str, "kind": "money" |
1568
+ "units" | "percent" | "number" | "text", "value": Decimal | None, "text":
1569
+ str | None, "currency": str | None, "field": str, "roles": [str], "key_types":
1570
+ [str]}`: `value` is
1571
+ `None` on a `"text"` figure (its word is in `text`), `column` says which of
1572
+ several (`"Securities"`, a currency, `"Hold"`; `""` = the figure itself), and
1573
+ `field` is the broker's own key. `roles` mark the money the broker lets you
1574
+ put into a new trade (`"available"`: IBKR's Current Available Funds, Alpaca's
1575
+ Buying power), its margin in use (`"margin_used"`) and its margin still free
1576
+ (`"margin_available"`); `margin_used` / `margin_available` are those
1577
+ figures' values. `key_types` names the instrument kinds those roles answer for on an
1578
+ account holding several kinds (Coinbase spot + US futures: `"CRYPTO"`,
1579
+ `"FUT"`); `[]` = every kind.
1580
+
1581
+ ```python
1582
+ f = while25.portfolio.funds()
1583
+ avail = next((g for g in f["figures"] if "available" in g["roles"]), None) if f else None
1584
+ while25.log(f'{avail["label"]}: {avail["value"]}' if avail else "available: not stated")
1585
+ ```
1586
+
1587
+ There is no `cash` figure. It used to exist and was filled with
1588
+ `available_margin` under a second name; a relabelled quantity is a wrong
1589
+ number, so it was removed rather than left to be believed.
1590
+
1591
+ ## Instrument rules
1592
+
1593
+ ```python
1594
+ inst = while25.data.instrument("EQ:US:AAPL")
1595
+ inst2 = while25.data.instruments(["EQ:US:AAPL", "EQ:US:MSFT"]) # a list, same order
1596
+ ```
1597
+
1598
+ The venue's own size and price rules for one instrument, so a strategy can
1599
+ size an order it already knows will be accepted — or explain a rejection
1600
+ without a round trip. With a broker attached they are that broker's own (its
1601
+ instrument list or its contract lookup); with none, the data source's. Every
1602
+ rule is `Decimal | None` (absent means the venue stated none):
1603
+ `size_increment`, `min_qty`, `max_qty`, `lot_multiple`,
1604
+ `price_increment`, `sub_band_price_increment`, `price_band_floor`,
1605
+ `multiplier`; `min_notional` is a `Money | None`; `price_steps` is the tick
1606
+ by price where it changes with the price (IBKR's rule for the contract),
1607
+ `(from_price, increment)` rows lowest first, `()` when the venue states none
1608
+ — when present it governs every price in place of `price_increment` and the
1609
+ band. `quote_currency`, `settlement_currency`, `tradeable` and
1610
+ `untradeable_reason` describe the row itself. An unknown key raises
1611
+ `While25Error` (code `INSTRUMENT_NOT_FOUND`).
1612
+
1613
+ ```python
1614
+ inst.step # lot_multiple, else size_increment; None if neither
1615
+ inst.tick_for(101.30) # the tick that governs THIS price (ladder step, else band)
1616
+ inst.check(quantity=15, price=101.30) # None = would pass; else the reason it would not
1617
+ inst.notice(quantity=15, price=101.30) # None = every rule on file; else what the venue judges
1618
+ inst.snap(ltp) # a float from the feed -> the exact tick-grid Decimal
1619
+ inst.offset(ltp, -2) # two ticks below, exact
1620
+ inst.ticks_between(ltp, target) # whole ticks apart, exact; None across a band floor
1621
+ ```
1622
+
1623
+ Prices reach a script as floats and stay floats — indicators want them so.
1624
+ `snap()`, `offset()` and `ticks_between()` are where a float becomes an exact
1625
+ figure: the float is read by its shortest decimal form (the tape's 100.05,
1626
+ stored as 100.0499999999999971, reads back as 100.05) and put on the venue's
1627
+ tick ONCE, so "two ticks below" and "how many ticks apart" are exact and the
1628
+ order you build from them is on the grid. Do the arithmetic on the snapped
1629
+ Decimal, never on the float (`100.05 - 0.10` is 99.94999999999999 in floats,
1630
+ and `check()` would refuse it as off-tick). `snap(price, mode="down")` and
1631
+ `"up"` pick the buyer's and the seller's side of a between-tick price.
1632
+
1633
+ On a ladder a tick is one step along the venue's grid (every price on the
1634
+ tick that governs it), so `offset()` and `ticks_between()` change increment
1635
+ at a step edge:
1636
+
1637
+ ```python
1638
+ # price_steps (0, 0.05), (3, 0.10): 0.05 below 3, 0.10 from 3 on
1639
+ inst.tick_for(3) # 0.10: the step AT 3
1640
+ inst.offset(2.95, 2) # 3.10 (2.95, 3.00, 3.10)
1641
+ inst.offset(3.10, -2) # 2.95, not 2.90
1642
+ inst.ticks_between(2.95, 3.10) # 2
1643
+ ```
1644
+
1645
+ `check()` is a **local, advisory** pre-check — it never calls While25 —
1646
+ mirroring the same size and price rules While25 itself enforces
1647
+ (`check_size`/`check_price`): positive; on-step; between the minimum and the
1648
+ maximum; at or above `min_notional` when a `price` is also given; on the
1649
+ tick `tick_for()` names when a `price` is given. Only a rule the venue states is
1650
+ judged: a missing step, minimum or tick, or a `min_notional` stated in another
1651
+ currency than the order's, refuses nothing — the order goes as typed and the
1652
+ venue judges it. A `min_notional` the venue states for orders by amount only
1653
+ (`min_notional_amount_orders_only`: Coinbase's `quote_min_size`, stated for the
1654
+ quote asset alone) holds no `quantity` either: such an order goes to the venue.
1655
+ `notice()` names each such gap so a script can log it, and
1656
+ returns `None` when every rule the order touches is on file. `check()`
1657
+ returning `None` means "While25 is expected to accept this," not a
1658
+ guarantee — While25 re-checks every order regardless, and its verdict is
1659
+ the one that counts.
1660
+
1661
+ ```python
1662
+ msg = inst.check(quantity=7)
1663
+ if msg:
1664
+ while25.log(f"skipping: {msg}")
1665
+ else:
1666
+ while25.buy("EQ:US:AAPL", 7)
1667
+ ```
1668
+
1669
+ ## Options: one contract from a description
1670
+
1671
+ ```python
1672
+ c = while25.option("AAPL", expiry="26th", right="CALL", strike="ATM+2")
1673
+ while25.buy(c["instrument_key"], c["lot_size"])
1674
+ while25.subscribe(c["instrument_key"], on_tick=self.on_option)
1675
+ ```
1676
+
1677
+ `option()` names ONE listed contract, worked out now from the same expiry and
1678
+ strike lists the Option Chain panel reads — the whole list of an expiry, not
1679
+ the panel's window around the money — so a strategy and the panel never name
1680
+ different contracts, and nothing has to be open first.
1681
+
1682
+ | Argument | Takes |
1683
+ |---|---|
1684
+ | `underlying` | a symbol (`"AAPL"`, `"NIFTY"`) or a full key (`"EQ:US:AAPL"`) |
1685
+ | `expiry` | a date (`"2026-11-20"`, a `date`), or a day of the month (`"26"`, `"26th"`, `26`): the next date on or after today that falls on it |
1686
+ | `right` | `"CALL"` / `"PUT"`, also `"C"` / `"P"` and `"CE"` / `"PE"` |
1687
+ | `strike` | a listed price (`230`, `"24500"`), or `"ATM"`, `"ATM+N"`, `"ATM-N"` |
1688
+ | `settlement=` | `"pm"` (the default) or `"am"`: on a date that lists both, which one — SPX monthlies settle on that morning's opening prices, SPXW at the close |
1689
+ | `atm_from=` | `"options"` (the default) or `"spot"`: what ATM is measured from — below |
1690
+
1691
+ **ATM is counted as the Options Builder counts it.** ATM is the listed strike
1692
+ nearest the money, a tie going to the higher strike. `ATM+N` is N strikes
1693
+ **higher** and `ATM-N` N strikes **lower**, for calls and puts alike — on a
1694
+ put, `ATM+2` is in the money. A step is one listed strike, not a fixed price
1695
+ distance.
1696
+
1697
+ - `atm_from="options"`: the money is the expiry's forward, measured from the
1698
+ call and put prices near the money — the figure the Options Builder centres
1699
+ on. It keeps moving while an index stands still in its closing auction, and
1700
+ it carries the dividends and interest the expiry is priced on. Where no
1701
+ forward can be measured (no quoted call and put near the money: a shut
1702
+ market, a quiet board) the underlying's price stands, and the result says
1703
+ so in `atm_from`.
1704
+ - `atm_from="spot"`: the money is the underlying's own price — the strike the
1705
+ Option Chain panel marks by default. A source that sends no price for the
1706
+ underlying (SPX on Alpaca) is refused rather than measured another way.
1707
+
1708
+ **What it turns on.** Counting from the money turns on the underlying's live
1709
+ price when nothing has (it stays on: it is the strategy's from then on). For
1710
+ `"options"` it also turns on the call and put prices of the strikes nearest the
1711
+ money for a moment to measure the forward, and turns off again every one the
1712
+ strategy did not already hold. A listed price turns nothing on.
1713
+
1714
+ **How long it takes.** It answers from what the terminal holds, so usually at
1715
+ once. The first lookup of an underlying, or of an expiry's strikes, on IBKR
1716
+ waits while IBKR answers — up to 30 seconds, the Option Chain panel's own wait;
1717
+ a first price waits up to 5 seconds. The strategy's code waits at that line
1718
+ meanwhile, so look a contract up when you need it — at start, or just before
1719
+ ordering — not on every tick.
1720
+
1721
+ It returns a dict:
1722
+
1723
+ | Key | |
1724
+ |---|---|
1725
+ | `instrument_key` | the contract — what `buy` / `sell` / `bracket` / `subscribe` take |
1726
+ | `symbol` | the venue's own name for it |
1727
+ | `underlying_key`, `expiry`, `settlement`, `strike` (`Decimal`), `right` (`"CALL"` / `"PUT"`) | what was picked |
1728
+ | `lot_size` | one lot, in units (`Decimal`): 1 on a US option, the lot on an Indian one. **Order quantities are in units**, so one lot is `quantity=c["lot_size"]` and two lots twice it |
1729
+ | `multiplier`, `currency` | `multiplier` is a `Decimal`, `None` where the venue states none |
1730
+ | `atm_strike`, `offset`, `atm_from`, `atm_price` | for an ATM strike: the strike counted from, N, what the money was measured from (`"options"` or `"spot"`) and that figure |
1731
+
1732
+ It never names a neighbouring contract instead. A description that names no
1733
+ listed contract raises `While25Error`, with nothing turned on or placed;
1734
+ malformed arguments raise `ValueError`.
1735
+
1736
+ | code | meaning |
1737
+ |---|---|
1738
+ | `NO_UNDERLYING`, `NO_OPTIONS` | the underlying is not an instrument name, or lists no options |
1739
+ | `NO_EXPIRY` | no expiry on that date (the message names the nearest before and after), or the date's only expiry settles at the other time (pass `settlement=`) |
1740
+ | `NO_STRIKE` | the price is not a listed strike (the message names the nearest listed) |
1741
+ | `OFF_THE_LIST` | `ATM±N` runs off either end of the strike list, or the money is beyond the listed strikes |
1742
+ | `NO_PRICE` | an ATM strike with no price to find the money on yet |
1743
+ | `NOT_LISTED` | the board lists no call (or no put) at that strike |
1744
+ | `TIMEOUT` | the venue was still looking it up after 30 seconds — ask again |
1745
+
1746
+ The underlying and the strike from the settings, the trigger on the index's
1747
+ own bars:
1748
+
1749
+ ```python
1750
+ import while25
1751
+ from while25 import Strategy, on
1752
+ from while25.inputs import Enum, Float, Str
1753
+
1754
+ class IndexBreakout(Strategy):
1755
+ id = "index_breakout"
1756
+ inputs = [Enum("index", choices=["NIFTY", "BANKNIFTY"], default="NIFTY"),
1757
+ Float("level", default=24000.0),
1758
+ Str("strike", default="ATM+1")]
1759
+
1760
+ @on.bar("IDX:IN:NIFTY", "5m") # both written out: a bar line
1761
+ @on.bar("IDX:IN:BANKNIFTY", "5m") # takes a symbol from the file
1762
+ def on_bar(self, ctx, bar):
1763
+ if bar["symbol"] != "IDX:IN:" + while25.params["index"]:
1764
+ return # the other index's bar
1765
+ if bar["close"] > while25.params["level"]:
1766
+ c = while25.option(while25.params["index"], expiry="28th",
1767
+ right="CE", strike=while25.params["strike"])
1768
+ while25.buy(c["instrument_key"], c["lot_size"])
1769
+ while25.subscribe(c["instrument_key"], on_tick=self.on_option)
1770
+
1771
+ def on_option(self, ctx, tick):
1772
+ ... # every tick of the option bought
1773
+ ```
1774
+
1775
+ `option()` works in a running strategy or app. A one-shot run is refused
1776
+ `NOT_IN_RUN`, and a call while the file is being loaded (at import time)
1777
+ `IMPORT_TIME_DATA`.
1778
+
1779
+ ## Combos: several option legs as one order
1780
+
1781
+ ```python
1782
+ legs = [
1783
+ while25.leg(while25.option("SPY", "2026-11-20", "PUT", "ATM-4"), "BUY"),
1784
+ while25.leg(while25.option("SPY", "2026-11-20", "PUT", "ATM-2"), "SELL"),
1785
+ while25.leg(while25.option("SPY", "2026-11-20", "CALL", "ATM+2"), "SELL"),
1786
+ while25.leg(while25.option("SPY", "2026-11-20", "CALL", "ATM+4"), "BUY"),
1787
+ ]
1788
+ c = while25.combo(legs, lots=1, name="Iron condor")
1789
+ c["combo_id"] # what cancel(), square_off() and my_position() name it by
1790
+ ```
1791
+
1792
+ `while25.combo()` places two to ten option legs as ONE combo: a spread, a
1793
+ straddle, an iron condor, placed the way Deploy in Options Execution places a
1794
+ design, through the same placer. Legs sent as separate orders can fill one and
1795
+ miss the next, leaving a position nobody chose; a combo goes to the broker as
1796
+ one order where the broker takes one, and all or none where it does not
1797
+ (below). `while25.orders.combo()` is the same call.
1798
+
1799
+ **A leg** is `while25.leg(contract, side, ratio=1, price=None)`:
1800
+
1801
+ | Argument | Takes |
1802
+ |---|---|
1803
+ | `contract` | an option's instrument key, or the dict `while25.option()` returned |
1804
+ | `side` | `"BUY"` or `"SELL"`, in any capitals |
1805
+ | `ratio` | how many lots of this leg per lot of the combo: a whole number, 1 or more (`1` and `2` for a 1x2 ratio spread) |
1806
+ | `price` | this leg's own limit, on an `"LMT"` combo only (below) |
1807
+
1808
+ `leg()` checks what it is given on the line that writes it, and returns a
1809
+ plain dict. A dict you write yourself with the same four keys
1810
+ (`instrument_key`, `side`, `ratio`, `price`) is a leg too; any other key in it
1811
+ is refused, so a `"qty"` or a `"lots"` never quietly leaves a leg of ratio 1.
1812
+ A combo is 2 to 10 legs, and names each contract once.
1813
+
1814
+ **`lots=` is how many of the combo**, a whole number, 1 or more. Each leg's
1815
+ order is lots x its ratio x its contract's own lot size, as While25's
1816
+ instrument list states it: one contract per lot on a US option, the
1817
+ exchange's lot on an Indian one. You never write a leg's quantity, and a
1818
+ contract whose lot size is not on file is refused (`NO_LOT_SIZE`) rather than
1819
+ sized by a guess.
1820
+
1821
+ **Market, or each leg's own limit — never a mix.** `order_type=` is every
1822
+ leg's:
1823
+
1824
+ - `"MKT"` (the default): no leg states a price.
1825
+ - `"LMT"`: every leg states its own limit, above 0, in the figures any
1826
+ price takes (a `Decimal`, an `int`, plain decimal text, or an exact float).
1827
+ Where the broker takes the combo as one order, its limit is the legs'
1828
+ limits netted by ratio: a bought leg adds and a sold leg subtracts, so a
1829
+ credit is negative, as IBKR writes it. Leg by leg, each leg works at its
1830
+ own limit.
1831
+
1832
+ ```python
1833
+ legs = [while25.leg(put_far, "BUY", price="1.10"),
1834
+ while25.leg(put_near, "SELL", price="2.05"),
1835
+ while25.leg(call_near, "SELL", price="1.95"),
1836
+ while25.leg(call_far, "BUY", price="1.00")]
1837
+ while25.combo(legs, order_type="LMT") # as one order: 1.10 - 2.05 - 1.95 + 1.00 = -1.90, a 1.90 credit
1838
+ ```
1839
+
1840
+ A limit combo with a leg stating no price, and a market combo with a leg
1841
+ stating one, are refused (`ValueError`) before anything is sent: the one
1842
+ order's limit is built from every leg's price, so a missing one would leave it
1843
+ unset, and a stray one would put a limit on an order nobody priced.
1844
+
1845
+ `product=`, `validity=` and `hours=` apply to every leg and read as
1846
+ `place()`'s do (`hours="rth"` is refused: leave it out for regular hours).
1847
+ `name=` (at most 64 characters) is the combo's name on Options Execution, Open
1848
+ orders and the Positions tab, and `tag=` (at most 20) rides on every leg's
1849
+ orders and events. Left out, the name is the strategy's `id`, and the tag is
1850
+ `py:` and that `id`, as on any order of the strategy placed with no tag. Every
1851
+ call mints its own `idempotency_key=` unless you pass one, as `place()` does.
1852
+
1853
+ **How it goes to the broker:**
1854
+
1855
+ | Broker | |
1856
+ |---|---|
1857
+ | IBKR | one combo order of up to 6 legs; a combo of more legs goes leg by leg |
1858
+ | Alpaca | one combo order of 2 to 4 legs; more go leg by leg. Options only, validity DAY only (left out, it is DAY; any other is refused), regular hours only (`hours="eth"` is refused), and a limit combo's net on Alpaca's 0.01 tick |
1859
+ | Upstox, Zerodha | leg by leg, in the order the legs are listed |
1860
+
1861
+ Leg by leg it is **all or none**: a refused leg withdraws the legs not yet
1862
+ filled, and a leg that already filled stays, for your script to deal with.
1863
+ The answer's `one_order` says which way it went.
1864
+
1865
+ **What it answers**, once While25 has handed the combo on:
1866
+ `{"ok": True, "combo_id": ..., "order_ids": [...], "one_order": bool,
1867
+ "deployment_number": int}`. `order_ids` is each leg's order, in the order the
1868
+ legs were given; `deployment_number` is the combo's number on Options
1869
+ Execution (`#5`; 0 when it has none). Every event of its legs carries
1870
+ `ev["combo_id"]` and your `tag=`, so a handler tells the combo's fills from
1871
+ everything else:
1872
+
1873
+ ```python
1874
+ @on.fill(tag="condor")
1875
+ def on_fill(self, ctx, ev):
1876
+ if ev["combo_id"] == self.combo_id:
1877
+ ctx.log(f"{ev['symbol']} {ev['side']} {ev['last_fill_quantity']} @ {ev['last_fill_price']}")
1878
+ ```
1879
+
1880
+ A refusal raises `While25Error` with its code, as a refused `place()` does,
1881
+ and nothing is placed. The SDK refuses what it can judge itself in words
1882
+ (`ValueError`) before anything leaves your script; While25 judges again:
1883
+
1884
+ | code | meaning |
1885
+ |---|---|
1886
+ | `BAD_COMBO` | not 2 to 10 legs, a contract twice, a side that is not BUY or SELL, a ratio or `lots` below 1 |
1887
+ | `BAD_ORDER_TYPE` | an order type that is not `"MKT"` or `"LMT"` |
1888
+ | `BAD_PRICE` | a limit leg with no price above 0, or a market leg with one |
1889
+ | `BAD_PRODUCT`, `BAD_VALIDITY`, `BAD_HOURS` | as for `place()`, `"rth"` included |
1890
+ | `BAD_TAG`, `BAD_NAME` | a tag over 20 characters, a name over 64 |
1891
+ | `NOT_AN_OPTION` | a leg that is not an option contract |
1892
+ | `NO_LOT_SIZE` | the instrument list states no lot size for a leg's contract |
1893
+ | `INSTRUMENT_RESOLVING` | a leg's contract is still being fetched from the venue: call `combo()` again in a moment |
1894
+ | `INSTRUMENT_NOT_FOUND` | the venue does not list a leg's contract |
1895
+ | `KILL_SWITCH_ACTIVE` | the kill switch is on |
1896
+ | `DUPLICATE_ORDER` | the `idempotency_key=` was used already: a resubmit needs a fresh key |
1897
+ | `COMBO_REFUSED` | the placer refused it; the message is its words |
1898
+ | `NOT_LIVE`, `NOT_READY`, `BUSY`, `STORE_ERROR` | the terminal is not on the live account; While25's order path is not up yet; too many script orders are queued; the combo's record could not be written |
1899
+ | the grant codes | `NO_LIVE_GRANT`, `GRANT_STALE`, `MODULE_STOPPING` and the rest every order hears |
1900
+
1901
+ **What it holds is the combo's own.** What its legs fill belongs to the combo,
1902
+ held by your strategy, and never joins your strategy's part of each contract:
1903
+ `while25.portfolio.my_position(key)["quantity"]` leaves it out, exactly as it
1904
+ leaves a bracket out, and `my_position(key)["combos"]` lists it, one entry per
1905
+ combo holding that contract:
1906
+
1907
+ | Key | |
1908
+ |---|---|
1909
+ | `combo_id`, `label` | the combo, and its name as Options Execution shows it (`"#5 Iron condor"`; `"Combo"` when it has no deployment) |
1910
+ | `quantity` | what the combo holds of this contract, a signed `Decimal` |
1911
+ | `product` | its pocket, as on a part |
1912
+ | `average_price`, `last_price` | `Decimal`, or `None` when not known |
1913
+ | `pnl` | While25's unrealised P&L on it, a `Money`, or `None` when the price or the multiplier is not known |
1914
+ | `deployment_number` | its number on Options Execution; 0 when it has none |
1915
+
1916
+ A contract you hold only through a combo is listed too, with its own
1917
+ `quantity` `Decimal(0)`, and `my_positions()` lists every contract once. In
1918
+ `while25.orders.mine()` a combo's legs still working appear under their own
1919
+ order ids with `role` `"COMBO_LEG"`: they are cancelled with the combo, never
1920
+ alone.
1921
+
1922
+ **Cancel it, or square it off — always whole.**
1923
+ `while25.orders.cancel(c["combo_id"])` cancels every leg still working, as one
1924
+ order where the broker holds one, and each leg hears `CANCEL`. A combo is
1925
+ never cancelled or changed a leg at a time: a leg's own id is refused
1926
+ `COMBO_LEG` by `cancel()` and `modify()` on every broker (where the legs
1927
+ went one by one, a cancelled leg would leave its siblings working with no
1928
+ unwind). To change a combo, cancel it by its id and place it again. The
1929
+ cancel is refused `NOT_ORDER_OWNER` when the combo is not your module's, and
1930
+ `NOT_WORKING` when nothing of it is working.
1931
+
1932
+ `while25.orders.square_off(c["combo_id"])` does what Sq Off does on its row in
1933
+ Options Execution: its legs still working are cancelled, then what it holds is
1934
+ closed at market, as one combo order where the broker takes one. It answers
1935
+ once While25 has taken it, with `{"ok": True, "square_off_id": ...,
1936
+ "bracket_id": ...}` (`bracket_id` is the combo's id here). Each close arrives
1937
+ as `NEW` and `FILL` under its own id, with `ev["combo_id"]` set, and one
1938
+ `SQUARE_OFF` event under the combo's id, with its `tag=`, says how it went:
1939
+
1940
+ | `ev["status"]` | when |
1941
+ |---|---|
1942
+ | `SENT` | the closes went out: `ev["reason"]` lists them and `ev["close_order_id"]` names the first |
1943
+ | `DONE` | it held nothing to close: its legs still working were cancelled |
1944
+ | `REFUSED` | it could not start; `ev["reason"]` says why, and nothing was closed |
1945
+ | `STOPPED` | nothing could go out; `ev["reason"]` says why |
1946
+
1947
+ Refused at once, with nothing sent: `NO_BRACKET` (the id names no open combo,
1948
+ nor bracket, of your module), `NOT_ORDER_OWNER`, `MARKET_CLOSED`, `NOT_LIVE`,
1949
+ `NOT_READY` and `BUSY`.
1950
+
1951
+ **In the app.** Options Execution's Running list shows the combo as
1952
+ `#N <name>`, with no saved design behind it: its Sq Off and Cancel work as for
1953
+ any deployment, and it has no Add. Open orders and the Positions tab show it
1954
+ under the same `#N`.
1955
+
1956
+ **Stopping the strategy.** The Stop window lists each combo that holds
1957
+ something, with what each choice does to it: "Stop and cancel its orders"
1958
+ keeps it (and cancels a combo still working, whole), "Stop and square off"
1959
+ closes it whole, as one combo order where the broker takes one.
1960
+
1961
+ An iron condor, entered on the first bar and closed whole if SPY closes beyond
1962
+ either short strike:
1963
+
1964
+ ```python
1965
+ import while25
1966
+ from while25 import Strategy, on
1967
+
1968
+
1969
+ class SpyCondor(Strategy):
1970
+ id = "spy_condor"
1971
+ combo_id = None
1972
+ closing = False
1973
+
1974
+ @on.bar("EQ:US:SPY", "5m")
1975
+ def on_bar(self, ctx, bar):
1976
+ if self.combo_id is None:
1977
+ picks = [(while25.option("SPY", "2026-11-20", right, strike), side)
1978
+ for right, strike, side in (("PUT", "ATM-4", "BUY"),
1979
+ ("PUT", "ATM-2", "SELL"),
1980
+ ("CALL", "ATM+2", "SELL"),
1981
+ ("CALL", "ATM+4", "BUY"))]
1982
+ c = while25.combo([while25.leg(p, side) for p, side in picks],
1983
+ lots=1, name="Iron condor", tag="condor")
1984
+ self.combo_id = c["combo_id"]
1985
+ self.low, self.high = picks[1][0]["strike"], picks[2][0]["strike"]
1986
+ elif not self.closing and not self.low < bar["close"] < self.high:
1987
+ while25.orders.square_off(self.combo_id) # the whole condor, at market
1988
+ self.closing = True
1989
+
1990
+ @on.order(tag="condor")
1991
+ def on_order(self, ctx, ev):
1992
+ if ev["event"] == "SQUARE_OFF" and ev["combo_id"] == self.combo_id:
1993
+ ctx.log(f"square off {ev['status']}: {ev['reason']}")
1994
+ ```
1995
+
1996
+ On NIFTY the same lines name NIFTY's contracts
1997
+ (`while25.option("NIFTY", "28th", "PE", "ATM-2")`), `lots=1` is one NIFTY lot
1998
+ of each leg, and on Upstox or Zerodha the legs go one at a
1999
+ time, all or none. `combo()` works in a running strategy or trading app; a
2000
+ one-shot run is refused `NOT_IN_RUN`. While25 takes at most 1,000,000
2001
+ lots, and a ratio of at most 10,000 on a leg.
2002
+
2003
+ ## Futures: one contract from a root
2004
+
2005
+ ```python
2006
+ c = while25.future("MNQ") # the contract the chart's continuous MNQ is on now
2007
+ while25.buy(c["instrument_key"], 1, stop_loss=20950)
2008
+ while25.future("MNQ", "next") # the one after it, for a roll
2009
+ while25.future("MNQ", "2027-03") # a named contract month
2010
+ ```
2011
+
2012
+ The chart's continuous line (MNQ1!) is no contract and takes no order: an
2013
+ order on it is refused on every broker. `future()` is how a strategy gets from
2014
+ a root to the dated contract to trade, worked out now from the contracts the
2015
+ Futures panel lists. It turns nothing on and keeps nothing.
2016
+
2017
+ | Argument | Takes |
2018
+ |---|---|
2019
+ | `root` | the root as the Futures panel names it (`"MNQ"`, `"NIFTY"`, `"CRUDEOIL"`); `"ROOT@MIC"` where two exchanges of one market list the same root |
2020
+ | `expiry` | `"front"` (the default), `"next"`, or a contract month (`"2027-03"`, `"202703"`) |
2021
+
2022
+ **"front" is the contract the chart's continuous line for the root is on
2023
+ now**, so it rolls when that line rolls: on IBKR and Upstox after the first
2024
+ full session in which the next contract traded more than it (at the latest
2025
+ after its last trading day), on Zerodha at expiry. Where the venue draws no
2026
+ continuous line there is no front to follow: `"front"` and `"next"` are
2027
+ refused, and a named month works. `"next"` is the first contract of a later
2028
+ month than the front. A month is that month's contract, as its key names it:
2029
+ MNQ's `"2027-03"` is `FUT:US:MNQ:202703`, MNQH7.
2030
+
2031
+ **Nothing is rolled for you.** It is worked out on every call; when the front
2032
+ has moved on, the strategy closes the old contract and opens the new one with
2033
+ orders of its own (a bracket's close is `square_off()`, under Orders):
2034
+
2035
+ ```python
2036
+ c = while25.future("MNQ")
2037
+ if self.bracket_id and c["instrument_key"] != self.contract:
2038
+ while25.orders.square_off(self.bracket_id) # out of the old contract
2039
+ res = while25.buy(c["instrument_key"], 1, stop_loss=self.stop_for(c))
2040
+ self.contract, self.bracket_id = c["instrument_key"], res["order_id"]
2041
+ ```
2042
+
2043
+ It returns a dict: `instrument_key`, `symbol`, `root`, `month` (`"YYYY-MM"`),
2044
+ `last_trade` (ISO date, or None when the venue states none), `lot_size` and
2045
+ `multiplier` (`Decimal`, or None when the venue states none), `currency`,
2046
+ `tradeable` and `untradeable_reason` (an untradeable contract's orders are
2047
+ refused, the reason says why), and `front` (True when it is the contract the
2048
+ chart's line is on now; None for a named month, which does not look). The
2049
+ contract it names is on the venue's list, so its first order is not refused as
2050
+ unknown. The first lookup of a root on IBKR, and the line's first look at its
2051
+ contracts, wait while the venue answers, up to 30 seconds.
2052
+
2053
+ | `While25Error.code` | when |
2054
+ |---|---|
2055
+ | `NO_ROOT` | not a root: a contract's key, or nothing |
2056
+ | `NO_FUTURES` | the venue lists no live futures for the root |
2057
+ | `AMBIGUOUS_ROOT` | two exchanges list the root; the message names `ROOT@MIC` for each |
2058
+ | `NO_FRONT` | `"front"` or `"next"` where the venue draws no continuous line for the root: name a month (the message lists them) |
2059
+ | `NO_NEXT` | no contract after the front is listed yet |
2060
+ | `NOT_LISTED` | the month is not listed (the message names the listed ones) |
2061
+ | `AMBIGUOUS_MONTH` | the month lists more than one contract (a weekly beside the monthly): order the one you mean by its key |
2062
+ | `TIMEOUT` | the venue was still looking it up after 30 seconds — ask again |
2063
+
2064
+ ## Two strategies, one account
2065
+
2066
+ A live strategy trades the **account**, not a private book. Everything it reads
2067
+ back is account-wide:
2068
+
2069
+ - `while25.portfolio.position(key)` is the account's net position on that
2070
+ instrument — another strategy's trades and a trade worked by hand in the
2071
+ terminal included. Size an exit from `my_position()`, what your module
2072
+ holds now, never from `position()`, or it can sell someone else's shares.
2073
+ A count of your own (the fills of the order ids you got back) goes stale
2074
+ when the whole position is squared off: read it again from `my_position()`
2075
+ on `POSITION_SQUARED_OFF`.
2076
+ - `@on.order` and `@on.fill` deliver every order event on the account — another
2077
+ strategy's, and the human's. There is no owner field; match on the
2078
+ `order_id` your call returned, or on a `tag` you set on your own orders.
2079
+
2080
+ The broker nets every fill on an instrument into one position; While25
2081
+ keeps each strategy's PART of it apart (2026-10-18). Two strategies may trade
2082
+ one instrument at once: each keeps its own part — changed by its own
2083
+ orders, ended only by a square off of the whole position (below) — its own stops, measured against that part, and its own Stop, which
2084
+ squares off that part and nothing else; the broker nets the parts. Brackets
2085
+ too: two strategies' brackets stand side by side on one instrument, each
2086
+ sized to its own fills.
2087
+
2088
+ **A coin held outright (crypto spot)** can never be sold short, so there a
2089
+ strategy sells only what its own part holds, less its sells already working
2090
+ (`SELL_EXCEEDS_PART` beyond that; a short bracket entry likewise). One
2091
+ strategy can never sell another's coins, or the human's.
2092
+
2093
+ **Where the venue takes its fees from the holding itself and does not report
2094
+ them per fill** — Alpaca today; each broker adapter declares it — nobody can
2095
+ say whose fill paid the fee, so While25 cannot keep separate parts of a
2096
+ coin: every stop and bracket on it follows the account's whole holding, and
2097
+ one strategy at a time trades it. A second strategy's order there (plain or
2098
+ bracket) is refused `LONG_ONLY_ONE_STRATEGY` while the first holds a part,
2099
+ has a working order or a live bracket, in words, naming it. A venue that
2100
+ reports its fees per fill has no such rule: its coins keep parts per
2101
+ strategy like everything else.
2102
+
2103
+ **Two Strategy classes inside one App are ONE owner.** The App's orders,
2104
+ grant and part are the App's (`py:<app id>`), whichever of its strategies
2105
+ placed them — so one of them can flatten the other's bracketed position
2106
+ exactly as a trade by hand could. Keep strategies that share an instrument in
2107
+ separate modules.
2108
+
2109
+ What the parts do not cover: a trade made by hand still nets against a
2110
+ strategy's position (it is the account owner's intent). A strategy stopped
2111
+ with a position open keeps it as its own part unless the Stop squared that
2112
+ part off: the part stays under the strategy's id through the Stop and through
2113
+ a restart of the app, and the Positions tab shows it under the strategy.
2114
+ Deployed again, the same strategy (the same `id`) reads it with
2115
+ `while25.portfolio.my_position(key)` and goes on from there, and its brackets
2116
+ and working orders are its own again.
2117
+
2118
+ **A square off of the whole position takes every strategy's units on it**:
2119
+ Square off on the position's row in the Positions tab, the daily loss limit's
2120
+ close, or the broker's own square off. Each strategy's part, brackets and
2121
+ combo parts on that position end at once (their stops and take-profits come
2122
+ off; the one close sells the units with the rest), and the strategy keeps
2123
+ running. Its module hears `POSITION_SQUARED_OFF` for each thing taken,
2124
+ `my_position()` no longer counts it from that moment, and what the units sold
2125
+ for counts in its closed P&L where that close's own fills state it.
2126
+
2127
+ ## Output
2128
+
2129
+ ```python
2130
+ while25.log("something happened") # the console
2131
+ while25.notify("RSI crossed 70") # a notice to the trader
2132
+ while25.chart.plot("sma", values, times) # a series on the price chart
2133
+ while25.ui.push("results", rows) # a table / chart / backtest in your app's own panel
2134
+ ```
2135
+
2136
+ Your app's own panel is the one place results show. `while25.viz` is not displayed anywhere —
2137
+ a call only prints a console line saying so.
2138
+
2139
+ `while25.notify(message, *, title="", level="info", symbol="")` tells the
2140
+ trader: a notice on screen, kept in the Monitors panel's Notices list. Any
2141
+ kind of module may call it; it returns nothing and never raises.
2142
+ `level` is `"info"`, `"warn"` or `"error"` (anything else goes as `"info"` and
2143
+ the console says so); `warn` and `error` stay on screen longer and are also
2144
+ kept in the app's Warnings & errors list. `title` is a short heading (120
2145
+ characters), `message` holds 2,000, `symbol` is the instrument it is about.
2146
+ A module may send 10 at once, then one every 2 seconds; past that they are
2147
+ dropped and the console says how many. In a one-off Run the notice is printed
2148
+ to the console and not sent.
2149
+
2150
+ While no While25 window is in front, each notice is also a notification from
2151
+ the computer itself (on Windows, a Windows notification), with its sound. Your
2152
+ script decides when: the app adds no spacing of its own. The Monitors panel
2153
+ has a tick for the notifications and one for the sound, both on at first.
2154
+ Every notice is also kept in the log on this computer (see "Monitors").
2155
+
2156
+ `while25.log(message, level="info")` writes one console line; `level` is
2157
+ `"info"`, `"warn"` or `"error"`, and a line over 8 MiB is cut and says so.
2158
+ `while25.chart.plot(name, values, times, overlay=True)` puts a series on the
2159
+ price chart; `while25.chart.draw(name, tool_type, anchors, config=, style=,
2160
+ label=)` puts a drawing on it — `anchors` is a list of `(time_ms, price)`
2161
+ pairs — with `hline(name, price)`, `trendline(name, t1, p1, t2, p2)`,
2162
+ `box(name, t1, p1, t2, p2)` and `label(name, time_ms, price, text)` as the
2163
+ usual shapes, `erase(name="")` to remove one drawing or every one the module
2164
+ made, and `tools()` for every tool type the chart knows. Drawing a name again
2165
+ replaces that drawing; a bad anchor or tool type is reported in the console,
2166
+ never raised. `while25.ui.push(slot, value)` is dropped with a console
2167
+ warning for a slot the layout did not declare or a value that is not JSON;
2168
+ one message to the terminal may be at most 16 MiB.
2169
+
2170
+ Output has a budget, per module. `print` and `while25.log` together may send
2171
+ 100 lines (256 KiB) a second, in bursts of up to 1,000 lines (1 MiB); past it
2172
+ lines are dropped and the console says how many, once a second. A plot, a
2173
+ drawing, an indicator or a `ui.push` slot updates at most 10 times a second,
2174
+ newest value wins, and the last value always arrives. Orders, data calls and
2175
+ signals are never counted, so printing in a loop slows nothing but the
2176
+ console. A message the terminal cannot handle (`while25.log(msg,
2177
+ logging.WARNING)`, say: the level must be a word) is dropped with an error
2178
+ line naming why; the module keeps running.
2179
+
2180
+ ## Monitors
2181
+
2182
+ A `Monitor` watches and tells you. It reads everything a strategy reads and
2183
+ is woken the same way, and it can never place, change or cancel an order:
2184
+ every order call raises `OrderRightsError`.
2185
+
2186
+ ```python
2187
+ import while25
2188
+ from while25 import Monitor, on
2189
+
2190
+ class BreakoutWatch(Monitor):
2191
+ id = "breakout_watch"
2192
+ label = "Breakout watch"
2193
+
2194
+ def on_start(self, ctx):
2195
+ self.rows = list(while25.warmup("IDX:IN:NIFTY", "5m", 20)) # the 20 bars before now
2196
+
2197
+ @on.bar("IDX:IN:NIFTY", "5m")
2198
+ def bar(self, ctx, bar):
2199
+ high = max(r["high"] for r in self.rows) # the 20 bars before this one
2200
+ self.rows = (self.rows + [bar])[-20:]
2201
+ if bar["close"] > high:
2202
+ while25.notify(f"closed at {bar['close']}, above the 20-bar high {high}",
2203
+ title="NIFTY breakout", level="warn", symbol="IDX:IN:NIFTY")
2204
+ ```
2205
+
2206
+ It keeps its own window of bars, started from `warmup()` (see "Warm-up"): the
2207
+ live series may hold no bars from before the module started.
2208
+
2209
+ Press **Start** on the file in the Code Editor, or on its row in the Monitors
2210
+ panel; **Stop** is in the same two places. There is no Deploy window, because
2211
+ nothing it does can trade. The Monitors panel lists every monitor, whether it
2212
+ runs, and what scripts have said. The AI chat can write a monitor and stop
2213
+ one; it cannot start one. You press Start.
2214
+
2215
+ Every notice and every AI question with its answer is also kept on this
2216
+ computer, in full and with its time, one CSV file a day: **Open log folder**
2217
+ in the Monitors panel. The data sent with a question is not kept.
2218
+
2219
+ One monitor can watch many symbols: several `@on.bar` or `@on.tick` lines, or
2220
+ `while25.subscribe(key, on_tick=self.method)` for symbols known only while
2221
+ running. Each running module is its own process, so write one monitor over
2222
+ twenty symbols, not twenty monitors. A monitor is not started again when the
2223
+ app restarts: start it by hand.
2224
+
2225
+ ### Asking the AI: `while25.ai.ask`
2226
+
2227
+ A monitor can ask the AI one question about what it found, and act on the
2228
+ answer:
2229
+
2230
+ ```python
2231
+ @on.bar("IDX:IN:NIFTY", "5m")
2232
+ def bar(self, ctx, bar):
2233
+ high = max(r["high"] for r in self.rows)
2234
+ self.rows = (self.rows + [bar])[-20:]
2235
+ if bar["close"] <= high:
2236
+ return # the free check: most bars end here
2237
+ verdict = while25.ai.ask(
2238
+ "Is this a clean breakout or a likely fakeout? The last row is the breakout bar.",
2239
+ data=self.rows, choices=["breakout", "fakeout"])
2240
+ if verdict == "breakout":
2241
+ while25.notify("clean breakout above the 20-bar high", title="NIFTY",
2242
+ level="warn", symbol="IDX:IN:NIFTY")
2243
+ ```
2244
+
2245
+ `while25.ai.ask(question, *, data=None, choices=None, timeout=60, then=None, tag=None)`
2246
+
2247
+ - `question`: at most 4,000 characters.
2248
+ - `data`: what the AI should read with it: text, or rows and figures (sent as
2249
+ JSON), at most 32 KiB. The AI sees only the question and this. It has no
2250
+ tools and cannot look anything up, so send what it needs.
2251
+ - `choices`: two to ten words. The answer is then exactly one of them, as
2252
+ written here.
2253
+ - `timeout`: seconds an answer may take, 5 to 120.
2254
+ - `then`: one of the monitor's own methods, to ask and carry on (below).
2255
+ - `tag`: with `then`, comes back with the answer: text, a number, or a list
2256
+ or dict of them, at most 1,000 characters as JSON.
2257
+
2258
+ **Ask and wait** (no `then`, as above): returns the answer as text, or `None`
2259
+ when there is none. It blocks: the monitor's other handlers wait until it
2260
+ returns. Right for a monitor that watches one symbol.
2261
+
2262
+ **Ask and carry on** (`then=self.method`): returns at once, `True` when the
2263
+ question was asked and `False` when it could not be. The answer comes later
2264
+ as one call of `method(ctx, answer, tag)`, with `answer` `None` when there
2265
+ was none. Right for a monitor over many symbols: each one that fires asks
2266
+ without waiting for the one before.
2267
+
2268
+ ```python
2269
+ SYMBOLS = ["EQ:US:AAPL", "EQ:US:MSFT", "EQ:US:NVDA"]
2270
+
2271
+ class BreakoutWatch(Monitor):
2272
+ id = "breakout_watch"
2273
+
2274
+ def on_start(self, ctx):
2275
+ self.rows = {s: list(while25.warmup(s, "5m", 20)) for s in SYMBOLS}
2276
+
2277
+ @on.bar("EQ:US:AAPL", "5m")
2278
+ @on.bar("EQ:US:MSFT", "5m")
2279
+ @on.bar("EQ:US:NVDA", "5m")
2280
+ def bar(self, ctx, bar):
2281
+ key = bar["symbol"]
2282
+ high = max(r["high"] for r in self.rows[key])
2283
+ self.rows[key] = (self.rows[key] + [bar])[-20:]
2284
+ if bar["close"] <= high:
2285
+ return
2286
+ while25.ai.ask("Is this a clean breakout or a likely fakeout? The last row is the breakout bar.",
2287
+ data=self.rows[key], choices=["breakout", "fakeout"],
2288
+ then=self.judged, tag=key)
2289
+
2290
+ def judged(self, ctx, answer, tag):
2291
+ if answer == "breakout": # the market has moved since the question: check again here if it matters
2292
+ while25.notify("clean breakout above the 20-bar high", title=tag, level="warn", symbol=tag)
2293
+ ```
2294
+
2295
+ A monitor may have 20 questions out at once; the app sends three at a time
2296
+ and the rest wait their turn. When a monitor is stopped, answers still on the
2297
+ way are dropped.
2298
+
2299
+ No answer (`None`, or `False` when the question never left) is never a raise,
2300
+ and the console says why: the allowance for monitor questions is used up, the
2301
+ AI is off or cannot be reached, too many questions are out, or no answer came
2302
+ in time. A call that could never work raises `ValueError` or `TypeError` (no
2303
+ question, too much data, bad choices, a `then` that is not one of the
2304
+ monitor's own methods, a `tag` without `then`).
2305
+
2306
+ Only a `Monitor` may ask. From a `Strategy`, an `App` or an `Indicator` it
2307
+ raises `While25Error` (code `AI_NOT_ALLOWED`), and a one-off Run cannot ask:
2308
+ a module that may trade never asks the AI.
2309
+
2310
+ The app asks for the monitor, with your sign-in, apart from the AI chat:
2311
+ a question never interrupts the chat, and it is counted on the monitors' own
2312
+ share of your plan's AI limits (its cost is also part of the day's total).
2313
+ The app tells you when 80% of the day's allowance is gone and again when it
2314
+ is used up; from then until the next day's starts (midnight UTC) a question
2315
+ gets no answer. Decide *whether* to ask in Python, as above: that check costs
2316
+ nothing. The Monitors panel's AI questions list shows each question and its
2317
+ answer.
2318
+
2319
+ ### A monitor inside a strategy
2320
+
2321
+ A strategy never asks the AI. A monitor asks, and sends the strategy a
2322
+ signal. The strategy lists the monitor as its own:
2323
+
2324
+ ```python
2325
+ import while25
2326
+ from while25 import Bars, Monitor, Strategy, on
2327
+
2328
+ class DipWatch(Monitor):
2329
+ id = "dip_watch"
2330
+ aapl = Bars("EQ:US:AAPL", "5m", keep=20)
2331
+
2332
+ @on.bar(aapl)
2333
+ def bar(self, ctx, bar):
2334
+ if bar["close"] > 0.97 * self.aapl.rows[0]["close"]:
2335
+ return # your own condition: most bars end here
2336
+ while25.ai.ask("Is this fall a steady slide or one sharp drop? The rows are 5-minute bars.",
2337
+ data=self.aapl.rows, choices=["slide", "drop"], then=self.judged)
2338
+
2339
+ def judged(self, ctx, answer, tag):
2340
+ if answer == "drop": # None (no answer) sends nothing
2341
+ while25.emit("dip_ok", {"close": self.aapl.last["close"]})
2342
+
2343
+ class DipBuyer(Strategy):
2344
+ id = "dip_buyer"
2345
+ monitors = [DipWatch] # its own: starts and stops with it
2346
+
2347
+ @on.signal("dip_ok", sender=DipWatch) # hears DipWatch, and nobody else
2348
+ def go(self, ctx, payload):
2349
+ while25.buy("EQ:US:AAPL", 10)
2350
+ ```
2351
+
2352
+ Give it its panel in the same file too: see "A strategy's panel: its desk".
2353
+
2354
+ `monitors` lists `Monitor` classes, so the monitor is written (or imported)
2355
+ above the strategy. Which file a monitor sits in decides nothing: one that no
2356
+ strategy lists is nobody's. Only a `Strategy` or a trading `App` may list
2357
+ any, and anything in the list that is not a `Monitor` class with an `id` is
2358
+ refused when the file is saved.
2359
+
2360
+ - **Deploy starts both, Stop stops both.** Deploying the strategy starts the
2361
+ monitors it lists, on the same code; when the strategy stops or halts, they
2362
+ stop. A trading App has the monitors its own class lists and those its
2363
+ Strategy classes list.
2364
+ - **The Deploy window has a box to tick**: the AI can be wrong, may give no
2365
+ answer, sees only what the monitor sends, and an order placed on its signal
2366
+ is a real order. A strategy that lists a monitor is not deployed until the
2367
+ box is ticked. It is asked at every deploy.
2368
+ - **Its signals reach its own strategy** and no other module that trades.
2369
+ - **Settings**: the monitor starts with the strategy's value for every input
2370
+ the two declare under the same name; its other inputs keep their defaults.
2371
+ - **If the monitor stops on an error**, the strategy keeps running and no
2372
+ signal comes. The app says so; start the monitor again from the Monitors
2373
+ panel, where it is listed as part of its strategy.
2374
+ - **A backtest starts no monitor**: no signal arrives there, and nothing asks
2375
+ the AI.
2376
+
2377
+ A monitor no strategy lists can signal a strategy too: only one deployed
2378
+ with the box ticked, which the Deploy window offers when the strategy has an
2379
+ `@on.signal`. Not ticked, the strategy deploys and no monitor's signal
2380
+ reaches it. You start and stop such a monitor yourself.
2381
+
2382
+ ## Indicators
2383
+
2384
+ One indicator, one label, as many lines as you like:
2385
+
2386
+ ```python
2387
+ import while25
2388
+ from while25 import Fill, Indicator, Plot, on
2389
+ from while25.inputs import Float, Int
2390
+
2391
+
2392
+ class MyBollinger(Indicator):
2393
+ id = "my_bb"
2394
+ label = "My Bollinger" # ONE legend entry for all three lines
2395
+ overlay = True
2396
+
2397
+ inputs = [Int("length", default=20, minimum=2, maximum=500, step=1),
2398
+ Float("mult", default=2.0, step=0.1)]
2399
+
2400
+ plots = [Plot("basis", color="#e0a34a", width=2),
2401
+ Plot("upper", color="#4aa3e0", style="dashed"),
2402
+ Plot("lower", color="#4aa3e0", style="dashed")]
2403
+ fills = [Fill("upper", "lower", color="#4aa3e0", opacity=0.08)]
2404
+
2405
+ warmup = lambda params: int(params.get("length", 20))
2406
+
2407
+ def compute(self, ctx):
2408
+ n = while25.params["length"]
2409
+ rows = while25.bars # While25 streams you the chart's bars
2410
+ ...
2411
+ self.times = [int(r["time"]) for r in rows]
2412
+ return {"basis": basis, "upper": upper, "lower": lower}
2413
+ ```
2414
+
2415
+ - `inputs` become a config dialog the user can edit — the same one built-in
2416
+ indicators use.
2417
+ - `plots` set the DEFAULT colour, width and line style. The user can still
2418
+ override every one of them in the chart settings, exactly as for a built-in.
2419
+ - `Plot(plot_type=...)` takes `line · histogram · area · stepline`;
2420
+ `Level(70)` draws a reference line and `Band(top, bottom)` shades a zone.
2421
+ - `compute()` returns a dict keyed by your plot names. Returning a name you did
2422
+ not declare is an error rather than a silently missing line. Every
2423
+ indicator writes its own `compute(self, ctx)`: a class without one is
2424
+ refused when the file is saved.
2425
+ - **A chart starts indicators and nothing else.** If a file on a chart is
2426
+ saved again as a `Strategy`, a `Monitor` or an `App` under the same id, the
2427
+ chart draws nothing for it and starts nothing: its log says so. Take it off
2428
+ the chart, and start the new module the way its kind is started.
2429
+ - **An indicator RECEIVES its series.** While25 streams the chart's series
2430
+ — scrollback included — to Python, and every change to it recomputes
2431
+ you; the client no longer sends bars. `while25.bars` is that array, oldest
2432
+ first, replaced whole every pass. `while25.forming` is the unclosed bar and
2433
+ is present only while a bucket is forming (otherwise `None`; it is never
2434
+ inside `bars`). `while25.price` is the price the chart's candles are built
2435
+ from: "last", or "mark" on a Binance futures chart set to Mark price (no
2436
+ volume). `while25.future_times` is the chart's projected grid. The
2437
+ times are the chart's own wire times, so
2438
+ `self.times = [r["time"] for r in rows]` lands every value on the candle it
2439
+ came from. Sourcing a second series is refused: `candles(...,
2440
+ source="live")` inside `compute()` raises `LIVE_IN_COMPUTE`. Two series
2441
+ drift after a scrollback, and the chart's by-timestamp merge then blanks
2442
+ the line exactly where the user scrolled.
2443
+ - **`warmup` declares what you need** — an `int`, or a callable of the params
2444
+ when it is derived (DEMA needs `2*period-1`). Short input reports
2445
+ `warming up — 12 of 39 bars` instead of drawing nothing. A bigger `limit` is
2446
+ never the answer: it truncates a fetch, and here there is no fetch.
2447
+ - **`Plot(name, color="", width=1, style="solid", plot_type="line",
2448
+ color_down="", opacity=1.0, overlay=None, visible=True)`.** `width` is 1 to
2449
+ 4; `style` is `solid · dotted · dashed · large-dashed · sparse-dotted`;
2450
+ `color_down` is a histogram's or bi-colour plot's second colour; `overlay`
2451
+ `None` follows the indicator's own `overlay`. `Fill(upper, lower, color="",
2452
+ opacity=0.08)` shades between two of your plots. `levels = [Level(70,
2453
+ color="", width=1, style="dashed")]` draws reference lines and `bands =
2454
+ [Band(top, bottom, color="", opacity=0.06)]` shades zones. `y_min` /
2455
+ `y_max` fix the pane's scale (RSI 0 to 100) and `precision` its decimals.
2456
+ `intrabar = True` recomputes as the bar forms, not only when it closes (a
2457
+ full recompute per tick: off by default). A declaration the chart cannot
2458
+ draw — no plots, a plot named twice, a fill naming a plot you did not
2459
+ declare, a band whose top is not above its bottom — is refused when the
2460
+ file is registered.
2461
+ - **`while25.instrument` and `while25.interval`** are the chart's: the
2462
+ symbol and interval it is drawing, set per compute, so one indicator works
2463
+ on any chart.
2464
+
2465
+ ### An indicator's numbers in a strategy
2466
+
2467
+ ```python
2468
+ from indicators.my_rsi import MyRsi
2469
+
2470
+ class TslaRsi(Strategy):
2471
+ id = "tsla_rsi"
2472
+ tsla = Bars("EQ:US:TSLA", "5m", keep=100)
2473
+
2474
+ @on.bar(tsla)
2475
+ def on_bar(self, ctx, bar):
2476
+ rsi = self.tsla.indicator(MyRsi, length=14)["rsi"]
2477
+ if rsi[-1] > 70:
2478
+ ...
2479
+ ```
2480
+
2481
+ `line.indicator(cls, *, forming=False, **params)` works an indicator out from
2482
+ a `Bars` line's own bars. It is `while25.indicator` with `bars=line.rows`:
2483
+
2484
+ `while25.indicator(cls, *, bars=None, forming=False, instrument="",
2485
+ interval="", **params)` works another indicator out in this process, from
2486
+ the bars you hand it, and returns exactly what its `compute()` returned.
2487
+ Nothing is drawn and no chart is needed. Only a chart hands an indicator bars
2488
+ by itself, so a strategy passes its own.
2489
+
2490
+ - `bars`: oldest first, your warm-up and `@on.bar` bars, or `candles()`
2491
+ rows. The indicator reads them as `while25.bars` in a chart's row shape
2492
+ (`time` in epoch ms, `open`, `high`, `low`, `close`, `volume`), so one
2493
+ written for a chart works unchanged; `while25.forming` is `None`.
2494
+ - `forming`: `True` also counts the bar still forming, see below.
2495
+ - `instrument`, `interval`: what it reads as `while25.instrument` and
2496
+ `while25.interval`; left out, the bars' own.
2497
+ - `**params`: its inputs, checked and defaulted as on a chart.
2498
+
2499
+ `ValueError`, without running it: fewer bars than its `warmup`, bars out of
2500
+ order or two at one time, a bar without a time or a price, bars of two
2501
+ series in one list (two `@on.bar` lines), an `instrument` or `interval` that
2502
+ is not the bars' own. With no `bars=`, an indicator that reads
2503
+ `while25.bars` raises `ValueError` saying so; only one called inside another
2504
+ indicator's `compute()` reads its caller's bars.
2505
+
2506
+ **Before the bar closes.** `@on.bar` wakes the strategy once a bar has
2507
+ closed. To act while it is still forming, ask from a tick handler with
2508
+ `forming=True`:
2509
+
2510
+ ```python
2511
+ @on.tick("EQ:US:TSLA")
2512
+ def on_tick(self, ctx, tick):
2513
+ rsi = self.tsla.indicator(MyRsi, forming=True, length=14)["rsi"]
2514
+ ```
2515
+
2516
+ It adds the bar still forming on that `@on.bar` line after your bars, as
2517
+ While25 last sampled it (about once a second; the chart's moving candle is
2518
+ the same bar). The indicator reads it as its last bar; your own list is not
2519
+ changed.
2520
+
2521
+ - Added only when it is the bar right after your last one: never a bar you
2522
+ already hold closed, and never past a closed bar your list has not got
2523
+ yet. Otherwise, and while nothing is forming, the indicator is worked out
2524
+ from your bars as they are.
2525
+ - `bars` must be those of one of the module's own bar lines (a `Bars` line,
2526
+ or an `@on.bar` line's warm-up and bars), whatever its interval: that line
2527
+ is what holds the symbol's prices while the module runs. Anything else
2528
+ raises `ValueError`.
2529
+ - Its `warmup` is counted in closed bars.
2530
+
2531
+ ## A panel
2532
+
2533
+ An `App` can declare its own panel. You declare a layout **once** and afterwards
2534
+ push values into named slots — While25 renders it, so a plugin panel cannot
2535
+ break the terminal's look or its rendering performance.
2536
+
2537
+ ```python
2538
+ import while25
2539
+ from while25 import App, on, ui
2540
+
2541
+ ui.panel("sensex_pulse", label="Sensex Pulse")
2542
+ ui.layout(
2543
+ ui.row(ui.metric("level"), ui.metric("chg")),
2544
+ ui.table("headlines"),
2545
+ )
2546
+
2547
+ class SensexPulse(App):
2548
+ id = "sensex_pulse"
2549
+
2550
+ @on.schedule(every="10m")
2551
+ def refresh(self, ctx):
2552
+ while25.ui.push("level", 81_234.5)
2553
+ while25.ui.push("headlines", [{"headline": "…"}])
2554
+ ```
2555
+
2556
+ Widgets available today are `row`, `metric`, `chart`, `table`, `text`, `view`
2557
+ and `html`. They are **display-only**; the interaction model is still being
2558
+ designed, and shipping a half-considered callback contract would freeze an API
2559
+ you would then be stuck with.
2560
+
2561
+ ### Choosing the component
2562
+
2563
+ **The default is an HTML page** — `ui.layout(ui.html("view"))`, built on the
2564
+ terminal's brand theme (see "HTML" below). Reach for something else only when it
2565
+ fits the job better:
2566
+
2567
+ | The job | Reach for |
2568
+ |---|---|
2569
+ | Almost anything — a dashboard, a desk, a monitor, a screener | `ui.html` (the default) |
2570
+ | Backtest or strategy results — equity, drawdown, monthly returns, statistics, trades | the `backtest` block, built with `ui.backtest_block(trades, data=[...])` and sealed by Python — the terminal's backtest view |
2571
+ | A chart inside your page | draw it in the page: inline `<svg>` built in Python, or CSS bars. For hover and tooltips, an optional `chart` block beside an `html` block in a `ui.view` |
2572
+ | The terminal's own components instead of markup | `tiles`, `kv`, `table` blocks in a `ui.view` |
2573
+
2574
+ Wiz is never required: a panel needs no chart block, and a chart needs no Wiz.
2575
+
2576
+ ### Blocks — `ui.view`
2577
+
2578
+ `ui.view(slot)` is the one to reach for first: push a dict describing WHAT to
2579
+ show and the terminal renders it in its own components — `header`, `tiles`,
2580
+ `kv`, `table`, `badges`, `text`, `progress`, `chart`, `backtest`, `html`,
2581
+ `section`, `row`, `divider`. A `chart` block is the interactive Wiz surface by
2582
+ default (hover, legend, resize; `"live": true` buys the SVG fast path for a
2583
+ data-rate redraw), and an `html` block is your own markup as one sandboxed
2584
+ section — so custom HTML and an interactive chart share ONE panel:
2585
+
2586
+ ```python
2587
+ ui.layout(ui.view("main")) # the ONLY widget → the view IS the panel
2588
+
2589
+ while25.ui.push("main", {"blocks": [
2590
+ {"kind": "header", "title": "Sector map"},
2591
+ {"kind": "row", "blocks": [
2592
+ {"kind": "html", "html": "<div class='card'><h1>Notes</h1><p>…</p></div>"},
2593
+ {"kind": "chart", "title": "Weight", "spec": {
2594
+ "kind": "treemap", "rows": rows, "x": "sector", "value": "mcap"}},
2595
+ ]},
2596
+ ]})
2597
+ ```
2598
+
2599
+ Tones: `money` (coloured by SIGN), `profit`, `loss`, `active`, `attention`,
2600
+ `error`, `muted`, `neutral`. Pass raw numbers, never pre-formatted strings, and
2601
+ `None` for "not known yet" — the terminal formats every number and shows `—`
2602
+ for absence, so a figure you do not have never reads as a zero you do. The
2603
+ docstring on `ui.view` carries every field.
2604
+
2605
+ #### The backtest block
2606
+
2607
+ A results view is the one thing a script never assembles. You hand over the
2608
+ **trades** and the **history they were built on**; While25 computes
2609
+ every figure from those and either seals the block or refuses it. Nothing the
2610
+ script computes (curve, statistics, currency) reaches the screen.
2611
+
2612
+ ```python
2613
+ import while25
2614
+ from while25 import backtest
2615
+
2616
+ span = while25.history_span("EQ:US:AAPL", "15m", "2025-01-01", "2025-06-30")
2617
+ inst = while25.data.instrument("EQ:US:AAPL")
2618
+ trades = []
2619
+ # ... your logic decides every trade, bar by bar; shown here for one trade:
2620
+ bars = span["bars"]
2621
+ bar, later = bars[10], bars[20] # the entry bar and the bar the exit is tested on
2622
+ stop = bar["low"] # a stop level your logic chose
2623
+ f_in = backtest.fill(bar, "buy", "open", instrument=inst)
2624
+ f_out = backtest.fill(later, "sell", "stop", instrument=inst, price=stop)
2625
+ if f_out is not None: # None: that bar never reached the stop; test the next one
2626
+ # intraday only when both fills share a trading date; held overnight is delivery
2627
+ product = "intraday" if f_in.date == f_out.date else "delivery"
2628
+ trades.append(backtest.trade(inst, "buy", 10, f_in, f_out, product=product))
2629
+
2630
+ while25.ui.push("main", {"blocks": [
2631
+ while25.ui.backtest_block(
2632
+ trades, # what backtest.trade() returned; every position closed
2633
+ data=[span["id"]], # the history_span answer id(s) the trades were filled on
2634
+ start_equity=0, capital=100_000,
2635
+ title="RSI(14) mean reversion", subtitle="EQ:US:AAPL · 15m · long only",
2636
+ notes="Signals on the close, fills at the next open.",
2637
+ logic={"Entry": ["RSI(14) crosses below 30", "fill at the next bar's open"],
2638
+ "Exit": "a stop at the entry bar's low"})]})
2639
+ ```
2640
+
2641
+ `backtest_block(trades, *, data, start_equity=0.0, capital=None, title=None,
2642
+ subtitle=None, notes=None, assume=None, logic=None)`. `data` is required (an id or a list of ids).
2643
+ `start_equity` is where the curve starts (0 = cumulative P&L); `capital` turns
2644
+ on the percentage figures (`None`: the user's default capital, if one is set).
2645
+ `assume` is what every trade was built under (`None`: the run's
2646
+ `backtest.defaults()`; see **Assumptions** below).
2647
+
2648
+ `logic` is the strategy's rules in your own words, shown above the figures in
2649
+ a "Strategy" panel captioned "from the script": a dict whose insertion order is
2650
+ the display order (`{"Entry": ["RSI(14) < 30", "close above the 200 SMA"],
2651
+ "Exit": "RSI(14) > 70"}`) or a list of `(name, lines)` pairs, where a line
2652
+ value is one str or a list of str. It is recorded as `[{"name", "lines"}]`.
2653
+ Any section name works: Universe, Entry, Exit, Sizing, Model, Features,
2654
+ Signal, Legs, Adjust, Pair, Hedge ratio, Rebalance. Limits: at most 10
2655
+ sections and at most 12 lines per section, a name at most 40 characters and a
2656
+ line at most 240 characters, every line a non-empty str. Past one,
2657
+ `backtest_block` raises `TypeError` (a wrong type) or `ValueError` (a wrong
2658
+ size) naming the field (`logic[1].lines[0]`), and the parent refuses a block
2659
+ whose `logic` has another shape whole (`R-SHAPE`, naming the field). The
2660
+ parent never interprets the words: it copies them to the sealed `logic`
2661
+ (`None` when there are none). Like `title`, `subtitle` and `notes` they may
2662
+ not claim While25's checks: "reconciled by While25" or "sealed by While25"
2663
+ in them refuses the block (`R-IMPERSONATE`).
2664
+
2665
+ **What the parent does.** On every push it replaces each backtest block, at any
2666
+ depth, with `{"kind": "backtest", "sealed": {...}}` or
2667
+ `{"kind": "backtest", "refused": [{"rule", "detail"}]}`. It re-derives each
2668
+ trade (`backtest.fill` and `backtest.trade`) on the bar it recorded when it
2669
+ delivered the `history_span` answer, with the instrument facts While25
2670
+ stated, and requires the same prices, costs and pnl, exactly. It marks the
2671
+ curve to market per bar (a bar's close counts only from the bar's END, time plus
2672
+ interval; the curve opens at `start_equity` 1 ms before the first bar). A
2673
+ `limit`, `stop` or `close` fill happens inside its bar and counts from that
2674
+ bar's end: an exit is gone before the bar's close could mark it, an entry is
2675
+ marked at that close. An `open` fill counts from the next point after its
2676
+ bar's start: the point at that start still shows the previous close, so a long
2677
+ sold at an open still shows the close before that open, and an open entry is
2678
+ held at its fill price until a close from a later bar is known (a close from
2679
+ before the fill never marks it). A fill past the last bar adds a point. Then it computes
2680
+ drawdown, statistics and the monthly table (each trade in the month of its
2681
+ exit fill's trading date). No While25 code decides
2682
+ when a trade happens: your script does.
2683
+
2684
+ **The rules.** A block that breaks one is refused whole, and nothing is drawn
2685
+ but the rule and its words (`R-SHAPE` included):
2686
+
2687
+ | Rule | Refused when |
2688
+ |---|---|
2689
+ | `R-SHAPE` | the block is not one `backtest_block()` builds (types, sizes), or the pushed value cannot be read; a push holding a backtest block and `NaN`, `Infinity`, a number past the double range (`1e400`) or an integer over 4000 digits is refused whole, naming it (a push with no backtest block passes untouched) |
2690
+ | `R-DATA` | a `data` id this module was never given, or one it dropped; a trade on an instrument no named answer covers; an answer naming no covered window or no exchange clock; two answers of one instrument that differ in vendor, feed, adjustment or session, or disagree on a bar both hold; two answers of one instrument on different intervals (fill and mark one instrument on one interval; read other intervals for signals without naming them in data). Different instruments may use different intervals |
2691
+ | `R-WINDOW` | a trade outside the covered window; no bar inside it |
2692
+ | `R-TRADE-DERIVED` | a trade that is not what `trade()` gives on the recorded bars, including everything `trade()` refuses (below): an impossible fill order, an `intraday` product held overnight, a quantity off the venue's step, a symbol listed as not equity; a trade built under other assumptions (values or sources) than the block declares, so two overrides mixed in one block; a block claiming `your default` for a value the user's defaults do not hold, or `built-in` where they hold one; an `exit_fill` exit that is not what `exit_fill` gives on its bar under the trade's same-bar rule and fill style |
2693
+ | `R-PRICE` | a price at or below 0 (a real negative futures price is refused too), or outside its bar's `[low, high]` widened by the leg's declared slippage, then the tick |
2694
+ | `R-FACTS` | While25 states no multiplier, tick or currency, or the lookup failed or timed out (never assumed, never 1); under real costs only (zero and custom costs read no tariff), a trade costed on another broker than the account's broker While25 states, or on the test broker's tariffs when the account is not the test broker. The facts are asked fresh for each changed push, so a broker switch is seen at the next one |
2695
+ | `R-CURRENCY` | more than one currency, across instruments or cost schedules |
2696
+ | `R-FLAT` | an open trade (no exit): close positions with a last trade |
2697
+ | `R-TIME` | a time that is not integer epoch milliseconds, `1e11 <= t < 1e14` |
2698
+
2699
+ **What the sealed block carries.** Money and ratios are **decimal strings**
2700
+ (exact; ratios to 8 places), times are epoch ms, counts are ints, and an absent
2701
+ figure is `None` or a missing key, never 0 (volume may be `None`). `win_rate` is
2702
+ a fraction (0 to 1); every `*_pct` is already times 100. Keys: `title`,
2703
+ `subtitle`, `notes`, `logic` (the script's rules, `[{name, lines}]` or `None`),
2704
+ `currency` (from While25, never the script),
2705
+ `start_equity`, `capital`, `sources[]` (per `data` answer: id, symbol, interval,
2706
+ `asked` window, `covered_from` / `covered_to` as exchange-local dates, vendor,
2707
+ feed, adjustment, session, `missing_days`, `calendar`, `calendar_tz`,
2708
+ `calendar_note`), `fill_rules[]`, `slippage[]`, `cost_schedules[]` (schedule,
2709
+ rate set, `backdated`, `note`, and `omitted`: what that schedule knowingly
2710
+ leaves out, a list that may be empty, e.g. the DP charge on Indian delivery
2711
+ sells, contract-note rounding, rounding to the cent), `assumptions[]` (what
2712
+ the fills assume, e.g. that a limit or stop fills when the bar's range
2713
+ touches its price, with no queue or partial fill, or under `through` fills only
2714
+ when the bar trades through it; empty when no limit or stop
2715
+ fill is used, and "risk-free <x>%" when Sharpe or Sortino is stated),
2716
+ `settings[]` (all six assumptions, see **Assumptions**), `gross`, `equity`, `drawdown`, `stats`, `monthly[]` (month of
2717
+ the exit fill's trading date) and `trades[]` (rows: `instrument`, `side`, `qty`, `entry_time`,
2718
+ `exit_time`, `entry`, `exit`, `multiplier`, `gross`, `costs_in`, `costs_out`,
2719
+ `pnl`, `entry_how`, `exit_how`), and `no_trades` (true when there are none: a sealed
2720
+ block with zero trades is valid). `gross` is true when every cost total is 0 and
2721
+ the view shows "GROSS, no costs". `stats` has `trades`, `wins`, `losses`,
2722
+ `breakeven`, `net_pnl`, `max_drawdown`, `costs_total`, `exposure_pct`, and,
2723
+ when defined, `win_rate`, `expectancy`, `best`, `worst`, `avg_win` (needs a
2724
+ win), `avg_loss` and `profit_factor` (need a loss), and with `capital`
2725
+ `return_pct` and `max_drawdown_pct`. Series are downsampled to 5,000 points;
2726
+ the newest 2,000 trades are listed (`notes` says so) and the statistics cover
2727
+ all of them. More than 20,000 trades is refused unread. The curve's last point
2728
+ is the last bar's end (its close known); `drawdown` and `benchmark` end there too.
2729
+
2730
+ `stats` also carries, each omitted when undefined (never `inf`, never a 0
2731
+ standing in for "not defined"):
2732
+
2733
+ - `sharpe`, `sortino`: from the curve's trading-day closes on the first
2734
+ source's calendar, each day's change r. At the built-in risk-free 0% (then
2735
+ `assumptions[]` says "risk-free 0%") r is used as is, a return on one
2736
+ constant base, so the ratios depend on neither `capital` nor `start_equity`;
2737
+ at a rate x above 0 (`assumptions[]` says "risk-free <x>%") each return is
2738
+ r / capital - x / 100 / days per year, so they need `capital` (no capital, no ratio). `sharpe` = mean / sample
2739
+ standard deviation, `sortino` = mean / sqrt(mean of min(r, 0)^2), each times
2740
+ sqrt(the calendar's sessions per year). Omitted under 20 daily returns, with
2741
+ zero deviation, or when no such year is known.
2742
+ - `cagr_pct`: with `capital` and a covered window (earliest `covered_from` to
2743
+ latest `covered_to`, inclusive) of at least 365 calendar days,
2744
+ ((capital + net) / capital)^(365.25 / days) - 1, times 100. Omitted on a
2745
+ shorter window and when the account ruined (capital plus the final net, or
2746
+ plus the curve's lowest (value - `start_equity`), at or below 0). `calmar` = `cagr_pct` /
2747
+ -`max_drawdown_pct` (with a drawdown).
2748
+ - `max_dd_duration_ms` (int; the longest time below a running peak, 0 without a
2749
+ drawdown) and `recovery_ms` (the deepest trough to the first point back at
2750
+ its peak; `None` if it never recovered).
2751
+ - With trades: `avg_hold_ms` (int; each trade's exit bar time less its entry
2752
+ bar time, bar start to bar start, so a one-bar trade is 0 and an overnight
2753
+ hold never is), `max_win_streak` and `max_loss_streak` (in exit order; a
2754
+ breakeven ends both), `trades_per_day` (trades / trading dates holding a
2755
+ bar), `turnover`, `costs_pct_of_gross` (with gross above 0), `largest_win`,
2756
+ `largest_loss`, and `payoff_ratio` = `avg_win` / -`avg_loss`.
2757
+ - A percentage or ratio 1e15 or more in size is omitted (no screen holds it).
2758
+
2759
+ `turnover` is money: the sum of (entry + exit) x qty x multiplier, both legs.
2760
+ `breakdown` holds `waterfall` {gross, costs, net} where `costs` is negative
2761
+ (minus the costs total) and gross + costs = net exactly; `costs_by_charge`
2762
+ [{charge "<schedule>.<charge>", amount}] (custom costs: one line, `custom`;
2763
+ zero costs: none) whose amounts are positive (what was
2764
+ paid) and sum to `costs_total`; `by_hour` [{hour 0-23, trades, net}] by each
2765
+ trade's entry bar time on the first source's `calendar_tz`, for trades on
2766
+ intraday bars only (a daily bar has no hour, so a daily backtest has an empty
2767
+ list); `by_weekday` [{weekday 0-6, Mon = 0, trades, net}] of the entry's
2768
+ exchange trading date; `by_side` and `by_instrument` [{side or instrument,
2769
+ trades, wins, net}]; `tz` (that `calendar_tz`). Each trade row also carries
2770
+ `hold_ms` (as above), `mae` and `mfe`: the worst and best open P&L in money,
2771
+ price only, no costs, at a price the position provably saw: its fills, every
2772
+ bar wholly inside the hold, and on the entry and exit bars only what provably
2773
+ followed the fill (a limit entry counts its bar's adverse extreme, a stop
2774
+ entry its favourable extreme, an open entry the whole bar, a close entry only
2775
+ its close; a close exit counts its whole bar, an open, limit or stop exit only
2776
+ its bar's open). A limit or stop fill rests on the touch assumption in
2777
+ `assumptions[]`. Both fills are counted, so `mae` <= min(`gross`, 0) and
2778
+ max(`gross`, 0) <= `mfe`.
2779
+
2780
+ `benchmark` {label, instrument, points, symbols} is buy and hold, no costs, starting
2781
+ at `start_equity` and marked like the curve at the curve's times. With one
2782
+ instrument in the data it is that instrument bought at its first bar's open:
2783
+ without `capital` 1 unit x multiplier, labelled "buy and hold <symbol>, no
2784
+ costs"; with `capital` capital / (first open x multiplier) units, labelled
2785
+ "buy and hold <symbol> with <capital>, no costs"; `None` under 2 bars. With
2786
+ two or more instruments in the data it is an equal-weight basket: each gets
2787
+ capital / N at its own first bar's open (cash until then), labelled "buy and
2788
+ hold, equal weight across <symbols> with <capital>, no costs" (the symbols in
2789
+ data order; the first 10, then "and N more"), and `instrument` is `None`.
2790
+ `symbols` lists the benchmark's instrument symbols in data order (one for one
2791
+ instrument, every member of a basket, at most 50). Without a capital (the block's or
2792
+ your default) there is no basket, since equal weight needs a capital: `None`,
2793
+ as for a member with no bar in its covered window. With `capital` the values
2794
+ are to 8 places.
2795
+ `prices` is a list of price views, one per instrument with a listed trade,
2796
+ ordered by first trade time (its earliest listed entry), then instrument key:
2797
+ {instrument, `symbol` (its `data` answer's symbol), interval, `trades` (its
2798
+ listed trades), bars [[t, o, h, l, c]], markers}. Each is that instrument's
2799
+ bars, at most 5,000 bars (every marked bar, the first, the last, then an even
2800
+ stride); past 4 instruments each view gets 5,000 x 4 / N bars, so a push
2801
+ holds at most 20,000 in all, and every marked bar is always kept. `markers`
2802
+ are one per listed fill on it: {t, price, side, kind "entry" | "exit", trade
2803
+ (index in `trades[]`)}, where `side` is the fill's side (a short's entry
2804
+ marker is a sell). With no listed trade, `prices` still shows the candles so
2805
+ you can see why nothing fired: one view per data instrument holding a bar, in
2806
+ data order, at most 4, each with no markers and `trades` 0. `price` is
2807
+ `prices[0]`, kept for older terminals.
2808
+
2809
+ **What the view shows.** Header, the Strategy panel (`logic`, "from the script"), tiles (net, return, CAGR, max drawdown,
2810
+ win rate, profit factor, Sharpe, trades, expectancy, costs), Performance (every stat above, each naming its
2811
+ definition; "—" when absent), the equity curve with the benchmark line and its
2812
+ label, Trades (with MAE, MFE and hold, and Export CSV of the rows exactly as
2813
+ sealed), Monthly, Distribution, Breakdown (the waterfall, costs by charge,
2814
+ by hour and weekday in the named tz, by side, by instrument) and Price
2815
+ (candles with each fill marked, one chip per instrument when there are two or more; a marker selects its trade row). When one
2816
+ `ui.push` to one slot holds two or more sealed backtest blocks (e.g. a `section` or
2817
+ `row` of them in that slot), a compare strip appears above them (each block's
2818
+ title, net, return, max drawdown, win rate, Sharpe and trades, copied from its
2819
+ seal; a refused block shows its status); blocks pushed to different slots each
2820
+ stand alone. So never re-draw any of it in `html`, `table` or a chart, and to
2821
+ compare settings push one block per setting in one push to one slot.
2822
+
2823
+ **Calculators** (`from while25 import backtest`). None loops over bars, holds a
2824
+ position or decides a trade; each answers one question exactly (Decimal, a
2825
+ fixed context, no clock, no randomness).
2826
+
2827
+ - `backtest.fill(bar, side, how, *, instrument, price=None, slippage=None, assume=None)`
2828
+ returns the `Fill` of one order on one bar, or `None` when the bar never
2829
+ reaches it. `how` is `open`, `close` (no `price`), `limit` or `stop` (needs
2830
+ `price`). A gap fills at the open, worse than the stop. Then slippage, then
2831
+ the venue's tick against the trader. No tick stated: `RULES_UNKNOWN`. The
2832
+ `Fill` carries its bar's `date` and `end` (time plus the bar's interval); a
2833
+ bar naming no interval of known length is `BAD_BAR`. `assume` (an
2834
+ `Assumptions`; `None` reads `backtest.defaults()`) sets the fill style:
2835
+ `touch` fills a limit / stop at an exactly equal low / high, `through` only
2836
+ when the bar trades past it. `slippage=None` applies the assumption's
2837
+ slippage (`slippage_stated` False); any `Slippage` given, even
2838
+ `Slippage.none()`, is stated. The `Fill` records `fills` and `assume` (the
2839
+ assumptions' fingerprint).
2840
+ - `backtest.first_exit(bar, side, *, stop, target, rule=None, assume=None)` returns
2841
+ `"stop"`, `"target"` or `None`: which exit this bar reaches first for a
2842
+ position entered on `side`. A bar that opens through a level reached it
2843
+ first; when both are touched inside the bar, `rule` (`stop_first` or
2844
+ `target_first`; `None` is the assumption's `same_bar`) says which to
2845
+ assume. Under `through` a level counts only when traded past.
2846
+ - `backtest.exit_fill(bar, side, *, instrument, stop, target, slippage=None, assume=None)`
2847
+ fills a position's bracket exit: `first_exit` picks the level, the opposite
2848
+ side fills there (the stop as a stop, the target as a limit), and the `Fill`
2849
+ records `bracket` (`stop`, `target`, `rule` as strings). `None` when neither
2850
+ level is reached.
2851
+ - `backtest.Slippage` is always against the trader: `Slippage.none()`,
2852
+ `Slippage.bps(n)`, `Slippage.ticks(n)`.
2853
+ - `backtest.cost_for(key, side, price, qty, *, product, on, multiplier)` and
2854
+ `backtest.costs(instrument, side, price, qty, *, product, on, broker=None)`
2855
+ return `Costs` (`lines`, `total`, `currency`, `schedule`, `rate_set`,
2856
+ `backdated`). `CostKey(country, exchange, segment, broker, symbol="")` is
2857
+ what identifies a fill to the registry; `costs()` reads it from the
2858
+ instrument and the account's broker. `product` is `intraday` or `delivery`; `on` is the
2859
+ fill's exchange-local trade date.
2860
+ - `backtest.trade(instrument, side, qty, entry, exit, *, product, broker=None, assume=None)`
2861
+ returns one round trip: `gross = (exit - entry) x qty x multiplier` (negated
2862
+ for a short), `pnl = gross - both sides' costs`. Each side is costed on its
2863
+ fill's trading date. This is what `backtest_block` takes. It refuses
2864
+ (`BAD_FILL`) an exit that cannot follow its entry: on one bar the order is
2865
+ open, then limit / stop, then close, so a close entry never exits on its own
2866
+ bar, and a limit or stop entry with a limit or stop exit on one bar is
2867
+ refused (the order of the high and low inside one bar is unknowable; use a
2868
+ finer interval); and a limit, stop or close entry is known only at its bar's end, so no
2869
+ other bar starting before that end may exit it, on any interval (a daily
2870
+ limit entry cannot exit on an hourly bar of the same day). `BAD_PRODUCT`: an `intraday` product whose entry and exit fall
2871
+ on different trading dates (a position held overnight is `delivery`).
2872
+ `BAD_QTY`: a quantity off the venue's size step (the lot, else the
2873
+ increment) or under its minimum, where the venue states them. Costs follow
2874
+ `assume` (`real`, `zero` or `custom`, below); `BAD_FILL` also for a fill
2875
+ made under other assumptions than the trade's.
2876
+ - `backtest.sessions(answer)` groups a `history_span` answer's bars by
2877
+ exchange trading day on the clock the answer names (`calendar_tz`); no clock
2878
+ stated: `CALENDAR_UNKNOWN`, never UTC.
2879
+
2880
+ **Assumptions.** Every backtest runs under six assumptions: `costs` (`real`,
2881
+ `zero` or `custom`), `slippage` (the default for a fill that states none),
2882
+ `fills` (`touch` or `through`), `same_bar` (`stop_first` or `target_first`),
2883
+ `risk_free` (percent per year, 0 to 100) and `capital`. Each value carries a
2884
+ source: `built-in` (While25's own: real costs, no slippage, touch, stop first,
2885
+ 0%, no capital), `your default` (what the user set in the terminal's settings)
2886
+ or `this backtest` (what the script chose).
2887
+
2888
+ - `backtest.defaults()` returns the run's snapshot of the user's defaults, a
2889
+ read-only `backtest.Assumptions`. While25 takes the snapshot when
2890
+ the run (or the module's start) arrives; a running script keeps it, and a
2891
+ change to the defaults applies from the next run. Re-pushes from that run
2892
+ re-seal under it. With no terminal (a plain import) every value is built-in.
2893
+ - `backtest.assume(**overrides)` returns `defaults()` with this backtest's own
2894
+ choices on top; each value it sets reads `this backtest`. Keys: `costs`,
2895
+ `custom_flat`, `custom_pct` (both needed with `costs="custom"`, refused with
2896
+ any other), `slippage` (a `Slippage`), `fills`, `same_bar`, `risk_free`;
2897
+ capital is `backtest_block(capital=)`. An unknown key, a `None` value (leave
2898
+ the key out to keep the default) or a bad value raises `BAD_INPUT` naming it.
2899
+ - It only returns the choice: pass it as `assume=` to every `fill()`,
2900
+ `exit_fill()` and `trade()` call and to `backtest_block()`. Calling
2901
+ `backtest.assume()` and passing it nowhere changes nothing.
2902
+ - An override applies to this backtest only: it never changes the user's
2903
+ defaults, and a script cannot claim `your default` (only the parent's
2904
+ snapshot can say that; the parent re-checks every source).
2905
+ - Declare it once and pass the same object to every `fill`, `first_exit`,
2906
+ `exit_fill`, `trade` and the `backtest_block`. Each fill and trade records
2907
+ the assumptions it was built under; a trade built under others than the
2908
+ block declares is refused (`R-TRADE-DERIVED`), so two overrides mixed in one
2909
+ block are refused. To compare settings, push one block per setting.
2910
+ - `slippage=None` on a fill means the default slippage (the assumption's;
2911
+ recorded as not stated). Any `Slippage` you pass, even `Slippage.none()`, is
2912
+ stated, and the block says how many fills set their own.
2913
+ - `same_bar` is enforced for exits built with `backtest.exit_fill`: the parent
2914
+ re-checks that a bar touching both the stop and the target exited at the one
2915
+ the rule picks. A plain `fill()` exit carries no bracket and is not checked,
2916
+ so use `exit_fill` for a bracket (not `first_exit` then `fill`). A block
2917
+ holding limit / stop exits not built with `exit_fill` says so in its
2918
+ assumptions ("same-bar stop and target order not checked for N exits not
2919
+ built with exit_fill").
2920
+ - Zero costs replace every charge, broker and statutory alike. Custom charges
2921
+ `custom_flat` on each fill (entry and exit, i.e. per order) plus `custom_pct`
2922
+ percent of that fill's turnover. Neither reads the cost registry, so
2923
+ `COSTS_UNKNOWN` and the account's-broker check do not apply; the venue's
2924
+ multiplier, tick and currency are still required.
2925
+
2926
+ ```python
2927
+ # one backtest, its own assumptions
2928
+ a = backtest.assume(costs="zero", same_bar="target_first")
2929
+ f_in = backtest.fill(bar, "buy", "open", instrument=inst, assume=a)
2930
+ f_out = backtest.exit_fill(later, "buy", instrument=inst, stop=95, target=110, assume=a)
2931
+ if f_out is not None:
2932
+ trades.append(backtest.trade(inst, "buy", 10, f_in, f_out, product="intraday", assume=a))
2933
+ while25.ui.push("main", {"blocks": [
2934
+ while25.ui.backtest_block(trades, data=[span["id"]], capital=100_000, assume=a,
2935
+ title="zero costs, target first")]})
2936
+ ```
2937
+
2938
+ The sealed block states them in `settings[]`: all six, always, in this order:
2939
+ costs, slippage, fills, same_bar, risk_free, capital, each `{name, value,
2940
+ source}` with `value` a wire string (`real` / `zero` / `custom`; the default
2941
+ slippage as `none`, `bps:<n>` or `ticks:<n>`; `touch` / `through`;
2942
+ `stop_first` / `target_first`; the risk-free percent; capital as a plain
2943
+ decimal or `None`). `costs` custom adds `flat` and `pct`; `slippage` adds
2944
+ `own` (an int: the fills that stated their own, shown as "N fills set their
2945
+ own"). Under zero or custom costs `cost_schedules[]` holds one schedule,
2946
+ "zero" or "custom: <flat> per order + <pct>% of turnover" (rate set "", not
2947
+ backdated, nothing omitted), and the view shows a badge that the costs are not
2948
+ the real tariff. The view shows the assumptions and their sources itself:
2949
+ never re-draw them.
2950
+
2951
+ **Costs are registry data.** Brokerage, taxes and fees come only from the dated,
2952
+ sourced cost registry While25 bundles with the SDK:
2953
+ each rate set has an `effective_from` and a source, and a fill is costed from
2954
+ the statutory schedule for its country, segment and exchange plus the broker's
2955
+ schedule. A missing schedule or rate is refused (`COSTS_UNKNOWN`), never costed
2956
+ as zero: Indian statutory charges before 2024-10-01 are refused, an exchange
2957
+ with no schedule is refused, and an instrument typed ETF has no cost segment
2958
+ and is refused. NSE's ETFs, SGBs, G-secs, InvITs and REITs trade in the cash
2959
+ segment and arrive typed as equity, but their charges are not equity charges:
2960
+ the registry's dated, sourced `non_equity` list (from NSE's own files) gives
2961
+ each such symbol a class, and a listed symbol is costed only from the
2962
+ schedules for its class, never as equity. An equity ETF (`equity_etf`: NSE's
2963
+ ETF list states its underlying as equity) pays STT on a sell only (0.001%
2964
+ delivery, 0.025% intraday; none on a buy); a gold, silver or debt ETF
2965
+ (`other_etf`) pays none; both pay the cash market's exchange charge, IPFT,
2966
+ SEBI fee, stamp duty and GST (`in_nse_eq_etf`, `in_nse_other_etf`, from
2967
+ 2024-10-01). Brokerage on an ETF is the broker's published equity delivery /
2968
+ intraday tariff (Zerodha and Upstox publish no separate ETF line;
2969
+ the sealed header says so). Still refused (`COSTS_UNKNOWN`): an ETF NSE does
2970
+ not class (international, hybrid), SGBs and G-secs (NSE publishes no
2971
+ transaction charge for them), InvITs and REITs, and an ETF on a broker with no
2972
+ ETF schedule. The symbol is compared NFKC-normalized and upper-cased,
2973
+ without zero-width characters, any whitespace, an exchange prefix (`NSE:`),
2974
+ a separated `EQ` or a `.NSE`, `.NS` / `.BO` suffix, and an Indian equity cost with no symbol, or with the list missing,
2975
+ is refused too. Costs follow the account's broker; the test broker's
2976
+ fixture tariffs serve only an account on the test broker. A
2977
+ broker tariff (undated pages) may be backdated to its first published rate set;
2978
+ the sealed `cost_schedules[]` then carries `backdated: true` and a `note`.
2979
+ Pass no costs yourself: they cannot be passed (zero and custom costs are
2980
+ assumptions, above, never a figure).
2981
+
2982
+ **Migrating from the old signature.** `backtest_block(equity, trades, ...,
2983
+ stats=, drawdown=, benchmark=, currency=)` is gone. `equity`, `stats`,
2984
+ `drawdown`, `benchmark` and `currency` raise `TypeError` naming the parameter:
2985
+ Python computes them. Build each trade with `backtest.trade()` and pass
2986
+ `data=[answer["id"]]`. The sealed block states the Sharpe, the benchmark and
2987
+ the rest itself; a figure you draw elsewhere is not the sealed result. Do not thin the data for the view: the parent downsamples for display
2988
+ and keeps every bar's high and low.
2989
+
2990
+ **What the seal cannot prove.** It proves the trades follow from the bars you
2991
+ were given. It cannot see **look-ahead** in your own logic (a signal that
2992
+ reads a bar it should not have seen yet), nor **best-of-many** (a parameter
2993
+ sweep where you show only the winner). It covers `backtest` blocks only: an
2994
+ `html` slot can still draw something that looks like a result, so the look of a
2995
+ view is not the proof; the sealed card is.
2996
+
2997
+ ### HTML — `ui.html`
2998
+
2999
+ `ui.html(slot)` is the app's page, and the default for a panel. Push a markup
3000
+ string; **you own the page — structure and look**, and your CSS renders as
3001
+ written. Build on the brand theme first — the classes below, the tokens and the
3002
+ styled bare tags — so the page reads as part of the terminal and follows its
3003
+ light/dark switch:
3004
+
3005
+ | Group | Classes |
3006
+ |---|---|
3007
+ | layout | `.page` `.stack` `.row` `.flex` `.col` `.wrap` `.between` `.center` `.grow` · `.grid-2` `.grid-3` `.grid-4` `.grid-auto` · `.span-2` `.span-3` `.span-4` `.span-all` |
3008
+ | spacing — N = 0…6 → 0 2 4 8 12 16 24px | `.p-N` `.px-N` `.py-N` `.m-N` `.mt-N` `.mb-N` `.gap-N` |
3009
+ | type | `.t-xs` 11 · `.t-sm` 12 · `.t-base` 13 · `.t-lg` 14 · `.t-xl` 16 · `.t-2xl` 20 · `.t-3xl` 24 · `.w-4` `.w-5` `.w-6` · `.t-up` · `.t-num` · `.t-mono` `.t-prose` · `.t-left` `.t-center` `.t-right` · `.micro` |
3010
+ | tone | `.c-profit` `.c-loss` `.c-data` `.c-bright` `.c-dim` `.c-amber` `.c-active` `.c-attn` `.c-error` (the older `.profit` `.loss` `.muted` … still work) |
3011
+ | ground | `.bg-0` `.bg-1` `.bg-2` `.bg-amber-dim` `.bg-profit-dim` `.bg-loss-dim` `.bg-attn-dim` `.bg-error-dim` |
3012
+ | components | `.header` + `.stamp` · `.card` > `.card-h` + `.card-b` · `.tiles` > `.tile` > `.k` `.v` `.sub` · `.stat` > `.stat-k` `.stat-v` `.stat-d` (`.stat-d.up` / `.down` add the arrow) · `.kv` (`<dl>`) · `.badge` + `-active` `-attention` `-error` `-profit` `-loss` `-warning` `-amber` · `.pill` · `.callout.info` / `.warn` / `.error` · `.progress > i` (width inline) · `.divider` · `.seg` > `span` (`.on` = selected) · `.section` + `.section-title` |
3013
+ | tables | zebra by default · `table.dense` · `table.sticky` (sticky header) · `.num` right-aligns |
3014
+ | heat (an HTML heatmap) | `.heat-p1`…`.heat-p5` gains, `.heat-l1`…`.heat-l5` losses — you pick the step |
3015
+
3016
+ Utilities win over components (`.card.p-0`, `.v.c-loss`). Your own `<style>`
3017
+ block (or inline `style`) always wins over the brand sheet, which sits in a lower
3018
+ cascade layer; bare CSS before your first tag is wrapped in `<style>` for you,
3019
+ never shown:
3020
+
3021
+ ```python
3022
+ ui.layout(ui.html("view")) # the ONLY widget → the view IS the panel
3023
+
3024
+ while25.ui.push("view", """
3025
+ <div class="card">
3026
+ <small>Day P&L</small>
3027
+ <div class="t-3xl t-num c-profit">+12,480.25</div>
3028
+ </div>
3029
+ """)
3030
+ ```
3031
+
3032
+ Declare either alone and it takes the whole panel — full height, no caption, no
3033
+ padding. Put it beside other widgets and it is one content-sized section among
3034
+ them.
3035
+
3036
+ You are not starting from a blank page: the terminal's theme tokens resolve
3037
+ inside (`var(--color-amber)`, `--color-profit`, `--color-loss`,
3038
+ `--color-text-dim`, `--color-surface-2`, …) and follow a theme switch, bare
3039
+ markup is already styled (headings, tables with tabular numerals and zebra
3040
+ rows, code, lists), and the class catalog above is there to use. Type is three faces by role — IBM Plex Mono for
3041
+ data, Inter for `<p>` / `<li>` prose, JetBrains Mono for code — on a four-step
3042
+ scale (`h1` 20, `h2` 16, `h3` 14, text 12, labels 11, tile values 22). A
3043
+ `.card` / `.tile` carries a 2px left stripe that names its meaning
3044
+ (`.tile.profit`, `.card.error`).
3045
+
3046
+ Nothing you write is snapped, stripped or rewritten — colours, fonts, shadows,
3047
+ gradients, radii and emoji render as written. Prefer the tokens to literal
3048
+ colours: a literal does not follow the light/dark switch. Charts are yours to
3049
+ draw: inline `<svg>` (build its `points` / `d` in Python, give it axes and
3050
+ labels — it keeps the `width` / `height` you set) or CSS bars (`.progress`,
3051
+ `.heat-*`). A backtest still goes in the `backtest` block.
3052
+
3053
+ It renders in a sandboxed frame **without script permission**: `<script>`,
3054
+ `on*` handlers and `javascript:` URLs are inert, so compute in Python and push
3055
+ new markup rather than scripting. CSS animations and `:hover` do work. Links
3056
+ open in the system browser (https only).
3057
+
3058
+ ### Desk blocks
3059
+
3060
+ A strategy's desk is its app panel. Build it from blocks in a `ui.view`; each
3061
+ helper returns one block and checks its shape at the call (`TypeError` or
3062
+ `ValueError` naming the field).
3063
+
3064
+ ```python
3065
+ import while25
3066
+ from while25 import ui
3067
+
3068
+ while25.ui.push("main", {"blocks": [
3069
+ ui.strategy_block(), # this module's reconciled figures
3070
+ ui.conditions("Entry", [
3071
+ ui.rule("RSI(14)", rsi, "<", 30, near=10),
3072
+ ui.rule("Close", close, "crosses_above", vwap, prev=prev_close),
3073
+ ], need="all"),
3074
+ ui.levels(price=close, levels=[ui.level("Stop", stop, tone="loss"),
3075
+ ui.level("Target", target, tone="profit")]),
3076
+ ui.timeline([(t_ms, "entered long 10"), (t_ms2, "stop moved", "attention")]),
3077
+ ui.chart_block({"kind": "line", "rows": rows, "x": "time", "y": ["spread"]}),
3078
+ ui.custom("Notes", html="<p>Anything else, framed as the script's own.</p>"),
3079
+ ]})
3080
+ ```
3081
+
3082
+ - `ui.strategy_block(strategy=None, *, open="auto", sections=None, title=None, capital=None)`:
3083
+ the same figures as the strategy's Live Strategies row, drawn by the terminal
3084
+ and marked Reconciled, headed by its equity curve. `strategy=None` is the
3085
+ module doing the push; in a strategy's desk, that strategy (an App that
3086
+ imports a Strategy class is that App: its orders are its own). `open`: `"auto"`, `"holds"`, `"working"`, `"combos"`,
3087
+ `"log"` or `False` (folded). `sections`: a subset of
3088
+ `["holds", "working", "combos", "log"]`. `capital`: what the strategy was
3089
+ given to trade, in its own currency (e.g. `5000`): the curve then shows its
3090
+ equity (capital plus Total P&L) from its first figure, with the % against the
3091
+ capital; without it the curve is the Total P&L against zero. No figure can be
3092
+ passed: any other keyword raises `TypeError` naming it, and Python drops
3093
+ every other key from a hand-built `{"kind": "strategy"}`.
3094
+ - `ui.rule(label, value, op, target, *, prev=None, near=None, unit=None, fmt=None)`
3095
+ and `ui.conditions(title, rules, *, need="all")`: `op` is one of `<` `<=` `>`
3096
+ `>=` `==` `between` (`target=[lo, hi]`, lo <= hi) `crosses_above`
3097
+ `crosses_below` (both need `prev`). `near` > 0 is the band the bar fills
3098
+ across, in the value's units. `unit` is a word after the distance
3099
+ (`"+32 pts"`); `fmt` is a suffix glued onto every figure of the rule, its
3100
+ value, target and distance (`fmt="x"` shows `1.8x`), never a number format.
3101
+ `need`: `"all"`, `"any"` or a count of 1 or more (more than the rules is
3102
+ never met, so dropping an unknown rule never raises). The terminal decides
3103
+ Met or Not yet; `value=None` shows the absent marker.
3104
+ - `ui.level(label, value, *, tone=None)` and `ui.levels(*, price, levels, title=None)`:
3105
+ the price against your levels; a `loss` stop and a `profit` target add
3106
+ reward/risk.
3107
+ - `ui.timeline(events, *, title=None)`: `(t_ms, text)` or `(t_ms, text, tone)`,
3108
+ `t_ms` an int (numpy's too) of epoch milliseconds.
3109
+ - `ui.chart_block(spec, *, title=None, live=False)`: the `chart` block (a Wiz
3110
+ spec dict, or a list of numbers).
3111
+ - `ui.custom(title, *, html)`: your own sandboxed markup, framed and labelled
3112
+ as the script's.
3113
+
3114
+ Numbers may be ints, floats, Decimals or numpy / pandas numbers. A NaN, a
3115
+ `pd.NA` (a nullable column's gap), a Decimal NaN or an infinite value,
3116
+ target, prev, near, level value or price (an indicator still warming up)
3117
+ becomes `None`, "not known yet", so a draw never halts on one; a wrong `op`,
3118
+ a `between` target that is not `[lo, hi]` or a crossing with no `prev` still
3119
+ raises.
3120
+
3121
+ Only While25 says where a figure was checked: any text a script puts on screen
3122
+ that says "Reconciled by While25" or "Sealed by While25" (any case, in a block's
3123
+ title, label, value, text or html, a `ui.html` page, a text, metric or table
3124
+ value) is replaced by a visible refusal (R-IMPERSONATE), and a panel or widget
3125
+ label that says it is replaced by "Refused label (R-IMPERSONATE)". Honest words
3126
+ such as "reconciled with broker" are fine.
3127
+
3128
+ ## Testing without a terminal
3129
+
3130
+ Nothing above needs While25 to import, so a module is an ordinary class:
3131
+
3132
+ ```python
3133
+ import while25
3134
+
3135
+ def test_it_logs_on_a_down_bar():
3136
+ seen = []
3137
+ class FakeCtx:
3138
+ params = {}
3139
+ def log(self, msg, level="info"): seen.append(msg)
3140
+
3141
+ fake = FakeCtx()
3142
+ with while25.use(fake): # the package acts on your fake
3143
+ MeanReversion().on_bar(fake, {"open": 2.0, "close": 1.0})
3144
+ assert seen
3145
+ ```
3146
+
3147
+ ## Errors
3148
+
3149
+ An exception in a handler **halts that module** and leaves its siblings running.
3150
+ It is not swallowed and the loop is not resumed: a module that kept going after
3151
+ an error could trade on bad state.
3152
+
3153
+ `While25Error` carries `.code` (the refusal code the tables above name) and
3154
+ `.message`; a `TIMEOUT` from an order call carries `.idempotency_key` too.
3155
+ `SubscriptionError` (`.keys`) and `OrderRightsError` (`.kind`) are
3156
+ `While25Error`s. A refusal the SDK can judge itself is a plain `ValueError`,
3157
+ raised before anything is sent.
3158
+
3159
+ ## Limits
3160
+
3161
+ - One thread runs a module's code: `on_start`, every handler, `run()` and
3162
+ `on_stop`, one after another. Handlers never overlap, so state on `self`
3163
+ needs no lock — and a handler that blocks holds every other one up.
3164
+ - A tick that has waited over a second with a newer tick for the same
3165
+ handler and symbol queued behind it is skipped; a schedule call is
3166
+ coalesced the same way. A closed bar, a fill, an order event, a signal and
3167
+ a news article always run, in order.
3168
+ - A data call that gets no answer within 30 seconds raises `TimeoutError`;
3169
+ an order call raises `While25Error` `TIMEOUT` after 25 (see Orders).
3170
+ - Each module runs in its own process, below the terminal's priority, with
3171
+ 2 GB of address space (`W25_WORKER_MAX_MB` changes it); a module over it is
3172
+ stopped as itself, and the terminal says so. A file it writes is at most
3173
+ 2 GiB (on macOS and Linux); one log or output line is cut at 8 MiB; one
3174
+ message to the terminal is at most 16 MiB. An `emit()` payload must pickle.
3175
+
3176
+ ## What the SDK does not do
3177
+
3178
+ - **No network calls of its own.** The SDK makes none (only the package
3179
+ installer reaches the internet), and everything `while25.*` gives you comes
3180
+ through While25. Nothing stops your own code making them: Requests,
3181
+ yfinance or ccxt work as they do anywhere else. What you fetch that way is
3182
+ yours to trust, and an order your code sends to a venue directly (with ccxt,
3183
+ or a broker's own API) skips every check While25 makes and never shows
3184
+ in the terminal.
3185
+ - **No installs while it runs.** Anything pip can install is yours to add
3186
+ before you deploy: from the Marketplace, or listed in `requirements.txt`
3187
+ (see "Your own files and packages"). While a strategy or trading App runs,
3188
+ its packages can't change.
3189
+ - **No sandbox promises.** Your script is your responsibility. While25 enforces
3190
+ its own risk limits on the money path and nothing more.
3191
+
3192
+ ## Licence
3193
+
3194
+ Apache-2.0.