State and order lifetime
The Context answers state questions locally (no engine round-trip), all maintained from the fill/cancel stream:
ctx.Position(symbol)– signed quantity and average price.ctx.WorkingOrders()– submitted orders neither filled nor cancelled; under lifetime v2, every unresolved attempt with its status and quantities, attached children included (next subsection).ctx.Flat(symbol)– true only when there is no position and no working order in the symbol. The safest entry gate there is, for a strategy that submits its own orders; an entry akit.Controllerowns is gated on the position instead (see the migration recipe).ctx.Exposure(symbol)– position plus working orders in one struct. On a continuous series both count a working order on the series’ held contract against the logical symbol.ctx.LifetimeV2()– true on a run that negotiated order lifetime v2 (the engine offeredlifetime-v2, as a backtest does by default and--lifetime v2does on a live run, and the strategy required or supported it), false under the legacy profile; settled beforeOnInit. The one question a strategy that serves both profiles asks (see Supporting lifetime v2 optionally).ctx.ActiveContract(symbol)– the dated contract a continuous series is currently served from, per logical symbol (see the strategy’s view of continuous futures).ctx.Instrumentof it describes the held contract on its own grid.ctx.HeldFront(symbol)– the front contract a deferred holding (B1, B2) is held behind, from the latest roll notice (see Held rank).ctx.Account()– the engine-maintained account snapshot: one balance per currency, the base first, andNetLiquidation, the whole account in its base currency (see Currencies).kit.Equity(ctx)returns the net liquidation. A live run pushes its own account before each bar, as a backtest does (The account in a live run).ctx.Instrument(symbol)– resolved instrument metadata (exchange, tick size and its source, point value, margin when served); populated from the universe-resolved push, which every run on the pb strategy wire receives before its first bar, a continuous run included (GLE-356). On the CSV strategy wires, v1 and v2, it stays empty (see “Declaring extra data and universe expansion”).ctx.Calendar(symbol)– the exchange calendar the engine pushed for the symbol’s root, with its lookups (TradeDate,Day,Span,NextBoundary,Complete); false until a push arrives, which the engine sends only to a strategy that asks for it (see Strategy SDK lookups).ctx.Portfolio()– the portfolio view: the positions, working orders and figures of the portfolio the strategy runs in, as of the decision; the zero view unless the strategy asks for it (see Reading the portfolio).ctx.Now()– the current bar’s close time, or a timer’sFiredAtat its decision: simulation time.ctx.DataAge(seriesID)– how old the series’ newest bar is atctx.Now(): 0 at a bar of the series, its staleness at a timer’s decision; false when there is no such series or it holds no bar (see Scheduled decision points).ctx.Log/Logf– diagnostic lines over the wire (what you saw printed as[smacross] INFO: ...). A deployed strategy’s lines go to the desk as well (see What the strategy says).ctx.Plot(name, value, style...)andctx.Annotate(annotation)– a value plotted, or a note made, on the barOnBaris deciding (see Plotting from a strategy).
Reading the portfolio
A strategy can read the portfolio it runs in before each of its decisions: the positions and working orders of every strategy in it (its members), the totals per symbol, and each member’s and the portfolio’s equity, drawdown, trade statistics and performance ratios, as of now (GLE-1372; the design is in docs/portfolio-view-spec.md). It asks by implementing PortfolioWatcher:
func (s *DDBrake) PortfolioNeeds() algolang.PortfolioNeeds {
return algolang.PortfolioNeeds{Curve: algolang.CurvePortfolio}
}and reads the view with ctx.Portfolio(). ddbrake, smacross with a drawdown brake (strategies/demo/go/ddbrake), reads its own drawdown at each bar. When its equity falls more than MaxDrawdown below its peak, it closes its position and stands aside for Cooldown bars:
view := ctx.Portfolio()
me := view.Summary(view.Reader())
if me.HasStatistics && me.DrawdownPct > s.next {
s.next = me.DrawdownPct + s.MaxDrawdown // the next step down
s.pause = s.Cooldown // close the position, stand aside
}The brake then goes on again only at a further MaxDrawdown of drawdown, or at MaxDrawdown once the drawdown has recovered under it. A brake that held until the drawdown recovered would hold for good: while the strategy stands aside, its equity does not move. make run-ddbrake runs it on the continuous E-mini S&P 500 daily series, 2015 to 2025 (it needs the marketfeed adapter and archive). At the end it prints the last view’s figures, which are the report’s.
- What it holds.
Members();Position(member, symbol)andPositions();Orders(member)(""for every visible member);Total(symbol), the portfolio’s net, gross, long and short quantity in the symbol, the members long and short, the notional, the working buy and sell quantity andIfAllFilled; and, for a member or for the portfolio (""),Summary,Stats(member, AllTrades|LongTrades|ShortTrades),PerformanceandEquity.Reader()is the strategy’s own member id. - The figures are the report’s, as of now. Every figure equals what the end-of-run report would show if the run ended at this bar: equity, net profit and drawdowns net of commission, as the equity curve is; trade P&L and the statistics columns gross, as the trade list is. The Sharpe ratio counts the day in progress at its latest point, as the report of a run ending mid-day does. A ratio that cannot be computed yet has its
Hasflag false: Sharpe and Sortino need 20 daily returns, the annual return a day. - Nothing from later. A view at a bar holds the marks and fills of that bar’s close and before; the orders the decision sends appear in the next view, not in this one.
- The curve accumulates. With
Curve: CurvePortfolio(orCurveMembers, every visible member’s too)Equityreturns the curve to date. The engine sends each point once and the SDK keeps the history, so a strategy pays nothing per bar for a long curve.CurveNone, the default, leavesEquityempty. - Read it in the decision. The view is replaced by the next one; keep a figure, not the view.
- Pushed, not queried. The engine sends the view before each decision of a strategy that asked, beside the account; a timer’s decision or a lifecycle turn reads the view of the bar before it, as it reads
ctx.Account(). A strategy that does not ask receives nothing new.
In a backtest the portfolio has one member, the strategy itself: its id is the run’s (ctx.RunID()), and the portfolio’s figures equal its own. This is enough to write and test a strategy against the API, and to use its own figures (a drawdown brake, sizing by the run’s equity curve). A strategy whose logic depends on its peers can only be judged where they run together, in AlgoDesk. The run’s Data notes say the view had one member.
Positions are the report’s: the open lots marked at the latest close, their quantity-weighted entry price as AveragePrice, and the symbol’s closed trades as RealizedPnL. A continuous series’ position is under its logical symbol, with the contract held in Contract. Its prices follow the run: the served (end-adjusted) prices the strategy’s bars have, or on a run that rebases (the default) the held contract’s own, where AveragePrice is the strategy’s ctx.Position(symbol).AvgPrice and OpenPnL stays as the report states it (The portfolio view across a roll, GLE-1504). Orders are the run’s working orders, with Reducing set on one on the other side of the position and no larger than it; on a lifetime-v2 run an order the admission guard holds back is there too, as OrderPending.
With the report off (--report off) the run keeps no statistics: the view carries positions, orders and totals, Summary reports HasStatistics false, and a Data note says so.
Visibility. A run-config file sets what each strategy may see, in the top-level portfolio object, overridable by a strategies entry or a run:
{
"portfolio": {"visibility": "all"},
"strategies": [{"strategy": "./bin/ddbrake", "visibility": "totals", "runs": [{"symbol": "ES"}]}]
}all (the default) sends every member’s rows; totals the portfolio’s totals and figures and the strategy’s own rows; none no view, with a Data note. In a one-member backtest all and totals send the same rows.
Live runs and the CSV wires. A member run at the desk (algo run --deploy) reads the desk’s view, with every member the portfolio file lets it see: on the desk’s SIM clock the view of each instant, and on the wall clock the desk’s view as of the last bar it stepped. Each view reaches the strategy once, before its next decision. Any other live run sends no view: the strategy reads the zero view (Valid() false), and the run says so when it starts. The view travels only on stdio-pb-v1: both CSV wires refuse a strategy that asks for it.
Plotting from a strategy
A strategy can plot its indicators and mark bars from OnBar, so that a viewer of its results draws them over its trades, as TradeStation draws a strategy’s plots (GLE-677). smacross plots its two averages:
closes := indicators.Closes(series)
fast := closes.SMA(s.Fast)
slow := closes.SMA(s.Slow)
ctx.Plot("fast", fast.Value(), algolang.PlotStyle{Color: "#2962ff"})
ctx.Plot("slow", slow.Value(), algolang.PlotStyle{Color: "#ff6d00"})and a strategy marks a bar with a note:
ctx.Annotate(algolang.Annotation{Text: "breakout", Position: algolang.AnnotationBelow,
Shape: algolang.AnnotationArrowUp})A value belongs to the bar being decided, the bar
OnBarwas called with, on that bar’s series. A plot is named by its series and its name, so a strategy that plots"fast"on two series has two plots.Its first call fixes a plot’s style for the run:
KindisPlotLine(the default),PlotHistogramorPlotDots;Paneis""to draw over the series’ prices, or the name of a sub-pane below them, shared by every plot that names it;Coloris"#RRGGBB", or""to let the viewer choose. Any other colour is dropped for the viewer to choose.
A later call’s style is ignored.
The last value of a bar is kept when a name is plotted twice in one bar. NaN, or an infinite value, is a gap.
An annotation has
Textand aShape(AnnotationCircle, the default,AnnotationSquare,AnnotationArrowUp,AnnotationArrowDown). It sitsAnnotationAbovethe bar (the default),AnnotationBelowit, orAnnotationAtitsPrice.Only a bar decision plots. A call from
OnInit, a warm-up or late bar, a lifecycle turn, a timer or another handler, or a plot without a name, is ignored with a warning printed once a run.Plots travel on the
stdio-pb-v1wire only, with the bar’sOrderResponse(plotsandannotations, fields an older engine ignores). On the CSV wires every call is ignored, silently, so a strategy that plots writes those wires as before.
A run that plotted writes them to its results folder as plots.json (Artefact formats), and the export holds them in its plots and annotations tables (The export file). Drawing them is the viewer’s: AlgoChart’s run tab draws them over the run’s charts.
A deployed strategy’s plots and annotations go to the desk instead, bar by bar, as it decides each bar (see What the strategy says). A live run with no desk has nowhere to send them, and drops each bar’s as the bar is decided.
The working view under lifetime v2
A run that negotiated lifetime-v2 (the strategy returned the token from RequiredCapabilities or SupportedCapabilities and the engine offered it; see Capability negotiation) keeps a different working view: the attempt-indexed view of the order-lifetime programme’s increment I3 (GLE-372, sdk/strategy/working.go). The SDK selects it once, before OnInit, from the negotiated capabilities and from nothing else. The engine offers the token on a backtest unless it runs under --lifetime v1, and on an emulated-live run under --lifetime v2 (Lifecycle turns), and on nothing else, so every run under the legacy profile keeps the v1 view, which is unchanged in every observable way: its contents, its map order and its wire bytes, and with them its one known gap, that when a bracket’s entry fills its children are live at the venue but absent from the v1 view (a Fill deletes the label and the children were no entries of their own). The v2 view holds them.
Attempts. Every physical submission under a label is an attempt. The SDK stamps Order.Attempt in place on each order OnBar returns and on each labelled attached child, 1-based and increasing per label, so the OrderResponse carries it; a value the strategy set is overwritten. A label’s counter survives the retirement of its attempts, so an attempt number is not reused within one strategy process, and an adopted frame advances each label’s counter to the attempt it carries, terminal entries and their children included, so a number the engine’s ledger already holds is not reused either. (ClientID, Attempt) names one attempt, and every event about it echoes both.
Entries. The view holds one entry per unresolved attempt: a submission OnBar returned, an attached child of one (an entry of its own from the moment its parent is tracked, Inactive until the parent fills), or an attempt restored from the live-mode adoption frame. Each is a WorkingOrder carrying, beyond Order and SubmittedAt, seven fields that stay zero on a v1 run: Status, FilledQuantity, RemainingQuantity, ParentClientID (the parent’s label on a child), OrderRef (the engine’s durable reference once an event carried one), CancelRequestID (the id of the strategy’s cancel request while it is pending) and ReplacesAttempt (the attempt this one replaced when a continuous roll re-placed the order, the latest such; 0 for an attempt the strategy submitted). Entries are kept in the order the view first learned of them, each parent followed by its children, a resubmission under a label at the end; a status change keeps an entry’s place, and WorkingOrders() and Exposure present that order every time.
Statuses. An entry’s status is always a live one:
| Status | An attempt that |
|---|---|
Submitting | was tracked and has no acknowledgement yet: the initial status. Under lifetime v2 the engine answers every submission with an OrderUpdate, Working on acceptance, at the instant or (on a backtest whose turn budget ran out) before the next event’s fills and cancels, so an entry is here briefly; a v1 engine sends none, and an entry stays here until a fill or a cancel. |
Working | was acknowledged by an OrderUpdate, or is a child activated by its parent’s full fill. |
PartiallyFilled | has executed in part and has quantity still working. |
PendingCancel | ctx.Cancel addressed and the engine has not yet answered, or answered Pending or Unknown (a live venue that has not confirmed the cancellation). |
Held, SubmissionUnknown | an OrderUpdate reported so: SubmissionUnknown on a live run whose venue left a submission’s fate open (Lifecycle turns), Held when the engine’s race guard holds a submission behind a pending cancellation (The engine race guard). |
Inactive | is an attached child whose parent has not filled. |
A terminal status (Filled, Cancelled, Rejected, Denied, Expired; OrderStatus.Terminal()) does not appear in the view: reaching one retires the entry. Retirement decides the children: a parent that retires filled turns its Inactive children Working in place, and one that retires any other way (cancelled, rejected, expired) takes them with it. A child already active through its own evidence, its own fill or OrderUpdate, is untouched by its parent’s end. Children belong to one generation of their parent’s label: a resubmitted bracket’s children are the new attempt’s.
Transitions. By event:
- a
Filladds its quantity toFilledQuantity; a stamped fill’sRemainingQuantityis authoritative (0 is a full fill), an unstamped one reduces the remaining quantity by the fill. Nothing remaining retires the entry filled; otherwise it becomesPartiallyFilled, or staysPendingCancelwithPartiallyFilledas the status a refusal restores. AnInactivechild’s own fill activates it. The position folds every delivered fill whether or not the view knows the attempt, as before. A fill with no identity at all (ClientIDempty,Attempt0, noOrderRef, no commission) is the venue’s cash settlement of a position whose dated futures contract expired (Contract expiry (lifetime v2), GLE-479): the position folds it, and the view, which cannot attribute it, leaves every entry as it was. - an
OrderCancelretires the entry, whatever its reason. - a
CancelReject(the v1 answer to a cancel the engine could not honour) returns the label’s oldestPendingCancelentry to the status it had before the request and clears itsCancelRequestID. - an
OrderUpdatesets the quantities when it accounts for them (FilledQuantity + RemainingQuantity > 0; a status-only update leaves them) and then the status: a terminal one retires the entry (filled only forFilled),PendingCancelmarks it pending,Unspecifiedleaves it, and while a cancel is pending any other status is recorded underneath as what a refusal restores. An update that names an attempt it replaces (ReplacesAttemptnot 0, a continuous roll’s) re-keys the replaced attempt’s entry to the new attempt in place and then moves it the same way (Order lifetime v2 across a roll). - a
CancelResponsemoves no quantities.Confirmedretires the entry (theOrderCancelthat follows is then a no-op);PendingandUnknownkeep itPendingCanceland take the response’sRequestID;Refusedwith terminal evidence inStatusretires it, and otherwise ends the pending cancellation and restores the live status, the response’s when it carries one.
Which attempt an event addresses. A stamped event (Attempt not 0) addresses exactly the live entry with that label and attempt, and is a no-op when there is none: a late OrderCancel, OrderUpdate or CancelResponse for a retired attempt resurrects nothing and touches no other attempt, and a terminal event applied twice changes nothing the second time. An unstamped event (every event a v1 engine sends) addresses the label’s oldest live entry, with three exceptions: an OrderCancel with reason Rejected addresses the newest, because a rejection answers the latest submission; an OrderCancel with reason ParentCancelled addresses the label’s oldest Inactive entry whose parent is no longer in the view, and is a no-op when there is no such orphan; and a CancelResponse addresses the oldest PendingCancel entry, else the oldest live one. The orphan rule exists for a bracket cancelled and resubmitted in one OnBar: the parent’s own OrderCancel has already retired the first generation’s children, so the ParentCancelled notices that follow it find no orphan and leave the second generation’s children, which belong to the live new parent, in place for its fill to activate. The engine delivers the events of an older attempt before those of a newer one under the same label, so the oldest-first rule addresses the right generation. No event creates an entry: the view mirrors what the strategy submitted or adopted, and an event about an unknown label or attempt changes nothing in it.
Cancelling. ctx.Cancel(clientID) is valid in every live status, Submitting included: a strategy need not wait for a Working acknowledgement. It addresses the label’s newest live attempt that is not already pending cancellation, else its newest live attempt, marks it PendingCancel at once and gives it a request id of the form <label>/<attempt>/c<n>, where n counts the strategy’s cancel requests (a re-request replaces the id). The request goes onto the wire with the attempt and the id (zero and empty on a v1 run, whose envelope is unchanged) and is sent even when no attempt of the label is live; the engine answers it. The attempt stays in the view, counted by Flat and Exposure, until the engine’s answer retires it (an OrderCancel, a confirmed CancelResponse) or refuses it (a CancelReject, a refused CancelResponse).
Observers. OnOrderUpdate and OnCancelResponse run after the view has moved on their event, exactly as OnFill runs after the position fold: a handler reads the view as the event left it. On a v1 run the view ignores both events and only the handler sees them, as in I2.
Flat and Exposure. Every entry is a commitment: a submission awaiting its acknowledgement, a pending cancellation, a held order, an inactive child. ctx.Flat(symbol) is false while any of them rests on the symbol (active-contract attribution on a continuous run included) and ctx.Exposure(symbol).WorkingOrders lists them in view order.
Copies. WorkingOrders() and Exposure return copies the strategy may keep or change, Order.AttachedOrders and their own children included; nothing a strategy writes to a returned slice, or to the order slice it returned from OnBar once OnBar has returned, reaches the view.
Adoption and corporate actions. OnAdoptedState under lifetime v2 replaces the view with the frame: each adopted order and its children in frame order, with its status (Working at top level and Inactive when nested if the frame carries none), quantities, attempt, reference and submit time; a terminal frame entry gets no entry but still advances its label’s counter; a v1 frame seeds Working entries with attempt 0 and the whole quantity remaining, which an unstamped event reaches. On a corporate action’s EFFECTIVE notice the view follows the engine’s books. A rename re-keys each attempt on the old ticker, its children included, to the new one and keeps its identity, status and cancel-request state, as the engine keeps the orders. A split, a stock dividend or a stock or mixed merger rewrites each attempt’s order and quantities on the symbol, keeping the same state, and drops an attempt whose remaining quantity floors to zero with its inactive children. That working-order rewrite is interim. In a backtest under v2, the default path since I22 (GLE-470), it finds nothing: the engine has already cancelled those orders, and their OrderCancel events retired the entries before the EFFECTIVE notice (Corporate actions and working orders (lifetime v2)), as the e9 demos’ conformance runs and the e9equity stop of GLE-498 confirm. An emulated-live run, whose venue still rewrites, reaches it, and the rest of I14 unit 2 (GLE-456) removes it with the live path’s cancels.
Lifecycle turns
Order lifetime v2 is the profile a backtest runs when it names none: since I22 (GLE-470, landed 2026-10-12) algo run without --lifetime runs a backtest, plain or continuous, under v2, and --lifetime v2 names the profile explicitly and selects it for an emulated-live run (unit 4b, GLE-378; engine/liveturn.go; see “On a live run” at the end of this section). The profile is increment I4 unit 4a of the order-lifetime programme (GLE-377; engine/lifeturn.go, engine/lifetimehost.go, engine/sim/attempt.go and sdk/strategy/lifetime.go), and engine/lifetimeprofile.go resolves the default. --lifetime v1 selects the legacy profile, byte-identical to the default before I22: the v1 exchange, the v1 events (attempt 0, no request id), no OrderUpdate, no CancelResponse, no turn, and the KBD masters unchanged; the legacy goldens name it. It is the rollback. A live run that names no profile stays v1, with its orders, venue exchange and ledger as before; so does a run under --schema TRADES, which has no strategy phase. --lifetime-turns N is the turn budget per instant under v2 (0, the default, selects 3). Under v2 the engine offers lifetime-v2 in Init, which the strategy must accept (Capability negotiation), and the strategy runs on the pb wire or on stdio-csv-v2: stdio-csv-v1 has no grammar for the capability or for the messages below, and the host (StdioHost, which carries the turns as the optional LifetimeHost) refuses each of them there with one text naming the pb protocol. The stdio-csv-v2 grammar carries them line for envelope, and a v2 run offers it ahead of v1 (Negotiating stdio-csv-v2). The profile runs on the plain backtest path, on a continuous backtest (a bare root or a :cont composite; since I15 unit 2a, GLE-453, whose rolls re-place the strategy’s orders as new attempts it is told of: Order lifetime v2 across a roll) and on the emulated-live path, and --lifetime v2 is refused before any spawn under --schema TRADES with engine: order lifetime v2 needs a strategy run (schema BARS, not TRADES). A live continuous futures run rolls under v2 since GLE-1446, with a ledger, on a venue fed from history, and since GLE-1503 on a real-time feed too, where the roll re-adjusts the series (A live continuous roll under order lifetime v2). A v2 backtest also cancels the working orders on an instrument across the corporate actions IBKR cancels them on, where v1 rewrites them (Corporate actions and working orders (lifetime v2)). Another value of --lifetime is refused naming both valid ones (engine: unknown order lifetime "v3" (want v1 or v2); the match is exact, so V2 is refused too), an empty one is the default, and a negative budget is refused naming the default. In a run-config file the two flags are the data keys lifetime and lifetime-turns, and a lifetime absent at every level is the default (The admission policy).
The default’s refusal. Under the default v2 a strategy that neither requires nor supports lifetime-v2 (Supporting lifetime v2 optionally) is refused at the handshake, as under an explicit --lifetime v2, and the refusal names the way back; nothing falls back to v1 silently. For the suite’s undeclared fixture program, built as undeclared:
algo: engine: undeclared: wire: the run selected lifetime-v2 but the strategy did not accept it; a strategy that does not implement the v2 order lifetime must run under the legacy execution profile (GLE-200 I2); lifetime v2 is the default for a backtest: run undeclared with --lifetime v1 (in a run-config file, "data": {"lifetime": "v1"}) for the legacy profile (GLE-470)
The hint names the strategy by its binary’s base name. Under an explicit --lifetime v2 the refusal is the capability law’s text alone, as before, and under --lifetime v1 the strategy runs. A program that speaks stdio-csv-v1 alone, whose grammar cannot carry the capability, is refused the same way, with the v1 codec’s text (Capability negotiation) and the same hint. Every strategy, demo and port in the tree declares lifetime v2 (I21, complete, and the family of 18 legacy strategy binaries since GLE-497’s backtest half), and none refuses a v2 backtest any more (the swing-breakout strategy’s bracket child and competing exit pair since GLE-480’s and GLE-473’s backtest halves; the e9equity demo re-places its stop after a split under v2 since GLE-498), so the flip refuses none of them; the refusal is for a strategy written outside the tree. A misspelt mode is refused for itself, since the mode decides the default: by the CLI (algo: --mode must be backtest or live, got "paper"), by a run-config file’s plan (engine: mode must be backtest or live, got "paper") and by engine.Run before the profile is resolved (engine: unknown run mode "paper" (want backtest or live)). --verify does not spawn the strategy, so it cannot see this refusal. The default also moves the v1-only refusals: a backtest that names no profile and sets an admission limit (The admission policy) runs under v2, where before it was refused as a v1 run; a live run that names none refuses an admission or transport limit with the v1 texts, as before; and --lifetime v1 with a limit is refused.
Provenance. A run records its profile and how it was chosen, default or explicit, whenever the profile is v2 or was defaulted. The report prints it on the line after the strategy line (lifetime: v2 (default), v2 (explicit), or v1 (default) on a live run that names none); result.json’s header carries "Lifetime": "v2", "LifetimeSource": "default"; report.html’s run details show an Order lifetime row, v2 (default); and the lifecycle trace’s run object carries "lifetime" and "lifetime_source" (The lifecycle trace schema). A live run writes no result.json and no trace, so it records its default in the report line alone, and a run under --schema TRADES records nothing. A run under an explicit --lifetime v1 records nothing anywhere: its report, result.json, report.html and trace are the legacy run’s, byte for byte, which is what a rollback relies on, and in a backtest the absent line says the run asked for v1 by name. The fills blotter, the continuous roll manifest, the series cache key and the derived run id involve no profile, so a default run and an explicit one of the same profile share them. Nothing changes on the strategy’s side: the SDK learns the profile from Init, a default v2 Init is the explicit one’s, and the SDK’s order constructors build the same orders under either profile (a Day time in force, a bracket’s children GTC).
The exchange at an instant. A bar is answered as before: the queued cancel requests, then one OrderResponse for the bar’s close. The engine applies the cancels first, then the submissions, and answers each one at the instant. Every submission gets an OrderUpdate: Working with the whole quantity remaining on acceptance; Denied with the simulator’s reason and nothing remaining on a denial, whose rejection cancel still follows before the next bar’s events, now stamped with the attempt. Every cancel request gets a CancelResponse: Confirmed, with the attempt’s status Cancelled and its remaining quantity, when the order was cancelled; Refused otherwise, with the terminal status, attempt and reference of the order it found as evidence, or without evidence when the label, or the attempt, was not submitted this run. The responses go out in request order, then the updates in order order, each on its own envelope, and each carries the attempt, the simulator’s reference (sim-N; a denied attempt has one too, since a denial creates a Rejected record, so a later cancel of it answers already terminal (rejected) with the status Denied) and the instant as its timestamp. The evidence status is the venue’s, mapped onto the wire’s, with one exception since unit 4b: a venue’s Rejected is Denied on every path, because every rejection the engine knows of arrives as a denial and was announced to the strategy as Denied, so the attempt’s later evidence says the same; the wire’s Rejected is kept for a venue that rejects an order it had accepted. A v2 run sends no CancelReject: a refused cancel is the classified response, plus the operator line the v1 loop prints (algo: cancel of order "lim1" from instance ES rejected: <reason>), and the book is untouched. The outcome Pending and the status SubmissionUnknown do not occur on the simulated path; a live run produces both (below).
Attempt-addressed cancels. A cancel request names the attempt the SDK stamped on it (ctx.Cancel, above), and the simulator cancels exactly that attempt (Simulator.CancelAttempt): a request for attempt 1 of a label reaches attempt 1 alone, even once attempt 2 has been submitted (the race guard admits attempt 2 only as attempt 1’s successor; The engine race guard). Attempt 0 keeps the v1 meaning, the label’s newest order, and the response then names the attempt the simulator resolved. A request for an attempt that has ended, whether the simulator compacted it out of the book, denied it at validation or settled it at submission (an MOC), is Refused with that record’s status as evidence (order "lim1" is already terminal (filled)); one for a label or attempt not submitted this run is Refused without evidence (unknown client order id "x" attempt 2 (never submitted this run)); an empty label is refused as addressing nothing. A refusal changes nothing in the book. The queued OrderCancel of a confirmed cancel carries the request id (the parent-cancelled notices of its children do not), and every fill and cancel the simulator produces under v2 carries its attempt: parent and child fills, OCO sibling cancels, Day expiries, explicit cancels and the shutdown sweep.
What grants a turn. An answer the strategy may want to act on grants it a lifecycle turn before the clock advances: every CancelResponse (a confirmed cancel releases a replacement; a refused one leaves intent unmet), every TimerRefused of an arm (Scheduled decision points) and every OrderUpdate whose status is neither Working nor Held (a denial, the race guard’s included). The Working acknowledgement of an accepted submission grants nothing, and nor does the Held one of a submission the race guard holds (The engine race guard), since the strategy just submitted that order, so a bar whose commands produce acknowledgements alone ends with them delivered and no turn. The engine writes one LifecycleTurn{at, turn, budget} envelope, at the instant and turn 1-based within it; the strategy answers exactly as it answers a bar, its queued cancel requests and then one OrderResponse whose for_bar is at; the loop applies and answers those commands in turn. A turn answered with no order, no cancel request and no timer command ends the instant. So a replacement can follow a confirmed cancel before the next matching bar: bar 1 returns the cancel of lim1, the Confirmed response grants turn 1, the turn returns lim2, whose Working update ends the instant, and bar 2 fills lim2, delivering lim1’s OrderCancel (with the request id) before the fill.
The budget. Turn k is granted while k is at most the budget. After each step’s commands are applied the engine checks, in this order: no outcome ends the instant; outcomes that grant nothing are delivered and end it, however the budget stands; only then, when the budget is exhausted, the step’s outcomes, acknowledgements included, are deferred whole to the next event (on a backtest; a live run delivers them at once, below), with one line on stderr, algo: lifecycle turn budget 3 exhausted at <instant> for instance <label>: N outcome(s) deferred to the next event. Deferred outcomes are delivered at the top of the next bar, before the bar’s corporate actions (since I14 unit 1), the previous instant’s rejection cancels and the bar’s fills and cancels, or at the end of data before the shutdown sweep, in order and before anything else of that instant. Budget 1 therefore always defers turn 1’s granting outcomes, so 2 is the smallest budget under which a turn’s own outcome can grant another turn; the default is 3. The engine re-admits nothing: a strategy that re-emits a denied order on every turn is stopped by the budget (under budget 2, three Denied updates, the last deferred to the next bar, then the three stamped rejection cancels).
The SDK’s side. A strategy decides on turns by implementing TurnHandler, OnLifecycleTurn(ctx, t LifecycleTurn) ([]Order, error), where t carries At, Turn and Budget. The SDK moves ctx.Now() to t.At first, whether or not the strategy has the handler; no bar is appended, no series moves and BarCount is unchanged. The handler reads the working view as the engine’s answers left it (the updates and responses arrived, and moved the view, before the turn), may queue cancels with ctx.Cancel, and returns orders that are labelled and tracked exactly as OnBar’s are: a label resubmitted in a turn gets its next attempt, a blank label the collision-safe auto id. The queued cancel requests go out before the response, an observer’s included, whether or not the strategy has the handler, and the queued timer commands after them (Scheduled decision points); a strategy without one answers every turn with an empty response. A handler error ends the run as an OnBar error does. The lifecycle trace records a turn’s submissions and cancel requests as strategy records through the same taps as a bar’s, at the turn’s instant, and a turn’s timer commands as timer records whose turn names it.
On a live run. --mode live --lifetime v2 (unit 4b, GLE-378) runs the same driver, lifetimeLoop, over venue-backed operations (engine/liveturn.go) in place of the simulator’s, so the exchange, the turns and the budget are the ones above, with the differences below. A submission goes through the live loop’s admission and submission sequence, the one the v1 loop uses: the attached-order and time-in-force refusals, the raw-frame translation, the ledger record before the venue call, the venue call and the reconciler registration. Its update is Working on acceptance and Denied with the venue’s reason on a denial, whose rejection cancel is keyed by the ledger reference so the ledger records the reject and maps it back to the label; a submission whose fate the venue left open is SubmissionUnknown, with the whole quantity remaining, and the reconciler resolves it (without a ledger there is no reconciler, and the run fails as a v1 run does). Updates and responses carry the ledger’s canonical reference as OrderRef, or the venue’s order id without a ledger. The teardown is the live loop’s, the same on both profiles (Tickets and cancels at the IBKR venue). Since I6 unit 3a the transport scheduler decides when each submission and cancel request reaches the venue (The transport scheduler); a request it queues is answered when it is sent, or at the end of the run.
Delivery at once. A live run defers nothing. When the budget is exhausted, the step’s outcomes, acknowledgements included, are delivered at once and grant no turn, with one line on stderr, algo: lifecycle turn budget 1 exhausted at <instant> for instance <label>: N outcome(s) delivered without a turn; the strategy decides on them at the next event. A deferred Working acknowledgement could otherwise land after the venue’s fill of the same attempt, which a venue produces on its own clock. Within the budget, turns are granted as on a backtest, and a Pending or Unknown response grants one too: it tells the strategy to wait. Holding a same-side replacement behind a pending cancel is the admission race guard’s (The engine race guard).
Attempt resolution. A cancel request addresses the attempt it names; attempt 0 resolves the label’s latest submission, and the response names the attempt resolved. The live loop knows an attempt by the order id the venue assigned it, so a request whose attempt has none (a label or attempt not submitted this run, or a label whose latest submission was denied or left open) is Refused without evidence, with no venue call and no ledger write: unknown client order id "x" (no broker order recorded for it this run), or unknown client order id "x" attempt 2 (no broker order recorded for it this run) when the request named the attempt. At attempt 0 this holds even when an earlier attempt of the label is still working. Here the live path differs from the simulator, which keeps a record of a denied attempt and refuses with it as evidence.
The request. For an attempt with an order id the loop records the ledger’s durable cancel intent (The order ledger) before the request leaves; a failure to record it is fatal (engine: cancelling order "L" for instance AAPL: engine: recording cancel request for <reference>: ...). The venue’s classified answer (Tickets and cancels at the IBKR venue) then passes through to the CancelResponse: Pending with the status PendingCancel and the venue’s text, Refused with the venue’s text, Unknown with the failure’s. A venue error, such as a transport failure, is an Unknown answer (cancel of broker order <id> unresolved: <error>), not an error of the run. A Pending answer prints nothing, an Unknown one algo: cancel of order "L" from instance AAPL unresolved: <reason> and a Refused one the v1 line quoted above, ending rejected: <reason>. A Confirmed, Pending or Unknown answer marks the order requested, so its cancel, when the venue reports it, is the strategy’s own and not a venue expiry. A Refused answer clears the intent only when this request recorded it and the venue did not report the order already pending cancellation, so an earlier request’s intent stands; a failure to clear it is fatal too. The IBKR adapter reports no remaining quantity on a cancel answer; the OrderCancel that follows carries it.
The post-submission poll. After the instant’s commands and turns, the loop polls the venue once more when an MOC was accepted at the instant or any cancel request was handled, addressed or not, which is the v1 rule: the events found are recorded in the ledger at once and delivered with the next bar’s batch, cancels ahead of fills (the simulator’s queue order), so a cancel the venue enacted at the instant reaches the strategy before the next bar’s fills.
Against a backtest. The emulator cancels synchronously but acknowledges with IBKR’s body, so a v2 emulated-live run equals the v2 backtest of the same strategy (fills, cash, positions, the sequence of events and GLE-195’s MOC contract) except that its cancel response is Pending with the status PendingCancel where the simulator’s is Confirmed; the OrderCancel follows from the post-submission poll. A same-side replacement sent with the cancel is therefore Held and then, released by that poll at the same bar, Working, where the backtest’s is Working at once (The engine race guard). The equality holds while a bar sends at most the transport scheduler’s five requests at its defaults; a run that sends more queues the excess to the next bar (The transport scheduler).
Known limits on the live path.
- The teardown sweep cancels every
Workingorder the account reports, another deployment’s included; restricting it to the ledger’s own orders is the ownership-aware shutdown of I9. - A live
Explicitcancel carries noRequestIDyet. I8 unit 2, whose cancel-intent records carry the request, adds it; the working view addresses the cancel by label and attempt meanwhile. - The live attempt map (
byAttempt, with each label’s latest attempt) keeps an entry per submission for the whole run, so it is bounded only by the run’s submissions; attempt lifetime across restarts is I8 unit 2’s. - Host I/O under the run’s cancellation and the concurrent drain of the strategy’s output landed as I4 unit 4c (GLE-416; Cancellation and strategy output): a host call in progress when the run’s context ends returns within 2 s, and the drain GLE-446 asked for serves every stdio wire. Since GLE-494 a SIGINT or SIGTERM ends the run’s context, and so does the strategy stall timeout when a run sets it (GLE-496; Stopping a run). A live run ended so returns from the call it interrupted without the teardown sweep: what is working at the venue stays working, as when the signal killed the process before. Classifying that exit, with a teardown under a context detached from the run’s, is I9’s (GLE-469); The engine host lists the limits that remain.
The engine race guard
Under lifetime v2 every new order passes the engine’s admission race guard before it can reach the venue (increment I6 unit 1 of the order-lifetime programme, GLE-419; engine/raceguard.go, engine/lifeturn.go and sdk/strategy/raceguard.go). It protects a strategy that cancels attempt A and submits a same-side B on the same symbol, in the same reply or a later one: a stop moved to a new level, an entry re-priced. A live venue acknowledges a cancel as Pending (Tickets and cancels at the IBKR venue) and A can still fill until the venue reports it cancelled, so a B sent at once can execute beside A: a long position protected by a sell stop A and its replacement B goes through zero to short. Owner decision D2 puts the wait for terminal evidence in the engine, not only in the strategy’s helper (The desired-order controller): the guard holds B until A has ended, and rejects B if A executes first.
The guard sits at the driver’s one admission point, apply (Lifecycle turns), so it applies on every lifetime-v2 path: the plain backtest, the emulated-live run and, since I15 unit 2a (GLE-453), the continuous backtest, on the pb wire and on stdio-csv-v2 alike (a v2 batch is read into the same reply). A v1 run has no driver and no guard, and is byte-identical. The simulator acknowledges cancels synchronously, and the driver applies a reply’s cancels before its orders, so a backtest holds nothing in the ordinary case and the KBD masters are unchanged. The one backtest hold is a cancel the simulator refuses because the MOC it addresses has already gone: under v1, in a later turn, an MOC that settled at its submission, refused with Filled as evidence; under v2, a cancel at a timer at or after the MOC’s send time (GLE-1375). The guard waits to observe the MOC’s fill, and the fill, delivered at the next bar, rejects the held order with cancel_race (with hold_shutdown when the request came at the last bar).
Direction, not exposure. The guard classifies a new order O by direction, not by an exposure scalar. Its blockers are the live attempts with a cancellation outstanding (pending, unknown or refused; below) that are on O’s symbol and side, or carry O’s label. With no blocker O is admitted and submitted exactly as before the guard; otherwise a refused blocker rejects it (cancel_refused), else an unknown one rejects it (cancel_unknown), else O is held. An order on the opposite side under another label is therefore admitted at once, even while a cancel on its symbol is pending: a protective stop placed while an add is being cancelled cannot add to the exposure the pending cancel already reserves, and the caps of the admission policy (unit 2) count the add as still executable. An unlabelled order matches by symbol and side only.
The same-label successor rule. An order with a label first meets its label’s previous attempt, the most recently tracked attempt under the label that has not ended, an attached child included. If that attempt is held, or live with no cancellation requested, the order is rejected as duplicate_live_label. If it has a cancellation requested, in the same reply or earlier, the order is its successor and the predecessor is one of its blockers, so the successor is held while that cancel is pending, on either side, and rejected when the cancel was refused or its outcome is unknown. Cancel-and-replace under one label in one reply is the ordinary form: the cancel is applied first, so the successor is admitted at once on a backtest and held until the cancel resolves on a live run.
Replacing in place. A hold is safe, but between A’s end and B’s release neither order works: for a moved stop, a window with no stop. A venue can change a working order’s price, size and time in force in place, and then there is one order throughout, so the outcome is “modified” or “filled first”, never both (GLE-1419; engine/modify.go). The driver recognises a replacement from the successor form above, the cancel of A and a same-label B in one reply, with no SDK verb and no proto change. When the step holds exactly one cancel request and one order under the label, the driver asks the venue to modify A instead of cancelling it and sending B, if all of these hold:
- A is the label’s previous attempt, top-level, sent with a venue id and with no cancellation outstanding, and the request addresses it;
- A and B are both limit, stop or stop-limit orders,
DayorGTC, with no legs, attached orders orCancelAt, on the same symbol and side, of the same type, with the same trailing amount, OCO group, display name and conviction: B changes only the limit price, the stop price, the quantity or the time in force; - B would be admitted at once had A’s cancel been confirmed: no refusal at the wire, no blocker but A, and accepted by the admission policy with A left out of its counts;
- the run can modify: a live run whose venue implements
ModifyOrder, with or without a ledger, transport limits or a trade director (each below).
The request carries B’s prices (translated to the venue’s raw frame, as a submission’s are), its time in force, its label and attempt, and the order’s total quantity: what A executed plus B’s quantity, never the remainder, so an execution in flight when the request lands is absorbed, not added to. The venue’s answer decides:
| Answer | What the strategy hears | The guard |
|---|---|---|
| applied | A’s cancel Confirmed (status Cancelled, A’s remainder, a reason beginning modified_in_place:), then B Working with A’s OrderRef | A’s attempt is revised to B: one attempt, B’s attempt number, prices and remainder; every later event of the broker order carries B |
| refused (a fill won the race, say) | as before: A’s cancel goes to the venue and B takes the guarded path | unchanged until then |
unsupported (sim.ErrModifyNotSupported) | as before | unchanged until then |
| unknown | A’s cancel Unknown; B is refused with cancel_unknown | A’s cancellation is unknown, as for an unknown cancel; it reserves the larger of A’s remainder and B’s quantity |
A modification that loses the race to a fill therefore drops B and the strategy hears A’s fill once: the venue refuses the modification with Filled as evidence, the cancel that follows is refused with the same evidence, B is held behind A, and A’s fill rejects it with cancel_race. An event that names an attempt the broker order carried before a modification still addresses the revised attempt, by its venue id. The simulated path has no modifier (the simulator confirms a cancel at once, so there is no gap to close), and a backtest replaces by cancel and new as before; the controller’s one-reply form submits the successor at the instant the turn used to, so the KBD masters and goldens are unchanged. The IBKR adapter modifies a limit, stop or stop-limit order it sent itself, so a live IBKR run moves such an order in place (GLE-1434; Modifying in place). venuetest.Scripted scripts the answers for the live loop’s tests (The scripted venue).
A modification answered later (GLE-1436; engine/modify_async.go). A venue may answer Pending and give its verdict later, as a sim.ModifyEvent on its event stream (VenueEvent.Modify, which the driver keeps to itself). Until the verdict comes:
- A’s cancel request stays unanswered, so it still gets exactly one response, when the verdict comes. The SDK already shows A pending cancellation from the request.
- B is
Held, with the reasonheld: waiting for the venue to modify order "S" attempt 1 (sell AAPL) in place. It is not a guard attempt of its own: A’s broker order is one order, which reserves the larger of its old and new remainders, never their sum, and counts once against the admission policy’s caps. A is marked pending cancellation, so an order that a pending cancellation would hold is held behind it. - The order has at most one modification in flight.
| Verdict | What the strategy hears |
|---|---|
| applied | A’s cancel Confirmed (modified_in_place:), then B Working. B’s remainder is the new total less everything executed, so an execution while the modification was pending is absorbed, not a reason to reject B |
| refused | cancel and new: A’s cancel goes to the venue now and its answer answers the request. B is admitted as a new order (held behind the cancel), or refused with cancel_race when A executed meanwhile |
| unknown | A’s cancel Unknown; B refused with cancel_unknown, as for a synchronous unknown answer |
| no verdict within the hold timeout | as unknown, with B refused as hold_timeout |
| A ended first (filled, or cancelled by the venue) | A’s cancel Refused with Filled, or Confirmed with Cancelled; B refused with cancel_race when A executed, otherwise admitted |
At the end of the run, a modification still pending answers A’s cancel Unknown and refuses B (hold_shutdown).
The latest terms win. A trailing stop moves on every bar, so the next change can come while a modification is pending. The strategy uses the same successor form: it cancels the held B and submits C in the same reply. If the venue could take C in place, the driver withdraws B (its cancel is Confirmed, as for any held order) and makes C the modification’s latest terms, Held in B’s place. C’s terms go to the venue once the request in flight is answered, so one request is in flight at a time and the last terms win. Until the order carries terms the strategy holds, its events carry the attempt the strategy holds it under: a fill under B’s attempt at the venue reaches the strategy as A’s. A withdrawal with no successor of its own abandons the modification: A’s cancel request goes to the venue at once, and the late verdict changes nothing. A sell stop of 10 that moves up a point a bar, on a venue that answers a step later:
| Instant | The strategy | The venue | The strategy hears |
|---|---|---|---|
| bar 0 | submits S attempt 1, stop 10 at 99 | books it as sv-1 | 1 Working |
| bar 1 | cancels 1, submits 2 at 100 | modification to 2 Pending | 2 Held |
| bar 2 | cancels 2, submits 3 at 101 | still pending | 2’s cancel Confirmed, 3 Held |
| bar 3’s observation | applies 2’s terms; the driver sends 3’s, Pending | nothing: sv-1 carries 2’s terms, and the strategy still holds it as 1 | |
| bar 4’s observation | applies 3’s terms | 1’s cancel Confirmed (modified_in_place: ... attempt 3's terms ...), then 3 Working on sv-1 |
Each request’s total quantity is its terms’ quantity on top of what A had executed when the strategy asked for them. An execution after the request is absorbed, however long the request waits to be sent: a stop of 10 asked for before a fill of 2 works 8.
On a run with a ledger (GLE-1435). The ledger records each order’s frame, and every execution must agree with it, so a modification is recorded in three kinds of line (The order ledger):
- the intent,
modify_request, before the request leaves: the successor’s attempt and terms. The request keeps the order’s canonical reference as its client id; revision, once the venue applied it: the record takes the new attempt, total, prices and time in force;modify_refused, when the venue refused it or cannot modify the order: the frame is unchanged.
While the intent is outstanding, an execution may reach the larger of the old and new totals. The record’s attempt stamps the order’s later fills and cancels with the attempt the strategy holds: B’s once B’s terms apply, A’s while the order carries the terms of a withdrawn successor. An unknown verdict leaves the intent outstanding for the run’s later observations or the next start (The execution fold).
Through the transport scheduler. A run with transport limits modifies too: a modification is one request in the window, and one the window cannot take waits in the cancel-request queue (The transport scheduler).
Under a trade director. The director decides B with the step’s batch first, as it decides a successor under cancel and new, and the modification carries the quantity it accepted (Replacements in place).
The cancel answers. A cancel request that reaches the venue is answered as before (Lifecycle turns), and the guard then records the answer for the attempt the request addressed (the attempt it named, or for attempt 0 the attempt the answer names; resolved as an event is, below):
| Answer | The attempt’s cancellation state |
|---|---|
Confirmed (the simulator’s; the IBKR adapter does not confirm) | none: the attempt ends, with its children |
Pending | pending |
Unknown | unknown, unless already pending (an earlier accepted request stands) |
Refused with the venue’s status PendingCancel, or a terminal one (Filled, Cancelled, Rejected), as evidence | pending: the venue says the attempt is ending or has ended, and the guard waits to observe that end and any execution before it |
Refused with the venue’s status Working | refused |
Refused without evidence | refused, unless already pending |
Only an answer whose outcome is Refused is read as a refusal; an answer with no outcome (the zero value) changes nothing. A refusal belongs to its step, one reply (a bar’s commands or one turn’s), or, for a cancel request the transport scheduler queued, the observation that sends it (The transport scheduler). Within the step the refused attempt is a blocker, so a same-side order or a successor in the same reply as the refused cancel is rejected with cancel_refused, and so is every order held behind the attempt. When the step ends, on every return path, the state returns to none: the refusal resolved the request, and the attempt is live with no cancellation outstanding. At the next step, the turn the refusal grants included, a same-side order is an ordinary submission. An unknown state persists until the attempt is observed ended or a later request for it is accepted; meanwhile every same-side order and every successor is rejected with cancel_unknown, and opposite-side orders are admitted. Holding them instead would end only in timeouts.
Withdrawing a held order. A cancel request that addresses a held attempt (its label and attempt; for attempt 0, the label’s most recent top-level attempt that has not ended, when that one is held) withdraws it without reaching the venue: the attempt ends with its children, and the response is Confirmed with the status Cancelled, the held quantity remaining, the instant as its timestamp and no OrderRef. A request for a held attached child alone withdraws nothing; it goes to the venue.
Release and the watermark. A held order is released only when every attempt it waits for is terminal with nothing remaining, having executed nothing while the order was held, and the execution watermark covers that end, so a fill reported after the status cannot be missed. The watermark is the batch of the poll that observes the end. The loops hand the guard every venue event once, in one batch per observation of the venue, and the guard applies a batch whole: every execution first, whatever the batch’s order, then every cancel (whatever its reason, a rejection included), and only then does it decide the held orders. The IBKR adapter’s poll reads the live orders before the trades (Tickets and cancels at the IBKR venue), so every execution that preceded a terminal status it reports is in the same batch, and a predecessor’s end observed in a batch releases a held order only when no execution of the predecessor is in that batch or was observed during the hold. A venue that reported an execution in a later poll than its order’s terminal status would defeat the rule; that would breach the adapter’s contract. The reconciler’s terminal events wait for the next poll (the review panel’s fix): reconciler.Step reads the orders after the bar’s poll has read the trades, so a terminal status it reports can postdate an execution that no batch has carried yet, and the guard observes those events with the next bar’s batch, after that poll’s executions.
Where the loops observe. A backtest observes at each bar’s close, after the simulator’s events for the bar are delivered and before the bar’s decision; a release is submitted there and counted, and its denial’s rejection cancel is queued like the bar’s own. A live run observes at each bar’s close after the position reconciliation and after the submitter has moved to the bar, before the decision: a release is submitted on the bar it belongs to, and a released MOC, which settles at submission, does not trip the position check before its fill is recorded. The live loop observes the post-submission poll too, so a cancel the venue has already enacted (the emulator’s) releases the held order at the same bar, as the simulator’s synchronous cancel admits it, and a release that accepted an MOC adds one more poll, as the bar’s own MOCs do. An emulated-live v2 run therefore keeps the backtest’s fills, cash and positions: where the backtest’s replacement is Working at once, the live run’s is Held and then Working at the same bar.
A race. Any execution of a predecessor, partial or full, while its cancellation is pending rejects every order held behind it with cancel_race. The execution is delivered as usual, and the strategy re-decides at its next decision against the new position and remaining quantity: outcomes decided at an observation are delivered at once and grant no turn. A full execution also ends the attempt. Every execution moves its symbol’s position in the oracle (below), whether or not the guard tracks its attempt.
Held is an order state. A hold is answered with an OrderUpdate whose status is Held, with the whole quantity remaining, the instant as its timestamp, a reason that names the attempt it waits for (held: waiting for the pending cancellation of order "A" attempt 1 (sell ES)) and no OrderRef; no line is printed. The SDK’s working view keeps the entry as Held (The working view under lifetime v2), so ctx.Flat is false and Exposure lists it, and the oracle counts it. A held order has no broker correlation until its release: no venue id, no ledger reference and no OrderRef, because the live loop allocates the reference when it submits. A crash during a hold therefore leaves nothing at the venue to recover, and the strategy re-decides after the restart. Release re-runs admission serially, in hold order, which is the strategy’s decision order: in this unit that is the path a new order takes to the venue (on a live run the transport scheduler, then the live loop’s attached-order and time-in-force refusals, the ledger record and the venue call), where the admission policy (unit 2) inserts its caps. A release is answered as an admitted order is (Working, Denied with the venue’s reason and its rejection cancel, or SubmissionUnknown), stamped with the instant of the release, or, when the transport scheduler queues it, Held until it is sent (The transport scheduler). Held, like Working, grants no turn: the strategy just submitted that order.
Bounded holds. Holding is a state change, not a wait inside the loop: the held orders are decided again, in hold order, at each observation and after the cancel requests of each step that has any. --lifetime-hold-timeout (RunConfig.LifetimeHoldTimeout, default 5m) bounds a hold: one as old as the timeout is rejected with hold_timeout. The timeout is checked last, so a release decided at the instant a timeout falls due wins. It runs on the run’s event clock, the instants the loops pass (bar closes and, since I12, timer instants), not the wall clock, so a backtest and an emulated-live run of the same bars time out at the same bar; on daily bars a hold that the post-submission poll does not resolve times out at the next bar. The live path is bar-stepped today; the plan’s operational clock for live holds, recorded as a replay input, arrives with a real-time runner. A negative timeout is refused before any spawn (engine: order lifetime v2 needs a hold timeout above zero (0 selects the default 5m0s), got -1s), and a v1 run ignores the flag. At the end of the run every order still held is rejected with hold_shutdown, in hold order, at the last bar’s close, and the rejections are delivered before anything is cancelled: before the backtest’s end-of-data cancellation (and the lifecycle trace’s working-set snapshot) and before the live teardown sweep. On a live run a failure delivering them does not skip the sweep; the first error is returned after it.
Which attempt an event addresses. The guard tracks one attempt per admission or hold, not one per label and attempt number: a top-level X attempt 1 and a bracket child labelled X with attempt 1 are two. An event (a fill or a cancel) or a cancel answer addresses the live attempts with its label and, when it carries one, its attempt number. Among them the one whose venue id (the broker order id of its submission, which a child shares with its parent) equals the event’s wins, a top-level attempt first, then the oldest. With no such candidate, an event whose venue id names an attempt of the label that has already ended addresses nothing, so a confirmed cancel’s echo cannot end the label’s live successor and release what is held behind it; otherwise the top-level candidate wins, then the oldest. The guard remembers the label and venue id of every ended attempt for the rest of the run. "" is no label: an order, a request or an event with an empty label matches no label and addresses no attempt (an unlabelled order still has blockers by symbol and side).
Attached children. The guard tracks each labelled attached child from its parent’s admission or hold, on the child’s own symbol or its parent’s when it names none. A child is held, live and ended with its parent’s admission, release, rejection, withdrawal, confirmed cancel and venue denial; otherwise it ends on its own events, a fill that completes it or any cancel of it, so it outlives its parent’s observed fill or cancel. A live child is its label’s previous attempt and can be a blocker; its own label is not checked when its parent is admitted. Live brackets are refused today, so children matter on a backtest only.
On a continuous run. The guard observes a continuous series’ events in the strategy’s frame: a fill translated onto the logical symbol (a roll leg left out), so its positions and the admission policy’s caps read the symbol the strategy trades, and a roll’s hidden cancels left out. A roll re-keys each attempt it re-places, in place, to the new attempt and broker id, and remembers the old broker id as ended (Order lifetime v2 across a roll). Since I15 unit 2c (GLE-474; engine/contbook.go) the guard books an attempt under the symbol its executions are observed on: an order pinned to a dated contract is filed under the logical symbol of the series whose chain holds the contract (every bar’s and every boundary’s contract, read at the call, so the book cannot change under an attempt: after a roll the outgoing contract is still the series’), and every symbol the guard reads, a query’s included, goes through the same book, so the logical symbol’s exposure, working-order count and blockers count a pinned order, by either name, until its attempt ends. At a roll that end is the roll’s delivered CANCEL_REASON_ROLL cancel, observed as a fill or the strategy’s own cancel is. A logical symbol, a plain symbol and every symbol of a run without continuous series book under themselves. A guard reason names the attempt by its booked symbol (order "pin" attempt 1 (sell fut:XCME:ES) for a sell pinned to ESH26), while the updates and denials the strategy receives keep the order’s own symbol.
The reasons. The guard’s decisions reach the strategy as OrderUpdate events whose Reason begins with a token and ": "; the rest of the text is for people, not for parsing. The SDK exports the tokens (sdk/strategy/raceguard.go):
| Token | SDK constant | Status | Meaning |
|---|---|---|---|
held | GuardHeld | Held | held behind the pending cancellation of an attempt on the same symbol and side, or of the label’s previous attempt; released (Working) once every such attempt has ended without executing |
duplicate_live_label | GuardDuplicateLiveLabel | Denied | the label’s previous attempt is held, or live with no cancellation requested |
cancel_race | GuardCancelRace | Denied | an attempt the order was held behind executed, in whole or in part, while its cancellation was pending |
cancel_refused | GuardCancelRefused | Denied | the venue refused the cancellation the order depended on, and the attempt is still working |
cancel_unknown | GuardCancelUnknown | Denied | the outcome of the cancellation the order depended on is unknown |
hold_timeout | GuardHoldTimeout | Denied | the order was held for the run’s hold timeout |
hold_shutdown | GuardShutdown | Denied | the run ended while the order was held |
hold_corporate_action | GuardCorporateAction | Denied | a corporate action on the order’s instrument cancelled its working orders while the order was held, so it is refused rather than released at its pre-action levels (I14 unit 1; Corporate actions and working orders (lifetime v2)) |
hold_contract_expired | GuardContractExpired | Denied | the order’s dated futures contract expired while the order was held, so it is refused rather than released onto a contract that no longer trades (I14 unit 2a; Contract expiry (lifetime v2)). The text names the attempt’s book, hold_contract_expired: the contract <book> expired while order "<client id>" attempt <n> (<side> <book>) was held; where order-taking ranks share the contract’s chain it names the contract itself, hold_contract_expired: the contract ESM26 expired while order "b1-held" attempt 1 (buy fut:XCME:ES:cont:ofs=B1) was held, and refuses only the attempts pinned to that contract (GLE-491) |
hold_rolled | GuardRolled | Denied | the order names a dated futures contract that a continuous series rolled out of while the order was held, so it is refused rather than released onto a contract the series has left, as the roll cancels the working orders pinned to that contract (GLE-491; Order lifetime v2 across a roll). The text is hold_rolled: the contract <from> left <series> at its roll <from>-><to> while order "<client id>" attempt <n> (<side> <book>) was held, for an unlabelled order hold_rolled: the contract <from> left <series> at its roll <from>-><to> while an unlabelled <side> order on <book> was held: hold_rolled: the contract ESM26 left fut:XCME:ES:cont:ofs=B1 at its roll ESM26->ESU26 while order "b1-held" attempt 1 (buy fut:XCME:ES:cont:ofs=B1) was held, hold_rolled: the contract ESH26 left fut:XCME:ES at its roll ESH26->ESM26 while an unlabelled sell order on fut:XCME:ES was held. It fires at every roll, a lone rank’s included, for each held attempt whose order names the outgoing contract; an attempt on the series’ logical symbol, or pinned to the incoming contract, stays held |
A guard denial carries nothing the venue would have given (no OrderRef, nothing remaining, an empty BrokerCode, which is the venue’s code), and no OrderCancel{Rejected} follows it, since the attempt reached neither the venue nor the ledger; a venue denial is followed by one. The engine’s refusal of an order whose price, stop price or trail amount is not finite (price_not_finite, Returning orders) reaches the strategy the same way, before every check in this table; unlike the guard’s denials it is recorded in the lifecycle trace, as a rejected submit. A strategy that hears denials only through OnCancel therefore does not hear the guard’s. The operator hears the venue denial’s line, here algo: order "B" (ES) from instance ES denied: cancel_race: order "A" attempt 1 (sell ES) executed while its cancellation was pending. Within one step the outcomes are, in order: the cancel responses in request order, then the updates of the held orders the step’s cancels decided, in hold order, then the updates of the step’s own orders; a guard denial among them grants a turn, as a venue denial does. Outcomes decided at an observation or at shutdown are delivered at once on both paths and grant no turn. The run’s order count, the report’s Orders figure, counts the submissions the venue answered: a hold counts nothing until its release, and a guard denial nothing (nor, on a live run, a pacing refusal; The transport scheduler).
The exposure oracle. lifetimeLoop.exposure(symbol) returns an exposureInterval for one symbol: Position, the signed sum of every execution the guard observed on the symbol this run, tracked or not, and on a backtest set to the simulator’s position after each corporate action on the symbol (a corporate action moves a position without a fill; Corporate actions and working orders (lifetime v2)), and Buys and Sells, by side, the remaining quantity (its quantity less its executions, at least 0) of every tracked attempt on the symbol that has not ended: held, working, partially filled, pending cancellation, or a submission whose outcome is unknown. A labelled child counts in full, as a contingent commitment (an OCO pair counts both legs); an unlabelled child is not tracked. An attempt the guard rejected, the venue denied, or that was withdrawn, cancelled or fully filled counts nothing. Low(), Position - Sells, and High(), Position + Buys, are the ends of the interval of positions the symbol can reach. A nil loop (a v1 run) answers the zero interval. The admission policy (unit 2) calls it at the guard’s two admission points, a new order and a release. There is one loop per strategy instance, so an account-level cap sums across instances.
Known limits and follow-ups.
- A parent’s blockers ignore its children’s sides: a buy entry with a sell-stop child is admitted while a sell stop’s cancel is pending, and once the entry fills both sell stops can execute and cross zero. The guard should treat a bracket as blocked by any blocker of its children’s sides, or hold the bracket. This must close before live brackets land.
- Every-exit teardown is I9’s. Only the run’s normal end rejects the held orders, answers what the transport scheduler still queues and sweeps the venue; a host, poll or venue error, or the run’s cancellation, returns without any of them, as before I6. I9’s ownership-aware halt and shutdown ends holds, answers the transport’s queues and runs a best-effort sweep on every exit, and its halt rejects held orders before any cancellation, as
shutdowndoes here. - The lifecycle trace (The order lifecycle trace) does not record guard denials as records; a release is recorded when it is submitted. The one exception is the roll’s
hold_rolledrefusals, listed in itsroll_accountrecord’sheld_refusedand counted by the summary’sroll_held_refusedsince GLE-491. The rest should be added if the trace is to explain every engine refusal. - The desired-order controller does not re-send a cancel whose answer was
Unknown; it waits for the engine’s answer. Since GLE-1363 acancel_unknownrejection blocks the intent only until that cancellation ends, and the unchanged intent then goes out again (The desired-order controller, “Transient blocks”). A re-send whose laterPendinganswer turned the rejections into a hold would shorten the wait. - The guard tracks only the attempts admitted this run: after a restart, adopted orders are not predecessors and their positions are not in the oracle. Recovery (I8 unit 2) must seed both.
- An unlabelled pinned order is tracked until the run ends, as any unlabelled order is: no event can address it.
The rest of I6. Unit 2 is the admission policy (The admission policy): the engine’s deterministic caps at both of the guard’s admission points (working-order counts by owner and instrument that count held, pending-cancel and unknown attempts; maximum quantity; exposure on both ends of the oracle’s interval), the event-time rate budget, their rejection reasons and the configuration surface, the hold timeout’s config key included. Two orders held behind one cancel then cannot together exceed a cap: at release the cap admits them in hold order while they fit. Unit 3a is the transport scheduler (The transport scheduler): pacing on the operational clock (per-attempt FIFO, cancels first, a bounded queue whose overload is visible, and a cancel of a submission not yet sent withdraws it and ends its attempt, as the guard’s withdrawal does for a held one), with conservative, configurable defaults because IBKR’s Web API reference publishes no pacing figures. Unit 3b (GLE-436) is IBKR’s order-reply-message policy (Order reply messages), which replaced the adapter’s blanket confirmed: true with an allow-list of message ids per deployment: any other reply is declined and reaches the strategy as a denial carrying IBKR’s text (reply_declined). Unit 3 does not depend on unit 2. With unit 3b, I6 is complete.
Tests. engine/tournament_guard_spec_test.go (40 tests) drives the guard through runLiveLoop over the scripted venue (the cancel-and-replace that does not cross zero, with no fill, a full fill and a partial fill during the pending cancel; the opposite-side admission; the unacknowledged cancel that times out), over the emulator (a release at the backtest’s bar), through runBarLoop over the simulator, and on the driver over scripted venue operations; engine/raceguard_review_test.go holds the review panel’s gap tests and the tests of its fixes; sdk/strategy/tournament_guard_spec_test.go pins the tokens and the view’s handling of a held order; and cmd/algo/tournament_guard_spec_test.go the flag. Six existing v2 tests were re-pinned for the same-label rule: their second attempt of a label is now the first’s successor in one reply, every addressing assertion kept, and the live-against-backtest comparisons read a held-then-released order as the backtest’s Working one.
The admission policy
Under lifetime v2 an order the race guard admits or holds then passes the engine’s admission policy, and so does a held order when the guard releases it (increment I6 unit 2 of the order-lifetime programme, GLE-430; engine/admission.go, engine/lifeturn.go and sdk/strategy/admission.go). The policy enforces the limits the run configures, each per strategy instance and each off at 0, the default: caps on the working orders, on the quantity of one order and on the position each symbol could reach, and an event-time budget of new orders. It reads the guard and its exposure oracle (The engine race guard) and changes neither. Its decisions are a function of the event inputs (the strategy’s orders, the cancel answers, the executions and their instants), so it decides alike on the plain backtest and the emulated-live path. A v1 run has no driver and no policy, and refuses a limit (below).
The caps. Each applies per strategy instance, and 0 turns it off:
| Flag | LifetimeLimits field | What it limits |
|---|---|---|
--max-working-orders N | MaxWorkingOrders | the instance’s working orders: every attempt the guard tracks that has not ended (held, working, partially filled, pending a cancellation, or a submission whose outcome is unknown), each labelled attached child one |
--max-symbol-working-orders N | MaxSymbolWorkingOrders | the same count on each symbol the order’s legs are on |
--max-order-quantity Q | MaxOrderQuantity | the quantity of the order and of each attached order, labelled or not |
--max-position Q | MaxPosition | on each symbol the order’s legs are on, the exposure oracle’s interval with the order added: the positions the symbol could reach if every working and held order executed, checked only at the end the order extends |
An order brings one leg for itself and one for each labelled attached child, on the child’s symbol or its parent’s when it names none; on a continuous run each leg’s symbol is the guard’s book of it, so a leg on a dated contract of a series’ chain counts on the series’ logical symbol (The engine race guard, since I15 unit 2c). An attempt that has ended (filled in full, cancelled, denied by the venue, rejected or withdrawn) counts nothing. The guard does not track an unlabelled attached child, so it adds no working order and no exposure; its quantity is still checked.
Only the end the order extends. max-position checks the high end, Position + Buys, against the limit when the order’s legs add a buy on the symbol, and the low end, Position - Sells, against minus the limit when they add a sell; an order with legs on both sides is checked at both, the high end first. A reducing order therefore passes: a sell is admitted while the high end is past the limit, and a buy while the low end is. An end can already be past the limit when executions the guard does not track have moved the position (an order adopted after a restart, I8); an exposure refusal then says so (below).
Held orders count. Every cap counts held orders. The base of each count, and of each interval, is every attempt the guard tracks that has not ended, held ones and those with a cancellation pending included (a pending-cancel attempt can still execute), and the new order’s legs are added to it. An order the guard is about to hold is checked without the attempts it is held behind: the live attempts whose cancellation is pending on its symbol and side, or under its label (their attached children still count). The guard releases it only after they have ended with nothing executed, and an execution of one rejects it, so the two cannot both execute. This is what keeps simulation and emulation in parity: the simulator’s synchronous cancel has already ended the predecessor when the backtest admits the replacement, and the live run, which holds the replacement, decides it as if the predecessor had ended. It also lets a strategy at a working-order cap move a stop on a live run without a spare slot.
A release is re-checked. When the guard releases a held order, the policy runs the caps again in the original decision order, which is hold order. The orders released before it in the same pass are live and count, and so do the held orders before it that stay held; the held orders after it, decided after it, are left out with their children. The released order counts with its children that have not ended, each at its remaining quantity. Two orders held behind one cancel therefore cannot together exceed a cap. The second is refused as it is held when the two would not fit; when the state moved while they were held (an execution the guard does not track), the release admits them in hold order while they fit and refuses the first that does not. While an order after it stays held, the interval projected with every held order can briefly pass a cap; its own release re-checks it, so what reaches the venue stays within the caps. A held order the policy refuses at its release ends with its children and does not reach the venue.
Brackets. A labelled child counts in full on its own side, as the oracle counts it: it is a contingent commitment, and both children of an OCO pair are reserved. A bracket’s children can execute only after its entry has, but the policy does not net them against it, so a buy entry of 5 with a take-profit and a stop of 5 each takes a flat position’s low end to -10. A symmetric bracket therefore needs a max-position of at least twice its child side. The plan does not discount OCO alternatives without a verified guarantee; netting a bracket’s children against its own entry is a follow-up.
Unlabelled orders. The guard tracks an order with an empty ClientID until the run ends, because no event can address it, so an unlabelled order holds a working slot for the rest of the run. The Go SDK labels every order and child it sends; only a strategy that writes the pb wire itself can send one. The first unlabelled order the policy accepts while max-working-orders or max-symbol-working-orders is set writes one line to stderr, once per run:
algo: note: an unlabelled order counts against the working-order limits until the run ends (no event can end it); give every order a ClientID
A refused order writes nothing, and the order itself is unaffected.
The rate budget. --max-submissions N with --submission-window D, set together, allows N new orders in any window D of event time. Each order the policy accepts, admitted or held, takes a place at its instant, the bar close the driver passes (every turn at one instant shares it); a bracket is one place. An order is refused when N places are less than one window old, so a place exactly one window old has left the window. An order the guard or a cap refuses takes no place; a held order keeps its place whether it is later released, refused or withdrawn; a release takes no place and is not refused by the budget. Cancel requests are not limited: a budget must not block flattening, and a burst of cancels is the transport scheduler’s to absorb on a live run, which paces them ahead of every submission and refuses none for overload (The transport scheduler). Because the places are taken at the strategy’s decisions, the moment the venue resolves a cancellation does not move the budget. The policy keeps at most N places and grows that store with the orders it accepts, not with N.
The reasons. A policy refusal reaches the strategy as a guard denial does (The engine race guard): an OrderUpdate with status Denied, the order’s quantity, nothing remaining, the instant as its timestamp, no OrderRef and no OrderCancel{Rejected} after it, and a Reason that begins with a token and ": ". It is ordered, delivered and granted a turn as a guard denial is, makes no venue call (so the report’s Orders figure does not count it), and prints the operator’s denial line, here algo: order "B" (AAPL) from instance AAPL denied: cap_quantity: quantity 11 exceeds the limit of 10 per order. The SDK exports the tokens as algolang.Policy* constants (sdk/strategy/admission.go):
| Token | SDK constant | Reason (Go format) |
|---|---|---|
cap_quantity | PolicyQuantity | cap_quantity: quantity %d exceeds the limit of %d per order |
cap_working_orders | PolicyWorkingOrders | cap_working_orders: %d working orders with this one, above the limit of %d |
cap_symbol_working_orders | PolicySymbolWorkingOrders | cap_symbol_working_orders: %d working orders on %s with this one, above the limit of %d |
cap_exposure | PolicyExposure | cap_exposure: the position on %s could reach %d with this order, beyond the limit of %d |
rate_budget | PolicyRateBudget | rate_budget: the budget of %d submissions per %s is used up |
At the low end an exposure reason names the negative reach and minus the limit (cap_exposure: the position on AAPL could reach -13 with this order, beyond the limit of -10). When the end it refuses at was already past the limit before the order’s legs were added (the base interval, less any attempts the order is held behind), the reason ends with ; it could already reach N without it: cap_exposure: the position on AAPL could reach 19 with this order, beyond the limit of 10; it could already reach 18 without it. On a continuous run a per-symbol reason names the booked symbol, the logical one, for an order pinned to a dated contract too (cap_exposure: the position on fut:XCME:ES could reach 4 with this order, beyond the limit of 3). The budget prints its window as a Go duration (rate_budget: the budget of 3 submissions per 2m0s is used up).
Precedence. The guard decides first, so its own refusals (duplicate_live_label, cancel_refused, cancel_unknown) come before any of the policy’s, and an order the guard would hold can be refused by the policy instead. Then the first check that fails decides, in this order: quantity, the instance’s working orders, each symbol’s working orders (the legs’ symbols in the order they first appear, the order’s own first), exposure (the same symbols, the high end first), the budget. A release is checked only once the guard has decided to release it (cancel_race, cancel_refused, cancel_unknown and hold_timeout stay the guard’s), from quantity to exposure; the budget does not apply.
Saturating arithmetic. The exposure sums saturate at the bounds of int64 instead of wrapping: the legs’ quantities by side, and the reaches Position + Buys and Position - Sells. A bracket whose two sell children of 1<<62 each sum past the largest int64 therefore reaches the bound and is refused, where a wrapped sum would have turned negative and skipped the low-end check. Whether the legs add a buy or a sell is read from the legs themselves, not from the sign of a sum.
Configuration. Six algo run flags set RunConfig.LifetimeLimits (engine.LifetimeLimits): --max-working-orders, --max-symbol-working-orders, --max-order-quantity, --max-position, --max-submissions and --submission-window (algo run flags). They are single-run flags, refused with --config like the others. In a run-config file they are data keys of the same names (Config files and run matrices), beside lifetime, lifetime-turns and lifetime-hold-timeout, which mirror --lifetime, --lifetime-turns and --lifetime-hold-timeout and had no config key before this unit:
"data": {
"adapter": "bin/file-csv-adapter",
"lifetime": "v2",
"lifetime-hold-timeout": "90s",
"max-working-orders": 8,
"max-position": 10,
"max-submissions": 20,
"submission-window": "1m"
}Each key may be set at any level (global, a strategies entry, a run): a key not set inherits, and an explicit 0 overrides an outer level’s value. Numbers must be whole JSON numbers (a quoted "4" is refused, naming the key) and durations Go duration strings such as "90s"; lifetime takes v1 or v2, and absent at every level it is the default, v2 for a backtest and v1 for a live run (GLE-470). Each run’s lifetime settings are checked as the plan is built, so a bad value stops algo run --config, and --verify before it prints the plan. The refusals, made before any spawn:
- a negative limit, naming its key:
engine: the admission limit max-position must not be negative (0 = no limit), got -1; - a budget whose count and window are not set together:
engine: the admission limit max-submissions needs a submission-window above zero, or the same forsubmission-windowwithoutmax-submissions; - any limit on a v1 run, under
--lifetime v1or on a live run that names no profile (a backtest that names none is v2, and its limits apply):engine: the admission limits need order lifetime v2 (--lifetime v2); a v1 run has no admission policy. A v1 run ignores--lifetime-turnsand--lifetime-hold-timeout, but a safety rail that silently did nothing would be the worse failure, so a limit is refused.
The defaults are off. With every limit at 0 the policy accepts every order and keeps no state, so a v1 run, a v2 run without limits and the KBD masters are byte-identical to before.
Simulation and emulation. The two paths can give the policy different inputs. The simulator confirms a cancel at once, while a live venue, the emulator included, answers Pending, and a pending-cancel attempt still counts. So an opposite-side order in the same step as the cancel counts the pending attempt on the live run but not in the backtest, and can be refused only live. That is consistent, since the inputs differ. A same-side replacement is held on the live run and checked without the attempt it waits for, so it is decided as the backtest decides it: an emulated-live run with a symbol cap, an exposure cap and a budget configured makes the backtest’s refusals, with the same texts, fills, cash and positions.
Per instance. There is one driver, one guard and one policy per strategy instance, so every limit counts one instance’s orders. Under owner decision D4 the programme runs one instance per account, so per instance is per account in its scope; summing instances that share an account is the account execution coordinator’s, GLE-360. One value of each cap applies to every symbol; per-symbol values are a follow-up.
The halt latch is I9’s. The plan’s safety rails also latch a halt when existing exposure already breaches a limit. This unit refuses the order and latches nothing: a latch must survive a restart (I7 and I8’s ledger and recovery), its response (reject the held orders, cancel entries, keep verified protection, keep observing fills) is I9’s ownership-aware halt, and its trigger, a position already past the limit, comes from executions the guard does not track, which are recovery’s (I8). The ; it could already reach N without it suffix makes that trigger visible now; owner decision D10 is re-checked at I9.
The index. The policy reads the oracle and the counts on every submission, so the guard now indexes the attempts it tracks, and those with a cancellation outstanding, by symbol, with a running count for the instance: exposure and the blocker check read one symbol’s attempts and the label’s, and removing an attempt from its symbol’s set takes constant time. Blockers are still named in the order they entered their cancellation state.
Known limits and follow-ups.
- Releasing a hold queue is quadratic in its length, since each release walks the held orders after it. Deferred: a hold queue is the same-side orders behind one pending cancel in one instance, a handful in practice, and a working-order cap bounds it; a running tally is a contained fix if a profile asks for one.
observescans the hold queue on each fill of an attempt whose cancellation is pending (unit 1’s code), under the same bound.- A bracket’s children are not netted against its entry, and each cap has one value for every symbol (above).
- The lifecycle trace does not record policy denials, as it does not record the guard’s.
- Refusing unlabelled orders outright under a working-order cap would change the contract; the note is the warning instead.
Unit 3. Unit 3a, the transport scheduler, follows (The transport scheduler): pacing on the operational clock, cancels first. Unit 3b, IBKR’s order-reply-message policy (GLE-436), replaced the blanket confirmation of every IBKR order warning with an allow-list of message ids per deployment (Order reply messages).
Tests. engine/admission_tournament_spec_test.go (22 tests) drives the policy on the driver over scripted venue operations (each cap at admission and at release, the held-order projection, the release order, the budget’s window and places, the precedence, the exact reasons, the note, and the index’s timing), through runLiveLoop over the scripted venue (two held orders behind one cancel), through runBarLoop over the simulator, against the emulator (the same refusals on both paths), and end to end through engine.Run and a run-config plan; engine/admission_review_test.go holds the review panel’s gap tests and the saturation test; and engine/runconfig, sdk/strategy and cmd/algo each pin the keys, the tokens and the flags in a tournament_admission_spec_test.go.
The transport scheduler
Under --lifetime v2 a live run sends its submissions and cancel requests to the venue through the engine’s transport scheduler (increment I6 unit 3a of the order-lifetime programme, GLE-435; engine/transport.go, engine/lifeturn.go and sdk/strategy/transport.go). The race guard and the admission policy decide whether an order may go to the venue; the scheduler decides when. It paces the requests to a configured number per window, queues what the window does not cover in two first-in first-out queues, every cancel request ahead of every submission, bounds the submission queue and refuses what does not fit, and sends again a request the venue refused for pacing. It changes when an admitted request reaches the venue, not what was decided, and every effect it has on the strategy is in the event stream: Held updates with the transport_queued reason, and late updates and responses. A backtest has no venue transport and no scheduler, and a v1 run has no driver, so both are unchanged and the KBD masters are byte-identical.
What is paced, and on which clock. A request is one call to the venue: a submission, whether a new order the guard admits or a held order it releases, a cancel request that does not address a guard-held order (one that does withdraws that order without reaching the venue, as before), or an in-place modification (below). At most --transport-requests requests (default 5), of every kind together, are sent within any --transport-window (default 1s), and each call counts at its instant whatever the answer. The window is the half-open interval (now - window, now], so a request sent at t no longer counts at t + window. The clock is the run’s operational clock, the instants the driver passes, and nothing else. On today’s live loop the venue is stepped one bar per iteration and every instant is a bar’s close or, since I12, a timer’s (Scheduled decision points), so the scheduler reads no wall clock: an emulated or scripted run is deterministic, and its event history and venue answers reproduce every decision the scheduler made. This window is not the admission policy’s rate_budget, which counts new orders at the strategy’s decisions in event time and is decided first.
Per bar on the stepped loop. With a window no longer than the bar interval, “N requests per window” means N per bar observation: the requests at one bar’s close (its observations, its decision and its turns) share the N, and a request queued at a bar waits for the next observation: the next bar’s, or the post-submission poll of a timer’s decision before it. At the default a full queue of 100 submissions drains in 20 bars, and a burst of 50 cancel requests in 10. An emulated v2 run that sends more than five requests at one bar therefore queues the excess to the next bar and diverges from its backtest; no golden does, since the masters are v1 runs. A real-time loop, not built yet, will pass the wall clock and dispatch between bars.
Order. Dispatch sends every queued cancel request in arrival order, then every queued submission in arrival order. Nothing overtakes a queued request of its own kind, and no submission overtakes a queued cancel request: a new cancel request is sent at once only when no cancel request is queued, and a new submission only when nothing is queued, each when the window allows; otherwise it joins the end of its queue, even when the window has room. So an attempt’s submission reaches the venue before any cancel request for it, since a request for a submission still queued withdraws it (below) rather than overtaking it.
Cancel requests. A cancel request goes through the window as a submission does, ahead of every submission, and is not refused for overload: the cancel queue has no bound of its own. Pacing them keeps a burst under the venue’s limit; unpaced, a burst beyond it could draw pacing refusals and a block that stops every request, polls included. A request for attempt 0 is pinned on arrival to the label’s latest submission sent to the venue (the attempt the venue operations would address now) and keeps that attempt while it waits. A request for the label and pinned attempt of a cancel request already queued joins it: nothing more is queued or sent, and when the queued request is answered each request that joined it gets the same answer under its own request id, in the order they joined. Joining keeps the cancel queue to one request per distinct label and attempt, and absorbs a strategy that cancels again at every turn.
Modifications (GLE-1436). An in-place modification (Replacing in place) is one request in the window, a call of the venue’s ModifyOrder. A venue that cannot modify the order (sim.ErrModifyNotSupported, as the IBKR adapter answers for an order it cannot modify) takes no place in the window, since nothing reached it. A modification the window cannot take now waits in the cancel-request queue, as the cancel request it answers, pinned to the predecessor’s attempt. The predecessor is marked pending cancellation, the successor is Held behind the modification, and nothing reaches the venue until dispatch reaches it. While it waits:
- a newer successor replaces its terms (the latest wins);
- a withdrawal of the successor turns it into the predecessor’s cancel request, in its place;
- a cancel request for the predecessor joins it and shares its answer;
- an execution that ends the predecessor removes it.
Once dequeued, it is sent and answered as a direct one is. If it is refused then, or the venue cannot modify the order, the cancel request it answers takes its turn at the head of the queue.
Withdrawal. A cancel request for a submission still queued, under its label and with its attempt or attempt 0 (the first such submission in queue order), withdraws it as the guard withdraws a held order: nothing reaches the venue, the attempt ends with its children, and the response is Confirmed with the status Cancelled, the whole quantity remaining, the instant as its timestamp and no OrderRef. It grants a turn.
A queued submission is held. A submission that cannot be sent at once is queued and answered with an OrderUpdate whose status is Held, with the whole quantity remaining, the instant as its timestamp, no OrderRef and the reason transport_queued: waiting for the venue transport (5 requests per 1s); like the guard’s Held, it grants no turn. While it waits the attempt is live with no venue id, reserved as an unknown submission is: the exposure oracle and the admission policy’s caps count it, the guard treats it as its label’s previous attempt, and the SDK’s working view keeps it Held. Once sent it is answered as a direct submission is (Working, Denied with the venue’s reason and its rejection cancel, or SubmissionUnknown), stamped with the instant it was sent. A held order the guard releases goes through the scheduler too, so it can be Held twice, behind a cancellation and then behind the window, before it is Working. No time limit applies: the guard’s hold timeout does not cover a queued submission, which waits until it is sent, withdrawn or refused at the end of the run, and the strategy, which sees it Held, can cancel it.
The queue bound. A submission that cannot be sent at once and finds --transport-queue submissions (default 100) or more already queued is refused: Denied with the reason transport_overload: the transport queue already holds 100 submissions, whose number is the queue’s length, and its attempt ends with its children. The operator hears the denial line, and the denial grants a turn as a guard denial does. The bound applies to a new arrival only: a submission the venue refused for pacing returns to the queue whatever the bound, and queued cancel requests do not count toward it.
Pacing refusals. A venue answer can be a pacing refusal: the venue refused the request for its rate limit without processing it, so the order is as it was and the request may be sent again. The venue marks such an answer Paced (a Denied sim.SubmitResult or a Refused sim.CancelResult): the scripted venue marks its Pacing refusals (The scripted venue) and the IBKR adapter an HTTP 429 on the place or the cancel endpoint (Tickets and cancels at the IBKR venue) and, since I6 unit 3b, on the confirmation of an order reply message (Order reply messages). A submission whose confirmation was refused for pacing is sent again as a whole: a new place call, which draws the reply again, and a new conversation. A pacing refusal pauses the transport for one window: nothing is sent before the refusal’s instant plus the window, cancel requests included. The refused request goes to, or stays at, the head of its queue, the observation stops there, and the request is the first sent when the transport allows. A submission refused for pacing when it was sent at once is answered Held, with no rejection cancel: transport_queued: the venue refused it for pacing (venuetest: pacing refusal); it is sent again when the transport allows. Each time a submission is refused for pacing, the live operations close, in the ledger, the reference it was sent under, and the retry goes under a new reference. A cancel request refused for pacing gets no response yet and waits at the head of the cancel queue. The report’s Orders figure counts the submissions the venue answered: a queued submission counts when it is sent, and a pacing refusal, an overload or a withdrawal counts nothing.
A queued cancel request. A queued cancel request is answered once, when it is sent, with the venue’s answer stamped with that instant; there is no interim response, so the response can come bars after the request. The SDK’s view shows the attempt pending cancellation from the request, and the race guard treats it as pending too: when the guard finds a live attempt for the pinned label and attempt with no cancellation outstanding, queueing the request marks it pending, so a same-side order, or the label’s successor, is held behind it rather than admitted or refused as a duplicate. An attempt already pending, unknown or refused is left as it is. When the request is sent, its mark is withdrawn first and the guard records the venue’s answer as it records a direct one: an unknown answer, or a refusal without evidence, then rejects the orders held behind it (cancel_unknown, cancel_refused) rather than leaving them held behind a mark. A request refused for pacing keeps its mark while it waits. A queued request is sent even when its attempt ended while it waited (filled, say), and the venue’s answer is delivered as any answer is.
The observation. The live loop’s observation (“Where the loops observe” under The engine race guard) hands the poll’s batch to the guard, then the scheduler sends what it queued as its window allows, then the guard decides its held orders, so a cancel sent at the observation can release an order held behind it there. The transport’s outcomes are delivered first, at once and with no turn; the submissions the venue answered add to the run’s order count, and the rejection cancels of those it denied are queued for the next bar, as a release’s are. The observation now ends the guard’s step: a refusal recorded there lasts until the observation ends, as a direct refusal lasts until its step ends, so a same-side replacement the strategy places at its next decision is an ordinary submission. A run without a scheduler records no refusal at an observation, so this changes nothing there.
Shutdown. At the end of the run the driver rejects the guard’s held orders (hold_shutdown), then answers what the scheduler still queues, and delivers all of it at once, with no turn, before the teardown cancels anything at the venue. Each queued submission is refused, in queue order, and its attempt ends: transport_shutdown: the run ended while order "B" attempt 1 (buy AAPL) was queued for the venue. Then each queued cancel request, followed by each request that joined it, is answered Unknown without reaching the venue, so every cancel request gets its one response: transport_shutdown: the run ended while this cancel request for order "A" attempt 1 was queued for the venue, naming the attempt pinned when it was queued. A modification still queued answers its cancel request in the same way and refuses its successor: transport_shutdown: the run ended while the modification of order "S" attempt 1 (sell AAPL) was queued for the venue. The operator hears the denial line of each refusal and the unresolved-cancel line of each answer. The teardown sweep that follows cancels whatever is working at the venue (Tickets and cancels at the IBKR venue).
The operator line and the counters. When any request was queued, refused for pacing or refused for overload over the run, the shutdown writes one line to stderr with the scheduler’s counters. An emulated run whose strategy places seven orders at one bar ends, at the defaults, with
algo: transport for instance AAPL: 7 request(s) sent, 2 queued (at most 2 at once), 0 pacing refusal(s), 0 withdrawn, 0 refused for overload
| Counter | Counts |
|---|---|
| request(s) sent | every call to the venue the scheduler made, pacing refusals and errors included |
| queued | every request that had to wait, once, when it first entered a queue (queued, or refused for pacing when sent at once); a request that joined another is not counted |
| at most N at once | the largest number of requests in the two queues together, right after one entered |
| pacing refusal(s) | every pacing refusal |
| withdrawn | every queued submission a cancel request removed |
| refused for overload | every submission refused because the queue was full |
The counters reach neither the run’s summary nor result.json yet.
The reasons. The scheduler’s decisions reach the strategy as OrderUpdate events, and its shutdown answers as CancelResponse events, whose Reason begins with a token and ": "; the rest of the text is for people, not for parsing. The SDK exports the tokens (sdk/strategy/transport.go):
| Token | SDK constant | Where | Meaning |
|---|---|---|---|
transport_queued | TransportQueued | Held update | the submission is queued for the venue, behind the window (waiting for the venue transport (N requests per D)) or after the venue refused it for pacing; released (Working, Denied or SubmissionUnknown) when it is sent |
transport_overload | TransportOverload | Denied update | the submission queue already held the run’s maximum |
transport_shutdown | TransportShutdown | Denied update, or a CancelResponse with outcome Unknown | the run ended while the submission, or the cancel request, was queued |
A transport denial carries what a guard denial carries (The engine race guard): the order’s quantity, nothing remaining, the instant as its timestamp, no OrderRef, an empty BrokerCode, and no OrderCancel{Rejected} after it.
Configuration. Three algo run flags set RunConfig.TransportLimits (engine.TransportLimits): --transport-requests, --transport-window and --transport-queue (algo run flags). Each 0 selects its default (5, 1s, 100), so every live v2 run has a scheduler. They are single-run flags, refused with --config like the others. In a run-config file they are data keys of the same names, set at any level as the admission policy’s keys are (The admission policy):
"data": {
"adapter": "bin/file-csv-adapter",
"lifetime": "v2",
"transport-requests": 4,
"transport-window": "2s",
"transport-queue": 50
}They are lifetime-v2 only. A v1 run, under --lifetime v1 or a live run that names no profile, has no scheduler and refuses any transport limit before any spawn (engine: the transport limits need order lifetime v2 (--lifetime v2); a v1 run has no transport scheduler), and a negative value is refused naming its key and default (engine: the transport limit transport-queue must not be negative (0 = the default 100), got -1); a run-config file’s values are checked as the plan is built. A v2 backtest accepts the limits and ignores them, since it has no venue transport, so one config file that names "lifetime": "v2", as above, serves both modes and the backtest is unaffected.
Recorded assumptions. The unit rests on three, stated here as assumptions until they are checked:
- IBKR’s pacing limits are not in its Web API reference (searched for “pacing”, “rate limit”, “429”, “Too Many Requests” and “throttling”), so the defaults are conservative and configurable: five requests per second, 100 queued submissions and a one-window pause after a pacing refusal. Figures recalled from memory rather than from the reference, about ten requests per second overall with stricter limits on some endpoints, leave room for what this unit does not pace: the polls, IBKR’s reply hops, the teardown sweep and the reconciler’s queries. IBKR’s pacing page or a paper-account probe should confirm them.
- An HTTP 429, on the place call or, since I6 unit 3b, on the confirmation of an order reply message, is read as IBKR’s rate limiter refusing the request before it was processed, so the scheduler sends the order again under a new ledger reference and closes the refused one. Were the reading wrong (IBKR created the order), the broker would hold two orders: the ledger would apply the first one’s fills under the strategy’s label, the race guard would credit them to the retry, and the run would not stop on its own. A paper-account probe of IBKR’s 429 is therefore a gate before live trading; after it, either a paced retry reuses its reference, so IBKR’s cOID uniqueness refuses a duplicate, or the run fails closed on any fill or open order under a closed paced reference.
- A v1 run has no scheduler, and it now hears an IBKR 429 on a submission, or on a confirmation since unit 3b, as a denial (the operator’s denial line and a rejection cancel before the next bar) where it heard an unknown submission left to reconciliation. v1 live runs only against the emulator today, which does not pace, so no output moves; the same probe gates it.
Known limits and follow-ups.
- Every-exit teardown is I9’s. Only the run’s normal end answers the queues: a poll, observation or instant error returns before that, as it returns before the guard’s shutdown rejections and the venue sweep. A queued submission was not sent, so nothing of it rests at the venue, but its shutdown denial is lost. I9’s every-exit teardown must call the scheduler’s shutdown (
transportShutdown) too. - Joining a cancel request scans the cancel queue, and removing a queued request copies the rest of its queue down, so a burst of joins and a drain are each quadratic in the queue’s length. The queues are small today (the cancel queue holds one request per distinct label and attempt, tens on today’s strategies, and the submission queue at most
transport-queue, 100 by default), buttransport-queuehas no upper bound: an index keyed by label and attempt for the join, and a cap or a head index for the submission queue, are follow-ups. - The scheduler keeps each label’s latest attempt for the rest of the run, one entry per label, as the live attempt map does (Lifecycle turns); evicting a label the guard has dropped is a follow-up.
- The live loop is stepped, so a queued request waits a bar. A real-time loop must pass the wall clock and dispatch between bars.
- The pause is one fixed window. A pause taken from
Retry-After, or an exponential back-off, follows the probe, since retrying at every window may extend IBKR’s block. - A queued submission has no time limit (above); one is a follow-up.
- The counters reach stderr only; adding them to the run’s summary or
result.jsonis a follow-up. - The scheduler is per run. A future multi-instance live run on one gateway must share one scheduler.
Tests. engine/aa_transport_tournament_spec_test.go (38 tests) drives the scheduler through runLiveLoop over the scripted venue (the window, cancels first, a withdrawal, a paced submission and a paced cancel, the overload, the shutdown), on the driver over scripted venue operations at chosen instants (the window’s boundary, the pause, the head kept at a paced dispatch, no overtaking, the mark and the join, a release through the transport, the counters, dispatch errors), and end to end through engine.Run against the emulator at the defaults; engine/transport_review_test.go holds the review panel’s seven gap tests; and a tournament_transport_spec_test.go in each of engine/venueibkr, engine/venuetest, engine/runconfig, sdk/strategy and cmd/algo pins, in turn, the 429 classification, the Paced mark, the keys, the tokens with the view’s handling of the transport’s updates, and the flags.
Scheduled decision points (timers)
Under lifetime v2 a strategy can ask for a decision at an instant of its own choosing, between bars if need be (increment I12 of the order-lifetime programme: unit 1, the engine’s scheduler, GLE-448, in engine/timers.go, engine/timerhost.go, engine/lifeturn.go and engine/sim/instant.go; unit 2, the Go SDK’s surface, GLE-451, in sdk/strategy/timers.go). It arms a one-shot timer for the instant, and at that instant the engine sends it a TimerFired, which it answers as it answers a bar. A deadline cancellation then does not wait for the next bar of the order’s symbol, and no data after the deadline is matched against the cancelled order. Timers run on the plain backtest, the emulated-live path and, since I15 unit 2c (GLE-474, 2026-10-09), the simulated continuous run (below, and Order lifetime v2 across a roll). A v1 run schedules nothing and refuses a timer envelope as before, so it is byte-identical, and the KBD masters are unchanged.
From a Go strategy. The SDK gives a strategy three Context methods that arm and disarm timers, two optional handlers and a staleness helper:
func (c *Context) ArmTimer(id string, at time.Time) error
func (c *Context) ArmSessionTimer(id, symbol string, kinds Boundary, offset time.Duration) (time.Time, error)
func (c *Context) CancelTimer(id string) error
func (c *Context) DataAge(seriesID string) (time.Duration, bool)
type TimerHandler interface {
OnTimer(ctx *Context, t TimerFired) ([]Order, error)
}
type TimerRefusalHandler interface {
OnTimerRefused(ctx *Context, r TimerRefused)
}ctx.ArmTimer(id, at) arms the one-shot timer id for the instant at, and ctx.CancelTimer(id) disarms it; arming an id that is armed replaces the timer when the engine admits the new arm. The SDK checks neither the id nor the instant. An empty id, a zero instant, an instant not after the decision or one after the run’s end goes to the engine as given, and the engine refuses it under the rules below, so every refusal reaches the strategy by one path, OnTimerRefused, with the engine’s code and text. The SDK keeps no view of the armed timers: the engine does not acknowledge an admitted arm, and a refused re-arm leaves the earlier arming in place, so a strategy keeps its own book from what it armed, OnTimer and OnTimerRefused.
The reply a command rides. The methods queue, and nothing goes out at the call. The queued commands go out with the reply to the current decision (a bar, a lifecycle turn or a timer’s), after its cancel requests and before its OrderResponse, in issue order, which is the order the engine applies them in. A command issued outside a decision, in OnInit, OnCalendar or an observer such as OnFill or OnTimerRefused, waits for the next decision’s reply. The warm-up reply and a late bar’s carry none, since the engine refuses a timer command in the first and the second answers no decision; queued cancel requests still go out with both, as before. An ArmTimer in OnInit therefore reaches the engine with the first main bar’s reply, and an instant at or before that bar’s close is refused timer_not_future (see Warm-up, below).
The session helper. ctx.ArmSessionTimer(id, symbol, kinds, offset) arms id at the first instant b + offset strictly after ctx.Now(), where b is a boundary of one of kinds on the exchange calendar of symbol (the Boundary bits of NextBoundary, such as BoundaryRTHClose; Strategy SDK lookups), and returns the instant in UTC, so the strategy can log or keep it. It searches with NextBoundary(Now - offset, kinds) and adds the offset back. A negative offset arms ahead of the boundary (“five minutes before the RTH close”), and a boundary whose shifted instant is not after Now is passed over for the next one; a positive offset arms after the boundary, and can take one that passed less than offset ago. With RTH windows of [13:30Z, 21:00Z) on 2026-03-30 and 2026-03-31, at Now = 2026-03-30T14:01Z:
kinds, offset | The search starts at | The timer is armed at |
|---|---|---|
BoundaryRTHClose, 0 | 2026-03-30T14:01Z | 2026-03-30T21:00Z |
BoundaryRTHClose, -5m | 2026-03-30T14:06Z | 2026-03-30T20:55Z |
BoundaryRTHClose, -7h | 2026-03-30T21:01Z | 2026-03-31T14:00Z |
BoundaryRTHOpen, +45m | 2026-03-30T13:16Z | 2026-03-30T14:15Z |
The helper sets the arm’s anchor to symbol as given (the engine maps it to its calendar root), so the engine admits the timer only when that calendar is complete from the decision to the instant (rule 5 below). It does not call Complete itself: admission follows the run’s own calendar-accept-unverified list, which the SDK does not know. It reads the calendar the engine pushed, so the strategy must ask for one (CalendarRequirer or CalendarObserver). It fails with the zero time, and queues nothing, when the run cannot carry timers (ErrTimersUnavailable, below), when no calendar serves the symbol’s root:
algolang: ArmSessionTimer("nq"): no exchange calendar serves "fut:XCME:NQ:M26"; a session timer needs its anchor's calendar (implement CalendarObserver or CalendarRequirer)
and when the calendar places no boundary of kinds after the search’s start, Now less the offset, with kinds printed as the number passed:
algolang: ArmSessionTimer("unknown"): the calendar of "fut:XCME:ES:M26" places no boundary of kinds 1 after 2026-04-07T21:00:00.000000000Z
There the search reached a trade date the calendar does not know, which NextBoundary answers with no boundary rather than skip it. The helper needs a decision instant. NextBoundary has no answer before the first served span either, and before the first bar, in OnInit and OnCalendar, ctx.Now() is the zero time, so the helper fails there (... after 0001-01-01T00:00:00.000000000Z with a zero offset), as it does when a positive offset puts the search before the first span. ArmTimer and CancelTimer work in those hooks. A strategy that wants a session timer from the start arms it at its first bar, as the demo below does.
Deciding at a timer. A strategy that implements TimerHandler gets OnTimer(ctx, t) at each timer it armed: t.ID, t.At, the instant armed, and t.FiredAt, the decision’s instant (equal to At on both stepped loops; a zero time stands for an instant the wire did not carry). The SDK answers it as it answers OnBar: the queued cancel requests, then the queued timer commands, then an OrderResponse carrying the returned orders, labelled (a blank ClientID becomes an automatic one) and tracked at FiredAt, each with its attempt stamped. A strategy without the handler answers every timer with an empty response, its queued commands still included. An OnTimer error ends the run as an OnBar error does (strategy_error; Run returns algolang: OnTimer: <err>).
What a timer’s decision shows. Before OnTimer runs, and whether or not the strategy has it, the SDK moves ctx.Now() to FiredAt (not At) and recomputes each series’ Fresh, which is true only when the series’ newest bar closed at FiredAt; at a timer between bars no series is fresh. Nothing else moves: no bar is appended, the series and ctx.BarCount are as the last bar left them, the account is not pushed again, and the working view holds every outcome delivered so far. ctx.DataAge(seriesID) gives the staleness: ctx.Now() less the CloseTime of the series’ newest bar, and true, the series keyed as ctx.Series keys it (the bars’ SeriesID, else their Symbol); 0, false when the Context holds no such series or the series holds no bar. It is 0 at a bar of the series, and it is not clamped. A lifecycle turn moves ctx.Now() but does not recompute Fresh. That is harmless: a turn shares its decision’s instant, so the flags that decision set still hold.
Hearing a refusal. A strategy that implements TimerRefusalHandler gets OnTimerRefused(ctx, r) for each TimerRefused, at the arm or at the timer’s instant: r.ID and r.At as armed (At is zero when the arm had none), r.Code, r.Reason (the engine’s text, which starts with the code) and r.Timestamp, the arming decision’s instant or, for timer_coarse, the timer’s own. The codes are constants:
| Constant | Code | Refused |
|---|---|---|
TimerRefusalInvalid | timer_invalid | at the arm: an empty id or no instant |
TimerRefusalNotFuture | timer_not_future | at the arm: an instant not after the decision |
TimerRefusalAfterEnd | timer_after_end | at the arm: an instant after the run’s end |
TimerRefusalCalendarIncomplete | calendar_incomplete | at the arm: an anchored timer whose calendar is not complete up to its instant |
TimerRefusalLimit | timer_limit | at the arm: a new id while 4096 timers are armed |
TimerRefusalCoarse | timer_coarse | at the instant: the bars are too coarse to decide there (coarse bars, below) |
A refusal is an observation, as a cancel response is: there is no reply, and no Context state changes, so ctx.Now() stays the last decision’s. Commands the handler queues go out with the next decision’s reply. An arm’s refusal grants a lifecycle turn, so that is usually the turn’s reply (the SDK answers a turn with the queued commands whether or not the strategy has a TurnHandler); a timer_coarse grants none, so it is the next bar’s. A strategy without the handler goes on as if nothing came, and the operator still sees the refusal’s line.
Silence and ErrTimersUnavailable. The methods log nothing, and a timer that fires prints nothing on the operator’s side. On a run that did not negotiate lifetime-v2 (Capability negotiation), which includes every run under the legacy profile (--lifetime v1, and a live run’s default) and every run on stdio-csv-v1, all three return algolang.ErrTimersUnavailable and queue nothing (ArmSessionTimer with the zero time), so the v1 wires stay byte-identical:
algolang: timers need order lifetime v2 (GLE-200 I12): require CapabilityLifetimeV2 and run under an engine that offers lifetime-v2 on stdio-pb-v1
Nothing else reports it. A strategy that drops the error believes its timer is armed, and the decision it counted on does not come, so check the error: the demo below places no order whose withdrawal it could not arm.
stdio-csv-v2. That wire has no timer lines (Time in force and what v2 refuses). The methods do not know the wire, so they queue there as on pb, and the runner refuses the next batch of any kind (a decision’s, a late bar’s or a warm-up block’s) before it writes anything of it, with an error,csv_unsupported,... line naming the first queued command; Run returns
algolang: a timer arm (timer "close") is not supported over the stdio-csv-v2 wire: it has no timer lines; a strategy that arms timers must run on the pb protocol (GLE-200 I12)
or the same with a timer cancel for a disarm. An arm in OnInit therefore fails at the run’s first batch. The engine’s stdio-csv-v2 host names the wire too, should it be asked to send a TimerFired or a TimerRefused, which no run reaches.
In the lifecycle trace. --lifecycle-json records each arm, disarm, fire and refusal as a timer record that names the decision it belongs to (GLE-458): the bar’s or the timer’s, and the lifecycle turn. A timer’s decision records its cancel requests and submissions through the taps a bar’s use, at the timer’s instant, after its fire record; no bar is counted. See The order lifecycle trace for the closetimer demo’s trace and The lifecycle trace schema for the keys.
Example. strategies/demo/go/closetimer (built by make build) rests a limit order below the market during a contract’s regular session and withdraws it at the RTH close, whether or not a bar of the contract closes then. It requires CapabilityLifetimeV2 and asks for the calendar (NeedsCalendar). At the first bar of a trade date that closes inside the date’s RTH window, it builds a GTC limit buy Distance below the close and arms the session timer for the RTH close less Lead; without the timer it places no order. OnTimer cancels the order if it is still working, and OnTimerRefused cancels it at once, since it can no longer be withdrawn on time (abridged):
// OnBar, at the trade date's first bar inside the RTH window:
o := algolang.LimitBuy(s.symbol, int64(s.Qty), bar.Close-s.Distance).Named("LE")
o.TIF = algolang.GTC
o.ClientID = "entry-" + date
at, err := ctx.ArmSessionTimer(ctCloseTimer, s.symbol, algolang.BoundaryRTHClose, -s.Lead)
if err != nil {
// No timer, no order: an order that cannot be withdrawn on time is not placed.
ctx.Logf("no entry on %s: %v", date, err)
return nil, nil
}
ctx.Logf("entry %s: buy %d at %g, withdrawn at %s", o.ClientID, s.Qty, o.Price, ctTime(at))
return []algolang.Order{o}, nil
func (s *CloseTimer) OnTimer(ctx *algolang.Context, t algolang.TimerFired) ([]algolang.Order, error) {
if t.ID != ctCloseTimer {
return nil, nil
}
age, _ := ctx.DataAge(s.series) // no bar travels with a timer
n := s.withdraw(ctx) // ctx.Cancel on each of the contract's working orders
ctx.Logf("timer %s at %s: withdrew %d order(s); the newest %s bar closed %s earlier", ...)
return nil, nil
}
func (s *CloseTimer) OnTimerRefused(ctx *algolang.Context, r algolang.TimerRefused) {
ctx.Logf("timer %s refused (%s): %s", r.ID, r.Code, r.Reason)
s.withdraw(ctx)
}It runs on the pb wire under lifetime v2, over a data adapter that serves exchange calendars (Engine side); the file-csv adapter serves none. TestTk12EndToEndDemo runs it through engine.Run over a fixture adapter: minute bars of fut:XCME:ES:M26 on 2026-03-12 closing from 14:31Z to 14:35Z, then none until a bar closing at 21:06Z that trades down to 90. The order, a buy at 98, is withdrawn at the 21:00Z close and nothing fills, where the same order left working (Withdraw=false) fills at 98 on the 21:06 bar:
[closetimer] INFO: entry entry-2026-03-12: buy 1 at 98, withdrawn at 2026-03-12T21:00:00Z
[closetimer] INFO: withdrawing entry-2026-03-12
[closetimer] INFO: timer close at 2026-03-12T21:00:00Z: withdrew 1 order(s); the newest fut:XCME:ES:M26 bar closed 6h25m0s earlier
[closetimer] INFO: cancel entry-2026-03-12: confirmed at 2026-03-12T21:00:00ZArming, re-arming and cancelling. On the wire, TimerArm{timer_id, at, anchor} arms the timer timer_id for the instant at, and TimerCancel{timer_id} disarms it. Both travel only in the strategy’s reply to a Bar, a LifecycleTurn or a TimerFired, anywhere before the reply’s OrderResponse (among its OrderCancelRequest envelopes). Anywhere else they are protocol errors that end the run, as before: the warm-up reply must be an OrderResponse, and the v1 bar reply reader refuses them. The engine applies a reply’s timer commands at the decision’s instant, after its cancel requests and orders, in wire order:
- An admitted arm replaces a timer already armed under its id and takes the next place in the arming order, as if it were new.
- A refused arm changes nothing: a timer already armed under its id stays armed as it was.
- A disarm removes the armed timer of its id. Disarming a timer that is not armed (not yet armed, fired, refused or disarmed) does nothing, and a disarm gets no answer.
A timer is absolute when anchor is empty. It is session-anchored when anchor names the symbol whose exchange calendar the strategy computed at from, with Calendar.NextBoundary (decision D-I11-7; Strategy SDK lookups). The engine does not recompute the instant: it admits an anchored timer only when that calendar is complete from the arming decision to the timer’s instant (rule 5 below), and it infers nothing about the calendar from bar stamps or bar lengths. A lifecycle turn answered with timer commands alone is not an empty answer: the commands are applied, and a refusal among them grants the next turn.
The checks at the arm. Each arm is checked against these rules in order, and the first that fails decides the refusal:
| # | Refused when | code | reason |
|---|---|---|---|
| 1 | the id is empty | timer_invalid | timer_invalid: a timer needs an id |
| 2 | at is unset | timer_invalid | timer_invalid: timer "t" has no instant |
| 3 | at is not after the decision’s instant | timer_not_future | timer_not_future: timer "t" at <at> is not after the decision at <decision> |
| 4 | at is after the run’s end | timer_after_end | timer_after_end: timer "t" at <at> is after the run's end at <end> |
| 5 | the timer is anchored and the anchor’s calendar is not complete over [decision, at + 1ns) | calendar_incomplete | calendar_incomplete: session timers: <root> over [<decision>, <at + 1ns>): <detail> (<reason>) |
| 6 | the id is not armed and 4096 timers are | timer_limit | timer_limit: timer "t": 4096 timers are already armed |
Instants in the reasons render as 2026-06-10T14:31:00.000000000Z. The run’s end is the last main bar’s close, which the strategy already has as Init.end_time. Rule 5 is the calendar stage’s precise-time admission, admitPreciseTime("session timers", anchor, decision, at + 1ns), whose refusal text the reason carries without its engine: prefix (Conformance checks and admission); the window runs from the decision to the timer’s instant inclusive, as NextBoundary reads it, hence the nanosecond and the .000000001Z end:
calendar_incomplete: session timers: fut:XCME:ES over [2026-03-12T14:31:00Z, 2026-03-16T14:00:00.000000001Z): trade date 2026-03-16 is not known to the holiday table (date-unknown)
The anchor’s root needs a served calendar, which the run fetches when the strategy sets needs_calendar or the operator passes --exchange-calendar (Engine side); without one every anchored arm is refused no-calendar, ending the run asked for no exchange calendar, and calendar-accept-unverified waives eras-unrecorded for timers as for any precise-time feature. Rule 6’s limit is a constant, not a run setting, and bounds a runaway strategy’s book: a re-arm of an armed id does not count.
A refusal at the arm. Each refused arm is answered with one TimerRefused{timer_id, at, code, reason, timestamp} envelope, with no reply: the id and the instant as the strategy asked (at unset when the arm had none) and the arming decision’s instant as its timestamp. The refusals of one step follow its other outcomes, in command order, and each grants a lifecycle turn, as a denial does: the decision the strategy asked for will not happen. The budget rules of Lifecycle turns are unchanged, so a backtest whose budget is exhausted defers them with the rest of the step’s outcomes. The operator hears one line per refusal: algo: timer "t" from instance MSFT refused: <reason>.
The decision. At its instant the timer is consumed, whatever follows, and unless the coarse check (below) refuses it the engine sends TimerFired{timer_id, at, fired_at}. Both stepped loops fire a timer at its own instant, so fired_at equals at. The strategy answers exactly as it answers a bar: its cancel requests and timer commands, then one OrderResponse whose for_bar is fired_at. The engine applies the commands at the instant through the same driver as a bar’s, so the race guard, the admission policy and, on a live run, the transport scheduler apply unchanged, and every submission and cancel request is answered as at a bar. The decision has its own turn budget: its turns count from 1 again, and two timers at one instant are two decisions with a budget each. A decision may arm another timer, re-arm its own for later, or disarm one due at the same instant that has not fired yet; each takes effect at once, so a timer armed for a later instant that still falls before the next bar fires in the same gap.
Ties. Bars closing at T reach the strategy in the co-close order (Backtest event ordering): the regular series other than the primary, then the primary, then the release-stamped series. A timer at T fires after every bar closing at T, of every class, and before every bar closing after T. Each bar closing at T holds data from before T, which is matched while the order is still working, and the timer’s decision then sees every bar of the instant. The venue’s own cancellations at T, when the run holds the root’s exchange calendar (a Day order’s session close, a GTC order’s quarter close; I13b, GLE-468), go between the two: in the events of the order’s own bar closing at T, after its fills, or else in the timer’s before hook, so the decision at T sees the order gone (Calendar cancellation instants (lifetime v2)). Timers at one instant fire in the order their arms were admitted, and a re-arm takes a new place at the end. A bar’s decision cannot arm a timer for its own close, even while co-closing bars are still to come: a timer at T is not after a decision at T (timer_not_future).
Missing-bar progress. A timer fires at its instant whether or not any bar closes near it: the loop delivers it before the first bar whose close is after it, or after the last bar. No bar is synthesised and no price moves. On a backtest the simulator’s clock moves to the instant (Simulator.AdvanceClock), so a submission or a cancel there is stamped at it, an order submitted there is matched only against later data, and a GTC order anchors at the instant’s trade date (see the known limits). A cancel the simulator confirms at the instant is answered Confirmed there; its OrderCancel follows with the next bar’s events, as at a bar. So a resting limit cancelled by a timer in the gap between two bars is not filled by the next bar, even when that bar trades through the limit. A timer due at the run’s end (the last bar’s close) fires after the last bar and before the end-of-data sweep, which cancels any order its decision submitted.
What the strategy has at a timer’s decision. Stale data, stated exactly: every bar that closed at or before the instant, and none after; on a backtest, every declared market event visible strictly before the instant, sent ahead of the TimerFired (Market events). No bar travels with the decision and none is synthesised, so the strategy measures each series’ data age as fired_at minus that series’ last bar close (ctx.DataAge in the Go SDK). The account state is not pushed again, so the marks are the last bar’s. The working view holds every outcome delivered so far: the outcomes deferred at the previous instant go out before the TimerFired, and those a timer’s decision defers go out at the next event, a timer or a bar. A denial’s rejection cancel still follows before the next bar’s events.
Coarse bars. A timer at T can be honoured only if every bar still to be matched lies wholly at or after T: data before T must be matched before the decision, and data after T after it. The engine holds no grid of bar boundaries (exchange hours come from the calendar, intervals vary by series and session, and event bars have none), so it reads the bars themselves, at the instant:
- The checked series are the venue series: each distinct pair of symbol and series id among the run’s main bars whose symbol is in the run’s venue universe and is not a release-stamped series (
cot:,macro:,fx:RBA:carry values, not price paths). The venue universe is the configured symbols and the declared tradeable ones (TradeableSymbols), on the backtest and the live path alike, so a declared data-only series does not block a timer: no order can rest on it. - Two series of one symbol (a
1mand a5mseries, or two sessions) are checked apart, since the simulator matches an order of the symbol against the bars of both. - For each checked series the engine takes its next bar, its first bar not yet processed. The series fails when that bar’s
ts_openis unset or before T. A next bar opening exactly at T passes, so an instant on a bar boundary (a5mbar’s close, a session close) is honoured. A series with no bar left passes, and at the run’s end nothing remains to check.
When a series fails, the timer is refused at its instant with timer_coarse: no decision and no turn, since there is no honest instant to decide at. The refusal is stamped with the timer’s instant, delivered at once, ahead of the next bar’s events, and printed on the operator’s line. It names the failing next bar earliest in loop order, by its ts_open alone, because its close is not knowable at T for an event bar or a sparse series:
timer_coarse: timer "t" at 2026-06-10T14:32:00.000000000Z: the bar of MSFT series MSFT@5m opening 2026-06-10T14:30:00.000000000Z straddles it
timer_coarse: timer "t" at 2026-06-10T14:35:00.000000000Z: the next bar of MSFT has no ts_open
The label is the bar’s symbol, followed by series <id> when its series id is set and differs from the symbol. Splitting a coarse bar’s path or ticks at the instant is a later refinement.
On a continuous run. Since I15 unit 2c (GLE-474; engine/conttimers.go) a simulated continuous run’s timers fire at their instants. Under lifetime v2 the series’ loop bars carry the ts_open of their original contract bars, the bar the strategy’s OpenTime comes from, so the coarse check reads a continuous series’ bars as it reads a plain series’: a timer in a weekend gap or a session’s pause is honoured, and one inside a daily bar is refused, naming the bar of the logical symbol (timer_coarse: timer "c" at 2026-03-08T12:00:00.000000000Z: the bar of fut:XCME:ES opening 2026-03-08T00:00:00.000000000Z straddles it). The venue universe the check is given holds each continuous series’ logical symbol beside the run’s venue symbols, since the loop bars carry the logical symbol while the simulator’s universe lists the series’ contracts. Before this unit a production run checked no continuous bar at all, so a timer inside a daily bar would have been honoured, while the engine’s fixtures, whose venue is the run’s symbols, refused every timer before the last bar because the loop bars carried no ts_open. Instants happen in order: a roll whose cut is strictly before the timer’s instant fires before the timer’s decision, with the simulator’s clock still at the outgoing contract’s last close, as before a bar, so the decision sees the incoming contract as the active one; a timer at the cut exactly decides first, since a roll is due on the first clock strictly after its cut, and the next bar’s roll then re-places the timer’s order as a new attempt. Two series’ rolls due before one instant fire in the order of their cuts, whatever the series order. A v1 run’s loop bars stay close-only, so the KBD masters are byte-identical; under v2 a continuous run’s Init window starts at its first loop bar’s open, as the plain path’s does, where a v1 run’s starts at the first close, and the calendar’s window widens to it (Engine side).
Warm-up. Warm-up has no decision, so no timer fires during it, and a timer command in the warm-up reply is a protocol error. The first decision is the first main bar’s, and an arm for an instant at or before it (inside the warm-up window) is refused timer_not_future. So a live run’s adopted orders are managed by a timer only when a main-loop decision arms one for a later instant and that timer’s decision acts on them.
On a live run. The live loop is stepped: the venue moves one bar per step, and the operational clock is the instants the loop passes, timer instants included, as for the transport scheduler. A timer due before bar i fires before the venue clock steps to bar i, so a cancel it sends reaches the venue before that bar’s data is matched. The due rule, the order, the coarse check and the refusals are the backtest’s. Before the decision the loop stamps the instant on its ledger bookkeeping (the trade date and the allocation instant) and on the submitter. After it, the loop takes the post-submission poll a bar’s decision gets (Lifecycle turns) when the decision handled a cancel request or accepted an MOC. Its events are recorded in the ledger at once and delivered with the next bar’s batch. The poll is an observation, so the race guard sees its events and can release a held order at the instant, and the transport scheduler sends what it has queued as its window allows. A poll failure ends the run with engine: live poll after the timer decision at <T>: <error>. Timers due at the run’s end fire after the last bar, before the teardown.
On a real-time feed. A run on --feed stream holds no bars ahead (Running live on a real-time feed), so its timers run on the clock (GLE-1440, owner ruling 10 Nov 2026):
- A timer fires when the clock reaches its instant, even when no bar is due, as in a session gap.
- A timer at a bar’s close fires after the bars closing then, as in a backtest. It waits for them up to the feed’s 2-second hold. A series whose bar misses the wait is noted and not waited for again until its next bar.
- No timer is refused
timer_coarse. That check exists because the simulator fills at bar resolution, and a real venue fills at any instant. So a timer inside a bar, which a backtest refuses, fires live. - An arm is refused as on history:
timer_not_future,timer_limit, andtimer_after_endpast--date-to. With an open--date-tothere is no end limit. On history the run’s end is its last bar’s close; on a stream it is--date-to, so a timer between the two is refused in a backtest and fires live.
A strategy whose timers pass its backtest gets the same timers live, at the same instants and in the same order against the bars.
MOC at a timer’s instant. In a backtest an MOC decided at a timer is accepted like one decided at a bar: it waits for its send time (Market-on-close orders, GLE-1375), and a timer armed before the send-time window opens is how an intraday strategy exits at that session’s close. A live run against the IBKR venue holds an MOC the same way, so it accepts one at a timer too: the timer’s instant is the decision the send time is placed from. A member run against the desk (--deploy) does not hold an MOC yet, and denies one at a timer. Every MOC submitted in such a run’s timer decision or its turns is denied before admission, with a Denied update whose reason is moc_at_timer: a market-on-close order settles at an observed close, and the timer decision at <T> has none (GLE-200 I12) and the denial’s operator line, algo: order "m1" (ES) from instance ES denied: moc_at_timer: .... The denial grants a turn, as a guard denial does, and counts no submission. A held MOC that would be released at a timer’s instant is denied with the same reason and ended, not sent: released by the decision’s cancel requests, or by the live post-submission poll’s observation, where the denial is delivered at once with no turn. An MOC at a bar’s decision, new or released, is unchanged.
The operator lines. A timer that fires prints nothing. The lines are:
algo: timer "<id>" from instance <label> refused: <reason>, one per refusal, at the arm or at the instant;- the denial line of each
moc_at_timerdenial; - the turn-budget lines of Lifecycle turns, at a timer’s instant as at a bar’s;
- on a live run, the poll failure above, which ends the run.
Known limits and follow-ups.
- Corporate-action cancels stay bar-granular: an action is applied at the first bar dated on or after its ex-date, after the timers due before that bar, so a timer between the ex-date and that bar sees the book as it was. Day and GTC cancellations are at their calendar instants since I13b (GLE-468, 2026-10-10), between the bars closing at an instant and the timers at it: a timer at or after an order’s session close or quarter close hears the cancel before its decision and cannot
Confirma cancel of an order the venue has ended, when the run holds the root’s exchange calendar (Calendar cancellation instants (lifetime v2)); without one, I13a’s bar-granular rules and the earlier limit remain. - A GTC order submitted at a timer instant anchors at the instant’s UTC date (the date of the instant less a nanosecond, as a bar without a session block closing there is dated), on the simulator and in the live ledger alike. On a session-keyed run that date can differ from the exchange trade date (a Globex evening), and near a quarter end so can the quarter its expiry counts from. I13b places the cancel instant from the calendar but keeps I13a’s anchor, so the anchor’s date is not taken from the calendar; that remains a follow-up.
- A live venue stamps its own cancel events with its own clock (the last bar’s, on the emulator and the scripted venue). A cancel sent at a timer therefore reaches the strategy as an
OrderCancelstamped with the venue’s clock on a live run and with the timer’s instant on a backtest; theCancelResponsecarries the instant on both. - The coarse check reads only whether a bar’s period began before T, which is knowable at T, with one edge: a refusal tells the strategy that a bar opening before T exists, though for a time bar its first trade can come after T. With two straddlers, the bar named is the one earlier in loop order, which says which of them closes first.
- The coarse check repeats its search over the venue series for each timer due before the same bar. A cache of each series’ next bar per bar step is a follow-up for runs with many venue series; the armed limit bounds the cost today.
- A submission the live transport scheduler queued and sends at a timer instant’s observation is not a held order, so a queued MOC sent there is not denied. Denying it is a follow-up if it matters.
- On a continuous run a roll the timer’s hook fires can fail, in its notice or in a step;
timerFirethen returns the roll’s error as is and the loop returns it, so the rejection cancels queued for delivery before the next bar are not delivered, as on every other timer error path (a roll that fails before a bar delivers them first). The simulator’s clock has not moved when that happens, and noTimerFiredwent out. - The lifecycle trace’s bar index on a roll a timer fires is the last observed bar’s, where a roll the bar fires carries the first incoming bar’s (Records and their order). Both are the latest bar observation; a reader of two traces should not take the difference for a defect.
- On a live continuous run under lifetime v2 (GLE-1446) a timer fires as in a backtest: every roll due before its instant fires first, made at the last bar’s close, so a timer past a cut sees the incoming contract (A live continuous roll under order lifetime v2).
- The SDK keeps no view of the armed timers. A view would need the engine to acknowledge an admitted arm on the wire; it is a follow-up only if strategies ask for it.
- A timer-driven MOC under a venue’s auction semantics is a GLE-195 question for later.
Tests. Unit 1’s engine/aa0_timers_tournament_spec_test.go (34 tests) drives the scheduler through runBarLoop over the simulator and runLiveLoop over the scripted venue, with a fake host that plays the strategy, and StdioHost over real pipes: the cancellation at a timer without a bar of the order’s symbol, no data after the deadline matched, ties with co-closing bars of every class and among timers, re-arming and refused re-arms, missing-bar progress, the run’s end, every refusal in order with its timestamp, line and turn, the armed limit, the coarse refusals, MOC at a timer (new and held), the clocks and market events at the instant, the warm-up rule over adopted live orders, the live step order, poll and ledger stamps, and v1 unchanged. engine/timers_review_test.go holds the review panel’s six gap tests: timer commands in real pb bar and turn replies, two timers at one instant with a budget each, the failing call’s results, a held MOC released in a timer’s live poll, a GTC order past its deadline cancelled at a timer, and the earliest straddler named.
Unit 2’s sdk/strategy/aa0_timers_tournament_spec_test.go (13 tests) drives the SDK’s runner over in-memory pipes with a scripted engine on stdio-pb-v1, stdio-csv-v2 and stdio-csv-v1, and calls the Context and the dispatchers directly: the reply order, the queue through the warm-up and late-bar replies, re-arms and cancels in a bar’s, a turn’s and a timer’s reply, refusals delivered with every field, the session helper’s instants and error texts, the stdio-csv-v2 refusal, ErrTimersUnavailable on every v1 wire, Fresh and DataAge at a timer, and every reply compared envelope for envelope, so nothing is logged. engine/aa00_sdktimers_tournament_spec_test.go runs the demo and a probe strategy end to end through engine.Run over a fixture adapter that serves minute bars and a calendar (the withdrawal at the close, the engine’s refusals in command order, a timer armed in a timer’s decision firing in the same gap, a v1 run unchanged) and checks the host’s stdio-csv-v2 refusals. sdk/strategy/timers_review_test.go holds the review panel’s regression for the session helper with an offset of the minimum duration and its six gap tests: a timer decision’s orders whole, boundaries shifted onto Now, searches before the first span, a refusal that leaves every piece of Context state as it was, arm instants to the nanosecond, and orders returned at a zero FiredAt.
Supporting lifetime v2 optionally
A strategy that requires lifetime-v2 runs under lifetime v2 (a backtest’s default, or --lifetime v2) and nowhere else: the SDK refuses the legacy profile before OnInit, and the raw CSV replay its tests pipe bars through offers nothing, so they are refused too. A strategy that has been migrated to v2 and whose legacy decisions are frozen, by its tests, its goldens or its fills blotter, has to run under both profiles from one binary. CapabilitySupporter (the order-lifetime programme’s increment I16, GLE-461) is that declaration:
type CapabilitySupporter interface {
SupportedCapabilities() []string
}The SDK calls it once, where it calls RequiredCapabilities (after the inputs are applied, before OnInit), and walks the tokens after the required ones under the same law, one at a time: a token the engine offered is accepted (duplicates collapsed, a token already required counted once); a token the engine did not offer is left out, and the run proceeds; a token this build does not define fails initialisation (init_failed), as it does for RequiredCapabilities. So the run’s profile alone decides: under v2, a backtest’s default or --lifetime v2, the run negotiates v2, under v1, --lifetime v1 or a live run’s default, it negotiates nothing, and no input has to agree with it. A strategy that supports nothing and requires nothing accepts nothing, and its InitAck is as before. The two declarations differ in what they refuse, not in what they accept:
| Declaration | The engine offers lifetime-v2 | The engine offers nothing |
|---|---|---|
RequiredCapabilities returns the token | v2 | refused before OnInit (capability_unsupported) |
SupportedCapabilities returns the token | v2 | v1, the InitAck with no capability |
| neither | refused by the host (offered and not accepted); on a backtest that names no profile the refusal names --lifetime v1 | v1 |
Since a backtest offers lifetime-v2 unless it names --lifetime v1 (I22, GLE-470), a strategy that declares neither runs on a backtest only under --lifetime v1; declaring support is what lets it run under the default (Lifecycle turns).
The strategy reads the outcome with ctx.LifetimeV2(), true from OnInit on when the run negotiated v2 (InitConfig.Capabilities carries the offer in OnInit as well), and branches on it: the attempt-indexed view, the OrderUpdate and CancelResponse events and the lifecycle turns are in force under v2 and absent under v1, so the v1 branch keeps its Day orders and its ctx.Flat gate and the v2 branch declares what should rest. Two of the programme’s acceptance statements hold through it: no strategy inherits a lifetime it did not declare (the support is in the strategy’s code), and the legacy profile is byte-identical (the v1 branch is the code that was there).
A strategy whose decisions do not depend on the lifetime, one that places market orders alone and gates them on the real position, declares support without a branch: it follows the run’s profile, and under either one its fills are the same. The SMA-crossover demo (strategies/demo/go/smacross) is that case since the order-lifetime programme’s increment I21 (GLE-467): its SupportedCapabilities returns the token, its OnBar is unchanged, and the shared conformance suite proves the two profiles agree on its fills; see Conformance under both lifetimes. The other Go demos that place market orders alone followed it in I21’s PR3a and PR3b (2026-10-11), each with a parity test beside it (over a fixture the file-csv adapter serves, over the bundled trade sample through the Databento adapter, or, for the three whose runs need the archive, a golden-tagged run under each profile), and so did the demos that place no order, printbars among them, each run under both profiles: a strategy with nothing to rest declares support and lets the run choose. The three e9 demos, two of which rest a GTC stop beside their market buy, followed in PR5 (2026-10-11) with the same declaration, their parity claim what holds for a resting stop (the rename re-keys it under both profiles; the split rewrites it under the legacy profile and cancels it under v2, the venue’s rule, and the demo then re-places it, GLE-498) and their stops across adoption pinned by a scripted session each. One thing a market-only strategy does keep from the lifetime: a market exit gated on the position alone submits a second flatten at a venue that holds the first across a decision, so since I21’s PR4 (2026-10-11) each such exit the audit found, in the seven market-only production strategies, the multi-series demo and the legacy exits of three migrated strategies, is gated on kit.Exiting as well, under both profiles, which changes nothing in the simulator (The exit-once gate).
One InitAck field does move with a migration. NEEDS_FILLS (needs_fills) follows the FillHandler interface, which a migrated strategy implements to forward fills to its controller, so a strategy that had no OnFill before acquires the flag under both profiles, on every wire, and its init_ack line changes in that field alone; the lookback, the name, the description and the inputs are where they were.
A strategy that branches, with its v2 entry as one standing intent of a kit.Controller (The desired-order controller; the exits, market orders under either profile, are left out):
type Retrace struct {
Size int64 `algolang:"default=1,min=1,desc=Units per entry"`
rc *kit.Controller
entry algolang.Order // the limit the last primary bar decided on
has bool
}
func (s *Retrace) SupportedCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2} // offered: v2; not offered: v1, unchanged
}
func (s *Retrace) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
rc, err := kit.NewController("retrace:")
if err != nil {
return err
}
s.rc = rc
return nil
}
// signal is the strategy's rule, decided on primary bars only: three lower closes.
func (s *Retrace) signal(ctx *algolang.Context, bar algolang.Bar) bool {
c := kit.Series(ctx, bar)
return c.Len() >= 4 && c.Close(0) < c.Close(1) && c.Close(1) < c.Close(2) && c.Close(2) < c.Close(3)
}
func (s *Retrace) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.IsPrimary(bar) {
return nil, nil
}
level := bar.Low - kit.Tick(ctx, bar.Symbol)
if !ctx.LifetimeV2() {
// The legacy path, as it was: a Day limit that lives one bar, gated
// on Flat and expired by the simulator.
if !ctx.Flat(bar.Symbol) || !s.signal(ctx, bar) {
return nil, nil
}
return []algolang.Order{algolang.LimitBuy(bar.Symbol, s.Size, level)}, nil
}
s.rc.Observe(ctx, bar) // the bar is the resting attempt's one window
if s.has = s.signal(ctx, bar); s.has {
s.entry = algolang.LimitBuy(bar.Symbol, s.Size, level)
s.entry.TIF = algolang.GTC // the one-bar life is the controller's rule, not the simulator's
}
return s.rc.Reconcile(ctx, s.desired(ctx))
}
func (s *Retrace) OnLifecycleTurn(ctx *algolang.Context, t algolang.LifecycleTurn) ([]algolang.Order, error) {
return s.rc.Reconcile(ctx, s.desired(ctx)) // the successor of a cancelled attempt goes out here
}
// desired: the standing entry while flat, as one one-window intent; nothing otherwise.
func (s *Retrace) desired(ctx *algolang.Context) []kit.Intent {
if !s.has || ctx.Position(s.entry.Symbol).Quantity != 0 {
return nil
}
return []kit.Intent{{Key: "entry", Order: s.entry, MaxWindows: 1}}
}
func (s *Retrace) OnFill(ctx *algolang.Context, f algolang.Fill) { s.rc.OnFill(ctx, f) }
func (s *Retrace) OnOrderUpdate(ctx *algolang.Context, u algolang.OrderUpdate) { s.rc.OnOrderUpdate(ctx, u) }Under lifetime v2 the entry is the attempt retrace:entry, declared GTC with MaxWindows: 1, cancelled by the next primary bar’s reconcile when it is still unfilled and re-declared at the turn the confirmation grants; under the legacy profile the same binary submits the Day limit it always did and the controller is not touched. The recipe this follows, and what it changes in a run’s artefacts, are in the next section.
The desired-order controller
A strategy on lifetime v2 need not write its own cancel-and-resubmit logic. kit.Controller (strategies/kit/reconcile.go; the order-lifetime programme’s increment I5, GLE-379) takes, at each decision, the orders the strategy wants resting, each under a logical key, and makes the venue match them through the working view: an unchanged intent is left alone, a changed or withdrawn one has its attempt’s cancellation requested through ctx.Cancel, and the submissions the decision needs come back for the callback to return. The strategy declares what should rest; the controller works out the commands. It is a value the strategy owns, driven from the one goroutine that runs its callbacks, with no goroutine, timer or global state of its own, and it reads the view through a three-method interface, kit.View (Now, WorkingOrders, Cancel), which *algolang.Context satisfies and the kit’s tests drive with a fake. It needs lifetime v2 (a backtest’s default; see Lifecycle turns): the attempt-indexed view is what it reads, the lifecycle turns are where most replacements go out, and the race guard is what makes a successor safe beside its cancel, so on a v1 run none of them is authoritative.
The first migrated strategy, a daily mean-reversion limit entry (the programme’s increment I16, GLE-461), the second, a cooldown-gated mean-reversion strategy (I18, GLE-463), the third, a reversal strategy (I17, GLE-462), and the fourth, a swing-breakout strategy whose stop entry and single exits follow the native policy the owner approved under decision D3 (I20a, GLE-466), all landed 2026-10-09, and the fifth, a range strategy whose decision groups, a bar’s orders as one OCA set, follow its own D3 policy (I19, GLE-465, the backtest half, landed 2026-10-10), run on it under lifetime v2 and on their legacy code under the legacy profile, from one binary (Supporting lifetime v2 optionally); the recipe they follow is below, with the reversal strategy’s extension of it to two intents, the close and the entry, the breakout strategy’s to the through rule, a stop entry and an exit ladder, and the range strategy’s to decision groups. Of the two strategies decision D3 held as regression-only, the breakout strategy’s competing OCO exits run under v2 in a backtest as one OCA set since 2026-10-12 (I20b, GLE-473, the backtest half); their live admission and the live half of the range strategy’s migration wait for native OCA groups in the IBKR adapter (GLE-471).
The API. Build the controller with NewController(prefix); the zero Controller has no prefix and Reconcile refuses it. The prefix names the controller’s scope: it owns every label that starts with the prefix and is longer than it, Label(key) is prefix + key, and Key(label) returns the key and true for a label in the scope, "", false otherwise (the bare prefix is outside). A prefix that is empty or contains a comma, a space, a tab, a line feed or a carriage return is refused; "p:", "demo/" and "x" are valid. Prefix() returns it.
type Intent struct {
Key string // the intent's name in the scope; the attempt label is Prefix+Key
Order algolang.Order // the order as it should rest; ClientID and Attempt are ignored
Group string // intents sharing a non-empty Group are replaced together; "" = the key alone
MaxWindows int // retire an attempt still live after this many eligible windows; 0 = no limit
}
type KeyState struct {
Known bool // the controller remembers the key
Live int // live entries under the key in the view (any status)
Pending bool // at least one of them is pending cancellation
Waiting bool // the intent wants a submission the controller is holding
Windows int // eligible windows of the key's newest live attempt
Lapsed bool // that attempt had MaxWindows windows and must retire
Stalled bool // an attempt's cancel-request budget is exhausted
Blocked string // the reason of the denial that blocks the intent; "" if none
// Transient is set beside Blocked when the block lifts by itself once the
// cancellation it waits for ends: a race-guard denial (GLE-1363).
Transient bool
Filled int64 // quantity filled under the key since the controller knew it
}
func NewController(prefix string) (*Controller, error)
func (c *Controller) Prefix() string
func (c *Controller) Label(key string) string
func (c *Controller) Key(label string) (string, bool)
func (c *Controller) Observe(v View, bar algolang.Bar)
func (c *Controller) Reconcile(v View, desired []Intent) ([]algolang.Order, error)
func (c *Controller) State(key string) KeyState
func (c *Controller) OnFill(_ *algolang.Context, f algolang.Fill)
func (c *Controller) OnOrderUpdate(_ *algolang.Context, u algolang.OrderUpdate)
func (c *Controller) OnCancelResponse(_ *algolang.Context, r algolang.CancelResponse)
func (c *Controller) Stalls() []Stall
func (c *Controller) TakeStalls() []Stall
func (c *Controller) Halt(reason string)
func (c *Controller) Resume()
func (c *Controller) Halted() (string, bool)
func (c *Controller) Reset(key string)Observe(ctx, bar) goes at the top of OnBar, before the decision: it records the bar as an eligible window of the resting attempts it belongs to. Reconcile(ctx, desired) is the decision, at the end of OnBar and in OnLifecycleTurn: it requests the cancellations through the view and returns the submissions, which the callback returns; a nil or empty declaration retires every attempt in the scope, and the returned slice is nil when there is nothing to submit. OnFill, OnOrderUpdate and OnCancelResponse have the FillHandler, OrderUpdateHandler and CancelResponseHandler signatures, so the strategy forwards each event with one line, or embeds the controller: OnFill counts the key’s filled quantity, OnOrderUpdate blocks a key the engine denied, OnCancelResponse records the outcome and reason of a cancel request for the stall that reports it. State(key) is the controller’s observation of a key as of its last call, the zero KeyState for a key it does not remember. Stalls() lists the attempts whose cancel-request budget is spent (below); TakeStalls() lists each once per round, for a strategy to log with kit.LogStalls(ctx, s.Name(), s.rc.TakeStalls()) after each Reconcile. Halt(reason) stops every command until Resume; Halted reports the reason. Reset(key) forgets a key. MaxCancelRequests is the cancel-request budget per attempt in one round, DefaultMaxCancelRequests (3) when left at 0, which NewController does; MaxCancelRecoveries is the number of further rounds, DefaultCancelRecoveries (1) at 0 and none when negative; MaxTransientRetries bounds how often a transient block of one frame lifts, DefaultMaxTransientRetries (3) at 0. A nil *Controller is a valid receiver: Reconcile returns an error, State the zero value, Halted "", false, Label the key unchanged, and the rest do nothing.
A one-window limit entry, sized from the position so that the intent stays stable across partial fills:
type Dip struct {
Size int64 `algolang:"default=2,min=1,desc=Units to hold"`
rc *kit.Controller
sym string
level float64
}
func (s *Dip) RequiredCapabilities() []string { return []string{algolang.CapabilityLifetimeV2} }
func (s *Dip) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
rc, err := kit.NewController("dip:")
if err != nil {
return err
}
s.rc = rc
return nil
}
func (s *Dip) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
s.rc.Observe(ctx, bar) // the bar is a window of the resting attempts
s.sym, s.level = bar.Symbol, bar.Close-0.25 // the signal, decided on bars only
return s.rc.Reconcile(ctx, s.desired(ctx))
}
func (s *Dip) OnLifecycleTurn(ctx *algolang.Context, t algolang.LifecycleTurn) ([]algolang.Order, error) {
return s.rc.Reconcile(ctx, s.desired(ctx)) // the same signal, re-sized: a successor that waited goes out here
}
// desired is what should rest now: the level, for the quantity still to execute.
func (s *Dip) desired(ctx *algolang.Context) []kit.Intent {
want := s.Size - ctx.Position(s.sym).Quantity
if want <= 0 {
return nil // nothing wanted: every attempt in the scope is retired
}
o := algolang.LimitBuy(s.sym, want, s.level)
o.TIF = algolang.GTC
return []kit.Intent{{Key: "entry", Order: o, MaxWindows: 1}}
}
func (s *Dip) OnFill(ctx *algolang.Context, f algolang.Fill) { s.rc.OnFill(ctx, f) }
func (s *Dip) OnOrderUpdate(ctx *algolang.Context, u algolang.OrderUpdate) {
s.rc.OnOrderUpdate(ctx, u)
}Intent and attempt. A key names an intent; each physical submission under it is an attempt, labelled Label(key) and stamped by the SDK (the controller submits with Attempt 0 and the view stamps the next number). The controller submits at most one attempt per key and treats more as interference (below). The successor of an attempt is the declaration of the decision that submits it: the controller caches no order to send later and invents no quantity.
Frame equality. An attempt is an intent when its Symbol, Side, Type, Price, StopPrice, TrailAmount, TIF and OCOGroup equal the intent’s (exactly, floats included: the strategy’s numbers are its own, and a level one tick away is a different intent), its remaining quantity equals the intent’s Quantity, and its attached children match the intent’s by label and on the same fields. So an intent’s Quantity is what is still to execute: a strategy that sizes from ctx.Position (or from State(key).Filled) declares a stable intent across partial fills, and a fill of 4 of 10 followed by a declaration of 6 is still met. ClientID, Attempt, SubmittedAt, FilledQuantity, OrderRef, CancelRequestID and ParentClientID play no part. A v1 entry (status Unspecified, no quantities) is compared on its Order.Quantity. The controller does not change an intent’s TIF: a resting order that should outlive one bar is declared GTC.
Met, retire, wait. An intent is met when its key has exactly one live attempt, that attempt is commandable (its status is neither Inactive nor PendingCancel: Submitting, Working, PartiallyFilled, Held, SubmissionUnknown and the v1 Unspecified all are), is the intent and has not lapsed; under lifetime v2 also when the key’s newest attempt is such an attempt and every older one is PendingCancel (a successor sent with its predecessor’s cancel, below, held while that cancel is pending), none of them an attached child or carrying one. A met intent produces nothing, so an unchanged ladder costs no command bar after bar. An intent that is not met retires every commandable attempt under its key, and so does the absence of an intent under a key that has attempts: one ctx.Cancel(label) per retired entry, which the view addresses to the label’s newest attempt not yet pending; an attempt already PendingCancel is not re-requested, and an Inactive child is not cancelled directly. An unmet intent is submitted only when its key has no live entry at all (none in any status, Inactive and PendingCancel included), none of its declared child keys has one, it is not blocked and its group is not being replaced, or, under lifetime v2, in the same reply as the cancellation of its key’s one entry when the venue could modify that entry in place to the intent (below); otherwise it waits, and State(key).Waiting says so. The submission is the intent’s Order labelled Label(key), attempt 0, each child labelled Label(childKey) in a fresh slice, every other field as declared.
A replacement in place takes one decision under lifetime v2 (GLE-1419). When the key has one entry, not already pending cancellation and in no group, and the intent changes only its limit price, stop price, quantity or time in force (both limit, stop or stop-limit orders, Day or GTC, with no legs, attached orders or CancelAt, on the same symbol and side, of the same type, with the same trailing amount, OCO group, display name and conviction), the decision that sees the change requests the cancellation and returns the successor in the same reply. The engine then modifies the order in place where the venue can, and otherwise holds the successor until the predecessor ends (Replacing in place); the strategy hears the cancel’s answer and the successor’s update together. A cancel-request budget spent leaves the successor waiting, as below. While a modification is pending (GLE-1436), the successor is Held behind it, and a further change replaces it the same way: the newest entry, a held successor the venue could still modify to the intent, retires with its successor in one reply, behind the predecessors already pending cancellation. Any other further change waits for those to end.
Any other replacement takes two decisions. The decision that sees the change requests the cancellation; the successor goes out at a later decision, once the view has retired the predecessor: a confirmed CancelResponse at the turn it grants, an OrderCancel, a terminal OrderUpdate or a full fill. A Pending or Unknown response keeps the predecessor live and the successor waiting; a Refused one restores the attempt, which the next decision retires again, up to the budget. On the simulated path the confirmation arrives at the instant of the request and grants a turn, so the successor goes out before the clock advances: bar N returns the cancel, the turn returns the successor, and bar N+1 finds it resting. The declaration the strategy makes at that turn is the one submitted, which is why the example re-declares in OnLifecycleTurn: a successor that waited, the residual after a fill during a cancel included, goes out there.
A fill during the cancel. p:k attempt 1 is S10@100; the strategy declares S10@99, a re-price, so the controller requests the cancel and sends S10@99 as attempt 2 in the same reply. On the simulator the cancel confirms at once, and no fill can land inside it. A live venue that modifies is asked for a total of 10, so a fill of 4 that lands first leaves 6 working at 99: the venue does the re-size. On a venue that cannot, the cancel is pending and attempt 2 is held behind it, and the intent is met. A fill of 4 then lands: the view shows attempt 1 with 6 remaining, still pending; State("k").Filled is 4; the position has moved; and the guard rejects attempt 2 with cancel_race (A race). The strategy declares S6@99 (10 less the fill count, or the position’s residual), which waits for attempt 1; the decision after attempt 1 ends sends it as attempt 3. The stale S10@99 never reaches the venue. TestTr5SDKFillDuringCancelResizesSuccessor runs this through the real SDK and wire. A replacement the venue could not make in place takes the two decisions above, and its successor is declared only after the fill.
Eligible windows and the lapse. The simulator evaluates a resting order against bars of its own symbol, on every series of the run, that close after the order became active (the fill simulator). Observe counts the same thing from the strategy’s side, per live attempt: a bar is a window of every live attempt whose Order.Symbol is the bar’s symbol and whose activation is strictly before the bar’s CloseTime; a bar is counted once per attempt (a second Observe with a bar not closing after the last counted close adds nothing); the bar’s SeriesID plays no part, so an auxiliary series of the same symbol counts, as the engine evaluates it. A top-level attempt is active from its SubmittedAt (the close of the bar or the instant of the turn that submitted it); an attached child from the first Observe or Reconcile that sees it other than Inactive, at ctx.Now() then, so the bar in which its parent filled is not its window and the next one is, as the simulator has it. An attempt that leaves the view forgets its windows; a successor starts at zero. An attempt a continuous roll re-places is no successor: the controller carries its windows, activation and cancel requests to the new number when it meets an entry whose ReplacesAttempt names an attempt it remembers, as it does when Observe runs at every OnBar (Order lifetime v2 across a roll). An intent with MaxWindows > 0 lapses an attempt that has had that many windows: the attempt is no longer the intent, so it is retired and the successor waits as for any replacement; MaxWindows 0 lapses nothing, and Observe still counts.
The lapse is the one-window helper. With MaxWindows: 1 and GTC, a limit submitted at bar N’s close rests through bar N+1, its one window; the reconcile at bar N+1 cancels it when it is still unfilled and returns the successor in the same reply (the same limit, or a re-priced one, is a replacement in place), and the successor rests through bar N+2. An auxiliary callback (a bar of another symbol) adds no window, so reconciling the same declaration on it cancels nothing: the acceptance case, that an auxiliary callback does not cancel a market or limit order the engine has not yet evaluated. Declare GTC, not Day, for the one-window semantics: on the simulated path the simulator’s own Day expiry retires a Day attempt before the lapse can act (the attempt is gone at the next bar, so the controller resubmits with no cancel), and GTC with MaxWindows: 1 is the form that also holds live.
Migrating a one-bar limit entry. The first migration (I16, GLE-461) distils to a recipe for a strategy whose legacy entry is a Day limit decided on each primary bar, expired by the simulator after one bar, with ctx.Flat as the gate for the next. The legacy path stays as it is, and the v2 path runs beside it under ctx.LifetimeV2():
- The standing declaration. The entry the primary bar’s rules produce, or none, is the declaration until the next primary bar: the same constructor, quantity and level as the Day order, with
TIFset toGTC, under one key withMaxWindows: 1. A bar whose rules produce no entry (the depth gate, a position open, the conditions not met, a zero quantity) clears it, andOnInitstarts with none. - A position gate, not
ctx.Flat. The intent is declared whilectx.Position(symbol).Quantity == 0, re-evaluated at the bar and at every turn, so a fill that lands while the attempt’s cancellation is pending withdraws a successor still to go out; one already held beside the cancel the race guard rejects (cancel_race).Flatcounts the resting attempt itself, and under v2 that attempt is the controller’s to retire, so gating onFlatwould block every later decision (the “permanent Flat-gate blockage” the acceptance names). Observeon every primary bar, before the decision, so the bar is counted as the resting attempt’s one window.Reconcileon every primary bar, then the exit. Whatever the bar decides, an exit, an entry, nothing, the depth gate included, it ends withReconcileunder the gate: a declaration of nil retires any resting attempt (a lapsed signal, a position opened by a fill). The bar’s orders are the controller’s submissions followed by the exit order, if the bar chose one; the exits stay what they were, market orders under the SDK’s auto label with their constructor’sDay.OnLifecycleTurnre-declares under the gate, and nothing else: no bar travels with a turn, so no signal, noObserve, no exit. A successor that waited goes out here, at the level the last primary bar decided (a lapsed or re-priced limit goes out at the bar, beside its cancel); a pending or refused cancellation leaves it waiting; a fill during the cancellation withdraws it. AFilledupdate grants a turn as well, which the cleared declaration and the gate make a no-op.- Forward
OnFillandOnOrderUpdateto the controller, so that aDeniedorRejectedentry blocks its frame: the turn the denial grants submits nothing, and the next primary bar’s signal, which moves the level, clears the block. - Non-primary bars return nothing: no signal, no
Observe, noReconcile, so an auxiliary callback cannot cancel the resting entry.
On the simulated path the result is the Day order’s life: the attempt rests through the next bar, its one window; when it is still unfilled, the bar’s reconcile cancels it and returns the successor at the new level in the same reply, before the clock advances, as the legacy bar submitted a fresh Day limit. Three limits are recorded with the first migration. On rules where a persisting signal always moves the level, the frame change retires the attempt on the same bar the window lapses, so MaxWindows: 1 and Observe cannot be told apart from frame equality by the strategy’s decisions; both are required all the same, as the declaration of the one-window intent, and reviewed rather than gated, as are the paths a fixture cannot reach (a bar whose rules give a zero quantity clearing the declaration, a Reconcile error ending the run). A partial fill is covered by the position gate, any open position withdrawing the declaration and retiring the attempt, and the resizing path is the controller’s own test. And the market exit keeps the legacy rules as they were, so a second bar that breaks the exit level while the first exit’s market order is still unfilled would return a second flatten; the simulator cannot reach it (a market order fills at the next open) and a live venue fills a market order at once, and the window was recorded for I21’s market-order audit rather than closed here. The audit closed it on 2026-10-11 (I21’s PR4): both exit sites are gated on kit.Exiting on both paths, so the second flatten waits for the first (The exit-once gate).
The second migration (I18, GLE-463), a cooldown-gated mean-reversion strategy whose entry is a market order by default and a limit by input, adds three things to the recipe.
An entry cooldown stays the legacy contract. A strategy that permits an entry only once so many primary bars have passed since the bar that last submitted one keeps that rule under v2 as it was, with “submits” read as “declares”:
- the anchor is the bar whose rules declare an entry, long or short, market or limit, filled or not; the controller’s first attempt goes out on that bar, and a successor it submits at a turn under the same standing declaration is the same decision, so the anchor stays at the declaring bar and the cooldown is not re-evaluated at a turn;
- nothing else moves it: not a fill, prompt or delayed, whole or partial, not an expiry, not a cancellation, not a denial, not an exit, so a re-entry after an exit waits for the anchor plus the cooldown as it did under v1;
- a bar in cooldown declares nothing, which retires the resting attempt at that bar’s reconcile (its one window has passed) and leaves the turn with no successor; with a cooldown of two bars or more the window bar is always in cooldown, so the lapse by
MaxWindowsis observable only with a cooldown of 0 or 1; - a delayed fill, one that lands after the strategy retired the attempt (the venue’s answer to the cancel is
pendingorrefused, or a live venue’s latency), opens a position as any fill does: the position gate withdraws the declaration at the next decision, the position is managed from the next primary bar, and the anchor is unchanged, so the fill cannot bypass the cooldown; - count the bars with the SDK’s own count,
ctx.Trade(bar).BarIdx, notSeries().Len(), which saturates at the lookback (the buffer is full from the first decision on a long enough archive), so a cooldown counted on it reads no bars elapsed after the first entry and blocks every later one. The cooldown reads differences of the count alone, so where the count starts is immaterial.
Market mode is the legacy path. The v2 lifetime is in force when ctx.LifetimeV2() is true and the limit input is set; in market mode under either profile the whole decision is the legacy code, the ctx.Flat gate and the cooldown included, the Day market order returned unlabelled, no intent declared (an Observe or an empty Reconcile commands nothing and is allowed; a declaration is not), and a turn answered with an empty batch. The simulator fills the market order at the next bar’s open, before any decision, so a market-mode run is identical under v1 and v2: the same fills, the client ids included, the same broker ids, and every count of the lifecycle trace equal (the v2 blotter alone carries the Attempt the SDK stamps on every v2 fill).
Pin every shared rule on the v2 path. The second migration’s advisor found its signal filters, its time stop and its protective suite pinned on the legacy path alone: the shared code ran them under v2, but a v2 path that dropped one passed the spec tests. Each got a wire case on the v2 path, the rule on and off, and the mutant that drops it is killed by that case alone; a migration’s tests reach every filter and stop on the v2 path itself, since the legacy tests do not.
Migrating a reversal: two intents. The third migration, the reversal strategy’s (I17, GLE-462), a mean-reversion strategy that fades sharp directional moves and whose entry may fire against a position (a stop-and-reverse: the flatten of the position, then the entry in the opposite direction, in that order), takes the recipe to two intents. In limit mode under lifetime v2 every order the strategy wants resting is an intent of one controller scoped to the strategy’s name, under one of two keys, and a reversal is the two declared together:
- The close is declared first, the entry after it. The close (key
close) is the flatten as the rules build it,kit.Flatten(symbol, position), a Day market order on the side that closes the position: set by a primary bar whose rules flatten, an exit or a reversal’s first leg, and standing until its own fills complete it; a bar whose rules do not flatten leaves it as it stands. The entry (keyentry) is the limit as the rules build it,TIFset toGTC,MaxWindows: 1, set or cleared by every primary bar as in the one-intent recipe and standing until the next. The controller sorts its submissions by key, socloseprecedesentryin a reversal’s batch, as the legacy slice had them; nothing is sequenced across turns: both intents stand, each ending through its own fills, whichever fill the venue reports first. An exit travels the same way: under v2 it is the close intent, not an auto-labelled order, so no order of the strategy’s leaves the v2 path outside the controller (the one-intent recipe left its exits outside it). - A standing declaration counts its fills and declares the remainder. Each intent is declared for its quantity less its fills, counted in the strategy from zero at the bar that set the declaration, from the fills under the intent’s own label on its own side (the controller’s
KeyState.Filledspans the key’s whole memory and is not side-aware, so a predecessor of the opposite direction filling during its cancellation would count against a fresh entry). A partial fill leaves only the remainder declared, which the partially filled attempt still meets, so there is no churn; should the attempt end before the remainder executes (a venue cancellation), the controller resubmits the remainder, not the original quantity, and a fill during the cancellation re-sizes the successor the same way. A count that reaches or passes the quantity withdraws the intent: the rule on both keys isquantity - fills > 0, so a venue execution larger than the ticket withdraws the key as a whole fill does, with no zero or negative declaration (whichReconcilerefuses, ending the run), and the count saturates at the quantity, so a later over-fill cannot wrap it and revive a completed declaration. - The close is sized from the position and by its own fills. Its quantity is the position at the deciding bar, not the entry’s (a two-lot short reversed with a one-lot entry declares a market buy of 2 and a limit buy of 1), reduced by its own fills and not by the position: when the entry’s fill is reported before the close’s, the position passes through zero onto the entry’s side and the close still stands for its whole quantity (a close re-sized from the position would cancel the market order and end flat, where the legacy pair ends in the new position). A bar whose rules flatten sets the close afresh, with no fills, so a completed close does not block the next flatten.
- The entry’s gate is its premise, not
ctx.Flatand not a flat position. The one-intent recipe’s gate does not transfer: a reversal declares its entry against a position, and the entry’s own partial fill moves the position onto its side. The entry is declared while the position has not moved against it since the bar that decided it (for a buy, the position at or above that bar’s; for a sell, at or below), re-evaluated at the bar and at every turn. A partial fill of the entry moves the position with it, so the remainder stays declared; a fill of its whole quantity, or more, withdraws it by the remainder rule; and a fill of an opposite-side predecessor during its cancellation moves the position against it and withdraws the successor, the one-intent recipe’s fill-during-cancellation rule, where the legacy live path would have held the decision by its working-order gate (the two agree that no entry goes out at that instant, and the next bar decides as the rules say). - The working-order gate becomes the controller’s law. The legacy gate, no entry while any order is working, is off on the v2 path: a resting attempt is the controller’s to replace or retire, and gating on it, or on
ctx.Flat, would block every later decision. One live attempt per key, replaced rather than stacked: a persisting signal, whose level has moved, retires the attempt at the bar’s reconcile, and the successor, a replacement in place, goes out beside the cancel (Replacing in place); a lapsed signal cancels with no successor, and the key is free for the next trigger. - Denials and rejections block the frame.
OnFillandOnOrderUpdateforward to the controller unconditionally, on every run (outside its scope the controller moves nothing), so aDeniedorRejectedupdate for the entry blocks the key for the frame of the refused submission: the turn the refusal grants submits nothing, and the next primary bar’s signal, which moves the level, clears the block and submits the new level as the next attempt. - The rest is the one-intent recipe.
Observeon every v2 primary bar before the decision, a reconcile on every v2 primary bar whatever it decides, the turn re-declaring both intents and nothing else, non-primary bars returning nothing beforectx.Trade, andOnInitbuilding the controller afresh with no standing declaration (one value may serve several sessions in turn); the handlers also tolerate a run on whichOnInitwas not called, a zero value answering a fill, an update and a turn with nothing. Market mode is the legacy path under either profile: the Day market orders under the SDK’s auto label, the working-order gate and the flatten-then-entry slice, noObserve, noReconcile, no standing declaration, a turn answered with an empty batch; the strategy still declares its support, so a v2 run negotiates v2 and runs the legacy decisions on the v2 wire, with the fills, the client and broker ids and every lifecycle count equal under both profiles.
Recorded with the reversal migration: MaxWindows: 1 and Observe are again unobservable by frame equality on rules where a persisting signal moves the level, so both are reviewed, and a review test that holds the level fixed pins the lapse at the window and the successor at the turn; a two-lot position is reached on the stdio-csv-v2 wire only through a venue-reported execution larger than its ticket (the wire carries no account state and the simulator fills whole), so the end-to-end fixture exercises no partial fill and the entry’s partial fill is pinned at the unit level against the standing declaration; the close keeps kit.Flatten’s Day (the engine accepts it, and the simulator fills a market order at the next open under either profile), a market order resting past a bar unfilled being a venue anomaly the standing close answers by re-declaring its remainder; and the duplicate-flatten window the one-intent recipe records for I21 does not arise on this path, on reading: a second bar that breaks the exit level while the close is unfilled sets the standing close afresh to the frame the resting attempt already meets, and the key law allows one live attempt. The legacy path, market mode under either profile and the legacy profile in limit mode, has the window, and I21’s PR4 (2026-10-11) gated its exit sites on kit.Exiting there alone, the v2 limit path left to the key law (The exit-once gate).
Migrating a stop-entry breakout: the through rule and an exit ladder. The fourth migration, a swing-breakout strategy’s (I20a, GLE-466), the first under a native policy the owner approved under decision D3 (GLE-464), is the first whose legacy orders are not limits. The strategy enters on a first-touch stop one tick through the last swing extreme, on the bar whose Dow flip breaks it, and in a position rests one exit per bar at a recomputed level: a next-day stop, then its mode’s exit (a three-day extreme, or the swing extreme one tick through). Under the legacy profile every one of them is a Day StopTouch, a stop that may rest on the wrong side of the market and fills at the first touch of its level, expired by the simulator after one bar. Under v2 nothing expires an order but the venue, a stop resting on the wrong side of the market has no ticket on the live map, and the simulator denies a plain stop at or through the last close, so every order needs a native form, and the recipe takes these patterns:
- The through rule, equality included. A first-touch level is read against the deciding bar’s close: a level strictly beyond it (a buy above the close, a sell below it) goes as a
GTCstop at the level; a level at or through the close, equality counting as through, goes as aGTCmarket order, which fills at the next open in the simulator as the first-touch stop did. The rule applies to entries and exits alike, so noStopTouchleaves the v2 path. Its one economic consequence is enumerated: an at-or-through decision whose next bar opens back inside the level fills at the open under v2, where the first-touch stop filled at the level, a better price by the gap; every other decision fills as before. - The entry is the one-window intent, with its successor at the cancel’s turn. The flip bar’s entry, in its native form, is the standing declaration under one key with
MaxWindows: 1, declared while the position is flat (the one-intent recipe’s gate;ctx.Flatis not consulted, a resting attempt being the controller’s to retire) and cleared by every other primary bar. The next bar is the attempt’s one window: when the attempt is still unfilled and the bar decides nothing, the bar’s reconcile cancels it with no successor; when the bar flips the other way, the bar cancels the lapsed attempt and declares the other side, and the successor goes out at the turn the confirmation grants, as the legacy bar submitted a fresh Day stop, while apendingorunknownanswer to the cancel holds it. A fill of any size withdraws the entry: a partial fill is not pursued, and the position it opened is managed from the next primary bar. - The exit ladder is one intent, sized from the position at every reconcile. Every primary bar with a position whose ladder rule yields a level sets the standing exit afresh, in its native form, under one key; the declaration carries it while the position is on the side it closes, with the quantity set to the position’s absolute size at that reconcile, the bar’s and every turn’s. No fill is counted in the strategy (it enters only when flat and has one exit at a time, so the position is the remainder): a partial fill of the exit leaves the remainder declared, which the partially filled attempt still meets, an attempt the venue ends early is resubmitted for the remainder, and a whole fill flattens the position, which withdraws the key. An unchanged level rests with no command, where the legacy bar re-placed a Day order; a changed level is cancelled at the bar and its successor, a replacement in place, goes out beside the cancel. Only a move to the market exit (the through case), a change of type, goes out at the turn.
- A position-wide gate retires a resting exit by declaring nothing. The strategy’s profitable-prior-flip gate suppresses exits as well as entries: while it holds, the legacy bar placed nothing and its Day exit expired. Under v2 the gated bar reconciles an empty declaration, which cancels the resting exit; the bars under the gate rest nothing, as before; and the first bar after it re-declares the exit as a fresh attempt at the then-current level. A fill that lands while that cancel is in flight (the venue refuses the cancel as filled) flattens the position, and the gated turn declares nothing.
- Every intent is
GTC, the market orders included. The stop because its life, one window for the entry and until replaced for the exit, is the controller’s rule and not the simulator’s Day expiry; the market order for uniformity, one rule for the strategy (IBKR accepts a market order underGTC, and the simulator fills it at the next open under either TIF). The reversal migration’s close keepskit.Flatten’sDay. The two are not in contradiction: that close is a flatten the rules re-declare until its fills complete it, this strategy’s market order is a through-rule entry or exit converted from a stop, and each strategy keeps one rule for its own orders. - A competing exit pair is one controller group under one stable OCO tag. The strategy’s remaining exit mode is a competing pair: from two bars since entry, a break stop one tick through the swing extreme (the swing low for a long, the swing high for a short) and a first-profitable-touch limit one tick through the entry price, the loser dying with the winner’s fill, which the legacy path places every bar as two Day orders under a per-bar
OCOGrouptag. Under v2 (I20b, GLE-473, the backtest half, landed 2026-10-12) the pair is two intents, the break stop under the exit ladder’s keyx_stopand the limit underx_target, both in the controller groupexitand both tagged with one stable venue OCO group, the controller’s prefix plus the group: the controller comparesOCOGroupas part of an attempt’s frame, so the legacy per-bar tag would replace the pair every bar (the range strategy’s stable tag, below, is the same idiom). The next-day stop at one bar since entry stays the ladder’s ungrouped, untaggedx_stop, so the other two exit modes are unchanged. The break stop takes its native form by the through rule; the limit stays aGTClimit whatever the close (marketable when the close is through it, which the simulator fills at the next open, as it filled the legacy limit); both are sized from the position at every reconcile, and both levels are the legacy pair’s arithmetic, kept literal. The key order submits the stop before the limit, D3’s order. A changed level replaces the pair as a unit: both legs are cancelled at the bar and both successors go out at the turn after both confirmations. The first fill cancels the sibling at the venue (the simulator’s standalone OCO:oco_triggered,triggered_bynaming the winner), which leaves the position flat and the pair withdrawn with no cancel request; the position-wide gate retires both legs by declaring nothing. Beyond the through rule’s own case, D3’s order has one known cost, recorded as the range strategy’s gap case is: a break stop decided at or through the close is a market order, and when the next bar opens back inside the level and reaches the target, the market order wins the simulator’s tie by submission order and exits at the open (on the end-to-end fixture, 92 where the legacy limit took 104.5). A market order executes at the open before any limit can, so reversing the order would produce a fill no venue would. The same gap is price-better when the bar touches the break level (92 against the legacy stop’s 90.75) and an earlier exit when it touches neither level (the legacy stop filling two bars later). - A feature the live adapter cannot carry yet is refused live, at adoption. The IBKR adapter drops
OCOGroupfrom a ticket until it has native OCA groups (GLE-471), so under v2 the strategy’sOnAdoptedStaterefuses the competing pair, naming the missing groups, at the adoption handshake every live run delivers and no backtest does (the range strategy’s mechanism, below: the SDK reportsadopt_rejectedand the run ends before any bar). The refusal reads the profile and the input alone, with the strategy’s mode unset too and whatever the adopted state holds; the other exit modes under v2, and every configuration under the legacy profile, adopt as before, so live behaviour is unchanged.OnInitrefuses nothing under either profile: until 2026-10-12 it refused the pair under v2 in a backtest as well, and until 2026-10-11 the disaster stop, both the owner’s decisions of 2026-10-09 in place of a half-migration on the legacy code under the v2 wire, each lifted when its native form landed (the pair above; the bracket child, GLE-480, the last pattern). The pair’s legs travel as two tagged orders: stdio-pb-v1, which the engine negotiates for a Go strategy, carries the tag, and stdio-csv-v2 cannot, so a v2 run forced onto that wire with the pair configured fails at the first pair, when the SDK refuses to write the tagged order, an operator error the strategy cannot see atOnInit. - A filled predecessor keeps its own setup. The review panel’s one upheld finding, fixed in the second commit. The next-day stop is anchored on the setup bar of the entry that opened the position (the flip bar’s extreme, or the fill bar’s if more extreme), and under v2 an entry’s cancellation can outlive its window bar: a long rests, the next bar flips down, cancels it and declares the short, the venue reports the cancel
pending(orunknown), which holds the successor, and the old long then fills before the next primary bar, its cancel refused as filled. The position is the long’s, and a single setup snapshot overwritten by the flip bar would anchor its stop on the short’s setup. So each side’s setup is kept with its own declaration, and the exit rule takes the setup of the side whose entry opened the position (consecutive flips alternate sides, so the side identifies the attempt). The legacy path cannot reach it, sincectx.Flatblocks the new entry, and its setup write, while an attempt works; it keeps its one snapshot. - A protective child rides inside its entry intent. The disaster stop, which the legacy path attaches to its first-touch entry as a stamped Day stop and cancels by name on the first bar after the fill, is under v2 the entry intent’s bracket child (GLE-480’s backtest half, landed 2026-10-11): a
GTCstop on the exit side for the entry’s quantity in the entry’sAttachedOrders, keyeddisasterand so labelled with the controller’s prefix, declared nowhere but inside the entry, with no standalone fallback. It anchors at the decided entry level before the through rule applies, so an entry the rule turns into a market order, which carries no stop price, has its anchor too, and its distance is the legacy one, the configured percentage of the level’s magnitude divided by the quantity, computed with the legacy arithmetic in the legacy operand order and as a statement of its own, so no multiply fuses into the level’s addition or subtraction and the level is the legacy child’s on the same bar, bit for bit. The simulator activates the child at its parent’s fill and settles it against the fill bar at once, so it protects the entry bar as the legacy child does. The first decision after the fill (in a backtest the fill bar’s ownOnBar, since a fill grants no turn) no longer declares the entry, so a child the fill bar did not reach is active under a key with no intent, and the controller retires it with one cancel request, as the legacy path cancels its child by name. A parent that lapses at its window or is replaced on a flip takes its inactive child along (parent_cancelled), a denied parent leaves the view with its child, and a successor entry carries a child of its own. A partly filled parent, a live case since the simulator fills whole, is withdrawn at the fill’s turn: its remainder is cancelled and the child, still inactive, endsparent_cancelledwith it; what IBKR does with such a child is the live half’s. A fill of the entry consumes the standing entry, so a turn between the child’s stop-out and the next bar (one a refused cancellation of the child grants, which a scripted or live session can reach and a backtest cannot) does not declare the filled entry again. The child travels inside its parent on the wire: stdio-pb-v1, which the engine negotiates for a Go strategy, carries it, and stdio-csv-v2 cannot, so a v2 session forced onto that wire with the disaster stop configured ends at the trigger bar with the SDK’s refusal.
Recorded with the breakout migration: MaxWindows: 1 and Observe are unobservable by frame equality for a third time, here because a flip is a one-bar event (the window bar clears the declaration, which retires the attempt whatever the window count), so both are reviewed; the exit’s side gate (no fixture flips the position’s sign while an exit stands), OnFill forwarding (no decision reads the controller’s fill count) and the legacy ctx.Flat gate (the simulator expires the Day order before the next decision) are reviewed too; the stdio-csv-v2 wire carries no instrument push, so its levels carry no tick and the gate case’s scripted venue reports no execution where the end-to-end fixture’s quarter-tick grid keeps the stop a tick below the bar’s low; and one live-only divergence: a partial fill of the entry is withdrawn at the fill’s own turn under v2 (the position gate drops the declaration and the controller cancels the remainder at once), where the legacy Day remainder kept working through the rest of the window bar. The simulator fills whole, so no fixture reaches it.
Recorded with the competing pair (I20b): three cases are reviewed, not run. A pair leg resting across a served cut is re-placed on the incoming contract with its tag intact and re-joins its sibling by the tag (no leg rested across a cut on the master window, the one roll re-placement there being the untagged next-day stop); the position-wide gate meeting a resting pair is pinned on the wire alone (on the end-to-end gate fixture the limit fills at a gap open before the gate holds); and a partial fill of one leg, live alone, lets the venue’s OCO end the sibling, which the controller then resubmits for the remainder to re-join by the tag, assuming that IBKR lets a fresh ticket into an OCA group whose other member is partly filled and that its OCA type leaves that remainder working, both for GLE-471 to verify. A programmatic live caller that bypasses the ledger receives no AdoptedState and so no refusal, the gap the range strategy’s migration records, closed by GLE-471’s adapter-side refusal.
Migrating decision groups: a bar’s orders as one OCA set. The fifth migration, a range strategy’s (I19, GLE-465, the backtest half), the second under a native policy the owner approved under decision D3 (GLE-464), is the first whose legacy orders are an OCO group, one per bar. On each primary bar the strategy’s rules yield its signals (a long entry level and a short entry level, each valid or absent) and its protection (the tightest of a channel exit, a risk stop and a trailing stop as the stop; a profit target), and its legacy builder turns them into one decision: flat, the long entry and the short entry, each a first-touch stop or a limit at its level, as one OCO choice; held, the protective stop, the target and the opposite signal (which reverses, at the position plus the order quantity, when the reversal is on and the direction allowed, and otherwise closes), in that order, as one OCO group, a close-only order of the same side, quantity and type as an earlier one merged into it at the tighter level. Every legacy order is Day under a per-bar OCO tag, expired by the simulator after one evaluation bar and re-issued from the next snapshot. Under v2 the same decision is one decision group of the controller, which the recipe takes as these patterns:
- One group per position state, and the group is the OCA set. Flat, the long entry and the short entry under the keys
<symbol>:1longand<symbol>:2short,Group<symbol>:entry; held, the protective stop, the target and the opposite signal under<symbol>:1stop,<symbol>:2targetand<symbol>:3opp,Group<symbol>:pos. Every member carries its group’sOCOGrouptag, so the controller’s replacement unit and the venue’s one-cancels-other set are the same thing: the simulator settles the group as a unit, the first fill cancelling the siblings (oco_triggered), and live, native OCA with “cancel remaining on any execution” (GLE-471) is a prerequisite, not imitated locally. The labels on the wire are the controller’s prefix plus the key,range:ES:1longand so on with a prefix ofrange:; the keys, the group names and the tags are frozen, since they appear on the wire, in the fills blotter and in the lifecycle trace. - The keys’ digits keep the legacy array’s order. The controller submits in key order, and the simulator breaks a same-bar tie between two stop-kind members by submission order, so the key order is the group’s economic priority: the long before the short, the stop before the target before the opposite signal, as the legacy slice had them. The policy’s own names (
long,short;stop,target,opp) would have put the reversal first, so the digit is the slot. - A stable OCO tag per group, not the legacy per-bar tag. Frame equality compares
OCOGroup, so a tag that changes every bar would make every intent “changed” every bar and the group would be replaced at every decision; with one tag per group (range:<symbol>:entry,range:<symbol>:pos) an unchanged group rests with no command. A replaced group’s successors form a fresh venue group all the same, since the predecessors are terminal before they are submitted, and a denied key’s later submission rejoins the resting group. - Every intent is
GTCwithMaxWindows0. A member’s life is until it fills, is cancelled by the venue’s OCO, or is replaced or retired by a later decision; no window limit, as the policy approved, soObserveis optional (it counts nothing). - The through rule on the rounded level, equality through. The level is rounded as the legacy builder rounds, away from an earlier fill (buy stops and sell limits up, sell stops and buy limits down), and the rounded price, the one that would be submitted and the one the simulator’s stop-side guard reads, is read against the deciding bar’s close: a stop slot strictly beyond the close (a buy above it, a sell below it) rests as a
GTCstop at the level; one at or through the close is aGTCmarket order, which fills at the next open in the simulator as the first-touch stop did, where a stop would be refused on the wrong side of the market. A limit slot (the target; the entries and the opposite signal in limit mode) rests as a limit whatever the close. - The merge runs before the conversion, as the legacy builder merges. A later slot of the same side, quantity and kind (a stop slot with a stop slot, a limit slot with a limit slot) collapses into the earlier one, on the rounded levels, which keeps its key and takes the tighter level (a sell stop the higher, a buy stop the lower; a sell limit the lower, a buy limit the higher); the merged slot is then converted, and it is at or through the close exactly when either level was. So, with one quantity, a through opposite signal carries a protective stop that is not through with it: long two with the stop at 95 and the short signal at 100, closing at 100, the group is one market sell of 2 under the stop’s key, as the legacy first-touch stop at the merged level, 100, filled at the next open. Merged after the conversion the stop at 95 would have rested beside the market order, and the simulator’s rank would have given the bar to the stop whenever the low reached 95, up to five points worse than the legacy run: the advisor’s finding, folded into the owner’s decision below. A stop slot and a limit slot do not merge whatever their forms.
- The priority rule, last: a
Stopin a later slot than a market-form member is left out of the group. The simulator settles a same-bar OCO group by its ambiguity convention, a stop-kind member before anything else and ties by submission order. Under the legacy profile every member but the target was stop-kind, so the array order decided every tie; under the through rule a through member is a market order, which the convention ranks after a stop-kind sibling: a through protective stop beside a stop-mode opposite signal would lose the bar to the reversal, and a through long beside the short stop would lose it to the short, where the legacy array ran the stop, or the long, first. So after the merge and the conversion the later stops go: a through long is the market buy alone; a through protective stop beside a reversal of a distinct quantity is the market sell and the target. An earlier stop-kind slot stays (after the merge it stands beside a later market-form member only with a distinct side or quantity, the flat pair or the reversal’s size, where the legacy array ran it first too): a short level that equals the close beside the long stop keeps both. Limits stay, since a limit ties with a market order and the tie goes to the earlier slot. The rule keeps the legacy outcome wherever the market-form order fills at the next open, which in the simulator it always does; the alternative, the full group under the simulator’s rank, was put to the owner, who chose this reading (2026-10-10). - Every quantity is the position’s at the reconcile. The stop and the target for the position’s absolute size, the opposite signal for that plus the order quantity when it reverses; no fill is counted in the strategy. A changed position re-sizes the group at the next decision, the bar’s or a turn’s.
- The group is replaced whole and retired by an empty declaration. A changed level in one slot retires every member (one cancel request per live attempt, in label order, and no submission at that decision), and every member goes out afresh at the turn the confirmations grant, so on the simulated path the protection gap is zero: the successors rest from the next bar, as the legacy re-issue did. A decision that declares nothing for a symbol (flat with no valid signal, held with no valid stop, target or opposite signal, or a changed side at a turn, below) retires every attempt of the symbol’s scope. After a fill the venue’s OCO has already cancelled the siblings, so the next bar’s declaration meets no live entry and submits afresh; a pending or unknown cancellation holds the whole group’s successors until its confirmation’s own turn; a denied or rejected member blocks its key alone until its intent changes, and rejoins the resting group then.
- The turn rule: re-declare the last bar’s decision for the same side, re-sized; a changed side waits for the bar. No bar travels with a lifecycle turn, so the strategy keeps, per symbol, the last primary bar’s decision context (the position’s side at the bar, the signals, the protection, the tick and the bar’s close, the through rule’s reference until the next bar) and at every turn re-declares it for the same position side with the quantities of the position at the turn; a symbol whose position has changed side since (an entry filled from flat, a stop or a reversal filled) declares nothing until its next primary bar, which decides the new side’s group from its own snapshot and the reset protection state, as the legacy path does. Recomputing the new side’s protection at the turn from the previous bar’s snapshot would anchor its risk, trail and target distances on a different bar than the legacy path does and so change fills the approved policy says are identical; the owner took the frozen reading (2026-10-10). Live it means a new position waits for its first primary bar before its protection is placed, exactly as under the legacy profile. The standing declaration is kept by value, because
OnFillmay reset the protection state before the turn re-declares the levels, and kept until the next primary bar replaces it. - A partial fill of a held member replaces the whole group. The policy had said the remainder rests and the next declaration at the remaining quantity is unchanged, which is true of the stop’s key alone: the re-sized target and opposite signal do not meet their attempts, the granularity is the whole group, and a ticket cannot join an existing OCA set, so the partially filled attempt’s remainder is cancelled with its siblings and resubmitted into the new array with them: three cancel requests at the fill’s turn, three successors at the turn the confirmations grant, sized from the position (the opposite signal at the remainder plus the order quantity). The owner’s clarification of D3 (2026-10-10). It is live-only, since the simulator fills whole, and it carries a live-only limit: the re-declared stop is the last primary bar’s level against the market as it stands at the turn, which may have moved through it since the bar, and the stop is then refused by the admission guard (its key blocked until the next decision moves it) or triggers at once. A partial fill of an entry is not pursued, as under the breakout migration: the side changed, so the turn declares nothing and the remainder is cancelled at once, where the legacy Day remainder worked through the rest of its bar.
- Live is refused until native OCA groups exist. The IBKR adapter drops
OCOGroupfrom a ticket today, so the decision groups have no live form until GLE-471 lands. The SDK gives a strategy no run-mode field, but every live run delivers anAdoptedState(the engine requires a ledger in live mode, and the ledger’s reconciliation sends it once, afterOnInitand before any bar), soOnAdoptedStaterefuses every live run under both profiles with a message naming both reasons, the legacy profile’s first-touch stops having no IBKR ticket and the v2 groups needing native OCA; the SDK reports it asadopt_rejectedand the run ends before any order. Once GLE-471 lands, its adapter-side refusal of a bareOCOGroupticket is the second guard, and lifting the adoption refusal is the live half’s own increment; a programmatic live caller that bypasses the ledger receives noAdoptedState, the gap that second guard closes. - The rest is the earlier recipes’.
OnFillandOnOrderUpdateforwarded to the controller on every run (outside its scope it moves nothing, so a legacy run’s auto-labelled fills are harmless);Reconcileon every v2 primary bar, whatever it decides, the bar’s orders being the controller’s submissions and nothing else; several primary symbols reconciled in symbol order, each with its own standing declaration;OnInitbuilding the controller afresh with no standing declaration, so one value may serve several sessions in turn; the handlers tolerating a run on whichOnInitwas not called; and a run under the legacy profile touching no controller state, answering a turn sent anyway with nothing.
Recorded with the range-strategy migration: OnFill forwarding is reviewed, not gated (no decision reads the controller’s fill count: every quantity is the position’s), and so are a Reconcile error ending the run and several primary symbols (every fixture has one); the OCA type IBKR applies and the behaviour of the siblings on a partial fill are GLE-471’s assumptions, unverified; and the economic differences from the legacy profile in the simulator are enumerated. An at-or-through decision whose next bar opens back inside the level fills at the open where the legacy first-touch stop filled at the level (price-better by the gap) or did not fill at all (an extra trade, after which the position’s later levels anchor on the v2 entry price); a bar that gaps beyond a through level and reaches the target in the same bar fills the market order at the open where the legacy group could fill the target (rare, price-worse by the gap, and inherent to the approved rule); and the priority rule leaves out a sibling the legacy group carried, which changes nothing wherever the market-form order fills at the next open, which is every time in the simulator.
What a migration changes. On the simulated path the fills can be identical under both profiles, field for field: the successor rests through the same bar the Day order did, so it fills at the same price on the same date, and the broker ids match, the same submissions in the same order. The first migration’s end-to-end fixture pins exactly that, and its v1 blotter byte for byte; the second’s does the same in limit mode, with the cooldown bar as the bar whose only command is the cancel. What differs is in the labels, the TIF, the cancels and the lifecycle trace’s counts (The summary), each with one cause:
| Difference | v1 | v2 | Why |
|---|---|---|---|
the entry fills’ ClientID | the SDK’s auto label | the controller’s prefix:key | the controller labels the intent |
| the exit fills’ auto-label sequence | after the entries’ numbers | from _1 | the entries no longer consume the auto sequence |
| the entries’ TIF in the trace | day | gtc | the one-window life is the strategy’s rule, not the simulator’s expiry |
cancel_requests, cancels_accepted, explicit_cancels | 0 | one per unfilled attempt | the strategy cancels what the simulator used to expire |
unsolicited_cancels (tif_expired) | one per unfilled attempt | 0 | nothing expires under v2 |
replacements | 0 | one per successor | an accepted submission under a client id the strategy has used before; under v1 every order carries a fresh auto label |
signals | the submission bars | the same, plus the bars whose only command is a cancel | a lapsed signal’s bar carries a cancel request under v2 and no command under v1; a bar that cancels and submits at its turn is a submission bar already |
Equal in both: submitted, accepted, denied, rejected, fills, first_eligible_evaluations, unfilled_resting, shutdown_cancels and working_at_end. Read a migration’s trace against its legacy trace in that order: the fills and the resting counts should match; the cancels should move from the unsolicited class to the explicit one, one for one; replacements should count the successors; and signals should grow by the lapsed signals. A difference outside those columns is a behaviour change with its own explanation to give.
A reversal strategy’s trace reads the same way with two keys in place of one, and differs from the table in four places. The flatten fills carry the controller’s label too (prefix:close), so in limit mode under v2 no order of the strategy’s carries an auto label and there is no exit sequence left to move; the flattens’ TIF stays day in the trace (kit.Flatten’s constructor, a market order), only the entries’ moves to gtc; a reversal’s batch is the close then the entry, the controller’s key order, where the legacy batch was the slice order; and replacements counts the close’s successors as well as the entry’s, since every flatten after the first is an accepted submission under a label the strategy has used before (the first migration’s exits, auto-labelled, counted none). The fills, the broker ids and the resting counts should still match, the cancels should still move class for class, and signals should still grow by the cancel-only bars. On the reversal migration’s end-to-end fixture the limit mode’s six fills are equal under both profiles, the reversal’s close at the next bar’s open and its entry at the limit among them; three tif_expired become three explicit cancels; replacements are 0 and 8 (attempts 2 to 7 of the entry and 2 to 3 of the close); and signals are 9 and 10, one cancel-only bar. In market mode the two profiles agree in every field and every count, since every decision there is the legacy path’s.
A stop-entry breakout’s trace, with the through rule and an exit ladder, moves outside the table in three columns, each with its cause, and its fills can move too. submitted falls: an unchanged exit level rests under v2 where the legacy bar re-placed a Day stop every bar, so the ladder’s submissions are its level changes, not its bars (on the breakout migration’s end-to-end fixture the three-day-extreme exit, whose level moves most bars, submits 5 under both profiles, and the swing-extreme exit, whose level rests, 3 under v2 against 9). Market orders appear, one per at-or-through decision, where v1 had stop_touch throughout and v2 has none. And replacements counts the ladder’s successors as well as the entry’s, every re-declared level being an accepted submission under a label the strategy has used before. The cancels still move class for class, the Day expiries becoming explicit cancels at the same instants, with one more explicit cancel where the position-wide gate retires an exit the legacy profile let expire. The fills are identical except on the through rule’s enumerated case: on the fixture whose trigger closes through its level, the v2 entry fills at the next open, 103, where the legacy first-touch stop filled at the level, 104.25, and the equity differs by that gap alone.
The strategy’s daily golden masters, run under lifetime v2 on the served continuous contract (the legacy masters stay the regression and are byte-identical under the legacy profile, --lifetime v1), read the same way at scale. The master with the competing exit pair, refused under v2 until I20b (2026-10-12), is read after the other two. No master configures the disaster stop (DisasterStopPct is 0 in each), so its bracket child moves none of them, under either profile. The other two have 78 strategy fills each under both profiles, their roll legs identical (10 and 16); 76 of the 78 are identical in side, quantity, price and timestamp, and the two that move are the same two entry decisions in both, each an at-or-through decision whose next bar opened back inside the level, so the market order filled at the open where the first-touch stop filled at the level: a sell a quarter point better and a buy three quarters better, which at four contracts (three in the second master’s buy) are the equity differences exactly, +200 and +162.5. No trade was added or lost, and every exit fill is identical: the other 30 of 32 market entries (31 of 33) and the three at-or-through exits were followed by an open through the level and filled at the legacy price. The lifecycle counts: submitted 235 against 185 and 457 against 170 (the swing-extreme exit rests for bars at a time), 32 and 33 of the v2 submissions market orders, replacements 183 and 168 against 0, cancel_requests and explicit_cancels 107 and 92 against 0, unsolicited_cancels (tif_expired) 157 and 379 against 0; no denial, no rejection, nothing working at the end. The 20 roll records are the same on both sides, and 3 and 6 of them carry a re-placed attempt under v2: a GTC exit resting across a served cut, which the engine re-places on the incoming contract (Order lifetime v2 across a roll) and the controller follows, with no level moved.
The master with the competing exit pair reads the same way: 78 strategy fills under both profiles, its 6 roll legs identical, 76 of the 78 identical, and the two that move the same two entry decisions as in the other two masters, by the same mechanism, +200 at four contracts, the equity difference exactly. Every exit fill is identical: the 34 pair exits have the same winner under both profiles (the limit 29 times, marketable or touched, the break stop 5 times, resting as a stop and touched) and the 5 next-day stops fill as before. No break stop was decided at or through the close on this window (its 32 market orders are 30 entries and 2 next-day stops), so none of the pair’s gap cases occurs: a through break stop needs a fill bar whose low is under the swing low, so that the next-day stop rests below the pair’s level and a later bar can close at that level without touching it. Over the v2 trace the pair’s law holds, no competing exit outliving its sibling’s execution: each of the 34 pair fills is followed at its instant by the sibling’s oco_triggered cancel naming the winner, with no cancel request for the sibling after it, every pair goes out stop first, and every cancel request for one leg has its sibling’s at the same instant. The lifecycle counts under v2 against the legacy profile’s: submitted 152 against 162 (an unchanged pair or next-day stop rests where the legacy bar re-placed it), 32 of them market orders; replacements 149 against 0; cancel_requests and explicit_cancels 40 against 0; unsolicited_cancels 34 against 84, the 34 oco_triggered cancels on both sides and the legacy profile’s 50 tif_expired becoming the 40 explicit cancels at the same instants (a next-day stop’s cancel when the pair takes over, both legs’ at a re-price); no denial, no rejection, nothing working at the end; and the 20 roll records the same on both sides, one carrying a re-placed attempt under both, the untagged next-day stop.
A multi-order strategy’s trace, with a decision group per bar, reads as the breakout’s with the group in place of the ladder, and its fills can move by the same rule. The range strategy has no golden master, so its parity is pinned on six fixture runs (two configurations, one of them in both reversal modes) with the legacy blotters recorded from main before any candidate existed, which every legacy run reproduces byte for byte. Under v2 the fills are identical on every fixture whose at-or-through decisions are followed by an open through the level (three of the six), and the three that differ do so by one enumerated mechanism each: a through-form entry whose next bar opens back inside the level fills at the open, 101.25 against the first-touch stop’s 101.5, and the target then anchors on the v2 entry (109.25 against 109.5); a through-form exit on a bar that crashes through the trail and the opposite signal together (two market sells, the stop’s first in the group, since a tie between two market orders goes to the earlier slot) fills at the next open, 100 against 99.5; and a through-form exit whose next bar does not reach the legacy level fills at the open, 100, where the legacy run stayed long, one extra trade. By mechanism, on the fixture that exercises most of the recipe: submitted falls, 41 to 33, since an unchanged group rests (the two bars whose group is unchanged submit nothing) and the simulator’s Day first-touch stops and limits become GTC stops, limits and market orders under the five labels, one market order per at-or-through decision (two, both the long entry alone, the short left out); the Day expiries become explicit cancels at the same instants, 26 tif_expired against 20 explicit, each replaced group cancelled whole at its bar with the successors at the cancels’ instant; replacements, 28, counts every successor of every member; the oco_triggered cancels fall, 7 to 5, because the legacy group was re-issued each bar (an OCO cancel per sibling at every fill of a re-issued group) while the v2 group rests (one per sibling per fill); the per-bar OCO tag becomes the group’s stable tag; and at no instant does a label have two live attempts, nor the symbol more than three. The fills, five under each profile, are identical there.
The same strategy under v1 and v2 over five years of daily ES on the served continuous contract (2015 to 2020), in its default configuration and in one with the channel exit, a trailing stop and the reversal, is the real-data evidence for the policy, not a master (nothing is checked in): every fill and every roll leg is identical, 137 and 232 strategy fills, 40 and 24 roll legs, the equity identical. The two at-or-through decisions that arose in five years, both a short’s trailing stop that the bar closed through, were each followed by an open through the level, so the legacy stop and the v2 market order filled at the same open, and no enumerated difference arose. The lifecycle counts: submitted 698 against 1473 and 1806 against 2620 (an unchanged level rests; under the defaults the opposite-signal exit is the only member of a held group, so most bars re-declare one key), every v2 submission a stop but the two market orders; replacements 675 and 1762 against 0; cancel_requests and explicit_cancels 471 and 1302 against 0; unsolicited_cancels 69 and 230, all oco_triggered, against 1315 and 2346, mostly tif_expired; the 20 roll records the same on both sides, with the same re-placed attempts, 20 and 40, under both profiles, the engine re-placing a resting attempt across a served cut and the controller following it (Order lifetime v2 across a roll).
Child policy. A child is declared inside its parent’s Order.AttachedOrders under its own key, carried in the child’s ClientID, one level deep. While its parent is unfilled it is an Inactive entry under that key: it is not cancelled directly (the parent’s cancellation takes it along), and it counts as a live entry of its key, so a top-level intent declared under that key waits. Once active, through its parent’s fill or its own evidence, it is an attempt under its key like any other: a top-level intent under that key that is the child’s frame keeps it with no churn (a protective stop re-declared standalone once the strategy is long), a different one retires it and submits the successor once it is gone, and the absence of any intent under that key retires it. A declared child frame that differs from the view’s is a changed parent: the parent is retired and resubmitted whole with its children. A parent whose declared child key still has a live entry (the earlier generation’s child, active after its parent filled) waits until that entry is gone: one attempt per key holds for child keys too. Declaring a parent does not declare its child keys: a child key becomes known when its entry appears in the view, or when a fill or a declaration names it.
Group transitions. A key’s group is the Group of its last declaration. A group is being replaced at a decision when any entry of a key in it is in the retire set or PendingCancel: every commandable attempt of every key in the group is retired too (a met member is no longer met) and no member is submitted at that decision. A group not being replaced takes a new member at once. So changing one leg of an exit pair cancels both legs and resubmits both together once both are gone; withdrawing one leg retires the other; a pending cancellation on one member, the strategy’s own ctx.Cancel included, holds the whole group. The coordination is the controller’s; nothing is atomic at the venue. Intents with an empty Group are independent, and Group is not OCOGroup: the one is the controller’s replacement unit, the other the venue’s one-cancels-other tag, which is part of the frame.
Denial blocks. An OrderUpdate with status Denied or Rejected for a label the controller has submitted blocks the key for the frame of its last submission, with the update’s Reason (or the status name, denied or rejected) as State(key).Blocked. A blocked intent is not submitted while its declared Order is the blocked frame; a different intent under the key clears the block and goes out, and so does withdrawing the key or Reset. Updates with any other status, updates outside the scope and updates for labels the controller has not submitted change nothing. This is where an invalid instrument, an unresolved ownership or a cap surfaces: as a denial the engine reports, which the controller does not retry. A strategy that does not forward OnOrderUpdate has no blocks: it resubmits a denied intent at every decision, bounded by the turn budget per instant and then once per bar.
Transient blocks. A denial from the engine’s race guard is not a verdict on the order: the guard refused it because a cancellation on the same symbol and side is pending, refused, unknown or raced, or because the label’s previous attempt is still live (the reason starts with cancel_race, cancel_refused, cancel_unknown, hold_timeout or duplicate_live_label; see The engine race guard). Such a block is transient (State(key).Transient, beside Blocked): the controller notes the attempts it waits for, the key’s own live attempts and the attempts on the same symbol and side whose cancellation is pending or was requested, and at the first decision at which none of them is still in the view it lifts the block, so the unchanged intent goes out again (GLE-1363). A guard denial is the engine’s alone and no OrderCancel{Rejected} follows it. Lifting is bounded: MaxTransientRetries lifts per frame (3 by default), after which the next race-guard denial of that frame blocks it until its terms change. A Rejected status and every other denial reason block as above.
The cancel budget. The controller counts the cancel requests it issues per attempt. An attempt whose count has reached MaxCancelRequests (DefaultMaxCancelRequests, 3, when the field is 0; a negative value is a budget of none and stalls every attempt) is not requested again in that round: it is stalled, State(key).Stalled reports it while the attempt is live and not pending, and any successor keeps waiting. A stalled attempt is granted MaxCancelRecoveries further rounds (DefaultCancelRecoveries, 1, when the field is 0; none when negative), each at a decision strictly later than the instant the previous round ran out (a later bar, never the turns of the same instant), with a fresh count. A request answered pending or unknown leaves the attempt pending cancellation and nothing more is asked until the engine answers; a refused one restores it, and the next decision asks again while the round lasts. So one attempt gets at most MaxCancelRequests × (1 + MaxCancelRecoveries) requests, whatever the venue answers, and no cancellation loops. A successor attempt starts with a zero count; Reset zeroes the key’s.
Stalls. A stalled attempt is a failure to cancel, never an expiry: it stays in the view and in the exposure until the engine reports it terminal, and the controller never treats it as gone. Stalls() returns one kit.Stall per stalled attempt as of the last snapshot (in label and attempt order): its key, label and attempt, symbol and side, the quantity still working, the requests made for it across every round, the round that ran out, whether it was the final one, and the last cancel response’s outcome and reason, which OnCancelResponse records. TakeStalls() returns those an earlier call did not return for the same round, and kit.LogStalls writes each as one line of the strategy’s log, led by its name:
Dip: cancellation stalled: dip:entry attempt 1 (TEST buy, 2 remaining) after 3 requests, last refused: venue busy; one recovery round at a later decisionThe final round’s line ends ; no recovery remains, the order stays live and counted.
Halt. While halted, Reconcile validates the declaration, records the declared keys (known, their group, a block cleared by a changed intent), refreshes Live, Pending, Windows and Stalled from the snapshot, leaves Waiting and Lapsed as the last non-halted Reconcile set them, forgets nothing, requests no cancel and returns nil, nil. Observe, OnFill and OnOrderUpdate keep recording.
Forgetting. The controller remembers a key from the first Reconcile that declares it, the first Observe or Reconcile that sees a live attempt under it, or an OnFill for it, until the first Reconcile at which the key is neither declared nor has a live entry; then everything about it is forgotten, State returns the zero KeyState, and a later declaration of the same key starts afresh, its block gone and its fill count at zero. Filled accumulates every scoped fill forwarded to OnFill across the key’s attempts, a fill for an attempt the view has already retired included. An attempt’s memory (its activation, windows and cancel count) lasts while it is in the view. Reset(key) forgets at once; live attempts in the view are learned again, as fresh attempts with zero windows and zero cancel counts, at the next call. After a live restart the controller is fresh in the same way: adopted entries in the scope are learned as attempts with zero windows and counts, and Filled restarts at zero.
Sorted commands. Cancel requests are issued in label order (byte-wise) and, within one label, newest attempt first, so that each ctx.Cancel addresses the attempt the controller counts it against; submissions are returned in key order. The declaration’s own order and the view’s order across labels do not affect the commands, so a decision is deterministic however the strategy builds its slice.
Validation. Reconcile validates the whole declaration before anything else and, on the first defect, returns nil and an error beginning kit: that names it, having commanded and remembered nothing: a key that is empty or contains a comma, a space, a tab, a line feed or a carriage return (other Unicode spaces are allowed); a key declared twice, as a key or a child key; an empty Symbol, a Side other than Buy or Sell, a Quantity that is not positive, a Type outside Market to StopTouch; a negative MaxWindows; a child that fails those rules or carries children of its own. A zero Price, StopPrice or TrailAmount is a value, not a defect, and TIF, OCOGroup and Group are not checked. The same validation runs while halted.
Scope and interference. The controller reads and commands labels in its scope and nothing else: an entry under another prefix, under no prefix or under the bare prefix is neither counted nor cancelled, whatever its symbol, and fills and updates outside the scope are ignored. Within the scope it submits one attempt per key; a key found with two live attempts, equal or not, has both retired (ctx.Cancel addresses a label’s newest attempt, so an older one cannot be retired selectively) and its successor waits until both are gone. One case needs a detour: a retired attempt masked by a newer Inactive child under the same label, where the label’s cancel would reach the child. The controller retires the child’s parent instead, when the parent is in the scope: the parent’s cancellation takes the child along, and the masked attempt is requested once the child has gone. With no parent in the scope nothing is requested and the successor waits; no foreign or inactive entry is cancelled (the review panel’s correctness fix, TestRcrMaskedAttemptRetiresTheChildsParent).
State. State(key) is computed at the end of every Observe and Reconcile from the snapshot that call read, and updated by OnFill (Filled) and OnOrderUpdate (Blocked). Live counts the key’s entries in the snapshot, so after a Reconcile that submits it counts what was read, the submission not yet tracked; Pending is read after the call’s own requests, which the view marks at once; Windows is the newest live attempt’s; Waiting and Lapsed are set by the last Reconcile, and Observe leaves them.
Known limits. Two findings of the review panel are recorded rather than fixed. A rejected attached child re-declared standalone with the same frame is not blocked: the block records submissions under the parent’s key, and declaring a parent does not declare its child keys, so the retry is the strategy’s and the turn budget bounds it; the rule was deferred to the first strategy migration with protective children (I16 and I18 have a bare limit entry and a market exit, the reversal migration, I17, a market close and a limit entry, and the range strategy’s, I19, declares its protective stop and target as top-level siblings of one OCA set, not as attached children). That migration is the breakout strategy’s disaster stop, its entry’s bracket child under v2 (GLE-480, the backtest half, landed 2026-10-11), and its backtest needs no child-specific rule: the simulator validates a child with its parent, so a bad child denies the whole entry and the controller blocks the entry’s key for that frame, and the strategy declares the child nowhere but inside the entry, so there is no standalone re-declaration to block. The live rule, for a venue that accepts a parent and rejects its child, stays deferred to GLE-480’s live half. And under foreign interference two rows with the same label and attempt number share one memory, assigned by view order, so when one of them leaves the memory rebinds; the SDK stamps attempts per label and the controller submits one per key, so duplicates arise only from outside, the effect is confined to the windows and cancel counts of the interfering rows, and a stable row identity would need OrderRef, which v1 and unacknowledged entries lack.
Cost. BenchmarkTr5UnchangedLadder declares the same ten-leg ladder on each of 525,600 one-minute bars, Observe then Reconcile, against a view that hands out a stable slice: about 1.3 µs per bar with no allocations (the tournament’s reference measured 3.6 µs and three). The real ctx.WorkingOrders() copies its entries on every call on top of that, the SDK’s cost rather than the controller’s. The controller does not sort, rewrite or retain the slice the view hands it.
The race guard beneath it. The engine’s admission race guard (The engine race guard; I6: same-side orders held behind a pending cancel on every path, owner decision D2) is the live safety net under the controller, and the controller does not depend on it, nor on Submitting surviving a bar: it reads a status only as Inactive, PendingCancel or any other live one. Held and SubmissionUnknown are live and commandable to it: a held attempt is a live attempt that waits, and may be cancelled.
Tests. strategies/kit/tournament_tr5_spec_test.go drives the controller over a fake view that follows the view’s laws (24 tests and the benchmark); strategies/kit/kit_reconcile_review_test.go holds the review panel’s gap tests; sdk/strategy/tournament_tr5_sdk_spec_test.go runs a controller-built strategy through the real runner, view, pb wire and lifecycle turns against a scripted engine (the stable-then-changed replacement at the turn, the 4-of-10 residual, the auxiliary bar, the denial, the bracket child’s window).
The exit-once gate
kit.Exiting(ctx, symbol) (strategies/kit/exiting.go; the order-lifetime programme’s increment I21, PR4, GLE-467, landed 2026-10-11) reports whether a working order on symbol opposes the strategy’s position there: an order whose side would reduce or close the position if it filled, a sell while long or a buy while short. It is the gate the programme’s market-order audit put on every market exit it found gated on the position alone, under both profiles.
Why. A market exit gated on the position alone,
if mp > 0 && exitRule {
return []algolang.Order{kit.Flatten(bar.Symbol, mp)}, nil
}submits a second flatten when the rule holds again on the next bar while the first flatten is still unfilled, and at a venue where a market order rests across a decision the two together reverse the position instead of closing it. The simulator cannot reach the window: a market order fills at the next bar’s open, before that bar’s decision, so the position is flat when the rule is read again. A live venue can hold a market order across a decision (a halted instrument, a closed session on an intraday grid, an outage, a venue that queues market orders at the open). The first migration recorded the window for the audit rather than closing it and the second recorded it again (The desired-order controller); the reversal migration’s controller-scoped close does not have it, since the key law allows one live attempt per key. The owner’s decision of 2026-10-10 (the plan’s Q2): a kit gate under both profiles, now, rather than a close intent per strategy under v2 alone, an engine-side admission rule that the legacy family’s reverse-in-one-bar batches would trip, or a recorded anomaly. It is the pattern of the e9reuse demo, a shortfall buy gated on ctx.WorkingOrders(), generalised.
The rules. The whole input is ctx.Exposure(symbol): the signed position and the working orders the Context selects for the symbol (a continuous series’ contract-addressed orders included, so no further symbol test is needed).
- A nil
ctxis false. - A flat position is false whatever is working: no position, or a symbol the
Contexthas not seen. A sell on a flat position is an entry, not an exit, and the strategies gate their entries onctx.Flatalready. - Otherwise it is true when any working entry’s
Sideopposes the position, a sell while the quantity is positive or a buy while it is negative. Each entry counts by its side alone: its type, time in force, quantity, status, attempt and reference are not consulted. Under v2 a submitting, held, inactive or pending-cancel attempt counts as a working one does. The question the gate answers is whether an exit is already in flight, and an attempt the SDK still lists is one the engine has not ended: a submitting attempt may be acknowledged a moment later, a held one sent, an inactive child activated by its parent’s fill, so a rule that counted live statuses alone would reopen the window on each of them. A partial exit in flight is true as well: a second flatten would over-sell. - The attached orders inside an entry are not walked. Under v2 a labelled attached child is an entry of the view in its own right, so an inactive sell child of a buy parent counts while long; the legacy map holds the parent alone, so there it does not. The asymmetry is the SDK’s views’, documented rather than papered over: none of the gated strategies attaches orders. The first migration that does, the breakout strategy’s disaster stop as its entry’s bracket child under v2 (GLE-480, the backtest half, landed 2026-10-11), calls no gate, its exits being controller keys under v2 and first-touch stops under the legacy profile, so the case stays GLE-480’s for a strategy that gates a market exit beside an attached child.
- It keeps no state and allocates nothing beyond
Exposure’s own.
Both views serve it. Under the legacy view the map holds an order from its submission until a fill, a cancel or an expiry removes its label; under v2 the attempt-indexed view holds every unresolved attempt until its terminal event, a fill, a confirmed cancel, a venue cancellation or an expiry (The working view under lifetime v2). So a confirmed cancel response reopens the gate under v2 and leaves it closed on the legacy view until the cancelled event, and a partial fill keeps it closed under v2 and reopens it on the legacy view, each as the SDK makes the view. An adopted position with an inherited resting exit is true from the first bar. The one view the gate cannot help is a Go strategy on a legacy run over stdio-csv-v1, whose map strands a filled order (Other languages); there ctx.Flat already blocks re-entry, and the gate adds no failure of its own.
The recipe. Gate a position-based market exit on it, and wait while it holds:
func (s *Trend) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
c := kit.Series(ctx, bar)
if c.Len() < 2 {
return nil, nil
}
mp := ctx.Position(bar.Symbol).Quantity
if mp > 0 {
if kit.Exiting(ctx, bar.Symbol) {
return nil, nil // the exit is still working: wait for it rather than send another
}
if c.Close(0) < c.Low(1) { // the rule may hold again on the next bar
return []algolang.Order{kit.Flatten(bar.Symbol, mp)}, nil
}
return nil, nil
}
if ctx.Flat(bar.Symbol) && c.Close(0) > c.High(1) {
return []algolang.Order{algolang.MarketBuy(bar.Symbol, s.Size)}, nil
}
return nil, nil
}An exit decided in one expression takes the gate inline, mp > 0 && !kit.Exiting(ctx, bar.Symbol) && exitRule; a position branch with several exits takes it at the head, as above, and the early return then withholds the whole branch while an exit works, a same-bar reversal entry included, which is the same rule (the entry would otherwise race the unfilled flatten). In the simulator the gate is open at every decision, since the flatten filled at the bar’s open, so every decision, blotter and golden is unchanged under either profile: the conformance parities and the goldens prove it. At a live venue the second flatten is withheld until the first ends, by a fill, a cancellation or an expiry, and the next bar whose rule holds flattens what is left.
The audit. What the audit read on main before the change, and what PR4 did with each row; the production strategies are named by class.
| Strategies | The exit | Exposed | PR4 |
|---|---|---|---|
| Five of the seven market-only production strategies, those that manage the position in one branch: the two long-only daily trend systems, the tail-risk hedge, the daily commodity trend system and the weekly-primary metals reversal strategy | kit.Flatten at up to three exits each (a signal, a hold cap, a stop level), gated on the position alone | yes | gated at the head of the position branch, if kit.Exiting(ctx, sym) { return nil, nil }, so while an exit works the whole branch is withheld, the flatten and, where the branch places one, a same-bar reversal entry alike |
| The daily runs strategy that pyramids and reverses on one bar | a flatten then an entry on one bar, the flatten gated on the position | yes | the gate seeds its one-flatten-per-bar closure: the flatten is withheld, a reversal’s entry leg still goes out, and once both fill the SDK’s position accounting reaches the end state the legacy pair reached |
| The ten-symbol basket rotation | a close then an open on one bar from ctx.Position; the rebalance repeats while the first close rests | yes | the gate is on the whole rebalance: a close in flight defers it |
The multiseries demo | MarketSell while long when the hourly trend is down or the fast average crosses below the slow one; the trend condition holds bar after bar while the sell rests | yes | gated in the sell’s case |
| The first and second migrated strategies (I16, I18) | the legacy market exit under both profiles, kept as main’s at the migration | yes, recorded at the migration | gated at every exit site, on both paths: under v2 the exit is a plain flatten beside the controller’s entry |
| The reversal strategy (I17) | in limit mode under v2 the close is a controller key; in market mode under either profile, and under the legacy profile in limit mode, the legacy flatten | the legacy path | gated at its three exit sites on the legacy path alone (workingGate && kit.Exiting): the v2 limit path keeps the key law, one live attempt per key, and a gate in its rules would reset the close’s fill count on a re-flatten bar; the reversal flattens in its entries are covered by its working-order gate on the legacy path and by the controller under v2 |
| The swing-breakout (I20a) and range (I19) strategies | controller-scoped closes | no | one live attempt per key; untouched |
The smacross demo | MarketSell of 1 + pos when CrossesBelow && pos > -1 (GLE-533: before, a sell of one when dir >= 0) | no | crossovers are edge-triggered and alternate: a second sell needs a cross above first, and the order is the difference between one unit on its side and the position, so a repeat finds nothing to trade; untouched by PR4 |
The e9reuse demo | a shortfall buy gated on ctx.WorkingOrders() | no | the gate the fix generalises; untouched (declared under both lifetimes in PR5, with parity over its ticker-reuse fixture) |
The e9equity and e9rename demos | enter once (ctx.Flat && !bought) | no | untouched; their GTC stops are PR5’s: declared under both lifetimes with parity over the split and rename fixtures, and the stops across adoption pinned by a scripted session each |
| The twelve other market-only demos | per demo; most rebalance to a target read from ctx.Position, which repeats while an order rests | to read | not edited in PR4; the plan assigns their reading to PR3’s preparation |
| The family of 18 legacy strategy binaries | the desk’s market exits and MOC closes | yes in principle | outside I21’s code scope: refused under v2 (PR6) until its migration, GLE-497, whose backtest half landed 2026-10-12: under v2 a market exit is one controller key, whose one live attempt is the guarantee, and an MOC close a native order; on the legacy path the shared Desk withholds a close of the whole position at market or at the close while one it sent is still working, the gate narrowed to its own closes (the exit set’s legs and an entry’s attached legs do not count) |
Tests. strategies/kit/aa00_cs21_exiting_tournament_spec_test.go drives a probe strategy that records Exiting at each bar of a scripted session (Conformance under both lifetimes) across the three profiles (the v2 view on both wires, the legacy view on pb): false while flat, flat with a buy working, long with nothing or a buy working, for a symbol the context has not seen and for one with a working order and no position; true while long with a sell working beside a buy, while the sell is pending cancellation or still in the legacy map after a cancel request with a further buy submitted after it (the opposing entry neither first nor last), and while short with a buy working beside a sell; the views’ own differences surface as the SDK makes them; an adopted long with an inherited resting sell is true from the first bar and an inherited buy false; the inactive child counts under v2 alone; and a nil context is false. cs21r_exiting_review_test.go holds the review panel’s gap tests: an opposing order counts before its acknowledgement (submitting under v2, in the map on the legacy view) and after a held update, and on a continuous series a contract-addressed opposing order that Exposure(root) includes closes the root’s gate. The hazard and the gate on the strategies are the scripted session harness’s exit-once tests, below.
Orders that outlive a decision
The exit-once gate covers a flatten that is still working. Under lifetime v2 an order persists until the engine ends it, and three more cases follow from that (GLE-1363): an entry only partly filled when the exit comes, an earlier signal’s orders still working when a later signal opposes them, and a cancellation the venue refuses, leaves unknown or never confirms. The kit answers them with two helpers that keep a withdrawn order counted until the engine reports it terminal, and never assume a cancel request removed it. In the simulator a market order fills whole at the next open, so neither case arises there and every blotter and golden is unchanged. Under the legacy profile orders live one bar, so the helpers send the plain flatten and start nothing.
kit.Withdrawer (strategies/kit/withdraw.go) withdraws working orders for a strategy without a controller. Withdraw(ctx, symbol, side) requests the cancellation of every working order on that side and returns how many are still live, pending cancellation included. It keeps the controller’s ledger per attempt: MaxCancelRequests requests in a round, MaxCancelRecoveries further rounds at later decisions, the last response’s outcome (forward OnCancelResponse), and Stalls and TakeStalls for an attempt whose budget is spent. Withdrawn(label, attempt) reports an attempt it took for withdrawal that the view still holds: an order whose fate is open.
kit.ExitRecovery is the exit of a strategy whose entries are market orders of any size. Exit(ctx, symbol, mp) withdraws the working orders on the position’s side (the entry’s remainder) and returns the flatten of the position. The recovery then lasts until the remainder has ended and the position is flat. Step is called at the top of each later decision. It asks again for the remainder’s cancellation within the budget, and flattens the part of the position the working opposing orders do not cover, such as late fills of the remainder or a flatten that did not fill. It reports busy while it holds the decision, so no entry goes out on top of an unresolved remainder. Turn does the same at a lifecycle turn, so a late fill is flattened without waiting for the next bar. A turn whose position has not moved since the last flatten sends none: a refused flatten is retried at the next bar, not at the turn its denial grants. A stalled remainder keeps the recovery open.
type Breakout struct {
Size int64 `algolang:"default=10,min=1"`
exit kit.ExitRecovery
}
func (s *Breakout) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
defer func() { kit.LogStalls(ctx, "Breakout", s.exit.TakeStalls()) }()
mp := ctx.Position(bar.Symbol).Quantity
if orders, busy := s.exit.Step(ctx, bar.Symbol, mp); busy {
return orders, nil // an exit's remainder or late fills are still being resolved
}
c := kit.Series(ctx, bar)
if c.Len() < 2 {
return nil, nil
}
if mp > 0 && !kit.Exiting(ctx, bar.Symbol) && c.Close(0) < c.Low(1) {
return s.exit.Exit(ctx, bar.Symbol, mp), nil // withdraws the entry's remainder too
}
if ctx.Flat(bar.Symbol) && c.Close(0) > c.High(1) {
return []algolang.Order{algolang.MarketBuy(bar.Symbol, s.Size)}, nil
}
return nil, nil
}
func (s *Breakout) OnLifecycleTurn(ctx *algolang.Context, _ algolang.LifecycleTurn) ([]algolang.Order, error) {
return s.exit.Turn(ctx), nil
}
func (s *Breakout) OnCancelResponse(ctx *algolang.Context, r algolang.CancelResponse) {
s.exit.OnCancelResponse(ctx, r)
}The strategies. Named by class, as in the audit above:
| Strategies | Under v2, since GLE-1363 |
|---|---|
| A long-only daily trend system, the daily commodity trend system and the weekly-primary metals reversal strategy | every exit goes through ExitRecovery: a partly filled entry’s remainder is withdrawn, late fills are flattened, and entries wait until the remainder has ended and the position is flat; the long and short sides alike where the strategy trades both |
| The daily runs strategy that pyramids and reverses on one bar | while any order on the symbol is working, or a withdrawal is unresolved, it decides on the accounted position (the position plus every live order’s signed remainder, so a pyramid on a pending add still adds one) and moves toward the target that gives: the orders against the move are withdrawn through a Withdrawer, the order that is right whatever they do goes out at once, and the rest waits until they end, sized from the position so a fill that raced its cancellation is reconciled; with nothing working each decision is as before |
| The reversal strategy (I17), in limit mode | an entry decided while flat is sized against the position projected through the standing close: on the close’s side it is reduced by the close’s remainder (to none when the close alone reaches the target), so a size-one reversal whose entry leg fills first stays size one; a close on the other side is stale and withdrawn; a close blocked by a permanent denial counts for nothing |
| The swing-breakout strategy (I20a, I20b) | its replacement exit, denied by the race guard while its disaster stop’s cancellation is unknown or refused, goes out unchanged once that cancellation ends (the controller’s transient blocks) |
| Every user of the controller: the strategies above with a controller, the first and second migrated strategies, the range strategy and the shared desk of the 18 legacy binaries | forward cancel responses and log each stall with kit.LogStalls |
The long-only daily trend system without the helper and the tail-risk hedge enter one lot at a time, so they leave no remainder; the basket rotation sizes its orders and is not yet covered.
Tests. strategies/kit/cancelfail_test.go drives the controller’s transient blocks, rounds and stalls, and the two helpers, over a fake view. Each strategy’s cancelfail_test.go runs its scenario under a scripted session: orders that survive several bars, both leg-fill orders and partial fills, pending, refused and unknown cancellations, a budget spent to its final stall, a denied close and late fills. Each test fails under a mutation that removes its fix.
Conformance under both lifetimes
strategies/conform (the order-lifetime programme’s increment I21, unit 1, GLE-467) is the shared conformance library the strategies’ test files claim their lifetime outcome with: market-only parity between the two profiles, the host’s refusal of a strategy that accepts nothing, a port’s byte-for-byte replay and, since I21’s PR4, a strategy’s decisions one by one under a scripted engine. It is imported by test files alone, beside the strategy it checks, and it runs the real thing: a backtest goes through engine.Run and the file-csv adapter, a port runs as a process, and a scripted session runs the strategy value in-process through algolang.Run. It has four parts.
The engine-backed checks. Build compiles a main package once per test (go build with CGO_ENABLED=0, memoised for the test’s lifetime, the binary in the test’s temporary directory). Backtest and TryBacktest make one run of a Run (the strategy’s import path, a bar CSV the file-csv adapter serves, its interval, the symbols, the range, the inputs, and the data wire when a declared series needs one: DataProtocol, as the CLI’s --data-protocol, since the engine chooses the wire from the configured series before the strategy declares its own, and the DBN wire cannot carry a weekly release series, GLE-311; and, since I21’s PR3b, the adapter and the bar construction when the run needs bars built from the trade stream: Adapter, "" or file-csv for the file-csv adapter and databento for the Databento file adapter over a trades file, with BarKind and Threshold as the CLI’s --bar-kind and --threshold, so the construction statistics, the trade tape and a declared series with a construction of its own reach the strategy as the engine’s end-to-end tests serve them; the three are validated with the rest of Run, before any build) under one profile, "v1" or "v2", with a fills blotter and a lifecycle trace written to a directory of the test, the performance report off and the series cache off, and return a Result: the blotter byte for byte, its fills decoded (BrokerOrderID and the fill’s fields; Attempt is the v2 frame’s and 0 on a v1 run), the trace’s summary counts and records, and what the engine printed. TryBacktest returns the run’s error; Backtest makes it fatal with the engine’s output. Parity runs v1, then v2, then applies Check. RefusedUnderV2 runs v2 alone and returns the host’s refusal of a strategy that accepts nothing (an error containing conform.LifetimeRefusal, the text of the engine’s error); a run that succeeds is fatal, since the strategy accepted lifetime v2, and a run refused for another reason is fatal too. ReadResult (PR3b) reads what a run made outside the suite wrote, the CLI’s --fills-json and --lifecycle-json, back into a Result under a named profile, so a golden-tagged test that runs a demo through the CLI and an adapter the suite cannot build (the marketfeed adapter over the archive) builds its two results that way and applies Check.
The claim. Check(v1, v2, want) is pure: it reads two results and the file Expect names, and returns the first failing claim, in this order:
- when
Expect.Goldenis set, the v1 blotter equals the frozen blotter byte for byte (the v2 blotter is not compared this way: the v2 frame addsAttemptto each fill), so the legacy profile is pinned as the migrations pin it; - the two fill lists have the same length and agree fill for fill on
ClientID,Symbol,Side,Quantity,Price,Timestamp(as an instant),CommissionandBrokerOrderID, in that order; - the claim is not vacuous: each profile has at least
MinFillsfills (2 when unset) and, unlessOneSided, a buy and a sell among them, so a run that does not trade cannot satisfy it; - every summary count of the lifecycle trace agrees between the profiles, over the union of the keys in sorted order, a key absent on one side read as 0 and the keys in
AllowDifferskipped; whenExpect.OneBaris set (GLE-1362, a strategy keeping its one-bar order life withkit.OneBar), the counts that life moves between the profiles are first checked against each other and then skipped: theunsolicited_cancelsv2 has fewer of than v1 (v1’sTIF_EXPIREDcancels) must equal theexplicit_cancels,cancel_requestsandcancels_acceptedit has more of, and itssignalsmay be more by no more than that (a decision that sent orders anyway is one signal under either profile); - when
MarketOnly, no record of either trace submits anything but aDaymarket order, requests a cancellation, or records a cancel other than the end-of-data one (reasonshutdown): atif_expiredwould mean a market order rested past its bar, anexplicitcancel that the strategy cancelled, and either fails the claim.
The port harness. Replay(t, cmd, transcript) runs a program over a frozen session transcript in the format of internal/wire/testdata/csv2/lifecycle_wait.txt (> engine lines, < strategy lines): the engine lines, in order, are the process’s whole standard input, fed at once and then closed, and its standard output, every log, line dropped, must be the transcript’s strategy lines in order, byte for byte, the hello line included; a line beyond the last, a line that differs and a line missing are each fatal, naming the transcript and the line. It is protocol-agnostic: it feeds engine lines and compares strategy lines whatever the grammar, so the one function replays the Python lifecycle fixture’s two stdio-csv-v2 transcripts and, since I21’s PR7a, the dual-grammar ports’ session transcript (smacross_sine.txt) through each dual-grammar port, the scripting four since PR7a, the compiled three since PR7b and the functional two since PR7c (The ports under both grammars). Decisions(t, cmd, input) runs a program with a stdio-csv-v1 replay input and returns, in order, the lines that are exactly noop or start with order,, the decision stream the shell crosscheck compares; V1ReplayInput(t, fixture, inputs) builds that input from a bar CSV exactly as scripts/smacross-crosscheck.sh does (the init line in replay mode, then one bar line per row with ts_open dropped and every field copied verbatim); ReadTranscript parses a transcript; and Toolchain(t, program) returns the program’s path or skips the test, naming the program, when it is not installed.
The ports under both grammars. pr7_ports_test.go applies the harness to the dual-grammar ports (I21 PR7a, PR7b and PR7c): TestPr7PortsDecisionsV1 (Decisions against the Go demo), TestPr7PortsReplayV2 (Replay over the frozen transcript, its hello token and name tag localised to each port) and TestPr7PortsEngineEndToEnd (engine.Run over a family head, a script or a binary the test built, under each profile, which Run cannot name, the two runs’ files read back through ReadResult and the engine’s output captured through the suite’s test hook), each a table the families extend; a compiled port’s row builds it into a directory of the test, through Toolchain, before the harness runs it (The ports under both grammars).
The scripted session harness. conform.Session (I21’s PR4, 2026-10-11) is a scripted engine for one strategy value, in-process: StartSession(t, strategy, cfg) swaps the process’s standard input and output for pipes whose other ends the session holds, starts algolang.Run on the strategy, and speaks the wire cfg.Wire names, conform.WireCSV2 (stdio-csv-v2, the line protocol of the order-lifetime v2 profile) or conform.WirePB (stdio-pb-v1, framed envelopes both ways); the test then writes the engine’s side and reads the strategy’s, decision by decision. It generalises the one-strategy harnesses the migrations’ wire tests carried, one copy per strategy on stdio-csv-v2 alone, and its pb side carries what pb alone carries, the adopted-state push. StartSession makes the handshake (the hello line checked, the protocol selection sent) and the init from SessionConfig, every field but Wire defaulted: RunID (session), Start and End (the year 2020), Instruments (one, TEST on XTST, a future with point value 1 in USD), Inputs by name, Offered, the capabilities the engine offers (nil offers nothing, so the strategy runs the legacy view; the v2 token offered to a strategy that supports it runs the v2 view, on either wire), BatchLimit for the csv2 init line (256) and Timeout, the bound on each wait on the strategy (zero is 30 seconds; any other value is used as given, a negative one ending every wait at once). The decoded init_ack is Session.Ack, with the capabilities the strategy accepted. The typed sends each convert the SDK value and carry it as the wire does: Warmup(bars...), a block the strategy buffers without a decision and answers with one empty batch at the last bar’s close; Bar, answered with one batch; Update, Fill, Cancelled and CancelResponse, which move the strategy’s view and are not answered; Turn(at, turn, budget), a lifecycle turn answered with one batch; and, on pb alone, Adopted(state), the live-mode adopted-state push, fatal on csv2 as not expressible. The raw Send(line) on csv2 and SendEnvelope(env) on pb carry what has no typed send (a late bar, a corporate action, a roll, a session line, a shutdown the session does not wait on), each fatal on the other wire. A send does not read the reply: every decision sent is followed by one read of its batch. Batch() reads one reply, on pb the cancel-request envelopes up to and including the OrderResponse, on csv2 the cancel and order lines up to and including the commit line, whose count must match, into a protocol-neutral Batch: At, the instant it answers; Cancels, the cancel requests as label, attempt and request id (attempt 0 and an empty id on the legacy view); Orders, decoded from what the wire carried (on csv2 the fields of the order line, its conviction and name included, on pb the OCO group, the attached orders and the combo legs as well; Attempt the label’s under v2 and 0 on the legacy view); and, on csv2, Lines, the command and commit lines byte for byte as the strategy wrote them, a dropped log line not among them. Every read drops log lines and envelopes and is fatal on an error line or envelope, with its text. Expect(what, want) reads one batch and compares its rendering with want’s line for line, a difference fatal with both renderings; ExpectEmpty(what, at) expects the empty batch at an instant; and RenderBatch(b) is the rendering, pure, in the stdio-csv-v2 grammar: one cancel line per request; per order its order line with the side, type and time in force as their wire tokens and each price in its shortest form, ,oco=<group> appended when it has one, then a leg line per combo leg and each attached order under attached; and last commit,<instant>,<count>, every field escaped as the wire escapes a csv2 field, so a label that carries a comma keeps its own column and two batches that differ render differently. Shutdown() sends the engine’s shutdown (end_of_data), waits for Run to return and ends the session, a non-nil result fatal; Exited() waits for Run and returns its error, the SDK’s when the strategy ended the run itself (an OnBar error), and returns it again without waiting afterwards. A session the test leaves open is ended by the cleanup StartSession registers as soon as it holds the capture mutex: the strategy’s input is closed, so Run returns with its closed-stream error, the exit is awaited for at most five seconds, then the streams are restored and the pipes closed, the strategy’s own ends included when Run has not returned, so a strategy blocked in OnBar leaves no descriptor open. Every send keeps the rule that fixed the send-against-exit race of the migrations’ harnesses (GLE-477): a strategy can read an item, act on it and exit before the write is observed complete, so a write that completes within a second of the exit succeeds, and the next send is fatal naming the exit with Run’s error. Every wait on the strategy is bounded by Timeout, one deadline across the log items a read discards, and every failure is fatal through the testing.TB given to StartSession, prefixed conform.Session:.
Its limits are the swap’s. While a session is open it holds the package’s capture mutex, taken without waiting: a second session, or a session started beside a backtest’s capture, is fatal at once, and Backtest, TryBacktest, Parity and RefusedUnderV2 started while a session is open wait for it to end. While it is open os.Stdout is the strategy’s output pipe, so a test must not print to it (a fmt.Print there corrupts the wire; it broke the pb frames in an exploratory driver): t.Log and os.Stderr are the outlets. A session is not safe for concurrent use, nor for a test that called t.Parallel. The legacy view is driven on pb: the csv2 codec carries no order without an attempt, which the SDK stamps under v2 alone, so a strategy that returns an order under the legacy view on csv2 is answered by the SDK with an error line in place of the batch, which the next read reports.
The harness’s first use is the exit-once evidence of the market-order audit (The exit-once gate). TestCs21ExitOnceHazardAndGate drives a flattener strategy in two variants under three profiles (the v2 view on both wires, the legacy view on pb): the entry at bar 0 fills; bar 1 flattens; the flatten is acknowledged working and not filled; on bar 2 the rule holds again, and the ungated variant submits a second flatten where the gated one submits nothing; the first flatten then fills, and the gated variant re-enters at bar 3 and flattens again at bar 4, the gate reopened, while in the ungated variant both flattens fill and the reversed position places no entry. Two consumer tests run the real strategies the same way: a long-only daily trend system over its PR2a fixture up to its first exit, then crafted bars whose closes break the previous high and the 35-bar high, so the signal exit holds again (the bars after the unfilled exit silent, the flat bar after the fill placing no sell), and the multiseries demo driven as the engine drives it (the sell unfilled, silent on the next two primary bars). Measured on main before the gate, both strategies submit a second sell on the bar after the unfilled exit under every profile; with it, each bar is silent. The harness’s own tests (strategies/conform/aa00_cs21_session_tournament_spec_test.go) start and shut a session down on each wire and view, check the configured init, a bar’s batch with its csv2 lines byte for byte, the warm-up block, the events moving both views as the SDK defines (a venue cancel with no request before it included), the turn with and without a handler, the adopted state on pb and its refusal on csv2, the strategy ending the run on an OnBar error, the fatal paths, the read timeout, a refused init, the output-ended diagnostic, the cleanup ending an open session, the legacy view on csv2 and RenderBatch on synthetic batches; cs21r_session_review_test.go holds the tests of the review panel’s fixes and its gap tests.
Its second use is the demo recovery of I21’s PR5 (2026-10-11), the claim of the plan’s section 6 that the e9equity and e9rename demos’ GTC stops survive adoption. e9_adoption_test.go beside each demo starts a session on pb under the v2 view and the legacy view, the two on which the SDK delivers the adopted state (the csv2 wire has no adopted-state line), with the demo’s symbols as the instruments; sends Adopted with the position and the stop as a working attempt (the complete v2 frame under v2, the nine v1 fields on the legacy view), then three flat bars above the stop, each answered with no order, a fill of the stop, and a fourth bar answered with no order; and shuts the session down. The demo runs wrapped in a probe that records its context’s view after each bar and fill: the first bar sees the adopted position and the adopted stop, the fill leaves the view flat with nothing working, and no batch carries an entry, a cancel request or a re-placed stop. A second scenario adopts the position alone, the stop having ended while the process was down (under lifetime v2 the venue cancels it at a split), and the ctx.Flat gate alone holds the entry on every bar. e9equity re-places a stop the venue cancelled for a corporate action only when it receives the cancel (GLE-498); a restarted demo did not, and knows no level to re-place it at, so it places nothing. Each demo recovers its entry latch in OnAdoptedState from the adopted stop (a working order on its symbol is its own), so the restarted demo does not buy a second lot once the stop-out leaves it flat. The engine-level recovery, the ledger fold and the venue reconciliation that produce the adopted state on the live path, is I8 unit 2’s.
Using it. A market-only strategy claims parity in three steps: the declaration, a fixture, and a test beside the strategy. The declaration is I16’s seam with no branch, since the decisions are the same under either profile:
// SupportedCapabilities: the strategy places Day market orders alone,
// gated on the real position, so it follows the run's profile.
func (s *Trend) SupportedCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}The fixture is a bar CSV under the strategy’s testdata that makes it trade (an entry and an exit at least; a sine or a ramp is enough for a crossover), and the blotter the strategy wrote over it under the legacy profile before the change, recorded once with --fills-json from main’s binary and committed as the golden. The test runs the suite:
func TestTrendMarketOnlyParity(t *testing.T) {
if testing.Short() {
t.Skip("builds and runs subprocesses")
}
v1, v2 := conform.Parity(t, conform.Run{
Strategy: "<module>/strategies/trend", // the main package's import path
Fixture: "testdata/parity/sine_1d.csv",
Interval: "1d",
Symbols: []string{"TEST"},
Start: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
End: time.Date(2020, 4, 10, 0, 0, 0, 0, time.UTC),
}, conform.Expect{
Golden: "testdata/parity/v1_fills.json",
MinFills: 4,
MarketOnly: true,
})
if v1.Trace.Summary["fills"] != v2.Trace.Summary["fills"] {
t.Fatalf("summaries v1 %v, v2 %v", v1.Trace.Summary, v2.Trace.Summary)
}
}A strategy that must not run under v2 claims the refusal instead, conform.RefusedUnderV2(t, run); a port claims its stream, with conform.Decisions against the Go demo’s over conform.V1ReplayInput, or conform.Replay over a frozen transcript.
The refusal’s first production consumer was the family of 18 legacy strategy binaries that rest Day stop and limit entries, attached protective children and per-bar OCO exit sets, re-emitted every bar (I21’s PR6, landed 2026-10-11, under the owner’s decision of 2026-10-10 to refuse the family then and migrate it after native OCA groups, GLE-471, and native brackets, GLE-480). Each binary had one test of a few lines that called RefusedUnderV2 through a shared helper of the family’s test harness, which wrote an eight-bar daily fixture, ran the one v2 backtest and required the engine’s refusal to name the binary. The family’s migration, GLE-497, whose backtest waited on neither ticket once the simulator settled OCA groups under v2 (I19’s backtest half) and bracket children (GLE-480’s backtest half), landed its backtest half in four parts on 2026-10-12: each binary now supports v2 and its test claims parity instead, both fills blotters frozen and v2’s fills equal to v1’s fill for fill, through the harness’s lbrtest.Conformance, and the refusal helper went with the last refused binary. The family is no longer a consumer of the refusal; live, each binary refuses a v2 run at the adoption handshake itself.
Measured. Three facts, measured on main before the suite existed and pinned by its tests. An undeclared Go strategy is refused under --lifetime v2: the engine returns engine: <strategy>: wire: the run selected lifetime-v2 but the strategy did not accept it; a strategy that does not implement the v2 order lifetime must run under the legacy execution profile (GLE-200 I2), so no market-only row can claim parity until it declares support, and at I22’s default flip, which landed on 2026-10-12 (GLE-470), every undeclared strategy and demo would stop running on a backtest that does not name --lifetime v1, so each declared first (RefusedUnderV2’s own test, which names v2 explicitly, used the printbars demo until I21’s PR3b, and since then the suite’s own undeclared fixture program, strategies/conform/testdata/undeclared, a strategy that places no order and declares nothing, kept under testdata so that ./... patterns leave it out of make test, go vet and the build list and Build compiles it through its import path alone; every demo is declared). With the declaration, the SMA-crossover demo’s v2 run reproduces its v1 run: over a 96-bar daily sine fixture (strategies/demo/go/smacross/testdata/cf21/, Fast 3 and Slow 8, one symbol, 2020-01-01 to 2020-04-10) each profile makes eight fills, four buys and four sells, equal field for field with equal broker ids (sim-1 to sim-8) and equal lifecycle summaries (8 submitted, 8 accepted, 8 fills, no cancel request and no cancel), every submission a Day market order; the v2 blotter differs from the v1 blotter only by the "Attempt": 1 the v2 frame adds to each fill, and the v1 blotter is byte-identical to the frozen one (testdata/cf21/v1_fills.json, written by main’s binary and frozen again when the demo began to reverse through flat, GLE-533: the first fill is one unit and the seven after it two). And a stdio-csv-v1 port is refused under v2 by the v1 codec, not silently run: wire: capabilities [lifetime-v2] are not expressible in stdio-csv-v1; run the strategy on stdio-pb-v1 (GLE-200 I2). The suite’s own tests (strategies/conform/aa00_cf21_tournament_spec_test.go; 34 with the demo’s) check every claim of Check on synthetic results, Backtest and Parity on the demo, RefusedUnderV2 on the undeclared fixture program, Replay on the Python lifecycle fixture over both of its transcripts, and Decisions across the Go, Python and shell ports (96 decisions, 8 orders, byte-identical); the first consumer is strategies/demo/go/smacross/aa00_cf21_conform_tournament_spec_test.go; the seven market-only production strategies followed in I21’s PR2a and PR2b (2026-10-11), each with a cf21_conform_test.go beside it over a crafted fixture under its own testdata/cf21/: in PR2a three daily fixtures of 120, 156 and 470 rows, one carrying a weekly release series beside the primary; in PR2b a daily primary with two weekly positioning series (493 rows), the one weekly primary with four weekly positioning series (680 rows, the run’s interval 1w), a daily primary with a weekly volatility series (51 rows) and a synthetic ten-symbol daily basket (5830 rows); every run with a release-stamped series names the pb data wire, the v1 blotters were frozen from the binaries built before the declarations existed, and no summary count is allowed to differ; eleven Go demos followed in PR3a (2026-10-11): seven that place market orders alone (multiseries, cpigate, alignpanel, cotcarry, esnqspread, ratetrend, gdprevision), each with a cf21_conform_test.go and a parity claim over the engine’s end-to-end fixture where one exists (the GLE-265, GLE-353 and GLE-408 fixtures, the last with the lake’s GDP vintages served as observations through Run.AdapterInputs) or a fixture crafted short (one-minute bars the adapter coarsens to a declared hourly series, a plain symbol with two release series, two plain symbols for a spread, the sine with short averages), and four that place no order (hello, refexpand, asofcheck, curvewatch), each run under both profiles with Backtest and zero submissions required of both traces; and the remaining seven in PR3b (2026-10-11): flowimbalance, tapereader and volumetrend, each with a cf21_conform_test.go and a parity claim over the bundled MSFT trade sample through the Databento adapter with the construction of its end-to-end test (Run.Adapter, Run.BarKind, Run.Threshold; the pb data wire for the statistics, the tape and the declared constructions), sessionref, oiconfirm and termcarry, whose runs need what no adapter the suite builds serves (a custom session window, the statistics and definition streams, a deferred composite), each with a golden-tagged test that runs it through the CLI and the marketfeed adapter under each profile over its archive window and applies Check to the two results read back with ReadResult, and printbars, the fifth no-order demo, run under both profiles once the suite’s refusal tests had moved to the undeclared fixture program; and the three e9 demos in PR5 (2026-10-11), the corporate-action probes of the engine’s end-to-end tests, each with a cf21_conform_test.go and a parity claim over its end-to-end fixture checked in under its testdata/cf21/ (the bars and the one-row corporate action, served through the file-csv adapter’s CorporateActions input in Run.AdapterInputs, at the end-to-end test’s capital): e9reuse, market-only, over the ticker-reuse fixture, and e9equity and e9rename, each a market buy and a GTC stop placed once, over the split and the rename, which claim what holds in place of MarketOnly, the same fills, the two submissions and the stop’s end, the rename re-keying the resting stop under both profiles and the split rewriting it under the legacy profile and cancelling it under v2 (the venue’s rule since I14 unit 1), after which the demo re-places it on the ex-date bar for the rewritten lot at the split-adjusted level (GLE-498), the seven counts that record the re-placement allowed to differ and pinned per profile; strategies/conform/conform_review_test.go holds the review panel’s gap tests, conform_dataprotocol_test.go the data wire’s and conform_adapter_test.go the adapter choice’s, the bar construction’s and ReadResult’s.
Limits. The engine prints its run header, its progress lines and its summary to os.Stdout, and RunConfig has no writer for them, so Backtest, TryBacktest, Parity and RefusedUnderV2 capture the output by swapping os.Stdout for a pipe for the duration of engine.Run, under a package-level mutex, drained by a goroutine while the engine runs (a run that prints more than the pipe’s buffer would block otherwise) and restored to the saved file itself; a failed capture is fatal rather than a partial buffer. They are therefore not safe for parallel tests: do not call them from a test that called t.Parallel. A Session holds the same mutex for its life, so a backtest started while a session is open waits for the session to end, and a session started while a backtest’s capture is in progress is fatal at once. A port run by Replay or Decisions has one minute from its start to exit, with a five-second WaitDelay so a grandchild holding the output pipe open (the shell port forks) cannot keep the wait from returning; each of its captured streams, standard output and standard error, is capped at 64 MiB, and a port that writes more is fatal at once, naming the stream, rather than held in memory until the deadline (a valid port writes kilobytes). The engine-backed tests build two binaries and run two backtests each, so they skip under go test -short and stay in make test, as the migrations’ end-to-end tests do (the owner’s decision of 2026-10-10). The library imports engine, so a consumer’s test binary links the engine; no strategy binary does.