while25
The Python SDK for the While25 trading terminal.
Write strategies, indicators, monitors and apps as classes. Declare what wakes them; While25 runs them and renders what they produce.
pip install while25
The SDK has no dependencies. You can write and unit-test a strategy on a
plain Python install and run it in the terminal unchanged — which is the point:
until pip install while25 worked, nobody could develop without a terminal.
A strategy
import while25
from while25 import Strategy, on
class MeanReversion(Strategy):
id = "mean_reversion"
label = "Mean Reversion"
version = "1.0.0"
@on.tick("EQ:US:AAPL")
def on_tick(self, ctx, tick):
while25.log(f"last {tick['ltp']}")
The package is the API. Inside a running module, while25.log,
while25.candles, while25.buy, while25.subscribe, while25.ui.push and
the rest act on the module the terminal is running — there is one module per
process, so nothing has to be passed around. The ctx a handler receives is
the same object, kept for the explicit style and for tests. Shorten the name
yourself if you like: import while25 as w25. While a module runs,
dir(while25.orders) (or .data, .portfolio, .market, .chart, .viz,
.ai) lists that name's calls.
A tick carries symbol, ltp, bid, ask, timestamp_ms and as_of (when
While25 last saw data for the instrument). bid, ask
and timestamp_ms are None when the venue has not sent them — never 0.
IBKR delivers bid and ask as separate updates, so one side is routinely
absent on a given tick; test for None before comparing.
Four kinds, one shape. They differ only in what they may emit and how the terminal presents them — not in what wakes them:
| Kind | For |
|---|---|
Strategy |
Something that trades |
Indicator |
Something drawn on the chart |
Monitor |
Something that watches and notifies |
App |
Something with its own panel: a strategy's desk is one |
What can wake a module
@on.tick("EQ:US:AAPL") # every tick, uncoalesced
@on.bar("EQ:US:AAPL", "5m") # each closed bar of that interval (hours="eth": the full session)
@on.bar(aapl) # the same, for a Bars line the class declares (see "Bars")
@on.schedule(every="10m") # a cadence — no market data needed
@on.signal("rebalance") # another module's while25.emit()
@on.signal("dip_ok", sender=DipWatch) # that signal from that one module only
@on.order(tag="mine") # order lifecycle events tagged "mine" (account-wide — see below)
@on.fill(tag="mine") # the same stream, narrowed to executions
@on.news("EQ:US:AAPL") # each live news article on that symbol (needs a news vendor)
A symbol known only once the module runs — one picked in its settings, or an
option while25.option() named — cannot go in a decorator: the decorators are
read from the file when it is saved, before any setting has a value. Turn its
prices on while running and name the method its ticks call:
def on_start(self, ctx):
self.coin = while25.params["coin"] # a Symbol setting
while25.subscribe(self.coin, on_tick=self.on_coin)
def on_coin(self, ctx, tick): # every tick of that coin
...
Each tick of that symbol then calls on_coin(ctx, tick), exactly as an
@on.tick line for it would. See "Live market data" below for the rules. Bars
have no such call: @on.bar takes a symbol written in the file. Where the
choice is a short list known in advance (NIFTY or BANKNIFTY), write a line for
each and read the setting inside the handler.
What each handler receives. @on.tick: (ctx, tick), the tick dict
above. @on.bar: (ctx, bar) with symbol, interval, hours ("" for
the regular session, "eth" for the full one), time_ms (the bar's start),
open, high, low, close and volume — closed bars only, never the one
still forming. @on.schedule: (ctx). @on.signal: (ctx, payload).
@on.order / @on.fill: (ctx, ev), the event dict under Orders.
@on.news: (ctx, article), a row as news() returns them.
@on.bar(symbol, interval, hours=None) takes the chart's intervals and the
session in an order's word: left out, the venue's regular session (futures
included); "eth", the full session. "rth" is refused. A regular and an
"eth" line on one symbol are two series, each delivered to its own
handler. An interval or session While25 cannot serve for that
instrument is refused BAD_INTERVAL / BAD_HOURS as a warning on the
module, which runs on with the rest.
@on.schedule(every=...) takes "250ms", "5s", "10m", "2h". The check
runs once a second, so nothing fires finer than that; a handler held up past
a period (a long history_span()) runs once and resumes its cadence, not
once per missed period. cron= and tz= are not implemented: a schedule
with no every= is refused at registration, like @on.position.
@on.order and @on.fill take tag= and symbol=, each an exact match;
left out, every event on the account. @on.signal(name, sender=None) wakes
on while25.emit(name, payload) from another running module. sender names
the one module the handler listens to, by its class or its id
(sender=DipWatch, sender="dip_watch"): that signal from any other module
does not reach it. Which signals reach a module that trades at all is under
while25.emit in "Start and stop".
Not deliverable: @on.position. Nothing publishes position changes to
this runtime, so a module declaring one is refused at registration with a
message saying so. That is deliberate: it used to register, report running,
and never fire, which is indistinguishable from a strategy whose logic is
wrong. (Bar, order and fill delivery went the same way once: declarable before
they were deliverable. They are deliverable now; the refusal is the rule that
keeps a registered module one that will actually wake.)
A module may declare several, or none. A module with a run() method has it
called once, after on_start, on the module's one executor thread — the
escape hatch for anything the declarative surface does not cover. Nothing
else of the module runs while run() runs (no handler, no schedule), so a
run() that loops checks while25.alive() each pass and returns when it is
False: that is the moment the terminal asked the module to stop, and a loop
that goes on is ended with the process two seconds later. A module with
neither a subscription nor run() is refused at registration: nothing could
ever wake it.
A class built on another. A module may subclass one of your own, and a method the child writes again replaces the parent's:
class Fast(MeanReversion):
id = "mean_reversion_fast"
@on.tick("EQ:US:AAPL") # tagged again: this tag is the one that counts
def on_tick(self, ctx, tick):
...
- Tagged again, the child's tag replaces the parent's for that method, so it is called once per event, on what the child's tag says.
- Written again with no tag, it keeps the parent's tag and is the method that runs.
- A method the child does not write is inherited as it is. So are
inputs,monitorsandBarslines; a child that declares aBarsline again under the same name moves the handlers on that line with it.
Start and stop
on_start(ctx) runs first, on the module's own thread, before any handler:
the module reads starting until it returns, so a long fetch there (a
warmup(), see "Warm-up") delays nothing but the module's own first decision.
A raise in it puts the module in error with the message, and nothing of it
runs.
on_stop(ctx) runs once when the module is stopped: by its Stop, a stop on
its panel, a restart of its code, or the app closing. A crash or a kill of
the process runs none of it. From the moment the Stop arrives,
while25.alive() reads False, handlers still waiting are skipped (the log
says how many), and every order call — buy, sell, place, bracket,
combo, cancel, modify, square_off — raises While25Error with code
MODULE_STOPPING and is not to be retried: the trader's Stop decides what
happens to the module's orders. on_stop may log, save its own files and
read what the module holds (while25.portfolio.my_positions(),
while25.orders.mine()); it has two seconds before the process is ended,
finished or not, and a raise in it is logged, never a halt.
When the computer sleeps, nothing runs. No price or bar reaches a module, no order goes out, and While25's held stops cannot act: a stop whose level was crossed meanwhile fires late, on the first price after waking (a stop the broker holds goes on working). On waking the module goes on with the prices that come now; it is not stopped. Its log says how long the computer was asleep ("The computer was asleep from 10:02 to 11:15 (73 min): no prices or bars reached this strategy, ..."), the app shows the same notice, and the bars it missed are not delivered after the fact.
while25.emit("name", payload) publishes a signal. Delivery is fire-and-forget to
running subscribers only: nothing queues, nothing replays, and a signal with
no listener is a no-op rather than an error. A publisher must not need to know
who is listening.
What reaches a module that trades (a Strategy, or an App that imports
one) depends on who sent it. A module that does not trade hears every signal.
| Sent by | Reaches a module that trades |
|---|---|
a Strategy or a trading App you deployed from the app |
yes |
a Monitor |
only when that module was deployed with the monitor box ticked |
| a strategy's own desk | its own strategy only (its buttons) |
any other App that does not trade, an Indicator |
never |
| anything else: a script started any other way than from the app, one that is not running | never |
A monitor a strategy lists as its own (monitors = [DipWatch]) signals that
strategy and no other module that trades (see "A monitor inside a strategy").
A signal that is held back is said once in the sender's log. A strategy that
acts on an indicator works it out itself, from its own bars (see "An
indicator's numbers in a strategy"). A handler with sender= hears only the
module it names, and only when the table lets that module through.
Typed inputs
import while25
from while25 import Strategy
from while25.inputs import Float, Int, Symbol
class Breakout(Strategy):
id = "breakout"
inputs = [
Int("length", default=20, minimum=2, maximum=200),
Float("threshold", default=1.5),
Symbol("instrument"),
]
def on_start(self, ctx):
self.length = while25.params["length"]
Import the types directly rather than from while25 import inputs — inside a
class body the inputs attribute shadows the module, so inputs.Int would
raise NameError.
The terminal renders these as a configuration form and validates before your code runs. On a strategy the form is part of the "Deploy LIVE — real money" window: one field per input, in the order declared, each filled with what was last entered for it on this machine, else its default.
A Symbol input is a search box over the same instruments the terminal's own
search finds (a continuous futures series is left out: no order can be placed
on one); its value is the instrument key picked, and while25.params[name]
reads it once the module runs. Declare as many as you need — each is its own
field, read by its own name. Because the value only exists once the module
runs, a module that watches it turns its prices on with
while25.subscribe(key, on_tick=...), never with @on.tick (see above).
Six types: Int(name, default, minimum, maximum, step), Float(...) the
same, Bool(name, default=False), Str(name, default=""), Enum(name, choices=[...], default) and Symbol(name). Every one takes label=, the
field's name on the form (the key when left out); Int and Float take
step=, the increment the form steps by. A default outside its own bounds, or
not among its choices, is refused when the class is declared. Values arrive
typed: while25.params["length"] is an int, and a value the form could not
coerce or that is out of range fails the start, naming the input, before your
code runs.
Market data
bars = while25.candles("EQ:US:AAPL", "5m", limit=200) # newest 200, LIVE series
old = while25.historical("EQ:US:AAPL", "1D", # a real vendor pull
start="2024-01-01")
today = while25.intraday("EQ:US:AAPL", "5m") # today, from the vendor
q = while25.quote("EQ:US:AAPL") # None if unknown
candles(..., source=) picks which store the bars come from, and the three
are different questions rather than fallbacks for one another:
source |
Reads | Raises when |
|---|---|---|
"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 |
"historical" |
a real vendor pull, cached; intraday intervals within a bar budget (below) | NO_DATA / BAD_RANGE |
"intraday" |
today's bars from the vendor, no cache | UNSUPPORTED_INTERVAL outside 1m/5m/15m/30m/1h |
An interval While25 does not know ("7m") is refused UNKNOWN_INTERVAL
on every source, never read as another. An indicator does not call
candles() at all: it receives the chart's own series as while25.bars
(see Indicators), and source="live" inside compute() raises
LIVE_IN_COMPUTE, because a second series drifts from the one drawn under
the plot with nothing to notice. "live" is for a strategy or an app reading
the series a chart, or its own @on.bar line, is filling. An analysis script
with no chart open wants "historical"; a backtest wants history_span()
(below), which has no bar budget.
start/end are ISO dates and apply to "historical" only. start is
honoured: While25 walks as many vendor requests as the range takes, back
to the history floor (2012) and, for an intraday interval, within a budget of
25,000 bars counted back from end. A start it could not reach is logged on
the module as a warning naming the date the answer really starts from, and
the rows carry it as .effective_start and why as .note ("" when the answer
covers the window). The budget is this call's limit, never the vendor's depth:
history_span() fetches every bar of the window. The rows also carry .session
("regular" or "full") and .adjustment ("raw", "split", or None
where the vendor states nothing — never read None as raw). A data call that
gets no answer within 30 seconds raises TimeoutError.
while25.history(...) still works and is exactly candles(..., source="live").
(while25.data.* is the same surface under its namespace.)
It is deprecated: the name promised a fetch it never performed, which is what
made people expect vendor data from it.
quote() returns None when the terminal has no data for that symbol — 0.0
is a real price, and a strategy that cannot tell "no data" from "worthless"
will act on the difference.
A quote carries symbol, ltp, bid, ask, open, high, low,
prev_close, volume, time (the venue's stamp), as_of (when While25
last saw data for it) and market_open (True, False, or None when it
cannot say); every figure is None until seen, never 0. ltp is the last
TRADED price: None until the instrument has traded in what the terminal
holds, even when it already has a bid and an ask for it. quotes([...])
answers one entry per symbol asked, in that order, None where there is no
data.
A candles(source="historical") call whose vendor fetch fails raises
IO_ERROR with the vendor's failure, even when earlier bars are cached: they
are never handed back as the answer the vendor did not give. Ask again.
A whole span of history
candles(source="historical") reads what the vendor serves in one call. For a
whole span, every bar between two dates, use history_span():
r = while25.history_span("EQ:US:AAPL", "5m", "2024-01-02", "2024-06-28")
bars = r["bars"] # the rows candles() returns, plus "regular"
r["missing_days"] # ["2024-03-11", ...]: trading days with no bar
The interval is one of 1m, 5m, 15m, 30m, 1h, 1D, 1W, 1M; the
other spellings While25 takes (1d, 1440, DAILY, 60, ...) come back
under that name.
While25 fetches exactly that window on a worker of its own, request by
request at the vendor's pace (a chart always goes first), with no cap that cuts
it short. Nothing is cached on disk: a window that has fully closed (its end
before the exchange's today) is kept in memory for While25's session, and
the same span asked again comes back from it with r["vendor_requests"] == 0
and a line in r["vendor_notes"] that says "served from memory". A window
still open is fetched every time. A refusal comes back in the vendor's own
words, as a While25Error with While25's code (TOO_WIDE, VENDOR_PACING,
PERMISSION, NOT_SUPPORTED, ...). It BLOCKS until the span is in, which takes
minutes on a paced vendor: call it from on_start, a schedule or a one-shot
run, never from a tick handler. Each request shows in the module's log
(history EQ:US:AAPL 5m: fetching history, part 3 of about 12; waiting, a chart is loading its history first while charts go first; waiting its turn, 2 fetches ahead while another module's fetch or a backtest runs — While25 fetches
one span at a time), and a Stop of the module stops the fetch (CANCELLED).
One span at a time per module: a second call while one is under way is
refused BUSY. A span that reports nothing for 180 seconds is given up
(TIMEOUT), and so is one still running after 30 minutes. A walk the vendor
stopped short raises with the vendor's words; its partial bars are not
returned.
hours="eth" and adjust="split" work as on candles(); so does price="mark"
(a Binance USD-M futures contract's mark candles, no volume; UNSUPPORTED_PRICE
elsewhere; left out, the last trade). The answer also
says session, adjustment, covered_from / covered_to (the dates it
covers), first_bar_ms (the first bar's time; None with no bars),
vendor, vendor_requests, vendor_notes (stretches the vendor said
held nothing) and calendar, the exchange calendar the instrument trades on
("XNYS", "XBOM", "CMES", "24/7"; "" when none is known).
missing_days lists the finished trading days of that calendar inside the
covered dates that have no bar: whole days only, None when no calendar is
known. Weekly and monthly series are not checked.
A span cut short (TOO_WIDE mid-walk, VENDOR_PACING, a vendor refusal) raises
While25Error whose .answer holds the partial answer: the bars it got, with
covered_from / covered_to, to inspect. It has no id, so a backtest can
never be sealed on it. If the call outlives its 30-minute wait it raises a plain
TimeoutError instead and the walk is cancelled at While25.
Bars: a bar line the module keeps
from while25 import Bars, Strategy, on
class Breakout(Strategy):
id = "breakout"
aapl = Bars("EQ:US:AAPL", "5m", keep=200)
@on.bar(aapl)
def on_bar(self, ctx, bar):
high = max(self.aapl.closes[:-1]) # the 199 closes before this bar
...
Bars(symbol, interval, *, hours=None, keep=200) declares a bar line on the
class and keeps its bars:
- It is the line's subscription: no separate
@on.bar(symbol, interval). - At start it holds its last
keepfinished bars beforeon_startruns, fetched by a warm-up with every check under "Warm-up" below. A refusal fails the start with its reason. - Each closed bar is added before any handler runs, and the oldest dropped
past
keep.
keep: 1 to 10,000. hours="eth": the full session. Intervals: 1m, 5m, 15m,
30m, 1h, 1D, 1W, 1M; another is refused when the file is saved (use
@on.bar(symbol, interval) and keep the bars yourself). @on.bar(line)
wakes a handler on the line's bars; with no handler the line is still kept,
for a tick handler to read. Any kind of module may declare lines.
On the module, self.aapl is the line:
self.aapl.rows |
the bars, oldest first, each as an @on.bar handler receives it |
self.aapl.last |
the newest finished bar, None before there is one |
self.aapl.closes |
every bar's close, oldest first |
len(self.aapl), self.aapl[-1], for bar in self.aapl |
as on a list |
self.aapl.indicator(cls, *, forming=False, **params) |
an indicator worked out from these bars (see "An indicator's numbers in a strategy") |
Read rows; While25 writes it.
Warm-up: the history a strategy decides from
A Bars line does all of this for you. warmup() is the same fetch by hand,
for a module that keeps its bars in its own way:
class Breakout(Strategy):
id = "breakout"
def on_start(self, ctx):
bars = while25.warmup("EQ:US:AAPL", "5m", 200) # the 200 bars before now
self.closes = [b["close"] for b in bars]
@on.bar("EQ:US:AAPL", "5m")
def on_bar(self, ctx, bar):
self.closes.append(bar["close"]) # carries on from the warm-up
...
A strategy that computes on bars (a 20-bar average, an RSI) needs the bars
before its first one. warmup(symbol, interval, bars, hours=None) gives the
last bars finished bars of one of the strategy's own @on.bar lines,
written as the line writes them (hours="eth" for an "eth" line); with no
such line it raises ValueError. Intervals: 1m, 5m, 15m, 30m, 1h, 1D, 1W,
1M; bars 1 to 10,000. To have an indicator do the computing, hand it these
bars: see "An indicator's numbers in a strategy".
It is fetched the way a backtest's history is — While25's history service, no cache, the vendor's own refusal — back from now until it holds the bars, and checked before it is handed on:
- Every trading day is there. A trading day of the instrument's exchange
calendar with no bar inside the warm-up refuses (
MISSING_DAYS, naming the days); a weekly or monthly line, a whole week or month. An instrument with no exchange calendar known has days nobody can check, and refuses too (NO_CALENDAR). - Nothing unfinished. A bar still forming is left out.
- Enough of it. Fewer than
barsfinished bars refuses (NOT_ENOUGH_HISTORY, saying how many there are) — after one wider fetch, since how far back the first may go is worked out before the calendar is known. - It joins the live bars. Where the line's live series and the warm-up
both hold bars, they are the same bars (
WARMUP_JOINnames the first live bar the history lacks: another bar grid, or a bar the vendor lost), and no bar that finished before the line was attached is missing from both (WARMUP_JOIN: the vendor had not published it yet — deploy again in a moment).
Call it in on_start: the strategy reads starting until it returns, and
nothing of it runs meanwhile. On an intraday line it first waits until 15
seconds after the line was attached, so the vendor has published the bar
that finished as the strategy started (that bar is never delivered live).
Each vendor request shows in the module's log,
and so in the last-log cell of its row in Live strategies; a Stop stops the
fetch, and the strategy ends stopped. Let a refusal raise: the start fails
with the reason, and the strategy never decides on history nobody checked.
The vendor's own codes come through as on history_span() (TOO_WIDE,
VENDOR_PACING, PERMISSION, TIMEOUT, CANCELLED, ...), and one span runs
at a time per module, a history_span() included (BUSY).
The rows have an @on.bar bar's keys — symbol, interval, hours,
time_ms, open, high, low, close, volume — so one piece of code can
read both, and the list carries .session, .adjustment, .vendor and
.calendar. A live bar the warm-up already gave (one that finished while it
fetched) is not delivered to the line's handlers again. The first live bar
after it is checked once more against the live series; a bar between the two
that reached the strategy neither way halts it with the reason (phase
warmup) before the handler runs.
News
rows = while25.news("EQ:US:AAPL", start="2026-08-01", limit=20) # oldest first
rows.truncated # True: the page cap was hit, older articles may exist
rows.errors # {instrument_key: "FAILED" | "PARTIAL"}: a vendor fetch that fell over
news(symbols, start=, end=, source=, limit=) answers from the same news
path the terminal's news panel reads. symbols is one symbol or a list of up
to 10; start / end are ISO dates or epoch milliseconds, end inclusive to
the end of its day; source names one outlet; limit caps articles per
symbol (50 by default, 200 at most). Each row has symbol, time_ms,
title and url always, and author, excerpt, body, source,
sentiment, sentiment_score, ... only when the vendor sent them (an absent
field is an absent key), plus in_market_hours (True / False / None).
With no news vendor configured it raises NO_PROVIDER rather than returning
an empty list. @on.news("EQ:US:AAPL") delivers each live article the same
way, one handler call per article; with no news vendor the line is accepted
and never fires.
Index members
while25.universes() # ["banknifty", "ndx100", ...]
while25.universe("ndx100") # [{"symbol", "name", "canonical_id"}, ...]
while25.universe_info("ndx100") # index, name, country, as_of, source, count
Dated reference data from the terminal's own constituent registry, read from
a file with no round trip. An index it does not hold raises ValueError
naming the ones it does — never an empty list.
Open data
Public filings and registers (SEC today), live from the source and never cached, through the same registry the AI reads.
while25.data.catalog("filings") # [{"id", "category", "description", "markets"}]
while25.data.describe("sec.company_filings") # params with choices, result columns
df = while25.data.fetch("sec.company_filings", symbol="AAPL")
df.attrs["dataset_id"] # "ds_..."; the AI sees the same id
df.attrs["provenance"] # provider, command, params, hosts, fetched_at
while25.data.get("ds_...") # a dataset fetched earlier this session
Dates come back as datetime.date. A refusal raises While25Error whose .code
says why: AMBIGUOUS (the symbol matches several companies; the message lists
them), CONTACT_REQUIRED (SEC needs a contact email, taken from your
While25 account, and none is available yet), INVALID_PARAMS, NOT_FOUND, NOT_COVERED, UNKNOWN_COMMAND,
DATASET_EVICTED, FETCH_FAILED (the message carries retry_after_s when the source said),
TOO_LARGE (the dataset is too big to hand over whole; it is kept: read it in pages
with while25.data.get(id, offset=, limit=, columns=, filter=)). Outside the
desktop app these calls raise RuntimeError.
Your own files and packages
The workspace is a real directory, and your module runs with it as the working directory. Relative paths are relative to it:
<workspace>/
├── indicators/ strategies/ monitors/ apps/ your modules
├── data/ files you drop in
├── lib/ packages you pip install
└── requirements.txt
import pandas as pd
df = pd.read_csv("data/straddles.csv") # a file you dropped in
df.to_parquet("data/straddles.parquet") # and one you write back
Drop files onto the workspace drawer in the Code panel and they land in
data/. A name that already exists is suffixed rather than replaced — silently
overwriting a file a running script is reading would change its results with
nothing to notice.
numpy and pandas ship with the terminal. Anything else is yours to install,
from the same drawer or by listing it in requirements.txt. Packages go to
lib/, which is on sys.path ahead of the bundled ones — so a version you pin
wins, rather than your install quietly doing nothing. lib/ belongs to the
installer: saving, deleting, moving or creating anything in it by hand is
refused ("lib/ is managed by the package installer — install or remove
packages instead"). Install before you deploy: while a strategy or trading App
runs, packages can't change.
The workspace is the unit that moves. On a cloud machine it is a mounted volume, so every path above means the same thing there as it does locally.
Live market data: a module is its own subscriber
A module is its own subscriber, like a chart or a watchlist row. When it
starts, While25 takes a subscription per instrument it declared
(@on.tick, @on.bar) that lasts exactly as long as the module runs —
whoever else holds the same instrument — and stopping the module releases
them. What While25 cannot give (over the plan's limit on live
instruments, SUB_CAP; no vendor for the key, NO_VENUE; a bar interval or
session it cannot serve, BAD_INTERVAL / BAD_HOURS) does not stop the
module: it runs with the keys it did get, and the refusal shows as a warning
on it (Live strategies shows it as its last error).
while25.subscribe("IDX:IN:BANKNIFTY") # ask for one more at runtime; True, or
# SubscriptionError with the refusal code
while25.subscribe("IDX:IN:BANKNIFTY", on_tick=self.on_bank) # ...and call on_bank per tick
while25.unsubscribe("IDX:IN:BANKNIFTY") # its prices, and the calls, end together
while25.market.is_open("IDX:IN:NIFTY") # True / False / None (cannot be placed)
A key turned on at runtime gets its live prices exactly as a declared one
does. Without on_tick= nothing is called for them — quote(key) reads the
latest. With it, every tick calls that method, as an @on.tick line would:
on_tick=takes one of the strategy's own methods (self.on_bank). A plain function, a lambda or another object's method raisesTypeError, and nothing is subscribed: the tick calls its handler by name on the strategy.- Subscribing the same key again with another method replaces the first.
unsubscribe(key), the strategy's stop or a halt ends the calls. - A key both declared in an
@on.tickline and named at runtime with the same method is called once per tick, never twice. - It works from
on_start(the usual place for a symbol a setting named), from any handler, and fromrun(). SubscriptionErroris raised only for what While25 refuses at once: codeNOT_RUNNING(the module is stopping or stopped) orBAD_REQUEST(not a key). While25's own refusals — over the plan's limit, no vendor for the key — come back as a warning on the module (Live strategies shows it as its last error) while it keeps running with the keys it did get; the call itself returned True. False means the terminal could not be reached.
Every tick and quote carries as_of — While25's arrival time — so a
script can tell a fresh price from a stale one instead of guessing. A quote's
open, high, low, prev_close and volume are None until the
engine has actually seen them (a vendor that sends them as separate ticks
leaves each unknown until its own tick lands) — never a 0 standing in for a
price. historical(..., start=) is honoured back to the history floor
(2012); a clamped start is logged as a warning.
Orders
The full broker surface, not a curated subset:
while25.buy("EQ:US:AAPL", 10)
while25.sell("EQ:US:AAPL", 10, order_type="LMT", price=195.0)
while25.bracket("EQ:US:AAPL", "BUY", 10,
take_profit=210.0, stop_loss=190.0)
# entry plus a stop, no target: the stop is armed when the entry fills
while25.buy("EQ:US:AAPL", 10, stop_loss=190.0)
# a trailing stop: follows the price 2.50 below it, sells when price turns back
while25.sell("EQ:US:AAPL", 10, order_type="TRAIL",
trail_amount=2.5, reduce_only=True)
while25.place("EQ:US:AAPL", "BUY", 10, order_type="STP",
trigger_price=189.0, product="intraday", validity="ioc")
# a cash amount instead of a share count — sent to the broker as the amount,
# where its venue takes one (Alpaca: a stock it trades in fractions)
while25.buy("EQ:US:AAPL", amount=5000)
# the same calls live under while25.orders.* too
Order types: MKT · LMT · STP · STP LMT · MIT · LIT · TRAIL — the order
ticket's own names, written exactly so (STP a stop that fires a market
order, STP LMT a stop-limit, TRAIL a trailing stop); no other spelling is
accepted. The auction types MOO · MOC · LOO · LOC are
refused at once (below). Groups: simple (a plain order) and basket (a
bracket) — passing stop_loss= makes it a bracket without you naming the
group; oco and oto are refused UNSUPPORTED.
product= is the pocket the order opens in: "delivery" (the default),
"intraday", "margin" or "normal", as the connected broker takes them for
that market; anything else is refused BAD_PRODUCT. A protective order states
the same product as the position it protects. The rest of place()'s
arguments ride through to the broker where it takes them: tag= (at most 20
characters, on every event of the order), idempotency_key=, symbol=,
disclosed_quantity=, is_amo= (an after-market order on an Indian broker),
slice=, and the group fields group=, group_id=, parent_order_id= and
linked_order_id=.
A bracket is an entry with a stop, and optionally a take-profit. While25
holds the stop and arms it the moment the entry fills, sized to what filled and
grown with every later fill, whether or not your script is still running. It
ends through its own exits only: its take-profit, its stop, or a square off of
it (while25.orders.square_off(), below, or Square off on its line in the
Positions tab). An order of your own beside it is a separate order: a plain
sell closes nothing of the bracket, its stop and take-profit keep working, and
the next of them to fill opens a position the other way. The one exception is a
coin at a venue that takes its fees out of the holding without reporting them
per fill (Alpaca today): there a bracket follows the holding, and ends when the
coin is gone, however that happens.
stop_loss=alone is "enter with a stop, exit on my own signal".stop_loss=withtake_profit=adds a resting limit order for the profit; whichever exit closes the position, the other is withdrawn.take_profit=alone is refused: it protects nothing, so it is not a bracket. Place the entry, then a limit order to take the profit.trail_amount=on a bracket makes its stop trail the price at that distance. It must be above 0: a trail of 0 or below is refused (ValueError), never sent as a fixed stop.
If the stop cannot be set when the entry fills (the price is already through
its level, after a fast fill or a gap), nothing is closed for you: @on.order
hears a REJECT under the stop's id (below), carrying your tag=, order type
STP, and a reason that starts the bracket's stop could not be set. The
position is open with no stop and what to do about it is your script's decision.
The bracket's stop has an order id of its own: the bracket's id followed by
-SL. It is the same for the bracket's whole life, so you can move the stop,
or take it off, while keeping the position:
entry = while25.buy("EQ:US:AAPL", 10, stop_loss=190.0)
stop_id = entry["order_id"] + "-SL"
while25.orders.modify(stop_id, trigger_price=195.0) # move it, say to break-even
while25.orders.cancel(stop_id) # take it off; the position stays
It answers once the entry has filled. Before that there is no stop yet, and the
call is refused NOT_WORKING. @on.order hears the stop under that id, with
your tag=:
ev["event"] |
when |
|---|---|
HELD |
it is set, on the entry's first fill; ev["trigger_price"] and ev["quantity"] are its level and size |
MODIFY |
it was moved, by you or from the chart, or the bracket re-sized it after a later fill of the entry |
MODIFY_REJECT |
a change was refused and it waits as it was; ev["reason"] says why |
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 |
CANCEL |
it ended without firing: you cancelled it, or the position is gone |
REJECT |
it could not be set at all (above) |
Only the level is yours to change. quantity= is refused, because the stop is
always the size of the position it protects, and price= is refused, because it
fires at market. A trailing bracket stop's level cannot be moved: it follows the
price. A stop you cancel stays off: the bracket does not put it back when a
later fill arrives, and its take-profit, if it has one, keeps working. To put
protection back, place a stop of your own with reduce_only=True. When the
stop fires, the exit order it places arrives as NEW and then FILL under that
order's own id, not the stop's, carrying your tag=.
To leave a bracket at a time you pick, square it off. A time exit is the usual case:
entry = while25.buy("FUT:US:MNQ:202612", 1, stop_loss=20950, take_profit=21100)
# ... at 15:55:
while25.orders.square_off(entry["order_id"])
It does what Square off does on the bracket's line in the Positions tab: the
bracket's take-profit and stop come off first, then what it holds is closed at
market, and the bracket ends. It squares off only your own bracket, and only
once its entry has filled. It answers as soon as While25 has taken it,
with {"ok": True, "square_off_id": ..., "bracket_id": ...}. What the square off
then does arrives at @on.order as SQUARE_OFF events under the bracket's id,
with the bracket's tag=:
ev["status"] |
when |
|---|---|
WITHDRAWING |
the take-profit and stop are being taken off; the close goes out once they are |
SENT |
the market close went out: ev["close_order_id"] is its id, ev["quantity"] its size |
DONE |
it finished: the bracket is closed, or it had already ended; ev["reason"] says which |
REFUSED |
nothing was closed: ev["reason"] says why (the kill switch is on, the broker link is down, or the close itself was refused) |
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 |
INTERRUPTED |
a restart of the app cut it short |
The close's own order also arrives as NEW and then FILL under
ev["close_order_id"], with no tag=. Refused at once, with nothing sent:
NO_BRACKET (no open bracket has that id), NOT_ORDER_OWNER (it is another
module's), NOTHING_HELD (its entry has not filled: cancel the entry instead)
and MARKET_CLOSED (its market cannot take the close now). It also works for a
bracket the broker holds.
validity= is how long the order lives (day · gtc · ioc · fok · opg · cls,
whichever the connected broker takes for that kind of instrument, and gtt for
a stop-limit Zerodha or Upstox holds: below). opg and
cls name the opening and the closing auction, so they go only on an order
sent straight to the broker (MKT, LMT, or a stop the broker holds):
a stop, stop-limit or if-touched order held here fires mid-session, when its
level is crossed, and is refused with them, and so is a bracket's STP LMT /
STP entry held here. Leave it
out and While25 uses the broker's normal one for the instrument: day almost
everywhere, gtc where there is no day order (crypto on Alpaca), and ioc
for an MKT order where the broker takes no other (crypto on IBKR: "MKT
Orders only support IOC"). A validity you state is sent as stated, and the
broker answers.
On a bracket, validity= is the entry's (checked against the same list).
The take-profit always goes out gtc where the broker offers it, so it does
not end at the close while the position is open; where the broker has no gtc
(Zerodha, Upstox) it goes out with the normal one and ends at the close.
The stop is held by While25 and never ends by time.
hours="eth" asks for extended hours too: pre-market and after-hours on a
US stock or ETF, sent to the broker with its extended-hours flag (IBKR
outsideRth, Alpaca extended_hours) — and on IBKR, Cboe's overnight session
(8:15pm to 9:25am New York) and its 4:15 to 5pm curb for the index options
that trade them (SPX, SPXW, XSP), any order type, IBKR answering for it.
Leave it out for regular hours. That is
the only choice — "rth" is refused, because on a future it changes
nothing (a futures order works every session the exchange runs, and a held
stop on a future already reacts to every price) and crypto never closes. So
"eth" means something on a stock, an ETF or such an index option only (a
stock or ETF option has no extended session, and Alpaca trades every option
in regular hours only); stated elsewhere it goes through and the broker
answers. A broker with no extended session (Zerodha,
Upstox) refuses it. A market or limit order is sent as asked and the
broker answers for it: Alpaca refuses an "eth" market order, and IBKR
answers one on a stock with its message 2109 (the flag "is ignored based on
the order type and destination") and works it in regular hours only. An order
While25 holds — a stop ("STP", "STP LMT"), an if-touched order
("MIT", "LIT"), a trailing stop, a bracket's stop — is judged at
placement (BAD_HOURS), never when it fires, by what the broker works
outside regular hours on that kind of instrument: on Alpaca (every kind) a
limit with "day" or "gtc", on IBKR stocks and ETFs a limit. There
an "eth" stop that would fire a market order ("STP", "MIT",
"TRAIL", a bracket's stop) is refused, and on Alpaca an "eth"
stop-limit stating "ioc" / "fok" too: use a stop-limit ("STP LMT"), or leave
hours out. On a bracket hours= is the whole bracket's: the entry, the
take-profit and the stop.
MOO · MOC · LOO · LOC are refused at once. No broker here is sent an
auction order type. Where the broker takes the auction as a validity, the
refusal says how: on Alpaca shares, order_type="MKT" (or "LMT") with
validity="opg" for the open or "cls" for the close.
A bracket's entry is MKT, LMT, STP LMT or STP, with exactly the
prices that shape takes; anything else is refused instead of being placed as a
different order. Its tag= rides onto the entry, the take-profit and the stop,
so @on.fill(tag=...) hears every one of them, and its idempotency_key= is honoured
like a plain order's: a retried bracket is refused DUPLICATE_ORDER, not
placed twice.
A stop or an if-touched order is held by While25, unless you ask the broker to hold it (held_by="broker", below).
STP LMT (stop-limit: trigger_price and price), STP (stop-market), MIT and
LIT (market / limit if touched) wait inside While25 and go out as a plain
market or limit order when price reaches trigger_price. A stop rests on the
far side of the market (a SELL stop below it); an if-touched order rests on the
near side (a SELL touch above it, a BUY touch below). A trailing stop
(order_type="TRAIL", trail_amount=2.5) is held the same way: it
follows the price at that distance and goes out as a market order when price
turns back by it. Held by While25, the distance is a price amount, never a
percentage, and a trailing stop takes no trigger_price= or price= of its
own; held by the broker (below) it takes the broker's own terms.
On Binance (spot and futures) While25 holds no STP LMT or LIT:
Binance judges a limit's price band when the order arrives, so the limit could
be refused when it fires. Refused INVALID_PARAMETERS, nothing placed: use
STP, or on spot a STP LMT with held_by="broker". A bracket's STP LMT
entry is unchanged.
On its own such an order is an entry: it fires at its level whatever you hold, so a stop left behind a position you have since closed opens a new position the other way. Say it is protection and it behaves like protection:
# sell 10 if price falls to 189 — only while the long is still held
stop = while25.sell("EQ:US:AAPL", 10, order_type="STP",
trigger_price=189.0, reduce_only=True)
With reduce_only=True the order is retired when the position is gone, fires
for no more than you hold, and places nothing if its side would add to the
position. Place it once the position exists (from your @on.fill), with the
same product= the position was opened with: a protective order that reaches
its level with nothing held is dropped, not placed. reduce_only is refused on
any other order type and on a bracket, whose own stop and target are protective
already.
A limit order that must rest: post_only=True. On a venue that takes the
flag (Coinbase, Binance) a post-only limit order is refused by the venue if it
would trade at once instead of resting on the book, so it only ever fills as
the resting side (the maker fee). Refused on anything but order_type="LMT",
on a bracket, and where the connected broker takes no such flag on that kind
of instrument (POST_ONLY_UNSUPPORTED, naming the broker).
# rest at 100,000 and never take: Binance refuses it if it would fill at once
while25.buy("CRYPTO:GLOBAL:BTC-USDT", 0.01, order_type="LMT", price=100000,
post_only=True)
Or have the broker hold it: held_by="broker". Left out (or "local"),
While25 holds the order as above, which works only while the app is
running. With held_by="broker" it is sent at once as the broker's own
stop order, held and triggered at the broker, so it works with the app closed:
# the same protective stop, held by the broker itself
stop = while25.sell("EQ:US:AAPL", 10, order_type="STP", trigger_price=189.0,
reduce_only=True, held_by="broker", validity="gtc")
Your script says it, order by order: the terminal's STOPS HELD BY setting is for the terminal's own tickets and never applies to a script.
- Where: only where the connected broker can hold that order type on that
kind of instrument, on a live account: IBKR, a stop (
STP), a stop-limit (STP LMT) and a trailing stop (TRAIL, sent as IBKR's TRAIL LIMIT with a limit offset), not on crypto; Alpaca, a stop, a stop-limit and a trailing stop on US stocks and ETFs, a stop and a stop-limit on options, a stop-limit on crypto (Alpaca starts a trailing stop from the market and has no trailing stop-limit, so a start level or a limit offset is refused with the reason); Zerodha, a stop (STP) and a stop-limit (STP LMT) everywhere (Zerodha itself refuses theSTPwhere the exchanges stopped it: NSE options, BSE); Upstox, a stop-limit everywhere and a stop (STP) except on option contracts. Anywhere else the order is refusedBROKER_HELD_UNSUPPORTEDand nothing is placed: it is never held by While25 instead. - The broker's rules apply to it, and the broker answers for them: IBKR
triggers most stops in regular trading hours only (a plain stop on a US stock
always), some outside them only when sent with
hours="eth". - It lives as long as its
validity=at the broker. Left out, that is the broker's normal one for the instrument (DAY on IBKR, so it ends at the close). Statevalidity="gtc"for a stop that must last, as above. - Zerodha has no
gtc: a stop-limit (STP LMT) that must last statesvalidity="gtt". Zerodha keeps it as its own GTT for up to a year and, when the price crossestrigger_price=, places a LIMIT order atprice=.gttis refused on anything else (anSTPtoo: a GTT only places a limit order), on a stop whose trigger is not on the stop side of the price now, and when no live price is held; Zerodha itself refuses one on an intraday position. Upstox takesgttthe same way, withprice=equal totrigger_price=. - It is an ordinary working order:
@on.orderhearsNEWwhen it goes to the broker (notHELD) andFILLwhen it fills;modify()andcancel()reach it at the broker. - With
reduce_only=Trueit is refused (aREJECTwith the reason) unless it reduces a position you hold and is no larger than it, because the broker fires a stop whole. While the app runs, it is cancelled when that position closes and cut, never grown, when the position shrinks. held_byis refused on a market or limit order, which goes to the broker at once anyway."local"and"broker"are read in any capitals, by the same rule as the terminal's own orders.- Every order event says who holds the order:
ev["held_by"]is"broker"for a stop resting at the broker as its own order,"local"for one While25 holds (itsHELD,MODIFY,MODIFY_REJECTandCANCEL), andNonefor an order nobody holds (a market or limit order, or the order a held stop placed when it fired). A script that restarts reads from it where each of its stops is. - A trailing stop the broker holds takes the broker's own terms:
trail_amount=(price points) ortrail_percent=(0 to 100; one of the two, never both),trigger_price=as the level it starts at (optional: left out, the broker starts it from the market), andtrail_limit_offset=to fire a limit that far from the stop level instead of a market order (a trailing stop-limit). Its level is the broker's to move:ev["trigger_price"]is the level the broker last reported, andmodify(id, trigger_price=...)is refused — change its distance instead, in the terms it was placed with (modify(id, trail_amount=3)ortrail_percent=2), or its limit offset (modify(id, trail_limit_offset=0.75)). A trailing stop While25 holds trails bytrail_amount=only and keeps it. - A bracket the broker holds:
held_by="broker"onbracket(...)(or on abuy/sellwithstop_loss=). The entry, the take-profit and the stop go to the broker as its own linked orders, so the whole bracket works with the app closed — where the connected broker holds brackets for that kind of instrument: IBKR (not on crypto); Alpaca (US stocks and ETFs, never with a trailing stop); Upstox (as a GTT: a limit entry, sent at once at its price, or aSTP LMTstop entry at its trigger — a market orSTPentry is refused; validitygtt). Anywhere else it is refusedBROKER_HELD_UNSUPPORTEDand nothing is placed, never held by While25 instead. Its take-profit's id is the id the call returns followed by-T, its stop's by-S(not-SL); each is an ordinary working order at the broker (NEW, thenFILL;modify()andcancel()reach it there), and when one exit fills the broker cancels the other. The stop is a stop-market order at the broker, or a trailing stop withtrail_amount=(a percentage is refused on a bracket; so istrail_limit_offset=, because a bracket's stop fires at market). Left out (or"local"), While25 holds the bracket's exits as above.
The id that call returns is the order's id for its whole life:
while25.orders.modify(stop["order_id"], trigger_price=191.0) moves it,
while25.orders.cancel(stop["order_id"]) removes it, and when it fires, the
order it places arrives in @on.order / @on.fill under that same id.
modify() returning only means the change was handed over. Whether it was
made arrives as an event: MODIFY when the order was moved or resized,
MODIFY_REJECT with the reason when it was not, in which case the order waits
exactly as it was. The commonest refusal is a level on the wrong side of the
current price (a SELL stop moved above it would fire at once). A trailing
stop's level cannot be moved at all: it follows the price (one the broker
holds takes a new distance instead, above). The same two events
arrive when the trader drags the order's line on the chart, so a script always
knows where its stop is:
@on.order(tag="mine")
def on_order(self, ctx, ev):
if ev["event"] == "MODIFY":
ctx.log(f"stop now at {ev['trigger_price']} for {ev['quantity']}")
elif ev["event"] == "MODIFY_REJECT":
ctx.log(f"stop not changed: {ev['reason']}")
@on.order hears a held order's whole life:
ev["event"] |
when | ev["status"] |
|---|---|---|
HELD |
While25 has accepted it and is holding it; ev["trigger_price"] is the level it waits at |
TRIGGER_PENDING |
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 |
MODIFY_REJECT |
a change was refused and it waits as it was; ev["reason"] says why |
still working |
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 |
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 |
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 |
NEW, then FILL |
it fired: the order it placed went to the broker, under the same id | as for any order |
Match these on ev["order_id"]. A trailing stop is not announced each time its
level follows the price; only a change somebody made is.
How long a held order waits (one While25 holds; a stop the broker holds
lives for its validity= at the broker, above). validity= applies to the
order it places when it fires. It also decides one more thing:
- An entry that states
validity="day"is withdrawn at the close of the session it trades in (the regular close withhours=left out, the extended session's close for"eth"), as a DAY order is at a broker, and@on.orderhearsCANCELwith the reasonwithdrawn at the close of the session: it was a DAY order. Placed after the close, its day is the next trading day. Before this it waited until it fired, so a "day" stop placed on Monday could fire on Thursday. - One that states
validity="gtd"is withdrawn at itsgood_till=, and@on.orderhearsCANCELwith the reasonwithdrawn at its end time: it was a GTD order. The order it places when it fires carries no end time: a limit goes"gtc", a market order as the broker sends one. - Leave
validity=out, or state"gtc", and it waits until it fires or is cancelled, across days. - A protective order (
reduce_only=True) is never withdrawn by time: a position must not lose its stop overnight, whatevervalidity=says, and one stated"gtd"is refused (INVALID_PARAMETERS). That is While25's rule: a protective stop the broker holds ends when itsvalidity=does (left out, DAY on IBKR: at the close), so state"gtc". - On a market that never closes (crypto) there is no close for the day to end
at, so a
"day"order waits too. - If the close cannot be read for the instrument, a
"day"entry is refused (INVALID_PARAMETERS, the message says so) rather than held to a close that was guessed: place it"gtc", or try again.
A bracket whose entry is a stop (order_type="STP" or "STP LMT") follows the same
rule: when its entry is day (stated, or left out where the broker's normal
validity is day), the waiting entry is withdrawn at the close and the bracket
ends (CANCEL on the bracket's id, reason the bracket's stop entry was withdrawn at the close of the session: it was a DAY order). State
validity="gtc" and it waits until it fires.
Which prices a held order looks at: those of its hours=. With hours=
left out, on a stock, an ETF or an option, regular-session prices only, a
bracket's stop included. Outside them it waits, and the first price of the next
session is judged against the session's last one, so a gap through its level
fires at the open. The order it places is a regular-hours order, so a stop that
fired on an after-hours price could only trade at the next open anyway, at
whatever that open was. For "eth" — and always on a future or a crypto
pair — every price, the extended session's included, and the order it places
when it fires goes out for extended hours too.
Figures are exact, never binary floating point. quantity, price,
trigger_price, take_profit, stop_loss, trail_amount, trail_limit_offset and amount each
accept a Decimal, an int (a NumPy or pandas integer too), a plain decimal
string ("10.5", ".5", "5." all work), or a float (a NumPy or pandas
float too) — but only when its value
is exact to at most 9 fraction digits. 0.1 is fine (Decimal("0.1")), and so
is 0.00005, although Python prints it 5e-05; 0.1 + 0.2 is refused,
because it is 0.30000000000000004 in binary floating point and rounding it to
"fix" it would be guessing at a number you did not write:
from decimal import Decimal
while25.buy("EQ:US:AAPL", 10, price=100.5) # float, exact -> fine
while25.buy("EQ:US:AAPL", Decimal("0.1") + Decimal("0.2")) # exact -> "0.3"
while25.buy("EQ:US:AAPL", 0.1 + 0.2) # ValueError: use Decimal("0.3") or "0.3"
bool, NaN, an infinity, a string in exponent notation ("1e10"), more than
27 whole digits and more than 9 fraction digits are always refused
(ValueError, naming the argument and the value) — never rounded, never
truncated. Trailing zeros are not fraction digits: "1.0000000000" is 1.
quantity= or amount= — exactly one, never both, never neither.
quantity is a share/contract count; amount is a cash amount in the
instrument's own quote currency, sent to the broker AS the amount where its
venue takes one, and the venue decides the units, so it spends exactly the
amount: Coinbase (market or limit, buying or selling), Binance (market orders,
buying or selling), Alpaca (crypto, and stocks it trades in fractions: market
or limit, DAY on stocks) and IBKR (a crypto market buy, which IBKR takes in
cash only: a crypto market buy by quantity= is refused). Nothing converts an
amount into units (2026-11-08): on any other broker, shape or instrument it is
refused in words (AMOUNT_NOT_TAKEN) and the order takes quantity=. An
amount order is market or limit only — it cannot carry a bracket
(take_profit=/stop_loss= need a quantity to size their own legs from); an
order sized by amount cannot be changed; and a strategy's sell needs
quantity= (its part sells no more than
it holds). While such an order works, its quantity is what has filled so
far and its pending_quantity is 0: the units are the venue's to decide. It
has ended at its COMPLETE event (below), never when pending_quantity
reads 0.
Every price defaults to None — absent, meaning "no price". price,
trigger_price, take_profit, stop_loss all default to None (a market
order has no price; an unset trigger or bracket leg is simply not there). A
stated price must be greater than zero: passing price=0 used to mean
"no price" and now raises ValueError("0 is not a price"). If you mean
"market order", leave price unset.
Every call blocks and returns the real answer, including a risk rejection — which raises, so a strategy can never mistake a refusal for a fill.
An order call can time out — 25 seconds with no answer from While25
(a slow broker, a contract still being looked up). It raises While25Error
with code TIMEOUT, and that is the one refusal that is not a refusal: the
order may still have been placed. The error carries the idempotency key the
order went out with (e.idempotency_key, also in its message). Pass it back
to place the order again safely — if the first went through, While25
answers DUPLICATE_ORDER instead of placing a second one — or wait for the
order's events on @on.order / orders.mine(). Whatever While25
answers after the wait is written to the module's console ("the order that
timed out WAS accepted by the terminal: OID-7", or "was refused: ..."). The
same holds for combo(); a cancel(), modify() or square_off() that
times out may still have been applied.
try:
res = while25.buy("EQ:US:AAPL", 10)
except while25.While25Error as e:
if e.code != "TIMEOUT":
raise
res = while25.buy("EQ:US:AAPL", 10, idempotency_key=e.idempotency_key) # never twice
There is no paper trading from Python. An order needs a live grant — the
confirmation a human completes in the panel before a strategy is deployed.
Without one, every order is refused with NO_LIVE_GRANT; nothing is simulated,
and nothing is quietly filled somewhere you were not looking.
That is deliberate. An ungranted order used to be redirected to the paper book, which made "deploy it and read the fills" a substitute for testing — against live market data, priced by a simulator with no contract multiplier, no F&O margin and no expiry. The fills looked real and the numbers were not.
To evaluate a strategy, backtest it in the script. Pull the history you want and run your logic over it. No orders are placed, so nothing needs granting:
rows = while25.history("EQ:US:AAPL", "1D", limit=500)
cash, pos = 100_000.0, 0
for prev, bar in zip(rows, rows[1:]):
if bar["close"] > prev["close"] and not pos:
pos, cash = 1, cash - bar["close"]
elif bar["close"] < prev["close"] and pos:
pos, cash = 0, cash + bar["close"]
while25.log(f"final equity {cash + pos * rows[-1]['close']:.2f}")
A script may cancel or modify only its own orders. Every place, cancel and
modify leaves the order stamped with the module that sent it — read from the
worker the call arrived on, never from your arguments, so a script cannot name
another module. While25 refuses NOT_ORDER_OWNER for any order id your
module did not place — another module's order (a strategy's take-profit leg
included), or one worked by hand in the terminal — and NO_LIVE_GRANT once your
module's grant is revoked or it stops, even for orders it placed earlier.
modify(order_id, *, quantity=None, price=None, trigger_price=None, trail_amount=None, trail_percent=None, trail_limit_offset=None) changes a
working order. Absent means unchanged — pass only what you want to change,
and at least one of them, or it raises (ValueError) rather than sending a
no-op to While25. The three trail terms are for a trailing stop the broker
holds: its new distance in the terms it was placed with (trail_amount= price
points or trail_percent=, never both) and a trailing stop-limit's new limit
offset; stated on an order that does not trail at the broker, or in the other
terms than its own, they are refused BAD_TRAIL:
while25.orders.modify("OID-123", price=196.0) # move the price only
while25.orders.modify("OID-123", quantity=5) # resize only
while25.orders.modify("TRAIL-1", trail_amount=3) # a broker trail: follow 3 points away
while25.orders.modify("OID-123") # ValueError: nothing to change
One exception, for a held stop-limit: moving its trigger_price alone carries
its limit price with it by the same amount, so the gap you set between them
stays (a sell stop-limit at 95 / 94 moved to 90 becomes 90 / 89). Pass price
as well to set the limit yourself. A limit-if-touched order's price is the
price you deal at, so it stays where you put it when its trigger_price moves.
Order events carry the same exact figures. An @on.order / @on.fill
handler's ev dict has event (NEW, FILL, COMPLETE, CANCEL, REJECT, MODIFY,
MODIFY_REJECT, CANCEL_REJECT — a cancel the broker refused, the order
still working — HELD, NOTICE, SQUARE_OFF, POSITION_SQUARED_OFF), order_id,
instrument_key, symbol, side, order_type, status, tag, reason,
timestamp_ms, held_by, combo_id, square_off_id and close_order_id,
and the figures: quantity, filled_quantity and pending_quantity as
Decimal (always stated), and price, average_price, last_fill_quantity,
last_fill_price as Decimal | None — None on anything that is not a fill
(a NEW, a CANCEL, a REJECT states no fill figures at all). The fill
prices (average_price, last_fill_price) are what the order filled at, with
no fee in them: fees are included where brokers send them, in a position's
average_price (see Positions and funds).
A FILL is one execution: it always states last_fill_quantity and
last_fill_price, and it is all @on.fill hears. An order that ends on its
last fill says so on that FILL (status COMPLETE). One that ends on the
venue's word with nothing new filled is told a COMPLETE (@on.order only):
status COMPLETE, the whole order's filled_quantity and average_price,
and None for last_fill_quantity and last_fill_price. An order by
amount= always ends this way, after its last FILL.
A SQUARE_OFF event (a bracket's square off, see Orders) is not an order:
it states only quantity, the close's size once the close is sent, and
None for the other figures; its square_off_id and close_order_id are
None on every other event.
A POSITION_SQUARED_OFF event says that what YOUR module held on an
instrument is no longer its own: the whole position was squared off (Square
off on the position's row in the Positions tab, or the daily loss limit), or
the broker squared it off itself. Only your module hears it, on its
@on.order handlers whatever tag= they name (a symbol= still applies:
a part of your own carries no tag), once per thing
taken: its part (order_id is ""), a bracket of its (the bracket's id and
tag) or a combo's part (combo_id). It is not an order: quantity is what
the module held there, product its pocket (as my_position() names it;
"" where a market keeps one position per instrument), side the side that
closes it (SELL for a long), reason the words, and every other figure is
None. my_position() reads the same from that moment. Read any count of
your own again from it, never just drop it (another pocket may still be the
module's), or the next exit sells units the module no longer has:
@on.order
def on_order(self, ctx, ev):
if ev["event"] == "POSITION_SQUARED_OFF":
mine = while25.portfolio.my_position(ev["instrument_key"])
self.held[ev["instrument_key"]] = mine["quantity"] if mine else Decimal(0)
combo_id names the combo an order is a leg of (see Combos): it is set on
every event of the combo's legs, of the closes its square off sends, and on
that square off's SQUARE_OFF events, and is None on an order of no combo.
trigger_price is Decimal | None too: the level a held order waits at,
None on an order that has none:
@on.fill(tag="mine")
def on_fill(self, ctx, ev):
ctx.log(f"filled {ev['last_fill_quantity']} @ {ev['last_fill_price']}")
Two refusals the order core makes AFTER the call has returned arrive this way
too, as a REJECT whose reason starts with the code. SELL_EXCEEDS_PART: —
a coin held outright (crypto spot) cannot be sold short, and the sell was for
more than this strategy's own part holds there, less its sells already
working (a short bracket entry is refused the same way): size a sell from
your own fills, never from the account's position(). LONG_ONLY_ONE_STRATEGY:
— a coin at a venue that takes its fees from the holding without reporting
them per fill (Alpaca today), while another strategy holds a part, a working
order or a live bracket on it: nothing to retry; pick another instrument, or
stop the other strategy first. See "Two strategies, one account".
You still cannot choose how a granted order executes — that is bound by the terminal, never by your script.
What the SDK refuses before anything leaves your script, as ValueError:
quantity= / amount= neither or both, a quantity or amount that is not
positive, amount= with a bracket or on anything but a market or limit
order, take_profit= without stop_loss=, group="simple" with a bracket,
reduce_only=True on anything but a stop / if-touched / trailing-stop order
or on a bracket, post_only=True on anything but a limit order or on a
bracket, held_by= that is not "local" / "broker" or stated on a
market or limit order, a trail (trail_amount=, trail_percent=,
trail_limit_offset=) on an order that does not trail or in terms its holder
does not take, a trail or limit offset of 0 or below, hours= other than
"eth" ("rth" included), and a stated price of 0 or below. While25
makes the same checks again on anything that reaches it; the codes
BAD_REDUCE_ONLY, BAD_HELD_BY, BAD_TRAIL, BAD_GROUP, BAD_HOURS and
BAD_NOTIONAL below are its words for them.
Refusal codes on while25.orders.* (and the while25.buy / sell / place / bracket shortcuts). Every order call can come back refused;
the code says why and what to do:
| code | meaning | what your script should do |
|---|---|---|
NO_LIVE_GRANT |
no human has granted this module live orders | deploy through the panel; nothing is simulated |
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 |
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 |
WRONG_LANE |
the order id belongs to a client-origin order | act only on orders your module placed |
GRANT_STALE |
the code changed since live orders were granted | redeploy — the grant belongs to the code the human read |
NOT_A_STRATEGY |
only class X(Strategy) may trade |
declare the kind, or drop the order calls |
NOT_ORDER_OWNER |
the order id is not yours | another module's order, or one worked by hand, is never yours to touch |
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 |
NOT_WORKING |
the order is not open (filled, cancelled, or unknown) | refresh your view of the book before acting |
UNSUPPORTED |
the venue/engine cannot do this (e.g. oco/oto groups) |
use bracket(...) — it is engine-managed |
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 |
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 |
MODULE_HALTED |
the module raised and halted; nothing from it is sent | fix the error and deploy again |
GRANT_ENDED |
the grant ended: the module stopped or its Stop ran | deploy again |
NOT_READY |
While25's order path, instrument catalog or options are not up yet | ask again in a moment — nothing was sent |
NO_ENGINE |
While25 is not attached to Python | ask again; my_position() / mine() say NOT_READY for the same |
BAD_ANSWER |
While25's answer could not be read (a figure that is not a number) | nothing to retry — report it |
BAD_PRODUCT |
product= is not delivery, intraday, margin or normal |
state one of them — nothing was placed |
BAD_TAG |
tag= is over 20 characters |
shorten it — nothing was placed |
BAD_NOTIONAL |
quantity= and amount= both stated (the SDK refuses this first, as ValueError) |
size the order one way |
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() |
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 |
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 |
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 |
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 |
BAD_POST_ONLY |
post_only=True on anything but a limit order (LMT) |
drop the flag, or place a limit order |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
NOTHING_HELD |
square_off() on a bracket whose entry has not filled |
cancel the entry instead — nothing was sent |
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 |
NOT_LIVE |
square_off() while the terminal is not on the live account |
nothing was sent |
A trail applies in two places. Standalone it is order_type="TRAIL", trail_amount=... — held by While25 at that fixed price distance, or by
the broker (held_by="broker", where the broker holds trailing stops: IBKR,
not on crypto) in the broker's own terms: trail_amount= or
trail_percent=, a trigger_price= to start from, a trail_limit_offset=
to fire a limit. On a bracket it is bracket(..., stop_loss=..., trail_amount=...), a fixed price distance whoever holds the bracket (a
percentage trail is refused there). trail_amount=, trail_percent= or
trail_limit_offset= on any other order (a market, limit, stop or
if-touched order) is refused in words rather than sent with no trailing stop
behind it.
Only a Strategy — or an App that imports one — may place orders.
Order rights go by kind: an Indicator, a Monitor or an ordinary App
calling any of buy / sell / place / bracket / combo / cancel / modify gets
OrderRightsError("<kind> modules cannot place orders") — raised in the worker
before any request leaves for While25, so nothing reaches a broker. It is a
While25Error (code ORDER_RIGHTS), so an existing except While25Error
catches it. While25 checks again in its own process, for every order
request whatever call sent it (the private ctx._call(...) included), and
answers ORDER_RIGHTS without sending anything; While25 enforces the same
rule on live grants. If something needs to trade, make it a
Strategy — or have a Monitor while25.emit() a signal that a Strategy
subscribes to, which keeps the trading decision behind the human
deploy-confirm: a monitor's signals reach it only with the box ticked at its
deploy. An ordinary App's and an Indicator's signals never reach a module
that trades, except a strategy's own desk (see while25.emit in "Start and stop"); a strategy works an
indicator out itself (see "An indicator's numbers in a strategy").
A strategy's panel: its desk. The strategy is what you deploy. Its panel
is an App its class names, desk = ..., written above it in the same file:
# strategies/breakout.py
from types import SimpleNamespace
import while25
from while25 import App, Bars, Strategy, on, ui
ui.panel("breakout_desk", "Breakout")
ui.layout(ui.view("main"))
class BreakoutDesk(App): # shows, never trades
id = "breakout_desk"
@on.signal("breakout_state", sender="breakout")
def state(self, ctx, payload):
s = SimpleNamespace(**payload)
while25.ui.push("main", {"blocks": [ui.strategy_block(), ui.timeline(s.events)]})
class Breakout(Strategy):
id = "breakout"
desk = BreakoutDesk
aapl = Bars("EQ:US:AAPL", "5m", keep=200)
@on.bar(aapl)
def bar(self, ctx, bar):
... # the logic, and its orders
while25.emit("breakout_state", {"events": [...]})
- Deploy starts both, Stop stops both. Deploying the strategy starts its desk and opens the desk's panel; when the strategy stops or halts, the desk stops. On the panel, the button is Deploy while the strategy is not running, and Stop is the strategy's Stop window.
- The desk shows, it never trades. Its
ui.strategy_block()shows its strategy. It hears what the strategy sends with@on.signal(name, sender="<strategy id>")(the id, as text: the strategy's class comes below it), and what it sends reaches its strategy (its buttons). A bug in the desk halts the desk, never the strategy. - Each part runs as its own kind: the strategy, its desk and its monitors
(
monitors = [...]) are separate scripts with separate rights. Creating one inside another (Breakout()in an App) runs its code as the caller: its triggers and bar lines never run, and a Monitor'sai.askis refused there.
Trading Apps, the old way. An App whose file imports a Strategy class by
name still trades and deploys, for scripts written that way: the App runs, the
strategy inside it is a plain object fed by hand, and every order is the App's.
import strategies.breakout (the module, not the class) does NOT make an App
trade, and neither does importing only the Strategy base; an Indicator, a
Monitor or a strategy's desk never trades, whatever it imports. A Strategy with
Bars lines held by a trading App is refused when the file is saved: those
lines would never be filled there. While a strategy or trading App runs, its
own file and every helper it imports are frozen (writes refused with
LIVE_STRATEGY); stop it to edit them. Editing any of them while it is
stopped changes the code the grant was confirmed for, so the grant has to be
confirmed again. Neither is restarted automatically after a Python restart — a
person starts it.
What the approval covers is what you import by name. The terminal reads
your imports without running them — import x, from x import y (inside a
function too), relative imports, from pkg import * when pkg/__init__.py
lists a literal __all__ — against your script's real sys.path, in its
order: in the terminal that is a project's own folder, then lib/, then the
bundled packages (numpy, pandas, while25), then the workspace, then Python's
own library. So a package in lib/, or a bundled one, with the same name as
a file of yours is the one that runs — name your files so they don't collide.
The workspace files it finds are hashed
into the revision the human confirms. The Strategy that makes an App trade
must be defined in the App's file or in one of those files: a Strategy reached
through importlib, __import__, a computed __all__ or a sys.path you
changed does not make it trade. A live strategy or trading App then loads only
those files, byte for byte as confirmed: importing any other workspace file —
or one changed since the confirm, or one outside the workspace that is not
Python's own library or an installed package — raises ImportError
(at start, or in the handler that imports it):
`helpers.late` is not part of the code approved for live trading — stop and redeploy to include it
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
pip install into lib/ are installed packages, not your code — so only
the installer changes lib/ (anything else is refused, see above), and while
any strategy or trading App runs, installing a package is refused with
"packages can't change while a strategy is running ('') — stop it
first"; starting a strategy or trading App while an install is under way is
refused with "packages are changing — wait for the install to finish, then
start ''". Any spelling of a frozen file is the file: another case on a
Mac's disk, a symlink or a hard link is refused the same. Not covered:
code you load yourself from a path — exec() of a file you read,
importlib.util.spec_from_file_location — and data files; they are yours to
keep stable. A live module whose imports run past 500 workspace files is not
covered at all: it runs, may not place orders, and says so in its log.
Positions and funds
p = while25.portfolio.position("EQ:US:AAPL") # None when flat
f = while25.portfolio.funds() # margin_used, margin_available, assets, figures — or None
if f is None:
why = while25.portfolio.funds_unavailable_reason() # the broker's own words
d = while25.portfolio.day_pnl() # today's ACCOUNT P&L (a Money) — or None
Figures are exact. position()'s quantity is a Decimal; its
average_price and last_price are Decimal | None; its pnl is a
while25.Money | None — a frozen (value: Decimal, currency: str) pair
that reads as "1234.5 USD". A position's last_price and pnl are None
until its instrument has ticked since the broker snapshot.
Binance futures P&L follows the account's "P&L on" choice (risk policy: Last price, the
default, or Mark price; the loss limits follow it): every row states pnl_price ("mark" |
"last") and mark_price (Decimal | None); a stop held there keeps the price the choice named
when it was placed (mine()["held_stops"][i]["triggers_on"]: "mark" | "last"); a trailing
stop on the mark placed before the contract's first mark waits for it (its trigger_price is
None until then);
average_price there is the fills' average (fees and funding are outside positions on Binance and
Coinbase futures); funds()["contract_settings"] is [{"instrument_key", "symbol", "margin_type": "cross" | "isolated", "leverage"}], as the tickets show them.
Fees are included where brokers send them. A position's average_price
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
reports none (Alpaca, Zerodha and Upstox today) it stays at the fill prices.
Don't add a fee the broker sent to it again yourself.
A symbol held under more than one product (intraday and delivery, say) comes
back as ONE combined position: quantity summed; pnl summed only when
every row states one and they are all in the same currency (a long in INR
and a short in USD cannot be honestly added, so it is None); average_price
is the quantity-weighted average, quantized to 9 decimal places, and only
across rows on the same side (a long averaged against a short is None,
never a guess). position()["rows"] keeps each broker row exactly as
reported, and ["products"] names them, so nothing is lost by combining.
day_pnl(), realised_pnl() and unrealised_pnl() are account-level
Money | None figures from the broker's own account line (day P&L falls back
to the terminal's portfolio summary when it holds rows); each is None when
nobody stated it — never a sum over positions, which vanish when a position
closes.
Never cached: a stale position feeding a sizing decision is a money bug.
When one of the combined rows states no quantity, the whole quantity is
None (never summed as 0), and then there is no side and no average_price
either.
What this module holds: my_position(), my_positions(), orders.mine()
mine = while25.portfolio.my_position("EQ:US:AAPL") # None when it has nothing there
every = while25.portfolio.my_positions() # one dict per instrument, [] for none
working = while25.orders.mine() # its working orders and held stops
position() is the account's; this is the module's own, changed by its own
orders and ended by a square off of the whole position (a
POSITION_SQUARED_OFF event says so), and kept across a Stop and a restart of the app, so a strategy
deployed again (the same id) reads where it left off. my_position(key)
takes the instrument key, or its symbol when that names one instrument the
module has (two: ValueError), and returns:
| Key | |
|---|---|
instrument_key, symbol |
the instrument |
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 |
product |
the part's pocket ("DELIVERY", "INTRADAY", "MARGIN"; "" where a market keeps one per instrument); None across several pockets (each is in rows) |
average_price, last_price |
Decimal, or None when not known |
pnl |
While25's unrealised P&L on the part, a Money; None when the price or the multiplier is not known |
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 |
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 |
rows, products |
each part as stated, one per pocket, and their pockets |
brackets |
its brackets there: bracket_id, group_label, side, product, quantity_held, entry_average, last_price, pnl, broker_held, waiting_for_entry |
combos |
its combos' legs there (see Combos) |
Parts in several pockets combine by position()'s rules. my_positions()
lists every instrument the module has a part, a bracket or a combo leg on.
orders.mine(instrument_key=None) lists its working orders and the stops
While25 holds for it, one dict each: order_id, instrument_key,
symbol, side, order_type (MKT, LMT, STP, STP LMT, MIT, LIT,
TRAIL), product, validity, hours, quantity,
filled_quantity, price, trigger_price, status (PENDING, OPEN, or
TRIGGER_PENDING for a stop held by While25), held_by, tag,
bracket_id, group_label and role (ENTRY, EXIT, TAKE_PROFIT,
PROTECTIVE_STOP, ENTRY_STOP, BRACKET_ENTRY, BRACKET_TAKE_PROFIT,
BRACKET_STOP, COMBO_LEG). All three are reads: they need no order
rights, on_stop may call them, and they are answered from what While25
already holds, so a strategy may ask every tick. NOT_READY while
While25 cannot tell yet (its order path is not up, or it is not attached
to Python): ask again, never read it as flat.
funds() returns {"margin_used": Money | None, "margin_available": Money | None, "assets": [...]}, or None when the broker has not stated the
account's funds at all — a panel must render that as unavailable rather than as
a number. Each figure is None where the venue does not state it: Alpaca
states no available margin, so its margin_available is None on a funded
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
service hours, and a broker that has told you nothing has not told you the
account is empty. Write if f is None:, never f = while25.portfolio.funds() or {} and never .get("margin_available", 0) — a fabricated zero is
indistinguishable from a drained account, which is the one mistake this API
is shaped to prevent. assets is [], never absent, when the venue states no
per-asset breakdown — each entry is {"asset": str, "free": Decimal | None, "locked": Decimal | None, "total": Decimal | None}, for the crypto venues
that report balances per coin.
figures is every figure the broker states, under its own names and in its
own order (the Funds tab's rows); [] from a While25 that sends none.
Each is {"section": str, "label": str, "column": str, "kind": "money" | "units" | "percent" | "number" | "text", "value": Decimal | None, "text": str | None, "currency": str | None, "field": str, "roles": [str], "key_types": [str]}: value is
None on a "text" figure (its word is in text), column says which of
several ("Securities", a currency, "Hold"; "" = the figure itself), and
field is the broker's own key. roles mark the money the broker lets you
put into a new trade ("available": IBKR's Current Available Funds, Alpaca's
Buying power), its margin in use ("margin_used") and its margin still free
("margin_available"); margin_used / margin_available are those
figures' values. key_types names the instrument kinds those roles answer for on an
account holding several kinds (Coinbase spot + US futures: "CRYPTO",
"FUT"); [] = every kind.
f = while25.portfolio.funds()
avail = next((g for g in f["figures"] if "available" in g["roles"]), None) if f else None
while25.log(f'{avail["label"]}: {avail["value"]}' if avail else "available: not stated")
There is no cash figure. It used to exist and was filled with
available_margin under a second name; a relabelled quantity is a wrong
number, so it was removed rather than left to be believed.
Instrument rules
inst = while25.data.instrument("EQ:US:AAPL")
inst2 = while25.data.instruments(["EQ:US:AAPL", "EQ:US:MSFT"]) # a list, same order
The venue's own size and price rules for one instrument, so a strategy can
size an order it already knows will be accepted — or explain a rejection
without a round trip. With a broker attached they are that broker's own (its
instrument list or its contract lookup); with none, the data source's. Every
rule is Decimal | None (absent means the venue stated none):
size_increment, min_qty, max_qty, lot_multiple,
price_increment, sub_band_price_increment, price_band_floor,
multiplier; min_notional is a Money | None; price_steps is the tick
by price where it changes with the price (IBKR's rule for the contract),
(from_price, increment) rows lowest first, () when the venue states none
— when present it governs every price in place of price_increment and the
band. quote_currency, settlement_currency, tradeable and
untradeable_reason describe the row itself. An unknown key raises
While25Error (code INSTRUMENT_NOT_FOUND).
inst.step # lot_multiple, else size_increment; None if neither
inst.tick_for(101.30) # the tick that governs THIS price (ladder step, else band)
inst.check(quantity=15, price=101.30) # None = would pass; else the reason it would not
inst.notice(quantity=15, price=101.30) # None = every rule on file; else what the venue judges
inst.snap(ltp) # a float from the feed -> the exact tick-grid Decimal
inst.offset(ltp, -2) # two ticks below, exact
inst.ticks_between(ltp, target) # whole ticks apart, exact; None across a band floor
Prices reach a script as floats and stay floats — indicators want them so.
snap(), offset() and ticks_between() are where a float becomes an exact
figure: the float is read by its shortest decimal form (the tape's 100.05,
stored as 100.0499999999999971, reads back as 100.05) and put on the venue's
tick ONCE, so "two ticks below" and "how many ticks apart" are exact and the
order you build from them is on the grid. Do the arithmetic on the snapped
Decimal, never on the float (100.05 - 0.10 is 99.94999999999999 in floats,
and check() would refuse it as off-tick). snap(price, mode="down") and
"up" pick the buyer's and the seller's side of a between-tick price.
On a ladder a tick is one step along the venue's grid (every price on the
tick that governs it), so offset() and ticks_between() change increment
at a step edge:
# price_steps (0, 0.05), (3, 0.10): 0.05 below 3, 0.10 from 3 on
inst.tick_for(3) # 0.10: the step AT 3
inst.offset(2.95, 2) # 3.10 (2.95, 3.00, 3.10)
inst.offset(3.10, -2) # 2.95, not 2.90
inst.ticks_between(2.95, 3.10) # 2
check() is a local, advisory pre-check — it never calls While25 —
mirroring the same size and price rules While25 itself enforces
(check_size/check_price): positive; on-step; between the minimum and the
maximum; at or above min_notional when a price is also given; on the
tick tick_for() names when a price is given. Only a rule the venue states is
judged: a missing step, minimum or tick, or a min_notional stated in another
currency than the order's, refuses nothing — the order goes as typed and the
venue judges it. A min_notional the venue states for orders by amount only
(min_notional_amount_orders_only: Coinbase's quote_min_size, stated for the
quote asset alone) holds no quantity either: such an order goes to the venue.
notice() names each such gap so a script can log it, and
returns None when every rule the order touches is on file. check()
returning None means "While25 is expected to accept this," not a
guarantee — While25 re-checks every order regardless, and its verdict is
the one that counts.
msg = inst.check(quantity=7)
if msg:
while25.log(f"skipping: {msg}")
else:
while25.buy("EQ:US:AAPL", 7)
Options: one contract from a description
c = while25.option("AAPL", expiry="26th", right="CALL", strike="ATM+2")
while25.buy(c["instrument_key"], c["lot_size"])
while25.subscribe(c["instrument_key"], on_tick=self.on_option)
option() names ONE listed contract, worked out now from the same expiry and
strike lists the Option Chain panel reads — the whole list of an expiry, not
the panel's window around the money — so a strategy and the panel never name
different contracts, and nothing has to be open first.
| Argument | Takes |
|---|---|
underlying |
a symbol ("AAPL", "NIFTY") or a full key ("EQ:US:AAPL") |
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 |
right |
"CALL" / "PUT", also "C" / "P" and "CE" / "PE" |
strike |
a listed price (230, "24500"), or "ATM", "ATM+N", "ATM-N" |
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 |
atm_from= |
"options" (the default) or "spot": what ATM is measured from — below |
ATM is counted as the Options Builder counts it. ATM is the listed strike
nearest the money, a tie going to the higher strike. ATM+N is N strikes
higher and ATM-N N strikes lower, for calls and puts alike — on a
put, ATM+2 is in the money. A step is one listed strike, not a fixed price
distance.
atm_from="options": the money is the expiry's forward, measured from the call and put prices near the money — the figure the Options Builder centres on. It keeps moving while an index stands still in its closing auction, and it carries the dividends and interest the expiry is priced on. Where no forward can be measured (no quoted call and put near the money: a shut market, a quiet board) the underlying's price stands, and the result says so inatm_from.atm_from="spot": the money is the underlying's own price — the strike the Option Chain panel marks by default. A source that sends no price for the underlying (SPX on Alpaca) is refused rather than measured another way.
What it turns on. Counting from the money turns on the underlying's live
price when nothing has (it stays on: it is the strategy's from then on). For
"options" it also turns on the call and put prices of the strikes nearest the
money for a moment to measure the forward, and turns off again every one the
strategy did not already hold. A listed price turns nothing on.
How long it takes. It answers from what the terminal holds, so usually at once. The first lookup of an underlying, or of an expiry's strikes, on IBKR waits while IBKR answers — up to 30 seconds, the Option Chain panel's own wait; a first price waits up to 5 seconds. The strategy's code waits at that line meanwhile, so look a contract up when you need it — at start, or just before ordering — not on every tick.
It returns a dict:
| Key | |
|---|---|
instrument_key |
the contract — what buy / sell / bracket / subscribe take |
symbol |
the venue's own name for it |
underlying_key, expiry, settlement, strike (Decimal), right ("CALL" / "PUT") |
what was picked |
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 |
multiplier, currency |
multiplier is a Decimal, None where the venue states none |
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 |
It never names a neighbouring contract instead. A description that names no
listed contract raises While25Error, with nothing turned on or placed;
malformed arguments raise ValueError.
| code | meaning |
|---|---|
NO_UNDERLYING, NO_OPTIONS |
the underlying is not an instrument name, or lists no options |
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=) |
NO_STRIKE |
the price is not a listed strike (the message names the nearest listed) |
OFF_THE_LIST |
ATM±N runs off either end of the strike list, or the money is beyond the listed strikes |
NO_PRICE |
an ATM strike with no price to find the money on yet |
NOT_LISTED |
the board lists no call (or no put) at that strike |
TIMEOUT |
the venue was still looking it up after 30 seconds — ask again |
The underlying and the strike from the settings, the trigger on the index's own bars:
import while25
from while25 import Strategy, on
from while25.inputs import Enum, Float, Str
class IndexBreakout(Strategy):
id = "index_breakout"
inputs = [Enum("index", choices=["NIFTY", "BANKNIFTY"], default="NIFTY"),
Float("level", default=24000.0),
Str("strike", default="ATM+1")]
@on.bar("IDX:IN:NIFTY", "5m") # both written out: a bar line
@on.bar("IDX:IN:BANKNIFTY", "5m") # takes a symbol from the file
def on_bar(self, ctx, bar):
if bar["symbol"] != "IDX:IN:" + while25.params["index"]:
return # the other index's bar
if bar["close"] > while25.params["level"]:
c = while25.option(while25.params["index"], expiry="28th",
right="CE", strike=while25.params["strike"])
while25.buy(c["instrument_key"], c["lot_size"])
while25.subscribe(c["instrument_key"], on_tick=self.on_option)
def on_option(self, ctx, tick):
... # every tick of the option bought
option() works in a running strategy or app. A one-shot run is refused
NOT_IN_RUN, and a call while the file is being loaded (at import time)
IMPORT_TIME_DATA.
Combos: several option legs as one order
legs = [
while25.leg(while25.option("SPY", "2026-11-20", "PUT", "ATM-4"), "BUY"),
while25.leg(while25.option("SPY", "2026-11-20", "PUT", "ATM-2"), "SELL"),
while25.leg(while25.option("SPY", "2026-11-20", "CALL", "ATM+2"), "SELL"),
while25.leg(while25.option("SPY", "2026-11-20", "CALL", "ATM+4"), "BUY"),
]
c = while25.combo(legs, lots=1, name="Iron condor")
c["combo_id"] # what cancel(), square_off() and my_position() name it by
while25.combo() places two to ten option legs as ONE combo: a spread, a
straddle, an iron condor, placed the way Deploy in Options Execution places a
design, through the same placer. Legs sent as separate orders can fill one and
miss the next, leaving a position nobody chose; a combo goes to the broker as
one order where the broker takes one, and all or none where it does not
(below). while25.orders.combo() is the same call.
A leg is while25.leg(contract, side, ratio=1, price=None):
| Argument | Takes |
|---|---|
contract |
an option's instrument key, or the dict while25.option() returned |
side |
"BUY" or "SELL", in any capitals |
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) |
price |
this leg's own limit, on an "LMT" combo only (below) |
leg() checks what it is given on the line that writes it, and returns a
plain dict. A dict you write yourself with the same four keys
(instrument_key, side, ratio, price) is a leg too; any other key in it
is refused, so a "qty" or a "lots" never quietly leaves a leg of ratio 1.
A combo is 2 to 10 legs, and names each contract once.
lots= is how many of the combo, a whole number, 1 or more. Each leg's
order is lots x its ratio x its contract's own lot size, as While25's
instrument list states it: one contract per lot on a US option, the
exchange's lot on an Indian one. You never write a leg's quantity, and a
contract whose lot size is not on file is refused (NO_LOT_SIZE) rather than
sized by a guess.
Market, or each leg's own limit — never a mix. order_type= is every
leg's:
"MKT"(the default): no leg states a price."LMT": every leg states its own limit, above 0, in the figures any price takes (aDecimal, anint, plain decimal text, or an exact float). Where the broker takes the combo as one order, its limit is the legs' limits netted by ratio: a bought leg adds and a sold leg subtracts, so a credit is negative, as IBKR writes it. Leg by leg, each leg works at its own limit.
legs = [while25.leg(put_far, "BUY", price="1.10"),
while25.leg(put_near, "SELL", price="2.05"),
while25.leg(call_near, "SELL", price="1.95"),
while25.leg(call_far, "BUY", price="1.00")]
while25.combo(legs, order_type="LMT") # as one order: 1.10 - 2.05 - 1.95 + 1.00 = -1.90, a 1.90 credit
A limit combo with a leg stating no price, and a market combo with a leg
stating one, are refused (ValueError) before anything is sent: the one
order's limit is built from every leg's price, so a missing one would leave it
unset, and a stray one would put a limit on an order nobody priced.
product=, validity= and hours= apply to every leg and read as
place()'s do (hours="rth" is refused: leave it out for regular hours).
name= (at most 64 characters) is the combo's name on Options Execution, Open
orders and the Positions tab, and tag= (at most 20) rides on every leg's
orders and events. Left out, the name is the strategy's id, and the tag is
py: and that id, as on any order of the strategy placed with no tag. Every
call mints its own idempotency_key= unless you pass one, as place() does.
How it goes to the broker:
| Broker | |
|---|---|
| IBKR | one combo order of up to 6 legs; a combo of more legs goes leg by leg |
| 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 |
| Upstox, Zerodha | leg by leg, in the order the legs are listed |
Leg by leg it is all or none: a refused leg withdraws the legs not yet
filled, and a leg that already filled stays, for your script to deal with.
The answer's one_order says which way it went.
What it answers, once While25 has handed the combo on:
{"ok": True, "combo_id": ..., "order_ids": [...], "one_order": bool, "deployment_number": int}. order_ids is each leg's order, in the order the
legs were given; deployment_number is the combo's number on Options
Execution (#5; 0 when it has none). Every event of its legs carries
ev["combo_id"] and your tag=, so a handler tells the combo's fills from
everything else:
@on.fill(tag="condor")
def on_fill(self, ctx, ev):
if ev["combo_id"] == self.combo_id:
ctx.log(f"{ev['symbol']} {ev['side']} {ev['last_fill_quantity']} @ {ev['last_fill_price']}")
A refusal raises While25Error with its code, as a refused place() does,
and nothing is placed. The SDK refuses what it can judge itself in words
(ValueError) before anything leaves your script; While25 judges again:
| code | meaning |
|---|---|
BAD_COMBO |
not 2 to 10 legs, a contract twice, a side that is not BUY or SELL, a ratio or lots below 1 |
BAD_ORDER_TYPE |
an order type that is not "MKT" or "LMT" |
BAD_PRICE |
a limit leg with no price above 0, or a market leg with one |
BAD_PRODUCT, BAD_VALIDITY, BAD_HOURS |
as for place(), "rth" included |
BAD_TAG, BAD_NAME |
a tag over 20 characters, a name over 64 |
NOT_AN_OPTION |
a leg that is not an option contract |
NO_LOT_SIZE |
the instrument list states no lot size for a leg's contract |
INSTRUMENT_RESOLVING |
a leg's contract is still being fetched from the venue: call combo() again in a moment |
INSTRUMENT_NOT_FOUND |
the venue does not list a leg's contract |
KILL_SWITCH_ACTIVE |
the kill switch is on |
DUPLICATE_ORDER |
the idempotency_key= was used already: a resubmit needs a fresh key |
COMBO_REFUSED |
the placer refused it; the message is its words |
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 |
| the grant codes | NO_LIVE_GRANT, GRANT_STALE, MODULE_STOPPING and the rest every order hears |
What it holds is the combo's own. What its legs fill belongs to the combo,
held by your strategy, and never joins your strategy's part of each contract:
while25.portfolio.my_position(key)["quantity"] leaves it out, exactly as it
leaves a bracket out, and my_position(key)["combos"] lists it, one entry per
combo holding that contract:
| Key | |
|---|---|
combo_id, label |
the combo, and its name as Options Execution shows it ("#5 Iron condor"; "Combo" when it has no deployment) |
quantity |
what the combo holds of this contract, a signed Decimal |
product |
its pocket, as on a part |
average_price, last_price |
Decimal, or None when not known |
pnl |
While25's unrealised P&L on it, a Money, or None when the price or the multiplier is not known |
deployment_number |
its number on Options Execution; 0 when it has none |
A contract you hold only through a combo is listed too, with its own
quantity Decimal(0), and my_positions() lists every contract once. In
while25.orders.mine() a combo's legs still working appear under their own
order ids with role "COMBO_LEG": they are cancelled with the combo, never
alone.
Cancel it, or square it off — always whole.
while25.orders.cancel(c["combo_id"]) cancels every leg still working, as one
order where the broker holds one, and each leg hears CANCEL. A combo is
never cancelled or changed a leg at a time: a leg's own id is refused
COMBO_LEG by cancel() and modify() on every broker (where the legs
went one by one, a cancelled leg would leave its siblings working with no
unwind). To change a combo, cancel it by its id and place it again. The
cancel is refused NOT_ORDER_OWNER when the combo is not your module's, and
NOT_WORKING when nothing of it is working.
while25.orders.square_off(c["combo_id"]) does what Sq Off does on its row in
Options Execution: its legs still working are cancelled, then what it holds is
closed at market, as one combo order where the broker takes one. It answers
once While25 has taken it, with {"ok": True, "square_off_id": ..., "bracket_id": ...} (bracket_id is the combo's id here). Each close arrives
as NEW and FILL under its own id, with ev["combo_id"] set, and one
SQUARE_OFF event under the combo's id, with its tag=, says how it went:
ev["status"] |
when |
|---|---|
SENT |
the closes went out: ev["reason"] lists them and ev["close_order_id"] names the first |
DONE |
it held nothing to close: its legs still working were cancelled |
REFUSED |
it could not start; ev["reason"] says why, and nothing was closed |
STOPPED |
nothing could go out; ev["reason"] says why |
Refused at once, with nothing sent: NO_BRACKET (the id names no open combo,
nor bracket, of your module), NOT_ORDER_OWNER, MARKET_CLOSED, NOT_LIVE,
NOT_READY and BUSY.
In the app. Options Execution's Running list shows the combo as
#N <name>, with no saved design behind it: its Sq Off and Cancel work as for
any deployment, and it has no Add. Open orders and the Positions tab show it
under the same #N.
Stopping the strategy. The Stop window lists each combo that holds something, with what each choice does to it: "Stop and cancel its orders" keeps it (and cancels a combo still working, whole), "Stop and square off" closes it whole, as one combo order where the broker takes one.
An iron condor, entered on the first bar and closed whole if SPY closes beyond either short strike:
import while25
from while25 import Strategy, on
class SpyCondor(Strategy):
id = "spy_condor"
combo_id = None
closing = False
@on.bar("EQ:US:SPY", "5m")
def on_bar(self, ctx, bar):
if self.combo_id is None:
picks = [(while25.option("SPY", "2026-11-20", right, strike), side)
for right, strike, side in (("PUT", "ATM-4", "BUY"),
("PUT", "ATM-2", "SELL"),
("CALL", "ATM+2", "SELL"),
("CALL", "ATM+4", "BUY"))]
c = while25.combo([while25.leg(p, side) for p, side in picks],
lots=1, name="Iron condor", tag="condor")
self.combo_id = c["combo_id"]
self.low, self.high = picks[1][0]["strike"], picks[2][0]["strike"]
elif not self.closing and not self.low < bar["close"] < self.high:
while25.orders.square_off(self.combo_id) # the whole condor, at market
self.closing = True
@on.order(tag="condor")
def on_order(self, ctx, ev):
if ev["event"] == "SQUARE_OFF" and ev["combo_id"] == self.combo_id:
ctx.log(f"square off {ev['status']}: {ev['reason']}")
On NIFTY the same lines name NIFTY's contracts
(while25.option("NIFTY", "28th", "PE", "ATM-2")), lots=1 is one NIFTY lot
of each leg, and on Upstox or Zerodha the legs go one at a
time, all or none. combo() works in a running strategy or trading app; a
one-shot run is refused NOT_IN_RUN. While25 takes at most 1,000,000
lots, and a ratio of at most 10,000 on a leg.
Futures: one contract from a root
c = while25.future("MNQ") # the contract the chart's continuous MNQ is on now
while25.buy(c["instrument_key"], 1, stop_loss=20950)
while25.future("MNQ", "next") # the one after it, for a roll
while25.future("MNQ", "2027-03") # a named contract month
The chart's continuous line (MNQ1!) is no contract and takes no order: an
order on it is refused on every broker. future() is how a strategy gets from
a root to the dated contract to trade, worked out now from the contracts the
Futures panel lists. It turns nothing on and keeps nothing.
| Argument | Takes |
|---|---|
root |
the root as the Futures panel names it ("MNQ", "NIFTY", "CRUDEOIL"); "ROOT@MIC" where two exchanges of one market list the same root |
expiry |
"front" (the default), "next", or a contract month ("2027-03", "202703") |
"front" is the contract the chart's continuous line for the root is on
now, so it rolls when that line rolls: on IBKR and Upstox after the first
full session in which the next contract traded more than it (at the latest
after its last trading day), on Zerodha at expiry. Where the venue draws no
continuous line there is no front to follow: "front" and "next" are
refused, and a named month works. "next" is the first contract of a later
month than the front. A month is that month's contract, as its key names it:
MNQ's "2027-03" is FUT:US:MNQ:202703, MNQH7.
Nothing is rolled for you. It is worked out on every call; when the front
has moved on, the strategy closes the old contract and opens the new one with
orders of its own (a bracket's close is square_off(), under Orders):
c = while25.future("MNQ")
if self.bracket_id and c["instrument_key"] != self.contract:
while25.orders.square_off(self.bracket_id) # out of the old contract
res = while25.buy(c["instrument_key"], 1, stop_loss=self.stop_for(c))
self.contract, self.bracket_id = c["instrument_key"], res["order_id"]
It returns a dict: instrument_key, symbol, root, month ("YYYY-MM"),
last_trade (ISO date, or None when the venue states none), lot_size and
multiplier (Decimal, or None when the venue states none), currency,
tradeable and untradeable_reason (an untradeable contract's orders are
refused, the reason says why), and front (True when it is the contract the
chart's line is on now; None for a named month, which does not look). The
contract it names is on the venue's list, so its first order is not refused as
unknown. The first lookup of a root on IBKR, and the line's first look at its
contracts, wait while the venue answers, up to 30 seconds.
While25Error.code |
when |
|---|---|
NO_ROOT |
not a root: a contract's key, or nothing |
NO_FUTURES |
the venue lists no live futures for the root |
AMBIGUOUS_ROOT |
two exchanges list the root; the message names ROOT@MIC for each |
NO_FRONT |
"front" or "next" where the venue draws no continuous line for the root: name a month (the message lists them) |
NO_NEXT |
no contract after the front is listed yet |
NOT_LISTED |
the month is not listed (the message names the listed ones) |
AMBIGUOUS_MONTH |
the month lists more than one contract (a weekly beside the monthly): order the one you mean by its key |
TIMEOUT |
the venue was still looking it up after 30 seconds — ask again |
Two strategies, one account
A live strategy trades the account, not a private book. Everything it reads back is account-wide:
while25.portfolio.position(key)is the account's net position on that instrument — another strategy's trades and a trade worked by hand in the terminal included. Size an exit frommy_position(), what your module holds now, never fromposition(), or it can sell someone else's shares. A count of your own (the fills of the order ids you got back) goes stale when the whole position is squared off: read it again frommy_position()onPOSITION_SQUARED_OFF.@on.orderand@on.filldeliver every order event on the account — another strategy's, and the human's. There is no owner field; match on theorder_idyour call returned, or on atagyou set on your own orders.
The broker nets every fill on an instrument into one position; While25 keeps each strategy's PART of it apart (2026-10-18). Two strategies may trade one instrument at once: each keeps its own part — changed by its own orders, ended only by a square off of the whole position (below) — its own stops, measured against that part, and its own Stop, which squares off that part and nothing else; the broker nets the parts. Brackets too: two strategies' brackets stand side by side on one instrument, each sized to its own fills.
A coin held outright (crypto spot) can never be sold short, so there a
strategy sells only what its own part holds, less its sells already working
(SELL_EXCEEDS_PART beyond that; a short bracket entry likewise). One
strategy can never sell another's coins, or the human's.
Where the venue takes its fees from the holding itself and does not report
them per fill — Alpaca today; each broker adapter declares it — nobody can
say whose fill paid the fee, so While25 cannot keep separate parts of a
coin: every stop and bracket on it follows the account's whole holding, and
one strategy at a time trades it. A second strategy's order there (plain or
bracket) is refused LONG_ONLY_ONE_STRATEGY while the first holds a part,
has a working order or a live bracket, in words, naming it. A venue that
reports its fees per fill has no such rule: its coins keep parts per
strategy like everything else.
Two Strategy classes inside one App are ONE owner. The App's orders,
grant and part are the App's (py:<app id>), whichever of its strategies
placed them — so one of them can flatten the other's bracketed position
exactly as a trade by hand could. Keep strategies that share an instrument in
separate modules.
What the parts do not cover: a trade made by hand still nets against a
strategy's position (it is the account owner's intent). A strategy stopped
with a position open keeps it as its own part unless the Stop squared that
part off: the part stays under the strategy's id through the Stop and through
a restart of the app, and the Positions tab shows it under the strategy.
Deployed again, the same strategy (the same id) reads it with
while25.portfolio.my_position(key) and goes on from there, and its brackets
and working orders are its own again.
A square off of the whole position takes every strategy's units on it:
Square off on the position's row in the Positions tab, the daily loss limit's
close, or the broker's own square off. Each strategy's part, brackets and
combo parts on that position end at once (their stops and take-profits come
off; the one close sells the units with the rest), and the strategy keeps
running. Its module hears POSITION_SQUARED_OFF for each thing taken,
my_position() no longer counts it from that moment, and what the units sold
for counts in its closed P&L where that close's own fills state it.
Output
while25.log("something happened") # the console
while25.notify("RSI crossed 70") # a notice to the trader
while25.chart.plot("sma", values, times) # a series on the price chart
while25.ui.push("results", rows) # a table / chart / backtest in your app's own panel
Your app's own panel is the one place results show. while25.viz is not displayed anywhere —
a call only prints a console line saying so.
while25.notify(message, *, title="", level="info", symbol="") tells the
trader: a notice on screen, kept in the Monitors panel's Notices list. Any
kind of module may call it; it returns nothing and never raises.
level is "info", "warn" or "error" (anything else goes as "info" and
the console says so); warn and error stay on screen longer and are also
kept in the app's Warnings & errors list. title is a short heading (120
characters), message holds 2,000, symbol is the instrument it is about.
A module may send 10 at once, then one every 2 seconds; past that they are
dropped and the console says how many. In a one-off Run the notice is printed
to the console and not sent.
While no While25 window is in front, each notice is also a notification from the computer itself (on Windows, a Windows notification), with its sound. Your script decides when: the app adds no spacing of its own. The Monitors panel has a tick for the notifications and one for the sound, both on at first. Every notice is also kept in the log on this computer (see "Monitors").
while25.log(message, level="info") writes one console line; level is
"info", "warn" or "error", and a line over 8 MiB is cut and says so.
while25.chart.plot(name, values, times, overlay=True) puts a series on the
price chart; while25.chart.draw(name, tool_type, anchors, config=, style=, label=) puts a drawing on it — anchors is a list of (time_ms, price)
pairs — with hline(name, price), trendline(name, t1, p1, t2, p2),
box(name, t1, p1, t2, p2) and label(name, time_ms, price, text) as the
usual shapes, erase(name="") to remove one drawing or every one the module
made, and tools() for every tool type the chart knows. Drawing a name again
replaces that drawing; a bad anchor or tool type is reported in the console,
never raised. while25.ui.push(slot, value) is dropped with a console
warning for a slot the layout did not declare or a value that is not JSON;
one message to the terminal may be at most 16 MiB.
Output has a budget, per module. print and while25.log together may send
100 lines (256 KiB) a second, in bursts of up to 1,000 lines (1 MiB); past it
lines are dropped and the console says how many, once a second. A plot, a
drawing, an indicator or a ui.push slot updates at most 10 times a second,
newest value wins, and the last value always arrives. Orders, data calls and
signals are never counted, so printing in a loop slows nothing but the
console. A message the terminal cannot handle (while25.log(msg, logging.WARNING), say: the level must be a word) is dropped with an error
line naming why; the module keeps running.
Monitors
A Monitor watches and tells you. It reads everything a strategy reads and
is woken the same way, and it can never place, change or cancel an order:
every order call raises OrderRightsError.
import while25
from while25 import Monitor, on
class BreakoutWatch(Monitor):
id = "breakout_watch"
label = "Breakout watch"
def on_start(self, ctx):
self.rows = list(while25.warmup("IDX:IN:NIFTY", "5m", 20)) # the 20 bars before now
@on.bar("IDX:IN:NIFTY", "5m")
def bar(self, ctx, bar):
high = max(r["high"] for r in self.rows) # the 20 bars before this one
self.rows = (self.rows + [bar])[-20:]
if bar["close"] > high:
while25.notify(f"closed at {bar['close']}, above the 20-bar high {high}",
title="NIFTY breakout", level="warn", symbol="IDX:IN:NIFTY")
It keeps its own window of bars, started from warmup() (see "Warm-up"): the
live series may hold no bars from before the module started.
Press Start on the file in the Code Editor, or on its row in the Monitors panel; Stop is in the same two places. There is no Deploy window, because nothing it does can trade. The Monitors panel lists every monitor, whether it runs, and what scripts have said. The AI chat can write a monitor and stop one; it cannot start one. You press Start.
Every notice and every AI question with its answer is also kept on this computer, in full and with its time, one CSV file a day: Open log folder in the Monitors panel. The data sent with a question is not kept.
One monitor can watch many symbols: several @on.bar or @on.tick lines, or
while25.subscribe(key, on_tick=self.method) for symbols known only while
running. Each running module is its own process, so write one monitor over
twenty symbols, not twenty monitors. A monitor is not started again when the
app restarts: start it by hand.
Asking the AI: while25.ai.ask
A monitor can ask the AI one question about what it found, and act on the answer:
@on.bar("IDX:IN:NIFTY", "5m")
def bar(self, ctx, bar):
high = max(r["high"] for r in self.rows)
self.rows = (self.rows + [bar])[-20:]
if bar["close"] <= high:
return # the free check: most bars end here
verdict = while25.ai.ask(
"Is this a clean breakout or a likely fakeout? The last row is the breakout bar.",
data=self.rows, choices=["breakout", "fakeout"])
if verdict == "breakout":
while25.notify("clean breakout above the 20-bar high", title="NIFTY",
level="warn", symbol="IDX:IN:NIFTY")
while25.ai.ask(question, *, data=None, choices=None, timeout=60, then=None, tag=None)
question: at most 4,000 characters.data: what the AI should read with it: text, or rows and figures (sent as JSON), at most 32 KiB. The AI sees only the question and this. It has no tools and cannot look anything up, so send what it needs.choices: two to ten words. The answer is then exactly one of them, as written here.timeout: seconds an answer may take, 5 to 120.then: one of the monitor's own methods, to ask and carry on (below).tag: withthen, comes back with the answer: text, a number, or a list or dict of them, at most 1,000 characters as JSON.
Ask and wait (no then, as above): returns the answer as text, or None
when there is none. It blocks: the monitor's other handlers wait until it
returns. Right for a monitor that watches one symbol.
Ask and carry on (then=self.method): returns at once, True when the
question was asked and False when it could not be. The answer comes later
as one call of method(ctx, answer, tag), with answer None when there
was none. Right for a monitor over many symbols: each one that fires asks
without waiting for the one before.
SYMBOLS = ["EQ:US:AAPL", "EQ:US:MSFT", "EQ:US:NVDA"]
class BreakoutWatch(Monitor):
id = "breakout_watch"
def on_start(self, ctx):
self.rows = {s: list(while25.warmup(s, "5m", 20)) for s in SYMBOLS}
@on.bar("EQ:US:AAPL", "5m")
@on.bar("EQ:US:MSFT", "5m")
@on.bar("EQ:US:NVDA", "5m")
def bar(self, ctx, bar):
key = bar["symbol"]
high = max(r["high"] for r in self.rows[key])
self.rows[key] = (self.rows[key] + [bar])[-20:]
if bar["close"] <= high:
return
while25.ai.ask("Is this a clean breakout or a likely fakeout? The last row is the breakout bar.",
data=self.rows[key], choices=["breakout", "fakeout"],
then=self.judged, tag=key)
def judged(self, ctx, answer, tag):
if answer == "breakout": # the market has moved since the question: check again here if it matters
while25.notify("clean breakout above the 20-bar high", title=tag, level="warn", symbol=tag)
A monitor may have 20 questions out at once; the app sends three at a time and the rest wait their turn. When a monitor is stopped, answers still on the way are dropped.
No answer (None, or False when the question never left) is never a raise,
and the console says why: the allowance for monitor questions is used up, the
AI is off or cannot be reached, too many questions are out, or no answer came
in time. A call that could never work raises ValueError or TypeError (no
question, too much data, bad choices, a then that is not one of the
monitor's own methods, a tag without then).
Only a Monitor may ask. From a Strategy, an App or an Indicator it
raises While25Error (code AI_NOT_ALLOWED), and a one-off Run cannot ask:
a module that may trade never asks the AI.
The app asks for the monitor, with your sign-in, apart from the AI chat: a question never interrupts the chat, and it is counted on the monitors' own share of your plan's AI limits (its cost is also part of the day's total). The app tells you when 80% of the day's allowance is gone and again when it is used up; from then until the next day's starts (midnight UTC) a question gets no answer. Decide whether to ask in Python, as above: that check costs nothing. The Monitors panel's AI questions list shows each question and its answer.
A monitor inside a strategy
A strategy never asks the AI. A monitor asks, and sends the strategy a signal. The strategy lists the monitor as its own:
import while25
from while25 import Bars, Monitor, Strategy, on
class DipWatch(Monitor):
id = "dip_watch"
aapl = Bars("EQ:US:AAPL", "5m", keep=20)
@on.bar(aapl)
def bar(self, ctx, bar):
if bar["close"] > 0.97 * self.aapl.rows[0]["close"]:
return # your own condition: most bars end here
while25.ai.ask("Is this fall a steady slide or one sharp drop? The rows are 5-minute bars.",
data=self.aapl.rows, choices=["slide", "drop"], then=self.judged)
def judged(self, ctx, answer, tag):
if answer == "drop": # None (no answer) sends nothing
while25.emit("dip_ok", {"close": self.aapl.last["close"]})
class DipBuyer(Strategy):
id = "dip_buyer"
monitors = [DipWatch] # its own: starts and stops with it
@on.signal("dip_ok", sender=DipWatch) # hears DipWatch, and nobody else
def go(self, ctx, payload):
while25.buy("EQ:US:AAPL", 10)
Give it its panel in the same file too: see "A strategy's panel: its desk".
monitors lists Monitor classes, so the monitor is written (or imported)
above the strategy. Which file a monitor sits in decides nothing: one that no
strategy lists is nobody's. Only a Strategy or a trading App may list
any, and anything in the list that is not a Monitor class with an id is
refused when the file is saved.
- Deploy starts both, Stop stops both. Deploying the strategy starts the monitors it lists, on the same code; when the strategy stops or halts, they stop. A trading App has the monitors its own class lists and those its Strategy classes list.
- The Deploy window has a box to tick: the AI can be wrong, may give no answer, sees only what the monitor sends, and an order placed on its signal is a real order. A strategy that lists a monitor is not deployed until the box is ticked. It is asked at every deploy.
- Its signals reach its own strategy and no other module that trades.
- Settings: the monitor starts with the strategy's value for every input the two declare under the same name; its other inputs keep their defaults.
- If the monitor stops on an error, the strategy keeps running and no signal comes. The app says so; start the monitor again from the Monitors panel, where it is listed as part of its strategy.
- A backtest starts no monitor: no signal arrives there, and nothing asks the AI.
A monitor no strategy lists can signal a strategy too: only one deployed
with the box ticked, which the Deploy window offers when the strategy has an
@on.signal. Not ticked, the strategy deploys and no monitor's signal
reaches it. You start and stop such a monitor yourself.
Indicators
One indicator, one label, as many lines as you like:
import while25
from while25 import Fill, Indicator, Plot, on
from while25.inputs import Float, Int
class MyBollinger(Indicator):
id = "my_bb"
label = "My Bollinger" # ONE legend entry for all three lines
overlay = True
inputs = [Int("length", default=20, minimum=2, maximum=500, step=1),
Float("mult", default=2.0, step=0.1)]
plots = [Plot("basis", color="#e0a34a", width=2),
Plot("upper", color="#4aa3e0", style="dashed"),
Plot("lower", color="#4aa3e0", style="dashed")]
fills = [Fill("upper", "lower", color="#4aa3e0", opacity=0.08)]
warmup = lambda params: int(params.get("length", 20))
def compute(self, ctx):
n = while25.params["length"]
rows = while25.bars # While25 streams you the chart's bars
...
self.times = [int(r["time"]) for r in rows]
return {"basis": basis, "upper": upper, "lower": lower}
inputsbecome a config dialog the user can edit — the same one built-in indicators use.plotsset the DEFAULT colour, width and line style. The user can still override every one of them in the chart settings, exactly as for a built-in.Plot(plot_type=...)takesline · histogram · area · stepline;Level(70)draws a reference line andBand(top, bottom)shades a zone.compute()returns a dict keyed by your plot names. Returning a name you did not declare is an error rather than a silently missing line. Every indicator writes its owncompute(self, ctx): a class without one is refused when the file is saved.- A chart starts indicators and nothing else. If a file on a chart is
saved again as a
Strategy, aMonitoror anAppunder the same id, the chart draws nothing for it and starts nothing: its log says so. Take it off the chart, and start the new module the way its kind is started. - An indicator RECEIVES its series. While25 streams the chart's series
— scrollback included — to Python, and every change to it recomputes
you; the client no longer sends bars.
while25.barsis that array, oldest first, replaced whole every pass.while25.formingis the unclosed bar and is present only while a bucket is forming (otherwiseNone; it is never insidebars).while25.priceis the price the chart's candles are built from: "last", or "mark" on a Binance futures chart set to Mark price (no volume).while25.future_timesis the chart's projected grid. The times are the chart's own wire times, soself.times = [r["time"] for r in rows]lands every value on the candle it came from. Sourcing a second series is refused:candles(..., source="live")insidecompute()raisesLIVE_IN_COMPUTE. Two series drift after a scrollback, and the chart's by-timestamp merge then blanks the line exactly where the user scrolled. warmupdeclares what you need — anint, or a callable of the params when it is derived (DEMA needs2*period-1). Short input reportswarming up — 12 of 39 barsinstead of drawing nothing. A biggerlimitis never the answer: it truncates a fetch, and here there is no fetch.Plot(name, color="", width=1, style="solid", plot_type="line", color_down="", opacity=1.0, overlay=None, visible=True).widthis 1 to 4;styleissolid · dotted · dashed · large-dashed · sparse-dotted;color_downis a histogram's or bi-colour plot's second colour;overlayNonefollows the indicator's ownoverlay.Fill(upper, lower, color="", opacity=0.08)shades between two of your plots.levels = [Level(70, color="", width=1, style="dashed")]draws reference lines andbands = [Band(top, bottom, color="", opacity=0.06)]shades zones.y_min/y_maxfix the pane's scale (RSI 0 to 100) andprecisionits decimals.intrabar = Truerecomputes as the bar forms, not only when it closes (a full recompute per tick: off by default). A declaration the chart cannot draw — no plots, a plot named twice, a fill naming a plot you did not declare, a band whose top is not above its bottom — is refused when the file is registered.while25.instrumentandwhile25.intervalare the chart's: the symbol and interval it is drawing, set per compute, so one indicator works on any chart.
An indicator's numbers in a strategy
from indicators.my_rsi import MyRsi
class TslaRsi(Strategy):
id = "tsla_rsi"
tsla = Bars("EQ:US:TSLA", "5m", keep=100)
@on.bar(tsla)
def on_bar(self, ctx, bar):
rsi = self.tsla.indicator(MyRsi, length=14)["rsi"]
if rsi[-1] > 70:
...
line.indicator(cls, *, forming=False, **params) works an indicator out from
a Bars line's own bars. It is while25.indicator with bars=line.rows:
while25.indicator(cls, *, bars=None, forming=False, instrument="", interval="", **params) works another indicator out in this process, from
the bars you hand it, and returns exactly what its compute() returned.
Nothing is drawn and no chart is needed. Only a chart hands an indicator bars
by itself, so a strategy passes its own.
bars: oldest first, your warm-up and@on.barbars, orcandles()rows. The indicator reads them aswhile25.barsin a chart's row shape (timein epoch ms,open,high,low,close,volume), so one written for a chart works unchanged;while25.formingisNone.forming:Truealso counts the bar still forming, see below.instrument,interval: what it reads aswhile25.instrumentandwhile25.interval; left out, the bars' own.**params: its inputs, checked and defaulted as on a chart.
ValueError, without running it: fewer bars than its warmup, bars out of
order or two at one time, a bar without a time or a price, bars of two
series in one list (two @on.bar lines), an instrument or interval that
is not the bars' own. With no bars=, an indicator that reads
while25.bars raises ValueError saying so; only one called inside another
indicator's compute() reads its caller's bars.
Before the bar closes. @on.bar wakes the strategy once a bar has
closed. To act while it is still forming, ask from a tick handler with
forming=True:
@on.tick("EQ:US:TSLA")
def on_tick(self, ctx, tick):
rsi = self.tsla.indicator(MyRsi, forming=True, length=14)["rsi"]
It adds the bar still forming on that @on.bar line after your bars, as
While25 last sampled it (about once a second; the chart's moving candle is
the same bar). The indicator reads it as its last bar; your own list is not
changed.
- Added only when it is the bar right after your last one: never a bar you already hold closed, and never past a closed bar your list has not got yet. Otherwise, and while nothing is forming, the indicator is worked out from your bars as they are.
barsmust be those of one of the module's own bar lines (aBarsline, or an@on.barline's warm-up and bars), whatever its interval: that line is what holds the symbol's prices while the module runs. Anything else raisesValueError.- Its
warmupis counted in closed bars.
A panel
An App can declare its own panel. You declare a layout once and afterwards
push values into named slots — While25 renders it, so a plugin panel cannot
break the terminal's look or its rendering performance.
import while25
from while25 import App, on, ui
ui.panel("sensex_pulse", label="Sensex Pulse")
ui.layout(
ui.row(ui.metric("level"), ui.metric("chg")),
ui.table("headlines"),
)
class SensexPulse(App):
id = "sensex_pulse"
@on.schedule(every="10m")
def refresh(self, ctx):
while25.ui.push("level", 81_234.5)
while25.ui.push("headlines", [{"headline": "…"}])
Widgets available today are row, metric, chart, table, text, view
and html. They are display-only; the interaction model is still being
designed, and shipping a half-considered callback contract would freeze an API
you would then be stuck with.
Choosing the component
The default is an HTML page — ui.layout(ui.html("view")), built on the
terminal's brand theme (see "HTML" below). Reach for something else only when it
fits the job better:
| The job | Reach for |
|---|---|
| Almost anything — a dashboard, a desk, a monitor, a screener | ui.html (the default) |
| 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 |
| 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 |
| The terminal's own components instead of markup | tiles, kv, table blocks in a ui.view |
Wiz is never required: a panel needs no chart block, and a chart needs no Wiz.
Blocks — ui.view
ui.view(slot) is the one to reach for first: push a dict describing WHAT to
show and the terminal renders it in its own components — header, tiles,
kv, table, badges, text, progress, chart, backtest, html,
section, row, divider. A chart block is the interactive Wiz surface by
default (hover, legend, resize; "live": true buys the SVG fast path for a
data-rate redraw), and an html block is your own markup as one sandboxed
section — so custom HTML and an interactive chart share ONE panel:
ui.layout(ui.view("main")) # the ONLY widget → the view IS the panel
while25.ui.push("main", {"blocks": [
{"kind": "header", "title": "Sector map"},
{"kind": "row", "blocks": [
{"kind": "html", "html": "<div class='card'><h1>Notes</h1><p>…</p></div>"},
{"kind": "chart", "title": "Weight", "spec": {
"kind": "treemap", "rows": rows, "x": "sector", "value": "mcap"}},
]},
]})
Tones: money (coloured by SIGN), profit, loss, active, attention,
error, muted, neutral. Pass raw numbers, never pre-formatted strings, and
None for "not known yet" — the terminal formats every number and shows —
for absence, so a figure you do not have never reads as a zero you do. The
docstring on ui.view carries every field.
The backtest block
A results view is the one thing a script never assembles. You hand over the trades and the history they were built on; While25 computes every figure from those and either seals the block or refuses it. Nothing the script computes (curve, statistics, currency) reaches the screen.
import while25
from while25 import backtest
span = while25.history_span("EQ:US:AAPL", "15m", "2025-01-01", "2025-06-30")
inst = while25.data.instrument("EQ:US:AAPL")
trades = []
# ... your logic decides every trade, bar by bar; shown here for one trade:
bars = span["bars"]
bar, later = bars[10], bars[20] # the entry bar and the bar the exit is tested on
stop = bar["low"] # a stop level your logic chose
f_in = backtest.fill(bar, "buy", "open", instrument=inst)
f_out = backtest.fill(later, "sell", "stop", instrument=inst, price=stop)
if f_out is not None: # None: that bar never reached the stop; test the next one
# intraday only when both fills share a trading date; held overnight is delivery
product = "intraday" if f_in.date == f_out.date else "delivery"
trades.append(backtest.trade(inst, "buy", 10, f_in, f_out, product=product))
while25.ui.push("main", {"blocks": [
while25.ui.backtest_block(
trades, # what backtest.trade() returned; every position closed
data=[span["id"]], # the history_span answer id(s) the trades were filled on
start_equity=0, capital=100_000,
title="RSI(14) mean reversion", subtitle="EQ:US:AAPL · 15m · long only",
notes="Signals on the close, fills at the next open.",
logic={"Entry": ["RSI(14) crosses below 30", "fill at the next bar's open"],
"Exit": "a stop at the entry bar's low"})]})
backtest_block(trades, *, data, start_equity=0.0, capital=None, title=None, subtitle=None, notes=None, assume=None, logic=None). data is required (an id or a list of ids).
start_equity is where the curve starts (0 = cumulative P&L); capital turns
on the percentage figures (None: the user's default capital, if one is set).
assume is what every trade was built under (None: the run's
backtest.defaults(); see Assumptions below).
logic is the strategy's rules in your own words, shown above the figures in
a "Strategy" panel captioned "from the script": a dict whose insertion order is
the display order ({"Entry": ["RSI(14) < 30", "close above the 200 SMA"], "Exit": "RSI(14) > 70"}) or a list of (name, lines) pairs, where a line
value is one str or a list of str. It is recorded as [{"name", "lines"}].
Any section name works: Universe, Entry, Exit, Sizing, Model, Features,
Signal, Legs, Adjust, Pair, Hedge ratio, Rebalance. Limits: at most 10
sections and at most 12 lines per section, a name at most 40 characters and a
line at most 240 characters, every line a non-empty str. Past one,
backtest_block raises TypeError (a wrong type) or ValueError (a wrong
size) naming the field (logic[1].lines[0]), and the parent refuses a block
whose logic has another shape whole (R-SHAPE, naming the field). The
parent never interprets the words: it copies them to the sealed logic
(None when there are none). Like title, subtitle and notes they may
not claim While25's checks: "reconciled by While25" or "sealed by While25"
in them refuses the block (R-IMPERSONATE).
What the parent does. On every push it replaces each backtest block, at any
depth, with {"kind": "backtest", "sealed": {...}} or
{"kind": "backtest", "refused": [{"rule", "detail"}]}. It re-derives each
trade (backtest.fill and backtest.trade) on the bar it recorded when it
delivered the history_span answer, with the instrument facts While25
stated, and requires the same prices, costs and pnl, exactly. It marks the
curve to market per bar (a bar's close counts only from the bar's END, time plus
interval; the curve opens at start_equity 1 ms before the first bar). A
limit, stop or close fill happens inside its bar and counts from that
bar's end: an exit is gone before the bar's close could mark it, an entry is
marked at that close. An open fill counts from the next point after its
bar's start: the point at that start still shows the previous close, so a long
sold at an open still shows the close before that open, and an open entry is
held at its fill price until a close from a later bar is known (a close from
before the fill never marks it). A fill past the last bar adds a point. Then it computes
drawdown, statistics and the monthly table (each trade in the month of its
exit fill's trading date). No While25 code decides
when a trade happens: your script does.
The rules. A block that breaks one is refused whole, and nothing is drawn
but the rule and its words (R-SHAPE included):
| Rule | Refused when |
|---|---|
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) |
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 |
R-WINDOW |
a trade outside the covered window; no bar inside it |
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 |
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 |
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 |
R-CURRENCY |
more than one currency, across instruments or cost schedules |
R-FLAT |
an open trade (no exit): close positions with a last trade |
R-TIME |
a time that is not integer epoch milliseconds, 1e11 <= t < 1e14 |
What the sealed block carries. Money and ratios are decimal strings
(exact; ratios to 8 places), times are epoch ms, counts are ints, and an absent
figure is None or a missing key, never 0 (volume may be None). win_rate is
a fraction (0 to 1); every *_pct is already times 100. Keys: title,
subtitle, notes, logic (the script's rules, [{name, lines}] or None),
currency (from While25, never the script),
start_equity, capital, sources[] (per data answer: id, symbol, interval,
asked window, covered_from / covered_to as exchange-local dates, vendor,
feed, adjustment, session, missing_days, calendar, calendar_tz,
calendar_note), fill_rules[], slippage[], cost_schedules[] (schedule,
rate set, backdated, note, and omitted: what that schedule knowingly
leaves out, a list that may be empty, e.g. the DP charge on Indian delivery
sells, contract-note rounding, rounding to the cent), assumptions[] (what
the fills assume, e.g. that a limit or stop fills when the bar's range
touches its price, with no queue or partial fill, or under through fills only
when the bar trades through it; empty when no limit or stop
fill is used, and "risk-free %" when Sharpe or Sortino is stated),
settings[] (all six assumptions, see Assumptions), gross, equity, drawdown, stats, monthly[] (month of
the exit fill's trading date) and trades[] (rows: instrument, side, qty, entry_time,
exit_time, entry, exit, multiplier, gross, costs_in, costs_out,
pnl, entry_how, exit_how), and no_trades (true when there are none: a sealed
block with zero trades is valid). gross is true when every cost total is 0 and
the view shows "GROSS, no costs". stats has trades, wins, losses,
breakeven, net_pnl, max_drawdown, costs_total, exposure_pct, and,
when defined, win_rate, expectancy, best, worst, avg_win (needs a
win), avg_loss and profit_factor (need a loss), and with capital
return_pct and max_drawdown_pct. Series are downsampled to 5,000 points;
the newest 2,000 trades are listed (notes says so) and the statistics cover
all of them. More than 20,000 trades is refused unread. The curve's last point
is the last bar's end (its close known); drawdown and benchmark end there too.
stats also carries, each omitted when undefined (never inf, never a 0
standing in for "not defined"):
sharpe,sortino: from the curve's trading-day closes on the first source's calendar, each day's change r. At the built-in risk-free 0% (thenassumptions[]says "risk-free 0%") r is used as is, a return on one constant base, so the ratios depend on neithercapitalnorstart_equity; at a rate x above 0 (assumptions[]says "risk-free %") each return is r / capital - x / 100 / days per year, so they needcapital(no capital, no ratio).sharpe= mean / sample standard deviation,sortino= mean / sqrt(mean of min(r, 0)^2), each times sqrt(the calendar's sessions per year). Omitted under 20 daily returns, with zero deviation, or when no such year is known.cagr_pct: withcapitaland a covered window (earliestcovered_fromto latestcovered_to, inclusive) of at least 365 calendar days, ((capital + net) / capital)^(365.25 / days) - 1, times 100. Omitted on a shorter window and when the account ruined (capital plus the final net, or plus the curve's lowest (value -start_equity), at or below 0).calmar=cagr_pct/ -max_drawdown_pct(with a drawdown).max_dd_duration_ms(int; the longest time below a running peak, 0 without a drawdown) andrecovery_ms(the deepest trough to the first point back at its peak;Noneif it never recovered).- With trades:
avg_hold_ms(int; each trade's exit bar time less its entry bar time, bar start to bar start, so a one-bar trade is 0 and an overnight hold never is),max_win_streakandmax_loss_streak(in exit order; a breakeven ends both),trades_per_day(trades / trading dates holding a bar),turnover,costs_pct_of_gross(with gross above 0),largest_win,largest_loss, andpayoff_ratio=avg_win/ -avg_loss. - A percentage or ratio 1e15 or more in size is omitted (no screen holds it).
turnover is money: the sum of (entry + exit) x qty x multiplier, both legs.
breakdown holds waterfall {gross, costs, net} where costs is negative
(minus the costs total) and gross + costs = net exactly; costs_by_charge
[{charge ".", amount}] (custom costs: one line, custom;
zero costs: none) whose amounts are positive (what was
paid) and sum to costs_total; by_hour [{hour 0-23, trades, net}] by each
trade's entry bar time on the first source's calendar_tz, for trades on
intraday bars only (a daily bar has no hour, so a daily backtest has an empty
list); by_weekday [{weekday 0-6, Mon = 0, trades, net}] of the entry's
exchange trading date; by_side and by_instrument [{side or instrument,
trades, wins, net}]; tz (that calendar_tz). Each trade row also carries
hold_ms (as above), mae and mfe: the worst and best open P&L in money,
price only, no costs, at a price the position provably saw: its fills, every
bar wholly inside the hold, and on the entry and exit bars only what provably
followed the fill (a limit entry counts its bar's adverse extreme, a stop
entry its favourable extreme, an open entry the whole bar, a close entry only
its close; a close exit counts its whole bar, an open, limit or stop exit only
its bar's open). A limit or stop fill rests on the touch assumption in
assumptions[]. Both fills are counted, so mae <= min(gross, 0) and
max(gross, 0) <= mfe.
benchmark {label, instrument, points, symbols} is buy and hold, no costs, starting
at start_equity and marked like the curve at the curve's times. With one
instrument in the data it is that instrument bought at its first bar's open:
without capital 1 unit x multiplier, labelled "buy and hold
What the view shows. Header, the Strategy panel (logic, "from the script"), tiles (net, return, CAGR, max drawdown,
win rate, profit factor, Sharpe, trades, expectancy, costs), Performance (every stat above, each naming its
definition; "—" when absent), the equity curve with the benchmark line and its
label, Trades (with MAE, MFE and hold, and Export CSV of the rows exactly as
sealed), Monthly, Distribution, Breakdown (the waterfall, costs by charge,
by hour and weekday in the named tz, by side, by instrument) and Price
(candles with each fill marked, one chip per instrument when there are two or more; a marker selects its trade row). When one
ui.push to one slot holds two or more sealed backtest blocks (e.g. a section or
row of them in that slot), a compare strip appears above them (each block's
title, net, return, max drawdown, win rate, Sharpe and trades, copied from its
seal; a refused block shows its status); blocks pushed to different slots each
stand alone. So never re-draw any of it in html, table or a chart, and to
compare settings push one block per setting in one push to one slot.
Calculators (from while25 import backtest). None loops over bars, holds a
position or decides a trade; each answers one question exactly (Decimal, a
fixed context, no clock, no randomness).
backtest.fill(bar, side, how, *, instrument, price=None, slippage=None, assume=None)returns theFillof one order on one bar, orNonewhen the bar never reaches it.howisopen,close(noprice),limitorstop(needsprice). A gap fills at the open, worse than the stop. Then slippage, then the venue's tick against the trader. No tick stated:RULES_UNKNOWN. TheFillcarries its bar'sdateandend(time plus the bar's interval); a bar naming no interval of known length isBAD_BAR.assume(anAssumptions;Nonereadsbacktest.defaults()) sets the fill style:touchfills a limit / stop at an exactly equal low / high,throughonly when the bar trades past it.slippage=Noneapplies the assumption's slippage (slippage_statedFalse); anySlippagegiven, evenSlippage.none(), is stated. TheFillrecordsfillsandassume(the assumptions' fingerprint).backtest.first_exit(bar, side, *, stop, target, rule=None, assume=None)returns"stop","target"orNone: which exit this bar reaches first for a position entered onside. A bar that opens through a level reached it first; when both are touched inside the bar,rule(stop_firstortarget_first;Noneis the assumption'ssame_bar) says which to assume. Underthrougha level counts only when traded past.backtest.exit_fill(bar, side, *, instrument, stop, target, slippage=None, assume=None)fills a position's bracket exit:first_exitpicks the level, the opposite side fills there (the stop as a stop, the target as a limit), and theFillrecordsbracket(stop,target,ruleas strings).Nonewhen neither level is reached.backtest.Slippageis always against the trader:Slippage.none(),Slippage.bps(n),Slippage.ticks(n).backtest.cost_for(key, side, price, qty, *, product, on, multiplier)andbacktest.costs(instrument, side, price, qty, *, product, on, broker=None)returnCosts(lines,total,currency,schedule,rate_set,backdated).CostKey(country, exchange, segment, broker, symbol="")is what identifies a fill to the registry;costs()reads it from the instrument and the account's broker.productisintradayordelivery;onis the fill's exchange-local trade date.backtest.trade(instrument, side, qty, entry, exit, *, product, broker=None, assume=None)returns one round trip:gross = (exit - entry) x qty x multiplier(negated for a short),pnl = gross - both sides' costs. Each side is costed on its fill's trading date. This is whatbacktest_blocktakes. It refuses (BAD_FILL) an exit that cannot follow its entry: on one bar the order is open, then limit / stop, then close, so a close entry never exits on its own bar, and a limit or stop entry with a limit or stop exit on one bar is refused (the order of the high and low inside one bar is unknowable; use a finer interval); and a limit, stop or close entry is known only at its bar's end, so no other bar starting before that end may exit it, on any interval (a daily limit entry cannot exit on an hourly bar of the same day).BAD_PRODUCT: anintradayproduct whose entry and exit fall on different trading dates (a position held overnight isdelivery).BAD_QTY: a quantity off the venue's size step (the lot, else the increment) or under its minimum, where the venue states them. Costs followassume(real,zeroorcustom, below);BAD_FILLalso for a fill made under other assumptions than the trade's.backtest.sessions(answer)groups ahistory_spananswer's bars by exchange trading day on the clock the answer names (calendar_tz); no clock stated:CALENDAR_UNKNOWN, never UTC.
Assumptions. Every backtest runs under six assumptions: costs (real,
zero or custom), slippage (the default for a fill that states none),
fills (touch or through), same_bar (stop_first or target_first),
risk_free (percent per year, 0 to 100) and capital. Each value carries a
source: built-in (While25's own: real costs, no slippage, touch, stop first,
0%, no capital), your default (what the user set in the terminal's settings)
or this backtest (what the script chose).
backtest.defaults()returns the run's snapshot of the user's defaults, a read-onlybacktest.Assumptions. While25 takes the snapshot when the run (or the module's start) arrives; a running script keeps it, and a change to the defaults applies from the next run. Re-pushes from that run re-seal under it. With no terminal (a plain import) every value is built-in.backtest.assume(**overrides)returnsdefaults()with this backtest's own choices on top; each value it sets readsthis backtest. Keys:costs,custom_flat,custom_pct(both needed withcosts="custom", refused with any other),slippage(aSlippage),fills,same_bar,risk_free; capital isbacktest_block(capital=). An unknown key, aNonevalue (leave the key out to keep the default) or a bad value raisesBAD_INPUTnaming it.- It only returns the choice: pass it as
assume=to everyfill(),exit_fill()andtrade()call and tobacktest_block(). Callingbacktest.assume()and passing it nowhere changes nothing. - An override applies to this backtest only: it never changes the user's
defaults, and a script cannot claim
your default(only the parent's snapshot can say that; the parent re-checks every source). - Declare it once and pass the same object to every
fill,first_exit,exit_fill,tradeand thebacktest_block. Each fill and trade records the assumptions it was built under; a trade built under others than the block declares is refused (R-TRADE-DERIVED), so two overrides mixed in one block are refused. To compare settings, push one block per setting. slippage=Noneon a fill means the default slippage (the assumption's; recorded as not stated). AnySlippageyou pass, evenSlippage.none(), is stated, and the block says how many fills set their own.same_baris enforced for exits built withbacktest.exit_fill: the parent re-checks that a bar touching both the stop and the target exited at the one the rule picks. A plainfill()exit carries no bracket and is not checked, so useexit_fillfor a bracket (notfirst_exitthenfill). A block holding limit / stop exits not built withexit_fillsays so in its assumptions ("same-bar stop and target order not checked for N exits not built with exit_fill").- Zero costs replace every charge, broker and statutory alike. Custom charges
custom_flaton each fill (entry and exit, i.e. per order) pluscustom_pctpercent of that fill's turnover. Neither reads the cost registry, soCOSTS_UNKNOWNand the account's-broker check do not apply; the venue's multiplier, tick and currency are still required.
# one backtest, its own assumptions
a = backtest.assume(costs="zero", same_bar="target_first")
f_in = backtest.fill(bar, "buy", "open", instrument=inst, assume=a)
f_out = backtest.exit_fill(later, "buy", instrument=inst, stop=95, target=110, assume=a)
if f_out is not None:
trades.append(backtest.trade(inst, "buy", 10, f_in, f_out, product="intraday", assume=a))
while25.ui.push("main", {"blocks": [
while25.ui.backtest_block(trades, data=[span["id"]], capital=100_000, assume=a,
title="zero costs, target first")]})
The sealed block states them in settings[]: all six, always, in this order:
costs, slippage, fills, same_bar, risk_free, capital, each {name, value, source} with value a wire string (real / zero / custom; the default
slippage as none, bps:<n> or ticks:<n>; touch / through;
stop_first / target_first; the risk-free percent; capital as a plain
decimal or None). costs custom adds flat and pct; slippage adds
own (an int: the fills that stated their own, shown as "N fills set their
own"). Under zero or custom costs cost_schedules[] holds one schedule,
"zero" or "custom: per order + % of turnover" (rate set "", not
backdated, nothing omitted), and the view shows a badge that the costs are not
the real tariff. The view shows the assumptions and their sources itself:
never re-draw them.
Costs are registry data. Brokerage, taxes and fees come only from the dated,
sourced cost registry While25 bundles with the SDK:
each rate set has an effective_from and a source, and a fill is costed from
the statutory schedule for its country, segment and exchange plus the broker's
schedule. A missing schedule or rate is refused (COSTS_UNKNOWN), never costed
as zero: Indian statutory charges before 2024-10-01 are refused, an exchange
with no schedule is refused, and an instrument typed ETF has no cost segment
and is refused. NSE's ETFs, SGBs, G-secs, InvITs and REITs trade in the cash
segment and arrive typed as equity, but their charges are not equity charges:
the registry's dated, sourced non_equity list (from NSE's own files) gives
each such symbol a class, and a listed symbol is costed only from the
schedules for its class, never as equity. An equity ETF (equity_etf: NSE's
ETF list states its underlying as equity) pays STT on a sell only (0.001%
delivery, 0.025% intraday; none on a buy); a gold, silver or debt ETF
(other_etf) pays none; both pay the cash market's exchange charge, IPFT,
SEBI fee, stamp duty and GST (in_nse_eq_etf, in_nse_other_etf, from
2024-10-01). Brokerage on an ETF is the broker's published equity delivery /
intraday tariff (Zerodha and Upstox publish no separate ETF line;
the sealed header says so). Still refused (COSTS_UNKNOWN): an ETF NSE does
not class (international, hybrid), SGBs and G-secs (NSE publishes no
transaction charge for them), InvITs and REITs, and an ETF on a broker with no
ETF schedule. The symbol is compared NFKC-normalized and upper-cased,
without zero-width characters, any whitespace, an exchange prefix (NSE:),
a separated EQ or a .NSE, .NS / .BO suffix, and an Indian equity cost with no symbol, or with the list missing,
is refused too. Costs follow the account's broker; the test broker's
fixture tariffs serve only an account on the test broker. A
broker tariff (undated pages) may be backdated to its first published rate set;
the sealed cost_schedules[] then carries backdated: true and a note.
Pass no costs yourself: they cannot be passed (zero and custom costs are
assumptions, above, never a figure).
Migrating from the old signature. backtest_block(equity, trades, ..., stats=, drawdown=, benchmark=, currency=) is gone. equity, stats,
drawdown, benchmark and currency raise TypeError naming the parameter:
Python computes them. Build each trade with backtest.trade() and pass
data=[answer["id"]]. The sealed block states the Sharpe, the benchmark and
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
and keeps every bar's high and low.
What the seal cannot prove. It proves the trades follow from the bars you
were given. It cannot see look-ahead in your own logic (a signal that
reads a bar it should not have seen yet), nor best-of-many (a parameter
sweep where you show only the winner). It covers backtest blocks only: an
html slot can still draw something that looks like a result, so the look of a
view is not the proof; the sealed card is.
HTML — ui.html
ui.html(slot) is the app's page, and the default for a panel. Push a markup
string; you own the page — structure and look, and your CSS renders as
written. Build on the brand theme first — the classes below, the tokens and the
styled bare tags — so the page reads as part of the terminal and follows its
light/dark switch:
| Group | Classes |
|---|---|
| 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 |
| 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 |
| 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 |
| 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) |
| ground | .bg-0 .bg-1 .bg-2 .bg-amber-dim .bg-profit-dim .bg-loss-dim .bg-attn-dim .bg-error-dim |
| 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 |
| tables | zebra by default · table.dense · table.sticky (sticky header) · .num right-aligns |
| heat (an HTML heatmap) | .heat-p1….heat-p5 gains, .heat-l1….heat-l5 losses — you pick the step |
Utilities win over components (.card.p-0, .v.c-loss). Your own <style>
block (or inline style) always wins over the brand sheet, which sits in a lower
cascade layer; bare CSS before your first tag is wrapped in <style> for you,
never shown:
ui.layout(ui.html("view")) # the ONLY widget → the view IS the panel
while25.ui.push("view", """
<div class="card">
<small>Day P&L</small>
<div class="t-3xl t-num c-profit">+12,480.25</div>
</div>
""")
Declare either alone and it takes the whole panel — full height, no caption, no padding. Put it beside other widgets and it is one content-sized section among them.
You are not starting from a blank page: the terminal's theme tokens resolve
inside (var(--color-amber), --color-profit, --color-loss,
--color-text-dim, --color-surface-2, …) and follow a theme switch, bare
markup is already styled (headings, tables with tabular numerals and zebra
rows, code, lists), and the class catalog above is there to use. Type is three faces by role — IBM Plex Mono for
data, Inter for <p> / <li> prose, JetBrains Mono for code — on a four-step
scale (h1 20, h2 16, h3 14, text 12, labels 11, tile values 22). A
.card / .tile carries a 2px left stripe that names its meaning
(.tile.profit, .card.error).
Nothing you write is snapped, stripped or rewritten — colours, fonts, shadows,
gradients, radii and emoji render as written. Prefer the tokens to literal
colours: a literal does not follow the light/dark switch. Charts are yours to
draw: inline <svg> (build its points / d in Python, give it axes and
labels — it keeps the width / height you set) or CSS bars (.progress,
.heat-*). A backtest still goes in the backtest block.
It renders in a sandboxed frame without script permission: <script>,
on* handlers and javascript: URLs are inert, so compute in Python and push
new markup rather than scripting. CSS animations and :hover do work. Links
open in the system browser (https only).
Desk blocks
A strategy's desk is its app panel. Build it from blocks in a ui.view; each
helper returns one block and checks its shape at the call (TypeError or
ValueError naming the field).
import while25
from while25 import ui
while25.ui.push("main", {"blocks": [
ui.strategy_block(), # this module's reconciled figures
ui.conditions("Entry", [
ui.rule("RSI(14)", rsi, "<", 30, near=10),
ui.rule("Close", close, "crosses_above", vwap, prev=prev_close),
], need="all"),
ui.levels(price=close, levels=[ui.level("Stop", stop, tone="loss"),
ui.level("Target", target, tone="profit")]),
ui.timeline([(t_ms, "entered long 10"), (t_ms2, "stop moved", "attention")]),
ui.chart_block({"kind": "line", "rows": rows, "x": "time", "y": ["spread"]}),
ui.custom("Notes", html="<p>Anything else, framed as the script's own.</p>"),
]})
ui.strategy_block(strategy=None, *, open="auto", sections=None, title=None, capital=None): the same figures as the strategy's Live Strategies row, drawn by the terminal and marked Reconciled, headed by its equity curve.strategy=Noneis the module doing the push; in a strategy's desk, that strategy (an App that imports a Strategy class is that App: its orders are its own).open:"auto","holds","working","combos","log"orFalse(folded).sections: a subset of["holds", "working", "combos", "log"].capital: what the strategy was given to trade, in its own currency (e.g.5000): the curve then shows its equity (capital plus Total P&L) from its first figure, with the % against the capital; without it the curve is the Total P&L against zero. No figure can be passed: any other keyword raisesTypeErrornaming it, and Python drops every other key from a hand-built{"kind": "strategy"}.ui.rule(label, value, op, target, *, prev=None, near=None, unit=None, fmt=None)andui.conditions(title, rules, *, need="all"):opis one of<<=>>===between(target=[lo, hi], lo <= hi)crosses_abovecrosses_below(both needprev).near> 0 is the band the bar fills across, in the value's units.unitis a word after the distance ("+32 pts");fmtis a suffix glued onto every figure of the rule, its value, target and distance (fmt="x"shows1.8x), never a number format.need:"all","any"or a count of 1 or more (more than the rules is never met, so dropping an unknown rule never raises). The terminal decides Met or Not yet;value=Noneshows the absent marker.ui.level(label, value, *, tone=None)andui.levels(*, price, levels, title=None): the price against your levels; alossstop and aprofittarget add reward/risk.ui.timeline(events, *, title=None):(t_ms, text)or(t_ms, text, tone),t_msan int (numpy's too) of epoch milliseconds.ui.chart_block(spec, *, title=None, live=False): thechartblock (a Wiz spec dict, or a list of numbers).ui.custom(title, *, html): your own sandboxed markup, framed and labelled as the script's.
Numbers may be ints, floats, Decimals or numpy / pandas numbers. A NaN, a
pd.NA (a nullable column's gap), a Decimal NaN or an infinite value,
target, prev, near, level value or price (an indicator still warming up)
becomes None, "not known yet", so a draw never halts on one; a wrong op,
a between target that is not [lo, hi] or a crossing with no prev still
raises.
Only While25 says where a figure was checked: any text a script puts on screen
that says "Reconciled by While25" or "Sealed by While25" (any case, in a block's
title, label, value, text or html, a ui.html page, a text, metric or table
value) is replaced by a visible refusal (R-IMPERSONATE), and a panel or widget
label that says it is replaced by "Refused label (R-IMPERSONATE)". Honest words
such as "reconciled with broker" are fine.
Testing without a terminal
Nothing above needs While25 to import, so a module is an ordinary class:
import while25
def test_it_logs_on_a_down_bar():
seen = []
class FakeCtx:
params = {}
def log(self, msg, level="info"): seen.append(msg)
fake = FakeCtx()
with while25.use(fake): # the package acts on your fake
MeanReversion().on_bar(fake, {"open": 2.0, "close": 1.0})
assert seen
Errors
An exception in a handler halts that module and leaves its siblings running. It is not swallowed and the loop is not resumed: a module that kept going after an error could trade on bad state.
While25Error carries .code (the refusal code the tables above name) and
.message; a TIMEOUT from an order call carries .idempotency_key too.
SubscriptionError (.keys) and OrderRightsError (.kind) are
While25Errors. A refusal the SDK can judge itself is a plain ValueError,
raised before anything is sent.
Limits
- One thread runs a module's code:
on_start, every handler,run()andon_stop, one after another. Handlers never overlap, so state onselfneeds no lock — and a handler that blocks holds every other one up. - A tick that has waited over a second with a newer tick for the same handler and symbol queued behind it is skipped; a schedule call is coalesced the same way. A closed bar, a fill, an order event, a signal and a news article always run, in order.
- A data call that gets no answer within 30 seconds raises
TimeoutError; an order call raisesWhile25ErrorTIMEOUTafter 25 (see Orders). - Each module runs in its own process, below the terminal's priority, with
2 GB of address space (
W25_WORKER_MAX_MBchanges it); a module over it is stopped as itself, and the terminal says so. A file it writes is at most 2 GiB (on macOS and Linux); one log or output line is cut at 8 MiB; one message to the terminal is at most 16 MiB. Anemit()payload must pickle.
What the SDK does not do
- No network calls of its own. The SDK makes none (only the package
installer reaches the internet), and everything
while25.*gives you comes through While25. Nothing stops your own code making them: Requests, yfinance or ccxt work as they do anywhere else. What you fetch that way is yours to trust, and an order your code sends to a venue directly (with ccxt, or a broker's own API) skips every check While25 makes and never shows in the terminal. - No installs while it runs. Anything pip can install is yours to add
before you deploy: from the Marketplace, or listed in
requirements.txt(see "Your own files and packages"). While a strategy or trading App runs, its packages can't change. - No sandbox promises. Your script is your responsibility. While25 enforces its own risk limits on the money path and nothing more.
Licence
Apache-2.0.
Metadata
Release files for while25 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| while25-0.1.0.tar.gz | 628.9 kB | Without provenance | Details for while25-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| while25-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for while25-0.1.0-py3-none-any.whl |
Total release size: 1.1 MB
Release files / while25-0.1.0.tar.gz
| Download URL | while25-0.1.0.tar.gz |
|---|---|
| Size | 628.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ce99c2e54dead191f7610085af18f7b28b56da632c0f4e3db46fa9467986f46d
|
|
BLAKE2b-256 checksum How to use checksums |
fee8bcc2586d1b9f4816021aac32d109e45e6477f8e0db2ec6c307702caee980
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.8
|
Release files / while25-0.1.0-py3-none-any.whl
| Download URL | while25-0.1.0-py3-none-any.whl |
|---|---|
| Size | 485.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
510d771f1a211a9a79cca7f6bfeb149af4476c4d1e7048277c0145b280c11b59
|
|
BLAKE2b-256 checksum How to use checksums |
c0dbe57b9e909104bfaf02dfa095650acf038471713431c20b41fc1ebaacbbb7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.8
|
Security for while25 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.