Orders and callbacks
OnBar returns a slice of orders. Build them with the constructors:
algolang.MarketBuy(sym, qty) algolang.MarketSell(sym, qty)
algolang.LimitBuy(sym, qty, price) algolang.LimitSell(sym, qty, price)
algolang.StopBuy(sym, qty, stop) algolang.StopSell(sym, qty, stop)
algolang.StopLimitBuy(sym, qty, stop, limit) algolang.StopLimitSell(sym, qty, stop, limit)
algolang.TrailingStopBuy(sym, qty, trail) algolang.TrailingStopSell(sym, qty, trail)Every constructor returns an Order struct you may adjust before returning it – most usefully ClientID (your handle for matching fills and cancels; make it deterministic, see below) and TIF (Day by default; also GTC, IOC, FOK).
A price, stop price or trail amount that is not a finite number (NaN, +Inf or -Inf), on the order or on one of its attached orders, is refused at the wire, before the trade director, the simulator or a live venue sees the order, whatever its type (GLE-1090). The reason names the first such level, price_not_finite: price=NaN or price_not_finite: attached=0 stop_price=-Inf; its token is algolang.PriceNotFinite. Under lifetime v2 the strategy hears an OrderUpdate Denied with that reason and no OrderCancel; under lifetime v1 an OrderCancel with reason Rejected before its next bar. The run goes on. The Go constructors never build such an order; a strategy written without the SDK, on the protobuf or stdio-csv-v1 wire, can send one. Zero and negative levels are not refused here.
algolang.Bracket(entry, takeProfit, stopLoss) wraps any entry order with a take-profit limit and a stop-loss stop. The two exits activate only when the entry fills, and they cancel each other (one-cancels-other); the fill simulator chapter has a worked example. Separately, orders that share a non-empty OCOGroup form a standalone one-cancels-other group: the first to fill cancels the rest. A group member may carry attached orders of its own, so two bracket entries around a bar can be OCO-joined, each with its protective stop: the winner’s attached orders activate at its fill and the losers’ are cancelled with them.
Naming orders
An order may carry a display name, as TradeStation names its orders LE, SE, LX, SX or Trail stop (GLE-666). Named returns a copy of the order with its Name set. A crossover that reverses on each cross names its two orders, as the smacross demo does:
switch {
case fast.CrossesAbove(slow) && pos < 1:
return []algolang.Order{algolang.MarketBuy(bar.Symbol, 1-pos).Named("LE")}, nil
case fast.CrossesBelow(slow) && pos > -1:
return []algolang.Order{algolang.MarketSell(bar.Symbol, 1+pos).Named("SE")}, nil
}
return nil, nilNamed names the order it is called on. A bracket’s children keep their own names, so name them through AttachedOrders, the take-profit first:
entry := algolang.LimitBuy(bar.Symbol, 2, 99)
entry.ClientID, entry.TIF = "trade", algolang.GTC
bracket := algolang.Bracket(entry, 105, 95).Named("LE")
bracket.AttachedOrders[0].Name = "LX target"
bracket.AttachedOrders[1].Name = "LX stop"
return []algolang.Order{bracket}, nilThe name is for display. It does not change how the order fills, and ClientID stays the order’s label, the intent key that fills, updates and cancels name. The simulator echoes the name on the order’s fills (Fill.Name), and every leg of a combo order carries the combo’s name. Roll legs, expiry settlements and corporate-action legs belong to no order and carry no name.
An order without a name is named in the performance report by its effect on each trade it touches: an entry is Buy for a long and Sell Short for a short, an exit Sell for a long and Buy to Cover for a short. The effect belongs to the trade, not to the fill: a fill through zero that closes a long and opens a short is the long’s exit, Sell when it is unnamed, and the short’s entry, Sell Short. A named fill gives both trades its name.
The names appear in:
trades.csvand the trades ofresult.json, with each order’s label, attempt and type and how the trade closed (Artefact formats);- the HTML report’s trade list, in its Entry order and Exit order columns (The trade list);
fills.json, as each fill’sName;- the export, as
fills.nameand the trades’entry_nameandexit_name(trades).
On the wire the name is the pb Order.name, echoed as Fill.name, and the twelfth field of a stdio-csv-v2 order line (The v2 line catalogue). stdio-csv-v1 cannot carry it and drops it.
Live: the IBKR venue’s fills do not carry the name yet, and the live ledger does not record it, so a live run’s trades show the default names.
Order lifetime examples
An order has three independent choices: its type says how it can fill (market, limit, stop); its time in force says when the venue expires it (Day, GTC, IOC, FOK); and the strategy’s policy says how long the strategy wants it working. A strategy can submit a GTC order and withdraw it after one bar, or leave the same order working for many bars. GTC is a time in force, not a synonym for lifetime v2.
Backtests default to lifetime v2. --lifetime v1 selects the legacy profile; live runs still default to v1. A strategy must declare its v2 support before it can run under v2 (see Supporting lifetime v2 optionally). The examples below use v2 except where a comparison names v1. Go fragments belong inside the indicated strategy callback; algolang is the strategy SDK and kit is the strategy kit package (strategies/kit).
| Setting in a backtest | How long an unfilled order works |
|---|---|
Day, lifetime v1 | One eligible evaluation bar, then automatic TIF_EXPIRED cancellation. |
Day, lifetime v2 with a usable exchange calendar | Until the relevant session’s DAY-cancel close, across every intervening bar. |
Day, lifetime v2 without a usable calendar for the order | It cannot rest: a resting Day order (limit, stop, stop-limit, trail, touch, LOC) is denied at submission, day_close_unplaced. A market or MOO order is unaffected. An MOC needs the calendar for its send time and is denied with moc_close_unplaced (Market-on-close orders). |
GTC, --gtc-expiry never (the default) | Across bars and sessions, with no age-based expiry; fills and other cancellation causes still end it. |
GTC, --gtc-expiry ibkr-quarter | Until the following quarter’s deadline, unless it fills or is cancelled earlier; example 8 below gives dates. |
IOC or FOK | One immediate evaluation window in this simulator. Its full-quantity fills make the two operationally identical; these are not substitutes for a live one-bar policy. |
Every ordinary order constructor still sets TIF: Day; switching to v2 does not change that field. Session-aware Day expiry needs the exchange calendar to have been requested and served, and complete enough to place the order’s end. A run can request it with --exchange-calendar, or the strategy can ask for it. Under v2 there is no fallback (GLE-1362): a resting Day order whose close the calendar cannot place is denied at submission with day_close_unplaced, the reason naming the root and the cause, so the strategy learns of it on its first such order instead of running silently under the v1 rule. A strategy that wants an order to work for one bar keeps that policy itself (example 6, kit.OneBar); one that wants it withdrawn at a known instant sets Order.CancelAt. See Calendar cancellation instants (lifetime v2) for the other switches and the coarse-bar limits. In live trading the venue applies its own expiry rules.
Example 1: next-bar execution and the legacy one-bar order
At bar N’s close, the market is 100 and the strategy returns:
entry := algolang.LimitBuy(bar.Symbol, 2, 99)
entry.ClientID = "entry"
return []algolang.Order{entry}, nil // TIF is Day.
Assume bar-resolution fills, no slippage, and one series of this symbol. The order cannot fill against bar N’s already-observed low. It first participates in bar N+1:
| Bar N+1 | Result under the legacy one-bar rule |
|---|---|
| Opens at 100, trades down to 98.5 | Buy 2 at the limit, 99. |
| Opens at 98, below the limit | Buy 2 at the better opening price, 98. |
| Stays above 99 | No fill; the simulator cancels the order at the bar’s end with TIF_EXPIRED. |
Under v2 that one-bar end belongs to the strategy, not the venue (example 6). Under v1 the strategy could return a fresh Day order at N+1’s close to try again during N+2. An ordinary market buy instead fills at N+1’s open; the next-bar execution rule survives the move to v2. An MOC has its own rule: under v2 it goes out at a send time shortly before a later session’s close (Market-on-close orders), under v1 it settles at the close it was decided on. The fill-price details are in When and how orders fill.
Example 2: a Day order on five-minute bars
Suppose a served exchange calendar places the session’s DAY-cancel close at 16:00, in the exchange’s local time. Submit the same Day limit at the 10:00 bar close, and suppose its price is never reached:
| Decision or boundary | Lifetime v1 | Lifetime v2 with that usable calendar |
|---|---|---|
| 10:00 | Submit the order. | Submit the order. |
| 10:05 | Its first bar ends; it expires. | It remains working. |
| 10:10 through 15:55 | Nothing is working unless the strategy submitted again. | The original order remains working. |
| 16:00 | Any latest one-bar order ends after its window. | The original order expires at the session close. |
Submitting at 16:00 itself selects the next session’s DAY-cancel close: the calendar chooses the first such close strictly after submission. That is why a Day order decided at a daily session close can still live through the next session. Changing this order to GTC lets it survive the 16:00 boundary, subject to the GTC rules below.
Do not submit another identical Day order every five minutes under the session-aware model merely to keep the first one alive. Each returned order is a new submission. Reusing a ClientID does not turn it into an amendment; v2 stamps a new attempt. Use the working view or the controller to decide whether another submission is needed.
Example 3: cancel one of three working orders by its label
At a bar close of 100, submit three independent bids once. Each gets its own ClientID, even though all three trade the same symbol:
near := algolang.LimitBuy(bar.Symbol, 2, 99)
near.ClientID, near.TIF = "ladder:near", algolang.GTC
middle := algolang.LimitBuy(bar.Symbol, 2, 97)
middle.ClientID, middle.TIF = "ladder:middle", algolang.GTC
deep := algolang.LimitBuy(bar.Symbol, 2, 95)
deep.ClientID, deep.TIF = "ladder:deep", algolang.GTC
return []algolang.Order{near, middle, deep}, nilThese orders have no OCO group and no attached children. While all three are still working, a later OnBar decides to withdraw just the nearest bid:
ctx.Cancel("ladder:near")
return nil, nil // No new submissions in this decision.
The argument is the strategy’s ClientID, not the symbol, the limit price, or the broker’s order reference. A label names an order’s logical role; v2 identifies its physical submissions with (ClientID, Attempt). ctx.Cancel(label) chooses the newest live attempt under that label that is not already pending cancellation (or the newest live attempt if all are pending). Give distinct simultaneous orders distinct labels and keep at most one unresolved attempt per role; the controller enforces that pattern. Do not use the same label for all three bids.
Assuming no fill races with the request:
| Moment | ladder:near at 99 | ladder:middle at 97 | ladder:deep at 95 |
|---|---|---|---|
| Before the request | Working | Working | Working |
Immediately after ctx.Cancel | PendingCancel | Working | Working |
| After cancellation is confirmed | Removed from the working view | Working | Working |
| A later bar opens at 100 and reaches a low of 98.5 | No order to fill | Still working | Still working |
| A subsequent bar opens at 100 and reaches 96.5 | No order to fill | Fills 2 at 97 | Still working |
Calling ctx.Cancel("ladder:middle") at a later decision would target that order instead. Calling ctx.Cancel(bar.Symbol) does not cancel all orders in the symbol: it addresses that literal string as a ClientID. An unknown or already-ended label receives a refusal, not a cancellation of some other order.
To inspect the unresolved attempts from a callback:
for _, w := range ctx.WorkingOrders() {
ctx.Logf("%s attempt=%d status=%s remaining=%d",
w.Order.ClientID, w.Order.Attempt, w.Status.String(), w.RemainingQuantity)
}WorkingOrders() is populated by the SDK from submissions and outcomes; it is not a fresh broker query. Under v2 a cancellation request leaves the attempt there as PendingCancel until the response or terminal event resolves it. OnCancelResponse observes the request’s answer; OnCancel observes an actual cancellation. A Pending or Unknown answer is not permission to treat the order as gone, and a fill can still arrive. See The working view under lifetime v2.
Example 4: withdraw one controller intent and keep the other two
For orders managed by a kit.Controller, change what the strategy declares. Suppose s.rc was built with kit.NewController("ladder:"). Use this helper to make the time in force explicit:
func gtcBid(symbol string, qty int64, price float64) algolang.Order {
o := algolang.LimitBuy(symbol, qty, price)
o.TIF = algolang.GTC
return o
}The first decision declares all three bids:
desired := []kit.Intent{
{Key: "near", Order: gtcBid(bar.Symbol, 2, 99)},
{Key: "middle", Order: gtcBid(bar.Symbol, 2, 97)},
{Key: "deep", Order: gtcBid(bar.Symbol, 2, 95)},
}
return s.rc.Reconcile(ctx, desired)The controller supplies the labels ladder:near, ladder:middle and ladder:deep. To withdraw near while the other two remain unfilled, the next decision declares only the other two:
desired := []kit.Intent{
{Key: "middle", Order: gtcBid(bar.Symbol, 2, 97)},
{Key: "deep", Order: gtcBid(bar.Symbol, 2, 95)},
}
return s.rc.Reconcile(ctx, desired)This requests the cancellation of ladder:near. The unchanged middle and deep attempts produce no command and keep their original submission times. Each declaration is the complete desired set for the controller’s scope, not a list of additions. On a multi-symbol controller, include the orders still wanted on the other symbols too.
| What a callback does | Meaning |
|---|---|
return nil, nil without reconciling | Submit nothing and request no withdrawal; existing orders keep their lifetimes. |
| Reconcile the same desired set | Keep matching attempts; submit any missing, unblocked intent. |
Reconcile a set omitting near | Withdraw near; preserve the other matching attempts. |
return s.rc.Reconcile(ctx, nil) | Request cancellation of every attempt owned by this controller; labels outside its scope are untouched. |
If the strategy calls ctx.Cancel("ladder:near") directly but keeps declaring near, the controller can put it back after cancellation. Withdrawal therefore belongs in the declaration. Likewise, after a fill, recompute the quantity still wanted or remove the filled intent; an unchanged declaration of another 2 is a request to buy another 2. The complete callback wiring, including OnLifecycleTurn, OnFill and OnOrderUpdate, is in The desired-order controller.
Example 5: replace a price without replacing unrelated orders
Continue example 4 with middle at 97 and deep at 95 still working. The strategy now wants middle at 96.5. Declare that new price and keep the deep declaration unchanged:
| Step | Controller action |
|---|---|
| Bar N’s decision sees the changed price | Request cancellation of ladder:middle attempt 1 and, in the same reply, submit attempt 2 at 96.5. Leave ladder:deep alone. |
| The engine answers | The simulator confirms the cancel and attempt 2 is Working. A live venue that can modify the order changes attempt 1’s price in place, and the strategy hears the same two answers; one that cannot leaves the cancel pending and holds attempt 2. |
| Cancellation is still pending | Attempt 1 can still fill; attempt 2 is Held, and the declaration is met. A fill of attempt 1 makes the engine refuse attempt 2 (cancel_race), and the next decision declares from the new position. |
| The next bar begins | Attempt 2 is working, or still held behind attempt 1’s pending cancel. |
The successor goes out with the cancel because only a price changed: the same symbol, side and order type, so the engine can ask the venue to modify the order in place instead, which leaves no instant with neither bid working (Replacing in place, GLE-1419). A change the venue could not make in place (a side, an order type, an attached order, a group replacement) takes two decisions as under lifetime v1: the cancel first, the successor once the view has retired attempt 1, usually at the lifecycle turn the confirmation grants. Either way, on a venue that cannot modify, the race guard holds the successor until attempt 1 has ended, so returning a new order with the old label never puts two physical orders to work.
The examples leave Intent.Group empty. If middle and deep instead shared a non-empty controller Group, changing one would retire and replace that group together. Intent.Group is the controller’s replacement policy; Order.OCOGroup is the venue’s sibling-fill policy. They are separate fields with separate effects.
Example 6: GTC at the venue, valid for one bar to the strategy
To keep a one-bar entry policy under v2, declare a GTC intent with one eligible window:
entry := algolang.LimitBuy(bar.Symbol, 2, 99)
entry.TIF = algolang.GTC
desired := []kit.Intent{{Key: "entry", Order: entry, MaxWindows: 1}}
return s.rc.Reconcile(ctx, desired)Call s.rc.Observe(ctx, bar) at the start of the relevant OnBar, before building that decision’s declaration. With a single series of the order’s symbol and no fill, the sequence is:
- Bar N closes: submit attempt 1 at 99.
- Bar N+1 trades: attempt 1 gets its one evaluation window.
- At N+1’s decision,
Observecounts that window.Reconcilerequests cancellation because the attempt has reachedMaxWindows: 1. - If the latest signal still wants the entry, reconciliation at the confirmation’s lifecycle turn submits attempt 2, using the latest declaration. If the signal has ended, declare no entry and no successor is submitted.
MaxWindows limits each attempt; it does not turn a repeated entry signal off. With MaxWindows: 0 (the default), an unchanged GTC attempt can remain working over many bars without cancellation and re-submission. A bar of another symbol adds no window. Counting is not a wall-clock deadline or a venue command: the strategy must observe and reconcile; live cancellation still needs confirmation. A scheduled withdrawal between bars needs a timer decision and suitable data resolution, or an Order.CancelAt (below).
A strategy that returns its orders afresh at every bar. A strategy written for v1’s one-bar Day rule, which returns the next bar’s stops and limits at each close and lets the venue end the unfilled ones, keeps that life under v2 with kit.OneBar (GLE-1362), without a controller:
type strategy struct {
onebar kit.OneBar // the zero value is ready
}
func (s *strategy) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
orders := s.rules(ctx, bar) // the orders for the next bar, as under v1
return s.onebar.Orders(ctx, orders), nil
}Under v1 Orders returns the orders unchanged. Under v2 it sends each resting order GTC and, at the next call, cancels (ctx.Cancel) every order the previous call returned that is still working, before the new ones go out. In the simulator that cancellation is confirmed at the next decision, at the close of the order’s one bar, before any later data is matched against it, so the fills are the v1 run’s. The trace differs: it counts explicit cancellations where v1 counts TIF_EXPIRED ones, and a decision reading ctx.Flat or ctx.Exposure still sees last bar’s orders working. Call Orders on every bar the strategy decides on, including those it returns nothing at, or the previous bar’s orders keep working. Six demos use it (dualdpo, forcepullback, fourbarfear, mfidirection, momentumfirst, triplescreen), and their conformance suites declare Expect.OneBar (Conformance under both lifetimes).
Withdraw at a known instant. Order.CancelAt asks the engine to request the order’s cancellation at an instant, on the strategy’s behalf (lifetime v2 backtests, GLE-1362):
entry := algolang.LimitBuy(bar.Symbol, 2, 99)
entry.TIF = algolang.GTC
entry.ClientID = "entry"
entry.CancelAt = bar.CloseTime.Add(30 * time.Minute)
return []algolang.Order{entry}, nilIf the order is still working at that instant, the simulator cancels it there, stamped at the instant, even when no bar of the order’s symbol closes then. The strategy hears a confirmed CancelResponse whose RequestID is algolang.CancelAtRequestID("entry", 1) (entry/1/cancel_at), then an OrderCancel with reason EXPLICIT and the same request id: the strategy’s own cancellation, so an OCO sibling keeps working. A fill on a bar closing at or before the instant wins. When a Day order’s session close and its CancelAt coincide, the venue’s TIF_EXPIRED wins, and when the close comes first the order ends there. The instant must be after the decision the order is submitted at (cancel_at_not_future otherwise). The order is denied cancel_at_unsupported under v1, on a combo, on an attached order (bracket children follow their parent), in a live run (the live loop schedules no cancellation yet) and over stdio-csv-v1. To end an order at its session’s close without a Day time in force, ask the calendar first:
if c, err := ctx.DayCancelClose(bar.Symbol, false); err == nil {
entry.CancelAt = c.At // equal to the close a Day order would end at
}ctx.DayCancelClose applies the rule the simulator applies to a Day order, from the decision instant, and fails with an error wrapping algolang.ErrDayCloseUnplaced when the strategy holds no calendar for the symbol’s root or the calendar cannot place the close. Pass true as the second argument only when the run accepts the root unverified (--calendar-accept-unverified), which the SDK is not told.
Example 7: a fill arrives while cancellation is pending
Suppose a long-only strategy wants to accumulate 10 units. Its GTC buy limit has 10 remaining when it decides to move the price:
| Event | Working order and position | Next action |
|---|---|---|
| Request cancellation of attempt 1 | PendingCancel, 10 remaining; position 0 | Wait. |
| A fill of 4 arrives before confirmation | PendingCancel, 6 remaining; position 4 | Still wait; do not submit a second order for 10. |
| Cancellation is confirmed | Attempt 1 retired; position 4 | Recompute the desired quantity as 10 - ctx.Position(sym).Quantity, giving 6. |
| Lifecycle turn reconciles | No old attempt remains | Submit attempt 2 for 6 at the new price. |
This is a live-event scenario; the current bar simulator emits full fills. If all 10 filled during cancellation, the desired quantity is zero and the strategy declares no successor. The controller compares a live attempt’s remaining quantity to the intent’s quantity, so a partial fill alone need not cause a replacement when the price is unchanged. Size from the current position or the controller’s per-key fill count, according to the strategy’s policy. Do not resend a cached order quantity after confirmation.
For a controller-owned entry, a position-based gate is also different from ctx.Flat(sym): Flat includes working orders, including the entry the controller already owns. Using it to decide whether that entry is still wanted would withdraw the entry merely because it is working.
Example 8: GTC across a quarter boundary
--gtc-expiry never is the simulator default: midnight, a session close, and a quarter boundary do not themselves expire a GTC order. The setting does not suppress explicit cancellations, OCO outcomes, corporate actions, contract expiry or the backtest’s shutdown sweep.
With --gtc-expiry ibkr-quarter, the submission’s exchange trade date anchors a deadline in the following calendar quarter:
| Physical submission | Deadline date |
|---|---|
| 30 September 2026, in Q3 | 31 December 2026, the end of Q4. |
| 1 October 2026, in Q4 | 31 March 2027, the end of Q1. |
| Submit on 30 September; cancel and replace on 1 October | The replacement has a fresh 31 March 2027 deadline. |
Repeatedly declaring an unchanged controller intent does not reset the deadline: the same physical attempt is still working. A fresh submission does reset it; a bracket child starts its own anchor when activated, and a continuous roll’s physical re-submission also takes a fresh anchor.
With a usable calendar under v2, cancellation occurs at the DAY-cancel close of the deadline quarter’s final trading day, adjusted for holidays, weekends and early closes. Without it, cancellation happens before the first bar whose trade date is after the deadline. An order can still fill on the deadline day’s bar. The strategy hears CancelReasonGTCExpired. This is a simulator option, not an instruction to a live venue to keep orders indefinitely; live expiry follows the venue. See GTC quarter-end cancellation for the CLI scope, trade-date anchoring and coarse-bar treatment.
Example 9: bracket children have their own lifetimes and labels
At a close of 100, build a limit entry with a target and protective stop:
entry := algolang.LimitBuy(bar.Symbol, 2, 99)
entry.ClientID, entry.TIF = "trade", algolang.GTC
bracket := algolang.Bracket(entry, 105, 95)
return []algolang.Order{bracket}, nilThe helper gives the children labels trade_tp and trade_sl, and GTC time in force. They are inactive until the entry fills, then form the OCO exit pair. The v2 working view tracks those inactive and active children as attempts of their own.
| Situation in the simulator | Result |
|---|---|
Cancel trade before the entry fills | The parent is cancelled; its still-inactive children end with ParentCancelled. |
| Entry fills, then target fills | The target’s fill cancels the sibling stop through OCO. |
Entry has filled; call ctx.Cancel("trade") | The parent is already terminal. This does not cancel its now-active children or close the position. |
Entry has filled; call ctx.Cancel("trade_tp") | Request cancellation of that active target alone. An explicit cancellation does not itself trigger the simulator’s sibling-fill OCO rule. |
Thus a single-order cancellation is different from withdrawing an exit set. If both exits should be withdrawn, request both active labels, or remove their intents from the controller’s desired set when the controller owns them. Cancelling an exit order leaves the position unchanged; closing the position requires an execution. These bracket examples describe the simulator: live native brackets and OCA groups have separate admission limits in Tickets and cancels at the IBKR venue.
Expiry and other unsolicited cancellations also apply to protective GTC orders. After one ends, the strategy decides whether protection is still needed and declares the appropriate replacement on its next decision; GTC alone does not recreate it. For example, a split can cancel the old stop under v2, and the strategy must use the updated position and price units when deciding its successor (see Corporate actions and working orders).
Reacting to fills and cancels
Implement the optional interfaces you care about; the SDK detects them by type assertion:
| Interface | Method(s) | Called when |
|---|---|---|
Initializer | OnInit(ctx, cfg) | Once, after inputs are applied, before any bar. Validate inputs; read cfg.Instruments, the run range. |
Lookbacker | Lookback() int | Once at init; sizes the history buffer and the warmup pre-roll. |
FillHandler | OnFill(ctx, fill) | An order (or bracket child) filled. The SDK updates ctx.Position before calling you. |
CancelHandler | OnCancel(ctx, cancel) | An order was cancelled: OCO sibling filled, TIF expired, rejected, shutdown, or, under lifetime v2, a corporate action on its instrument (Corporate actions and working orders (lifetime v2)). |
CorporateActionObserver | OnCorporateAction(ctx, notice) | An equity capital action is announced or becomes effective. Informational. |
RollObserver | OnRoll(symbol, from, to, ...) | A continuous future changes active contract. Informational. |
RebaseObserver | OnRebase(ctx, rebase) | On a run that rebases (the default since GLE-1502), at each roll of an adjusted continuous series, after OnRoll and after the SDK has moved its own state onto the incoming contract’s basis. Places no orders (see Re-adjusting at each roll). |
AdoptHandler | OnAdoptedState(ctx, state) | Live startup reconciliation seeds existing broker state; an error refuses startup. |
Shutdowner | OnShutdown(ctx) | Once, at end of data. Print summaries here. |
SessionHandler | OnSessionStart/End | Reserved; no session events are generated in this build. |
MultiSymbol | IsMultiSymbol() bool | Declares the strategy must see all portfolio symbols in one instance. |
DataRequirer | DataRequirements() []DataRequirement | Once at init; declares extra data series and symbols beyond the run’s universe (above). |
TradeableDeclarer | TradeableSymbols() []string | Once at init; admits declared symbols to the tradeable (venue) universe. |
SeriesAligner | AlignedSeries() []AlignedSeries | Once at init; declares views that carry one series’ latest value onto every bar of another (see Aligned series). |
UniverseHandler | OnUniverseResolved(ctx) | Once, after the engine resolves the (possibly expanded) universe, before the first bar; ctx.Instrument is populated. A non-nil return refuses the run. |
CalendarRequirer | NeedsCalendar() bool | Once, after OnInit; true sets InitAck.needs_calendar, asking the engine for the exchange calendar of each root (see Strategy SDK lookups). |
CalendarObserver | OnCalendar(ctx, cal) | Once per pushed root, before the first warm-up bar and after the SDK has stored the calendar, so ctx.Calendar answers inside it; implementing it also sets needs_calendar. A non-nil return refuses the run. The engine pushes one calendar per root it was served (see Engine side). |
PortfolioWatcher | PortfolioNeeds() PortfolioNeeds | Once, after OnInit; sets InitAck.needs_portfolio, asking the engine for the portfolio view before each decision, with the detail and curves it returns (see Reading the portfolio). |
CapabilityRequirer | RequiredCapabilities() []string | Once at init, after inputs are applied and before OnInit; declares the capabilities the run must put in effect: algolang.CapabilityLifetimeV2 and, for combo orders, algolang.CapabilityComboOrders beside it. A token the engine did not offer refuses the run before OnInit (see Capability negotiation). |
CapabilitySupporter | SupportedCapabilities() []string | Once at init, where RequiredCapabilities is called; declares the capabilities the strategy accepts when the engine offers them and runs without when it does not. An offered token is accepted, one the engine did not offer is left out and the run proceeds, an unknown one fails initialisation. ctx.LifetimeV2() reports the outcome (see Supporting lifetime v2 optionally). |
OrderUpdateHandler | OnOrderUpdate(ctx, update) | One attempt’s status transition (lifetime-v2 only). Under lifetime v2 the working view has already moved on it when the handler runs; on a v1 run no ctx state moves. |
CancelResponseHandler | OnCancelResponse(ctx, response) | The classified answer to one cancel request (lifetime-v2 only). Like OnOrderUpdate: the view first, then the handler. |
TurnHandler | OnLifecycleTurn(ctx, turn) | One lifecycle decision turn (lifetime-v2 only): the engine has delivered the outcomes of the strategy’s commands at the turn’s instant and grants a decision on them before the clock advances. Answered as OnBar is, with orders; no bar arrives and no series moves. See Lifecycle turns. |
TimerHandler | OnTimer(ctx, t) | A timer the strategy armed fired (lifetime-v2 only): a decision at t.FiredAt, answered as OnBar is, with orders. No bar arrives; ctx.Now() moves to FiredAt and each series’ Fresh is recomputed first. See Scheduled decision points. |
TimerRefusalHandler | OnTimerRefused(ctx, refusal) | The engine refused a timer, at its arm or at its instant (lifetime-v2 only); refusal.Code is one of the TimerRefusal* constants. An observation: no reply, and no clock moves. |
The last seven are the SDK’s side of the order-lifetime programme’s v2 protocol (GLE-367 defined it, GLE-377 put it in effect, I12 added the timers and I16 the optional support; the wire is in the protocol reference). A strategy that implements the v2 order lifetime returns []string{algolang.CapabilityLifetimeV2} from RequiredCapabilities; the SDK matches it against the engine’s offer before OnInit and refuses the run, with Error code capability_unsupported and a non-nil Run error, when the engine did not offer it. A strategy that implements both lifetimes returns the same token from SupportedCapabilities instead: the SDK accepts it when the engine offers it and leaves it out when the engine does not, the run proceeds either way, and ctx.LifetimeV2() tells the strategy which profile it is on (Supporting lifetime v2 optionally). A backtest offers it by default and an emulated-live run under --lifetime v2 (Lifecycle turns); the legacy profile (--lifetime v1, and a live run’s default) offers nothing, so there a strategy that requires nothing is unaffected and its InitAck is byte-identical, while a backtest that names no profile refuses a strategy that accepts nothing, naming --lifetime v1. OrderUpdate carries the attempt (ClientID, Attempt, OrderRef), its Status (an OrderStatus, whose Terminal() is true for Filled, Cancelled, Rejected, Denied and Expired and whose String() renders pending_cancel and the like), the original, filled and remaining quantities, Reason and BrokerCode, ParentClientID, OwnerID and ReplacesAttempt (since I15 unit 2a, the attempt a continuous roll replaced when the engine itself re-placed the order, 0 on every other update; Order lifetime v2 across a roll); CancelResponse carries the attempt, the RequestID it answers, an Outcome (a CancelOutcome: Confirmed, Pending, Refused or Unknown) and the attempt’s Status and RemainingQuantity as evidence. Both timestamps are the zero time.Time when the wire carries none. The SDK delivers every OrderUpdate and CancelResponse envelope it receives, whatever was negotiated, and a strategy without the observer ignores it: keeping them off a v1 run is the host’s job, not the SDK’s. On a run that negotiated lifetime-v2 each of them moves the attempt-indexed working view before the observer sees it (I3, GLE-372; see The working view under lifetime v2); on a v1 run neither moves anything: ctx.WorkingOrders and ctx.Flat still move on OnFill and OnCancel alone, and a confirmed cancel reaches the view through its OrderCancel event. ctx.Position moves on OnFill alone under either view. On the same footing, Fill (Attempt, ExecID, OrderRef, RemainingQuantity), OrderCancel (Attempt, OrderRef, RequestID, RemainingQuantity), Order.Attempt, AdoptedState.OwnerID and the complete AdoptedOrder frame (TrailAmount, OCOGroup, AttachedOrders, Attempt, OrderRef, Status, FilledQuantity, RemainingQuantity, SubmittedAt, OwnerID) exist on the SDK types. Under lifetime v2 the SDK stamps Order.Attempt on every submission, ctx.Cancel carries the attempt it addresses and a request id, and OnAdoptedState restores the view from the full frame; on a v1 run all of them are zero, the SDK stamps nothing, a cancel request carries the label alone and the view is seeded from the nine v1 fields. The engine’s side of the exchange on the simulated path (attempts echoed on Fill and OrderCancel, the two events, the classified cancel responses and the turns) is the v2 profile, the programme’s increment I4 unit 4a; the live path’s turns are unit 4b’s, and the full adoption frame belongs to persisted ownership (I7). The view is written to be exact with stamped events and right with the unstamped ones a v1 engine sends.
Timers. Under lifetime v2 a strategy can also ask for decisions of its own (I12; Scheduled decision points). Three Context methods queue timer commands, which go out with the reply to the current decision:
| Method | Returns | Queues |
|---|---|---|
ctx.ArmTimer(id, at) | error | the arm of the one-shot timer id for the instant at; a re-arm of an armed id replaces it |
ctx.ArmSessionTimer(id, symbol, kinds, offset) | (time.Time, error) | the arm of id at the first calendar boundary of kinds plus offset strictly after ctx.Now(), anchored on symbol; returns the instant. Needs the symbol’s calendar and a decision instant, so it fails in OnInit and OnCalendar |
ctx.CancelTimer(id) | error | the disarm of id |
On a run that did not negotiate lifetime-v2 the three return algolang.ErrTimersUnavailable and queue nothing. They log nothing, so a strategy that relies on a timer checks the error. On stdio-csv-v2, which has no timer lines, the runner refuses the next batch instead (csv_unsupported).