Orders
Market, limit, stop, bracket, trailing and cash-amount orders; modify, cancel, and what a timeout means.
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.* tooOrder 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 staysIt 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 platform's STOPS HELD BY setting is for the platform'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 platform'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 platform: 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 twicePaper trading is your broker's, not While25's. While25 has no simulator
of its own. To trade without real money, connect your broker's paper account
(Alpaca's paper account, or IBKR's paper login) and deploy there: orders go to
that account and fill as the broker fills them. Either way 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. While25 once filled ungranted orders on a simulator of its own, which made "deploy it and read the fills" a substitute for testing — against live market data, priced with no contract multiplier, no futures margin and no expiry. The fills looked real and the numbers were not. A broker's paper account fills by the broker's own rules.
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 platform — 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 changeOne 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 platform, 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 platform 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 platform 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 platform 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 itA 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.