Backtests
Any logic, any model, any mix of instruments and timeframes: you write the loop, the platform seals the result.
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 , no
costs"; with capital capital / (first open x multiplier) units, labelled
"buy and hold with , no costs"; None under 2 bars. With
two or more instruments in the data it is an equal-weight basket: each gets
capital / N at its own first bar's open (cash until then), labelled "buy and
hold, equal weight across with , no costs" (the symbols in
data order; the first 10, then "and N more"), and instrument is None.
symbols lists the benchmark's instrument symbols in data order (one for one
instrument, every member of a basket, at most 50). Without a capital (the block's or
your default) there is no basket, since equal weight needs a capital: None,
as for a member with no bar in its covered window. With capital the values
are to 8 places.
prices is a list of price views, one per instrument with a listed trade,
ordered by first trade time (its earliest listed entry), then instrument key:
{instrument, symbol (its data answer's symbol), interval, trades (its
listed trades), bars [[t, o, h, l, c]], markers}. Each is that instrument's
bars, at most 5,000 bars (every marked bar, the first, the last, then an even
stride); past 4 instruments each view gets 5,000 x 4 / N bars, so a push
holds at most 20,000 in all, and every marked bar is always kept. markers
are one per listed fill on it: {t, price, side, kind "entry" | "exit", trade
(index in trades[])}, where side is the fill's side (a short's entry
marker is a sell). With no listed trade, prices still shows the candles so
you can see why nothing fired: one view per data instrument holding a bar, in
data order, at most 4, each with no markers and trades 0. price is
prices[0], kept for older versions of the platform.
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 platform'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 platform (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.