Fill simulation
Orders returned from OnBar go to the engine’s built-in simulator, which holds a cash account per run: cash in, cash out, commission always a cost, the margin the open positions require locked against it (Margin).
A backtest runs the order-lifetime v2 profile unless it names --lifetime v1 (since I22, GLE-470; Lifecycle turns): the engine acknowledges every submission and answers every cancel request, an order rests until the strategy or the venue ends it, and the venue’s own terminations follow IBKR’s rules: the exchange calendar’s Day and GTC instants (Calendar cancellation instants (lifetime v2)), contract expiry, corporate actions and, on a continuous run, a roll’s re-placement (Order lifetime v2 across a roll). The fill rules below are the same under both profiles; where the legacy profile’s lifetimes differ, the section says so, and --lifetime v1 reproduces them byte for byte.
When and how orders fill
The golden rule for ordinary bar-driven orders: you decide at a bar’s close, and your order first participates in the next bar’s path. A market order therefore fills at the next bar’s open – the first price that existed after your decision – never at the close you just saw. An unfilled order may remain working through later bars: its time in force, the run’s calendar facts and the strategy’s cancellation policy decide when it ends. See Order lifetime examples for Day versus GTC, one-bar policies and selective cancellation. A market-on-close order goes out at a send time shortly before a later session’s close under lifetime v2, and settles at the close it was decided on under v1 (Market-on-close orders).
At bar resolution the simulator knows only each bar’s OHLC, and resolves each order type conservatively:
| Type | Fills when (buy side; sells mirror) | At price |
|---|---|---|
| Market | always, on the next bar | open + slippage |
| Limit | bar low <= limit (strictly below under --limit-fill through; on a tick grid that is at least one tick past) | min(open, limit) – the open when the bar gapped through your limit |
| Stop | bar high >= stop | max(open, stop) + slippage |
| Stop-limit | stop leg as Stop, then rests as Limit | trigger price if it already satisfies the limit; else a resting limit from the next bar |
| Trailing stop | the engine-held stop (trail distance from the best price since activation) is touched | min/max(open, stop) + slippage; the stop ratchets from each bar’s close and never moves against you |
Slippage (--slippage-ticks, in ticks) is adverse and applies to market-style executions only – a limit price is a hard bound that can never be slipped through. The offset is the tick count multiplied by the traded symbol’s own tick size, so one setting is correct across symbols of different price scales (0.25 for ES, 0.01 for an equity). The tick size is resolved per instrument from the data adapter’s reported tick_size; a continuous run reads its root’s instrument metadata once, at startup (GLE-325). If slippage is on (> 0) and a traded symbol’s tick size cannot be resolved, orders on that symbol are rejected rather than mis-priced.
Market-on-close orders
algolang simulates market-on-close (MOC) itself (GLE-1375). Under order lifetime v2, the backtest default, an MOC does not settle at the close the strategy has just seen. It waits until a send time shortly before its session’s regular-hours (RTH) close, then goes out as a market order. IBKR offers MOC tickets for stocks and ETFs only, and the exchanges’ MOC cut-offs are early and cannot be cancelled after them; one rule for every instrument keeps the backtest and the live desk alike. Reports still show the order as MOC.
Which session. An MOC goes out in the first session whose send-time window opens after the decision. The window’s opening, not the send time, is the cut-off, so a strategy can tell which close it will get.
- On daily bars, an MOC decided at Monday’s close goes out at Tuesday’s send time and fills near Tuesday’s close.
- Intraday, an MOC decided before the window opens goes out in that session. One decided at or after the opening, the session’s last bar included, goes out in the next session.
- To exit at today’s close from an intraday strategy, decide before the window: on a bar that closes before it, or at a timer armed ahead of the close, for example
ctx.ArmSessionTimer("eod", sym, algolang.BoundaryRTHClose, -5*time.Minute). An MOC decided at a timer is accepted like one decided at a bar.
When it goes out. The send time lies in a window from 4 min 30 s to 10 s before the RTH close the exchange calendar places, so an early close moves the window with it. For a 16:00 close the window runs from 15:55:30 to 15:59:50. Nothing goes out within 2 s of a whole minute or a 10-second mark, which leaves the middle of each 10-second gap (:x3 to :x7). Those are the seconds when the close draws a burst of orders: two OHLCV studies of ES, NQ, YM, RTY, QQQ and SPY found the cost of a market order’s tail several times higher there. The send time is drawn among the seconds left, with sub-second jitter, from a generator seeded by the calendar root and the session’s trade date. Every run picks the same send time for the same root and session, so a backtest repeats exactly. The schedules are data, one per family of instruments (engine/mocsend/schedules.json): index futures and US equities share the US equity close’s, and every other root takes the generic rule.
The price. The first price observed at or after the send time, plus the run’s slippage:
| The run has | The MOC fills at | Anchored |
|---|---|---|
| Bars | the close of the bar covering the send time (its open when the send time is the bar’s open) | close |
An intra-bar path (--path-interval, --include-path) | the close of the path’s bar covering the send time | intrabar, or close on the path’s last bar |
| Trade prints (tick resolution) | the first print at or after the send time, at its timestamp | tick |
On a bar longer than the window, a daily bar for one, with no path to say what traded at the send time, that is the bar’s close. The run’s data notes count those fills on a fill path line, and the fills with no data at the send time, which take the next observed price:
fill path market-on-close fills priced at the close of a bar longer than the send-time window; an intrabar path prices the send timeThe report’s simulator: line adds moc_released=N moc_coarse=N moc_no_data=N moc_bar_close=N when any MOC filled.
Cancelling. Until its send time an MOC is cancellable like any other order, and its CancelAt applies. A cancel at or after the send time is refused: the order has gone out. An MOC whose send time comes after the run’s last bar is cancelled by the end-of-run sweep.
The calendar. The send time needs the exchange calendar of the order’s root. A strategy that sends MOC orders asks for the calendar (CalendarRequirer), or the run passes --exchange-calendar. When the run has no calendar for the order’s root:
On a run whose every series is daily or longer, the MOC fills at the close of the next bar of its symbol, plus slippage, and an attached one at the close of the bar its parent fills in. On daily bars that is the close the calendar would have given. The data notes count these fills:
fill path market-on-close fills with no exchange calendar priced at the close of the next daily barOtherwise, intraday, the session’s close cannot be known, and the MOC is denied at submission with
moc_close_unplaced(algolang.DenyMOCCloseUnplaced), the reason naming the root and the cause.
An MOC a calendar cannot place, because it places no RTH close in the next two sessions, is denied the same way. The report’s simulator: line adds moc_close_unplaced=N when there were any.
An attached MOC. An MOC can be attached to an order, its parent. It goes out only if the parent fills, at the send time of the session the parent fills in, and an unfilled parent’s cancellation cancels it. A strategy on daily bars can place a buy limit for Tuesday at Monday’s close and be out by Tuesday’s close if it fills. algolang.AttachMOC(entry) attaches the MOC that closes the entry: the opposite side, the entry’s symbol and quantity, Day, labelled the entry’s ClientID plus _moc (an automatic label when the entry has none). It copies the entry’s attached orders rather than sharing them:
entry := algolang.LimitBuy(sym, 1, 4980)
entry.ClientID = "dip"
return []algolang.Order{algolang.AttachMOC(entry)}, nil // dip, with dip_moc attached
Appending a MarketOnCloseSell to AttachedOrders by hand does the same.
- The limit fills on Tuesday: the MOC goes out at Tuesday’s send time.
- The limit does not fill: nothing goes out. At Tuesday’s close the strategy can leave the limit working for Wednesday, the MOC still attached, or cancel it, which cancels the MOC.
- When the run cannot tell whether the parent filled before or after the send time, because both fall in one bar, the parent counts as filling first. A parent that fills after the send time sends its MOC at the next allowed second of the window; after the window’s last one, at the next session’s send time. An MOC is never sent after the RTH close.
- The MOC shares its siblings’ OCO group: a protective stop’s fill cancels it, and its fill cancels the stop.
Under lifetime v2 an MOC rests like any other order until its send time, so it may itself be a parent and may join an OCO group:
- Orders attached to an MOC activate at its fill. A protective stop attached to an MOC entry therefore works from the close the entry fills at, not before it.
- An MOC with an
OCOGrouptag joins the group’s working orders: whichever fills first cancels the others. An MOC exit tagged with a position’s stop and target exits at the close unless the stop or the target fills first, and their fill cancels it.
Under --lifetime v1 both are denied, as the MOC settles at submission. A live run refuses attached orders, an attached MOC among them, and an MOC in an OCO group.
In the run’s records. A held MOC’s fill says how it went out. The fill blotter’s report (--fills-json) carries SentAs, always MKT, and SendAt, the send time; the lifecycle trace’s fill record carries them as sent_as and send_at. An MOC filled at a bar’s close for want of a calendar has SentAs and no SendAt. Every other fill has neither, so a blotter or trace with no held MOC is unchanged.
Lifetime v1. Under --lifetime v1 an MOC settles at submission at the observed close, as it did before GLE-1375, so the legacy profile’s results are unchanged. A live run refuses an MOC under v1: no live venue can fill an order at a close it has already observed.
Live runs. A live run under v2 holds an MOC in the engine and never sends IBKR’s MOC ticket (engine/livemoc.go). The send time is placed by the backtest’s rule, from the run’s exchange calendar, and at the send time the engine sends a Day market order under the MOC’s reference. Until then the order is the engine’s alone:
- the strategy can cancel it, at once, with no call to IBKR;
- a change to it is made by cancel and new, never in place;
- the broker does not list it, and reconciliation’s open-orders poll leaves it alone.
Its fill comes back as the MOC’s, without the SentAs and SendAt a backtest’s fill carries; the ledger’s moc_release line records them. An emulated run fills it as a backtest does: the engine sends a due MOC just before the step that reaches its send time and stamps that instant on the emulator (POST /admin/arrival), so the send times and the fills match a backtest of the same strategy.
On a live run an MOC is refused at submission:
- under
--lifetime v1; - with no calendar for its root (
moc_close_unplaced), except on an emulated run whose every series is daily or longer, where it goes out at the close of the next bar of its symbol, as in a backtest; - in an OCO group, or with a price, a stop price or a trail amount.
Attached orders, an attached MOC among them, stay refused live, and a member run against the desk (--deploy) does not hold an MOC yet.
The ledger. The order line records the MOC as MOC with its send time, send_at. At the send time, before the market order leaves, a moc_release line records the instant and the ticket sent:
{"kind":"order","canonical_id":"demo-k7x2q3mz4a-9","client_id":"flat","symbol":"fut:XCME:ES:M26","side":"SELL","quantity":1,"type":"MOC","tif":"DAY","attempt":1,"submitted_at":"2026-03-11T19:52:00Z","send_at":"2026-03-11T19:58:04.011999583Z"}
{"kind":"moc_release","canonical_id":"demo-k7x2q3mz4a-9","type":"MKT","send_at":"2026-03-11T19:58:04.011999583Z"}An MOC line with a send_at and no release is still held, and the broker has never seen it. A restart takes it back as a working MOC, with a log line, and the engine holds it again. A released MOC is matched at the broker by its reference, like any order; one that is missing there refuses the start, as any order missing at the broker does.
A missed send time. When the engine was down at an MOC’s send time, the restart decides as of the instant the run is back:
- before the session’s RTH close, the MOC goes out at the next allowed second of the window, or, with none left before the close, as below;
- at or after the close, nothing is sent. The run prints an alarm,
algo: ALARM: market-on-close order "<reference>" (<symbol> <side> <qty>) was not sent: its send time <T> and its session's close passed while the engine was down (GLE-1375), and the strategy receives the order’s cancel with reasonCANCEL_REASON_MOC_SEND_MISSED(12; the SDK’sCancelReasonMOCSendMissed, tokenmoc_send_missedon stdio-csv-v2 and in the lifecycle trace).
On an emulated run “back” is the open of the first bar the run steps.
Tick resolution
The bundled Databento adapter serves raw trades as well as bars, so the simulator can do better than OHLC: at tick resolution it replays each bar’s actual trade prints and fills your orders against the real intra-bar path. --simulation-resolution is auto by default, which uses tick when all of these hold, and falls back to bar otherwise:
- single series in the run (one trade stream to replay),
- time bars (activity bars’ windows aren’t addressable by time),
- no
--replicate(cloned bars have no faithful trade stream), - the adapter advertises the TRADES schema,
- the data’s coverage is tick-granular over the window.
Forcing --simulation-resolution tick when a precondition fails errors out instead of degrading; bar always works. The resolution actually used is recorded in the report’s simulator: line, and the run’s header says how the orders filled (GLE-1360): fills: tick path, or, at bar resolution, bar path (P), where P is the intra-bar path the simulator walked: none for the bars’ OHLC alone, the path interval (1m) under --path-interval, or native for the adapter’s own constituents under --include-path. Series on different paths name each once (bar path (1m, 5m)). The summary plate’s title line and the FillPath field of result.json say the same. When auto falls back, the run’s data notes give the reason as a fill path line, one line per reason across the set:
fill path bar, not tick: the adapter does not advertise the TRADES schemaIf a tick-resolution bar has no prints, market orders fall back to its open while other orders cannot match in that window. An attached trailing stop currently loses its known parent fill price in this fallback and may miss a protective exit at the next print; see the simulator finding.
--limit-fill sets how much evidence a limit fill needs. conservative (default) requires a print strictly through your limit price at tick resolution – a touch is not a fill, because in a real book a touch may never reach your order. At bar and path resolution it still fills on a touch (a bar low exactly at a buy limit), as the table above shows. through requires the trade-through at every resolution: a buy limit fills only on a bar or path constituent whose low is strictly below it (a sell limit, a high strictly above it), which proves a print beyond the limit. A stop-limit whose trigger price equals its limit is a touch too, so its leg triggers and rests instead of filling on the trigger. Fill prices do not change. Live runs refuse through, because the venue decides fills; a member on its desk’s SIM clock carries it, since the desk fills there (Fill settings on a desk). optimistic fills on the touch at tick resolution; use it only to measure the optimistic/pessimistic spread, never for results you intend to trust.
Fill settings per run
How a run’s orders fill inside a bar is the run’s own setting (GLE-1603). In a config file the five fill settings are keys of a run’s data object, and each run may have its own:
| Key | Values | When no level sets it | Flag |
|---|---|---|---|
simulation-resolution | auto, tick, bar | auto | --simulation-resolution |
bracket-ambiguity | conservative, optimistic, path_direction | conservative | --bracket-ambiguity |
limit-fill | conservative, through, optimistic | conservative | --limit-fill |
include-path | true, false | false | --include-path |
path-interval | an interval, such as "1m" | none | --path-interval |
{
"global": {"strategy": "bin/smacross", "bar-interval": "5m",
"data": {"adapter": "marketfeed-adapter", "limit-fill": "through"}},
"runs": [
{"id": "aapl-paths", "symbol": "eq:XNAS:AAPL",
"data": {"simulation-resolution": "bar", "path-interval": "1m", "bracket-ambiguity": "path_direction"}},
{"id": "spy-auto", "symbol": "eq:ARCX:SPY"}
]
}Here aapl-paths fills at bar resolution on each bar’s 1-minute path, and spy-auto on its trades where the run qualifies for them (Tick resolution); both fill limits only on a trade-through.
Levels. Like every
datakey, a setting may sit inglobal, in astrategiesentry or in a run, and the most specific level wins. An empty string is the key left out.The flags are defaults.
--simulation-resolution,--bracket-ambiguityand--limit-fillmay accompany--config. Each is then the setting of every run whose config sets the key at no level; a key, at any level, overrides its flag. This is the reverse of the other flags--configtakes, which override the file. Without the flag, a run that sets no key fills as it always has.--include-pathand--path-intervalstay single-run flags.There is no
pathresolution. A path is walked at bar resolution: setpath-interval(orinclude-path) and leave the resolution atautoorbar. Underautothe run takes the tick path where it qualifies and walks the bars’ paths where it does not;baralways walks them.Refusals. A value the key does not take is refused when the file is loaded, naming the key’s level, its values and the one given:
runs[0].data.simulation-resolution: must be auto, tick or bar, got "path" (an intra-bar path is walked at bar resolution: set path-interval, and leave the resolution at auto or bar) runs[1].data.limit-fill: must be conservative, through or optimistic, got "touch"
result.json records each run’s Resolution, BracketAmbiguity and LimitFill as the run was given them, and FillPath says how it filled.
A deployed run carries the same keys, and on a SIM desk the desk fills by them (Fill settings on a desk).
The rule as a library
algo run resolves a run’s fill settings with the package engine/fillpath, and applies them to its simulator with it. A program that fills a run’s orders itself, as the SIM desk does, calls the same package and so gets the answer the run’s backtest gets:
| Call | What it gives |
|---|---|
runconfig.Run.FillSettings() | An expanded run’s fillpath.Settings: its five keys, with its bar kind. |
Settings.Resolve(fillpath.Data) | tick or bar, with the note saying why auto fell back, or the refusal of an explicit tick. Data is the number of series, whether one is continuous (engine.IsContinuousSymbol), whether the adapter advertises TRADES (DataClient.SupportsTrades) and fillpath.TickCoverage. |
fillpath.TickCoverage(coverage, start, end) | Whether the first symbol’s coverage (DataClient.FetchCoverage) is tick-granular over the run’s window. |
Settings.Apply(&simConfig, resolution) | The simulator’s resolution, bracket and limit conventions, and whether it walks paths (Settings.WalksPath: a path asked for, at bar resolution). |
fillpath.TradeRange(bars), fillpath.TradeWindows(bars, trades) | At tick resolution: the range to read the trades over, and each bar’s window of them, [ts_open, ts_close) by ts_recv. |
Settings.PathSpec(series, interval) | On a walked path: the wire bar spec that reads a series’ bars with their path, the one the backtest requests; nil for a series the run walks no path on. |
Settings.Name(resolution, series) | The header’s tick path or bar path (1m). |
fillpath.Resolutions, BracketAmbiguities, LimitFills, and CheckResolution and its two fellows | The values each key takes, and their refusals. |
Where in its bar a fill happened
Every fill the simulator makes carries its bar anchor (sim.BarAnchor): the series, the bar’s open, and the place (open, intrabar, close, tick, cut, settlement). Since GLE-1603 the anchor also carries the span of the bar the simulator’s walk was covering when the fill happened, From and To:
| Fill | Span |
|---|---|
| On a walked path | The constituent it happened in, from its open to its close. A synthetic path’s leg (--path-heuristic), which carries no times, gives the whole bar. |
| At tick resolution | The print’s instant, From and To alike. A window with no prints gives the whole bar. |
| At bar resolution | The whole bar, from its open to its close. |
| Outside a walk | None: a market-on-close order filled at the close it was decided on, an expiry’s settlement, a combo’s legs. |
Fill times do not change: a path fill is still stamped at its bar’s close, and the span says where inside the bar it happened. The anchor reaches a fill observer (sim.Config.FillObserver) and the fill’s event (sim.VenueEvent.Bar). result.json, fills.json and the export are unchanged.
Path resolution (--include-path)
Between OHLC and ticks sits a third option. When your adapter coarsened the bars it serves – a daily bar built from 1-minute bars, say – it often still holds those finer bars. --include-path asks for them: each coarse bar arrives with its intra-bar path, the finer constituent bars it was aggregated from. At bar resolution the simulator then walks that path in order instead of guessing from OHLC, so it knows whether the high came before the low.
That changes fills. The classic case is a bracket whose bar crosses both the take-profit and the stop-loss: at plain bar resolution the --bracket-ambiguity convention has to guess which hit first; with the path, the simulator simply sees which the price reached first and fills that one. Trailing stops likewise ratchet across the path – tightening on an early constituent and firing on a later one within the same coarse bar – instead of ratcheting once from the close. So a path run’s fills can differ from the same run without it; that is the point. The run’s header names the path it walked, fills: bar path (native), or bar path (1m) at a named --path-interval (GLE-1360); without the opt-in it is bar path (none).
--include-path is opt-in and needs an adapter that advertises it (serves_path); against an adapter that does not, the run refuses to start rather than silently ignoring the flag:
algo: engine: adapter databento-adapter does not advertise BARS/BARS_TIME
serves_path (intra-bar path) ...; rerun without the path opt-in or use a
path-capable adapter
A continuous symbol walks the path of the contract it holds. A bare root (fut:XCME:ES) or a :cont composite (fut:XCME:ES:cont:adj=none, fut:XCME:ES:cont:ofs=B1) takes the path wherever its composite serves one (GLE-1332): on epoch buckets, on an intraday grid (rth, eth, utc-day), and on a 1d session bar at a named granularity. The engine asks the feed’s composite for the path, and the simulator walks each piece at the held contract’s own prices: the pieces the dated contract carries, never re-priced by the adjustment constants. Your strategy receives its bars as the run gives them, with no path: the held contract’s own prices under the default roll rebase, the adjusted ones with --roll-rebase=false. Over the archive this run fills order for order as the same run on the June 2024 contract fut:XCME:ES:M24 does (118 fills, 10 of them different from the run at bar resolution):
bin/algo run --strategy bin/roundnumbers --symbol fut:XCME:ES --bar-interval 30m \
--session rth --inputs Step=10 --path-interval 1m \
--date-from 2024-03-18 --date-to 2024-06-07A bar that contains a roll is walked from the cut, in the incoming contract. On an epoch bucket that straddles the cut, the feed assigns the whole bucket to the incoming contract (straddle=incoming), and the path holds that contract’s own trading before the roll, while your position was still in the outgoing contract. Those pieces are not walked: the roll executes at the cut, and the walk starts there. So a market order resting into the bucket fills at the first price after the cut, not at the bucket’s open before it, and a level only the pieces before the cut reached does not fill on that bar. The run’s data notes say how it routed the bar (--symbol fut:XNYM:CL --bar-interval 1d --continuous-clock epoch --path-interval 1m over January 2026):
roll straddles fut:XNYM:CL@1d 1 bar crosses a roll cut, 2026-01; each is walked from the cut in the incoming contract
and its degradation.json keeps the note in full:
bar straddles the cut CLG26->CLH26 at 2026-01-14T23:00:00Z: its bucket crosses the cut and the feed assigned it to the incoming contract CLH26 (straddle=incoming); routed by instant on its path: the roll executes at the cut and the simulator walks the bar's path from it, in CLH26; the 960 piece(s) before the cut are not walked
Without a path the bucket keeps its routing by bar (GLE-286): every fill on it, even at its open, is in the incoming contract. A utc-day grid bar that straddles a roll already executes from the cut in the incoming contract (GLE-444); with the path, the simulator walks the remainder’s pieces. A session bar never contains a roll: marketfeed refuses a session composite whose cut is not the first instant of a trade date (GLE-1333).
A served path the engine cannot walk fails the run, naming the bar, rather than being walked wrongly: a piece that spans the cut (PATH_ACROSS_CUT; name a path interval whose grid holds the cut, such as 1m), a piece of another contract than its bar (PATH_CONTRACT), a piece stamped with another adjustment constant than its span’s (PATH_CONSTANT), a non-finite price (PATH_PRICE), and a roll bar with no piece after the cut (PATH_EMPTY_AFTER_CUT).
The warm-up, the reach-back of an aligned series and the trade director’s history ask for no path: nothing walks those bars. A continuous series the strategy declares takes the path under the same rules as the run’s own, and the adapter must advertise serves_path for it.
What still refuses the path. A 1d or 1w continuous series that reads the feed’s session composite (with --session, or with none, when the default clock reads the eth session composite) is refused where that composite serves no path: a bare --include-path, since a session’s path is served at a named granularity only, and any path on a 1w bar, whose trade-week fold carries none. The refusal comes before any spawn, under the reason continuous_path_unavailable:
engine: continuous_path_unavailable: series fut:XCME:ES@1w: --path-interval 1m (or the path-interval key) asks for the intra-bar path of fut:XCME:ES, a bare futures root, whose bars the engine reads from the feed's eth session composite at 1w, whose trade-week bars carry no path; run 1d with --path-interval for a path run
The refusal is an *engine.ContinuousPathRefusal (Reason, Series, Symbol, Kind, Root, Flag, Read, Remedy), returned unwrapped (errors.As). The flag clause is --path-interval <d> (or the path-interval key) when the series’ request names a cadence, otherwise --include-path (or the include-path key); a composite reads fut:XCME:ES:cont:adj=none, an adapter composite (:cont). It covers the run’s flags and their config keys (data.include-path, data.path-interval), a series’ own construction keys (include-path, path-interval), and a continuous series the strategy declares, refused at its declaration with the same text. Checks that come first keep their own words: the session path rules (below), which a configured series with a --session meets before this one, the structural path-interval rules, and live mode’s refusal of a continuous symbol it cannot roll. A --config plan fails at build, before its first run.
Before GLE-1332 every path request on a continuous symbol was refused (GLE-550), because the engine’s composite reads asked for no path; before GLE-550 such a run filled at bar resolution with no warning. Tests: engine/gle1332_contpath_test.go (the raw-frame path, parity with a dated-contract path run, each roll-bar outcome, the path refusals), engine/tournament_contpath_spec_test.go, engine/contpath_mutation_review_test.go, engine/contpath_review_test.go, cmd/algo/contpath_build_test.go, and over the archive TestGoldenGLE1332ContinuousPathParity (the run above against fut:XCME:ES:M24).
It applies to time bars only, and the path stays private to the engine – your strategy still receives plain fixed-size bars, exactly as without the flag; only the fill simulation sees the finer detail. Tick resolution, when it applies, is finer still and takes precedence (the path is then unused). The data wire auto-prefers stdio-pb-v1 for path runs, because stdio-dbn-v1 cannot represent fractional volume or odd intervals exactly.
A session bar’s path
A 1d trading-day session bar (--session eth, rth or session) carries the path on a dated contract or an equity (GLE-1331), at a named granularity:
bin/algo run --strategy bin/smacross --symbol fut:XCME:ES:H25 --bar-interval 1d \
--session rth --path-interval 1s \
--date-from 2025-01-01T00:00:00Z --date-to 2025-03-01T00:00:00ZThree requests are refused before any process starts, each with its own message:
a bare
--include-path. Marketfeed serves a session’s path only at a named granularity, because a session’s native constituents are 1s bars, tens of thousands per session. Add--path-interval 1sor1m:engine: series fut:XCME:ES:H25@1d-rth: a trading-day session carries the intra-bar path at a named granularity only: add --path-interval (or the path-interval key), such as 1s or 1m, to --include-path (or the include-path key); the session's native 1s constituents are not served unnameda
1wsession bar, whose weekly fold carries no path;a custom window, whose one bar per trade date marketfeed serves with no path.
A continuous symbol takes a session path the same way (GLE-1332): --symbol fut:XCME:ES --bar-interval 1d --session rth --path-interval 1s reads the feed’s session composite with each session’s path, and the simulator walks it at the held contract’s prices (Path resolution). Marketfeed never puts a roll inside a session bar, so every bar’s path is one contract’s. With no --session a continuous 1d series reads the eth session composite and follows the same rules: a bare include-path or a 1w bar is refused (continuous_path_unavailable). The granularity follows the usual rules: strictly finer than 1d, and a whole divisor of it.
A session bar runs from its first trade to its last, so its open and close sit off any grid. Marketfeed builds its path on the UTC epoch grid of the granularity. It rebuilds the two edge pieces from the session’s own 1s tape, clamped to the bar’s open and close, so at 1m or coarser they are usually shorter than the granularity. Every other piece spans a whole bucket, and a bucket with no trades is missing. The engine checks each path on receipt against that law, and checks that the pieces reconstruct the bar: the first open, the highest high, the lowest low, the last close and the summed volume. A bar whose close is the settlement price is exempt from the close check alone. A path that breaks the law fails the run at the wire, naming the bar, so it is never walked:
engine: marketfeed: bar 2025-02-05T20:59:31Z: session path does not reconstruct its bar (volume)
The walk is the same as for any daily bar. Fills carry the session’s close as their timestamp. IOC and FOK orders expire, and the engine’s clock moves, at the session’s close. Trailing stops ratchet constituent by constituent. For GTC expiry, every constituent takes the bar’s trade date. An eth session opens the evening before its trade date, so dating its first constituents by their own close would put them on the day before.
The warm-up asks for no path. Neither does the reach-back of an aligned series or the trade director’s history. Nothing walks those bars, and a dated contract’s early, thinly traded history holds sessions too short to carry a path, which marketfeed refuses (1s path is not finer than the session span). The same refusal ends a run whose own window holds such a session: the first months of a back-month contract at 1s, for example. Start the window where the contract trades actively.
Which level a bar reached first
A bar records its open, high, low and close, not the path between them. When one bar reaches two of your levels – two entry stops, or an entry and its stop loss – the fill depends on which it reached first, and the bar cannot say. The simulator answers in one of four ways, each chosen by the run, with no change to the strategy. The most authoritative one available applies:
- Tick resolution, where the adapter serves trade prints and the coverage is tick-granular (Tick resolution). The prints say which level traded first; the conventions only break a tie inside one print.
- A declared path.
--path-interval 1m(which implies--include-path) walks each bar’s minute constituents in order. It needs an adapter that advertisesserves_path(marketfeed does), and the run reads the minute bars of its whole window: a 30-minute bar carries 30 of them. A1dsession bar takes a path too, at a named granularity (A session bar’s path). A continuous symbol (a bare root or a:contcomposite) walks the path of the contract it holds, and a bar that contains a roll from the cut (GLE-1332, Path resolution). --path-heuristic midpoint. The bar is walked as three monotone legs: open, high, low, close when the open is strictly above the bar’s midpoint (open > low + (high - low)/2), otherwise open, low, high, close, so an open exactly on the midpoint walks the low first. The extreme nearer the open comes first. Orders fill at their levels along the legs, a filled order’s children activate on its leg, and--bracket-ambiguitystill decides inside one leg.legacyreproduces the legacy engine’s comparison bug for bug (the open price against half the range), which almost always walks the high first; use it only for parity with that engine.- Bar resolution (the default). The bar is one ambiguous interval:
- two members of one OCO group of the same kind, such as two entry stops, tie, and the one submitted first fills while the other is cancelled. The bar’s direction and the open’s distance to each level play no part, even when the bar opened through the other level;
- a stop that the bar opens beyond fills at the open;
- an attached child activates at its parent’s fill and is settled against the same bar. When a child stop loss and a child limit target are both reached,
--bracket-ambiguitypicks between them (conservative, the default, takes the stop loss).
The strategy sees plain bars under all four: the path stays private to the engine, and only fills follow it. A decision that depends on the order of touches, rather than an order the simulator fills, needs a finer primary grid, and even then two events inside one of its bars stay ambiguous. Nothing fills on a warm-up bar, so a warm-up, an aligned reach-back and the trade director’s history ask the feed for no path, whatever the series (GLE-1336): a 200-bar 1d warm-up at --path-interval 1s would otherwise fetch some 17 million pieces only to drop them.
Two demos show the difference (GLE-524, row 30 of the nseries register’s V-867). Each places one OCO pair of stop entries a session on an intraday grid, with attached children, and their spec tests run the simulator three ways on the same constructed bars:
| Fixture | Bar resolution | --path-heuristic midpoint | --path-interval 1m |
|---|---|---|---|
tdrebo: entry stops at 5007.75 and 4992.25 around an open of 5000; the bar O 5006 H 5013 L 4991 C 4995 goes down first | the buy (submitted first), then its stop loss in the same bar: -775 at 50 a point | the open is above the midpoint 5002: the buy, then its target at 5012.5: +237.50 | the sell, then its stop loss on the way up: -775 |
roundnumbers: stops at 5270 and 5260; the bar opens at 5255, through the sell stop, and rises to 5277.25 | the buy at 5270 | the sell at the open, 5255 | the sell at 5255 |
tdrebo (DeMark’s TD Range Expansion Breakout, as Perl gives it) also classifies DeMark’s TD Range Projection tolerance scenarios from its own bars, each of which turns on which of two levels came first, and logs them; a scenario whose two events fall in one grid bar is ambiguous at that grid, and a declared path cannot resolve it, since the strategy does not see the path. Over the archive, on the June 2024 E-mini contract from 18 March to 13 June 2024, roundnumbers (Unger’s round numbers) at a step of 10 on the 30-minute rth grid chooses a different entry under the three conventions on five of 63 sessions: bar resolution buys on all five, the minute path sells on all five, and the heuristic sells on three. TD REBO’s two entry levels lie 0.764 of the prior session’s true range apart, and on the same contract no 30-minute bar reached both, so its three runs agree. The continuous root fut:XCME:ES walks the same minute path over the contract’s span: roundnumbers on it from 18 March to 7 June 2024 fills order for order as on fut:XCME:ES:M24 (GLE-1332).
An opt-in tie rule for same-kind OCO members at bar resolution (for example, the level nearer the open first) was considered and not built: the heuristic and the path already resolve the tie, and the engine stays unchanged.
The money knobs
bin/algo run ... --strategy bin/smacross --symbol MSFT --bar-interval 1m \
--initial-capital 50000 --commission-per-order 1.00 --slippage-ticks 1 \
--simulation-resolution bar simulator: resolution=bar bracket_ambiguity=conservative limit_fill=conservative slippage_ticks=1
3 fills, commission 3.00, realized PnL -0.34
open MSFT -1 @ 261.0800 (last 261.0300, unrealized 0.05)
equity 49996.71 (capital 50000.00, return -0.0066%)
| Flag | Default | Meaning |
|---|---|---|
--initial-capital | 100000 | Starting cash of the run’s account, in its base currency: 50000, or USD50000 with the currency named. |
--base-currency | USD | The account’s currency (ISO 4217). Capital is in it, and so is commission unless it names another; see Currencies. |
--margin-model | report | report, enforce or off; see Margin. |
--commission-per-order | 0 | Flat charge per fill: an amount in the account’s currency (1.50), or one with its currency (EUR1.50, 1.50EUR), converted at each fill; see Currencies. |
--commission-per-share | 0 | Per-share/contract charge per fill, in the same form (both can apply). The two amounts that are not zero must share one currency. |
--slippage-ticks | 0 | Adverse slippage in ticks (x each symbol’s tick size) on market-style fills. |
The simulator: block reads: the conventions in force (recorded verbatim so a result is never separable from its assumptions), fill count, total commission, realized PnL (average-cost basis, before commission), any open positions marked at the last close with their unrealized PnL, and final equity = cash + marked positions, with the return on capital.
Currencies
An account has one base currency, USD unless --base-currency (or a run config’s initial-capital currency) names another. Capital is in the base currency, and so is commission unless it names another (see below). Each instrument trades in its own currency, which the adapter reports in its instrument metadata (InstrumentInfo.currency; marketfeed reads it from its registry). NIY, the CME Nikkei 225 future in yen, is in JPY, at ¥500 a point. A continuous series takes its root’s currency for every contract it holds. An instrument the adapter names no currency for is in the base currency; one whose metadata cannot be read is taken the same way, and the run says so on stderr.
An account in which every instrument and the commission are in the base currency is unchanged: it reads no exchange rate, and its fills, equity and artefacts are the same bit for bit. When an instrument is in another currency:
Cash moves in the instrument’s currency. A NIY fill moves yen; a fill in the base currency moves base cash. Commission is charged in the base currency.
The account is valued in the base currency. Marked equity, closed equity and realized P&L convert each currency at the rate in force at the bar being marked. The rate in force is the latest published at or before that instant, so no rate is used before its publication.
The rates come from the feed. They are the Reserve Bank of Australia’s daily reference rates, which marketfeed serves as
fx:RBA:<FROM>-<TO>, each stamped 17:00 Sydney on its rate date. For each currency the engine reads the direct pair (fx:RBA:JPY-USDinto a USD account) or, when the feed has none, the inverse pair and inverts it, which is marketfeed’sCrossRaterule. The rates are the account’s input, not the strategy’s: they stay out of the strategy’s bars and the BENCH line. A run whose bars negotiated stdio-dbn-v1 reads them over a second connection to the same adapter on stdio-pb-v1, the only wire that carries them.A missing pair refuses the run. The RBA publishes AUD, CAD, CHF, EUR, GBP, HKD, JPY, KRW and USD crosses, but no CNH or SEK. The engine also refuses a run with no rate in force at its start, reading from two weeks before it: a daily reference rate last published earlier than that is not taken as in force. A direct pair that starts after the run’s start is bridged by the inverse pair until it has a rate. A rate served without its publication time refuses the pair:
algo: fx: the run trades in SEK and its account is in USD, but the feed serves neither fx:RBA:SEK-USD nor fx:RBA:USD-SEK over the runThe strategy sees every currency.
ctx.Account()lists one balance per currency, the base first, each with its open positions marked in that currency.AccountState.NetLiquidationis the whole account in the base currency, zero or negative included, andkit.Equityreturns it.The report converts each trade at its exit. A trade’s profit, its slippage and the trade statistics are in the base currency. A trade in another currency is converted at the rate in force at its exit, or at the end of the run if it is still open.
trades.csvthen gains three columns afterrun:currency,fx_rateandprofit_local(the profit in the trade’s own currency).result.jsonrecordsBaseCurrencyand each symbol’s currency. A report in a base currency other than USD labels money with its code (JPY 11,188,985.10) in place of$.
The sum of the trades and the equity curve no longer agree to the cent once the account holds a second currency. Each trade converts at its exit’s rate, while the equity values the account’s yen at the rate of every bar. The difference is the translation gain or loss on the foreign balance, and the report’s pairing residual carries it.
make run-fxbook runs smacross on ES and NIY in one USD account over 2023–2024:
simulator: resolution=bar bracket_ambiguity=conservative limit_fill=conservative slippage_ticks=0
170 fills, commission 0.00, realized PnL 12997.07
...
equity 104349.57 (capital 100000.00, return +4.3496%)
account currency USD; P&L by currency (rate to USD at the end of the run):
USD realized 1925.00, unrealized -7687.50
JPY realized 1730000.00, unrealized -150000.00 = USD 11072.07, -960.01 at 0.00640004
The yen P&L, ¥1,730,000 realized, is $11,072.07 at the 0.0064 dollars per yen of the end of 2024. make run-fxbook FXBOOK_BASE=JPY FXBOOK_CAPITAL=15000000 runs the same book in a yen account, where the dollar leg converts at 156.249 yen per dollar and the trade statistics read in yen:
account currency JPY; P&L by currency (rate to JPY at the end of the run):
JPY realized 1730000.00, unrealized -150000.00
USD realized 1925.00, unrealized -7687.50 = JPY 300779.31, -1201164.15 at 156.249
...
trade stats (gross): All Long Short
net profit JPY 2,466,431.76 JPY 11,446,542.58 -JPY 8,980,110.82
A commission can be in a currency of its own (GLE-1413): --commission-per-order EUR1.50, or a config’s "commission-amount": "EUR1.50". A bare amount is in the base currency. Each fill’s commission is converted into the base currency at the rate in force at the fill, read from the same RBA series, and the fill, the trades, the slice tables and the reports show the converted amount. A benchmark converts each of its legs’ commission at the leg’s time. The commission alone does not make the account hold a second currency: an account whose instruments are all in the base currency prints no P&L-by-currency block, and its trades.csv keeps its columns. result.json records the currency as CommissionCurrency, absent when it is the base, and report.html lists it beside the commission amounts. A run the feed has no rate for is refused before it starts:
algo: fx: the run charges its commission in EUR and its account is in USD, but the feed serves neither fx:RBA:EUR-USD nor fx:RBA:USD-EUR over the run
A portfolio of several runs adds their figures as they are, so its runs should share a base currency.
Margin
The adapter serves each futures contract’s initial and maintenance margin per contract, in a currency, with its provenance (Instrument metadata). marketfeed serves its registry’s seed, or an IBKR capture where one was taken. The engine reads the requirement as of the run’s start, so a capture taken after the run began is never used:
- a plain contract takes its own requirement;
- a continuous series’ contracts take the root’s, except that each contract a deferred schedule holds takes its own, read as of its span’s start (Held rank). A held contract the feed serves no margin for takes the root’s, since a registry seed is the product’s;
- a maintenance margin the feed leaves at 0 is the initial margin;
- a requirement with any other invalid figure (a maintenance margin above the initial, negative, or not a number) is ignored, and the run says so on stderr;
- a symbol whose metadata cannot be read requires no margin under
report, with a warning, and refuses the run underenforce, which could not make its check.
The simulator then holds the open positions to it. --margin-model (a run config’s margin-model setting) chooses how:
| Model | What it does |
|---|---|
report (default) | Computes the margin the open positions require at each bar, locks it in the account and records margin calls, but denies nothing. A run’s fills are exactly those it had without margin. |
enforce | Also denies an order that adds exposure the account cannot carry. |
off | Computes nothing. |
The enforce check. An order that grows a position (opens it, adds to it, or flips it to a larger size) is denied when the initial margin the account would then require exceeds its net liquidation. The requirement counts every open position, each converted into the base currency at the rate in force. A reducing order, a flattening order and a flip to no larger a size are always accepted. Only the order itself counts, not other working orders, and an engine roll leg is never checked. The denial reason starts with the stable token margin_initial:.
Margin calls. A margin call is a fall of the net liquidation below the maintenance margin the positions require, recorded once per fall. The simulator records it and liquidates nothing.
What the strategy sees. ctx.Account() carries:
InitialMarginandMaintenanceMarginin the base currency, withHasMargin;Margins, each position’s requirement in its own currency;- the base balance’s
Locked(the initial margin) and itsFree.
kit.BuyingPower(ctx) is the net liquidation less the initial margin.
What the report shows. The simulator: block names the model, the largest initial margin and the margin calls, then where every requirement came from: its source (the registry’s seed, or an IBKR capture with its date, flagged when it depends on the capturing account), naming the symbols each source covers. The performance block adds:
- the largest margin;
- the return on margin, which is net profit over the largest margin;
- the margin-call count;
- a Max margin column for each symbol.
result.json records the model and each symbol’s requirement with that provenance (Source, CapturedAt, AccountDependent, Contract). A run whose adapter serves no margin is unchanged.
make run-margin runs smacross on ES and NQ with 80,000 of capital under enforce, 2023–2024. The registry’s initial margins are 46,080 for ES and 89,054 for NQ, so the account carries an ES position and never an NQ one: every NQ entry is denied, 74 orders in all. (smacross reverses through flat, and enforce never denies a flip to no larger a size, so with the capital for both first entries it would have nothing left to deny.)
algo: order "smacross_1672869600000000000" (fut:XCME:NQ) from instance fut:XCME:ES,fut:XCME:NQ denied: margin_initial: buy 1 NQH23 needs initial margin 89054.00 USD with the open positions; net liquidation is 80000.00 USD
...
85 fills, commission 0.00, realized PnL -1050.00
...
equity 71262.50 (capital 80000.00, return -10.9219%)
margin enforce: max initial 46080.00 USD, 0 margin calls
margin sources: registry-seed (18 symbols, ESH23 to NQZ24)
...
max margin 46080.00 | return on margin -18.96% | margin calls 0
MARGIN_MODEL=report runs the same book with every order filled: 146 fills, and equity 70,367.50 against a largest margin of 135,134, with 30 margin calls. The margin was more than the account’s capital, which report records but does not stop. A margin call does not close a position.
make test-golden runs the same book over 2023 under both models (TestGoldenSmacrossMarginModels): report must report the largest initial margin of 135,134 and enforce that of ES alone, 46,080; enforce must name the registry seed as the source, deny at least one order with margin_initial: and make fewer fills than report, which denies none.
Brackets and OCO
Bracket attaches a take-profit and a stop-loss to an entry. The exits activate only when the entry fills, and form an OCO pair – when one fills, the other is cancelled with reason OCOTriggered. This compiles and is the canonical shape:
func (b *Breakout) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.Flat(bar.Symbol) {
return nil, nil // an entry or its exits are still live
}
entry := algolang.MarketBuy(bar.Symbol, int64(b.Size))
entry.ClientID = "breakout_1"
// Take profit 1.00 above the close, stop loss 0.50 below.
return []algolang.Order{
algolang.Bracket(entry, bar.Close+1.00, bar.Close-0.50),
}, nil
}The child orders inherit the entry’s symbol and quantity, get GTC time in force, and get ClientIDs derived from the entry’s (..._tp, ..._sl) so your OnFill/OnCancel can tell them apart. If the entry is cancelled before filling, the children are cancelled too (ParentCancelled – they were never live). Attached orders nest one level only.
Same-bar ambiguity. What if one bar’s range crosses both the target and the stop? A bar cannot say which the path hit first. The --bracket-ambiguity convention decides, and is recorded in the report:
| Value | Assumption |
|---|---|
conservative (default) | The stop filled first. Matches Interactive Brokers’ paper-trading simulator. |
optimistic | The target filled first. Sanity check only. |
path_direction | Bar closed above its open: target first; otherwise stop first. A heuristic. |
At tick resolution the ambiguity all but vanishes – the trade prints say which level traded first – and the convention only breaks per-print ties.
Time in force. A resting Day order gets one evaluation bar of its own symbol and expires at that bar’s close if unfilled. A Day bracket child activated during a bar survives that activation bar and gets its own next bar window. GTC orders remain working until filled or cancelled, and under --gtc-expiry ibkr-quarter until the venue’s quarter-end deadline (next subsection). IOC and FOK cancel after their immediate evaluation window; because the simulator fills whole orders, they are operationally identical here. This one-bar Day convention does not depend on exchange-session callbacks; its mismatch with a trading session on sub-daily bars is the finding that opened GLE-200. Under lifetime v2, when the run holds the symbol’s exchange calendar, the session takes the bar’s place: a Day order rests to the DAY-cancel close of the session it was submitted into and a GTC order under the quarter model to the quarter’s final trading close, each cancelled at that instant (I13b, GLE-468; Calendar cancellation instants (lifetime v2)); v1, a run without calendars and an order the calendar cannot place keep the rules above.
Pre-trade risk limits
Orders can pass through a trade director before they reach the simulator: a configured set of rules (caps on exposure, margin, drawdown and value-at-risk, a ranking of one instant’s entries, and operational controls) that refuses or trims the part of an order that opens risk. The simulator fills what the director lets through. See Trade director.
An order’s optional conviction, which the director ranks by, is described in Order conviction.
Combo orders
A combo order trades several dated contracts as one order that fills all its legs or none (GLE-409), as an Interactive Brokers combo (BAG) order does: a calendar spread, say, without the leg risk of two separate orders. Each leg names a contract, the action it takes when the combo is bought, and its ratio; selling the combo reverses every leg. The combo’s price is the net per unit: the sum over its legs of ratio × leg price, bought legs added and sold legs subtracted. Buying the spread “buy June, sell March” pays June − March, which may be negative.
// RequiredCapabilities: combos need order lifetime v2 and combo-orders.
func (s *CalSpread) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2, algolang.CapabilityComboOrders}
}
legs := []algolang.ComboLeg{
algolang.BuyLeg("fut:XCME:ES:M26", 1),
algolang.SellLeg("fut:XCME:ES:H26", 1),
}
buy := algolang.ComboMarket(algolang.Buy, 2, legs...) // 2 spreads at market
limit := algolang.ComboLimit(algolang.Buy, 2, 50, legs...) // at a net of 50 or better
sell := algolang.ComboLimit(algolang.Sell, 2, 60, legs...) // sell at 60 or better
A combo’s Symbol is its legs’ combo symbol (ComboSymbol: combo:B1@fut:XCME:ES:M26|S1@fut:XCME:ES:H26), its Quantity the combo units, and its ClientID and attempt one identity: the combo is one order. Cancel it by its ClientID and every leg goes with it; replace it as any order under lifetime v2. Each leg is a dated futures contract of the run (two or more, each once, with a positive ratio). ctx.Flat and ctx.Exposure count a working combo on each of its legs’ contracts.
How the simulator fills one. Bars cannot say whether two legs’ highs and lows happened at the same moment; only their opens, and their closes, are known to coincide. So a combo is evaluated at an instant at which every leg has a bar (one close time), and only there:
- a market combo fills at the legs’ opens;
- a limit combo fills at the opens when the net there is at or through its limit (at or below for a buy, at or above for a sell), else at the closes when the net there is, else not at this instant.
Each leg fills at its own price at that point, as a fill of its own contract. A market combo’s legs are slipped per leg (--slippage-ticks, on each leg’s executed side); a limit’s are not. Each leg pays its own commission. An instant at which a leg has no bar fills nothing: the combo waits for an instant with all its legs. A combo placed on a bar is evaluated only against bars closing after it. Day, IOC and FOK combos have one evaluation window, the first complete instant, and are cancelled TIF_EXPIRED if it does not fill them; GTC waits. Under lifetime v2 with every leg’s exchange calendar held, a Day combo rests instead to the earliest of its legs’ session closes and a GTC combo under the quarter model ends at the quarter’s final trading close (Calendar cancellation instants (lifetime v2)). A combo is cancelled CONTRACT_EXPIRED with its first leg to expire.
A cancel between the legs’ bars waits for the instant (GLE-486). The engine gives the strategy a decision on every bar, and a combo’s instant completes only with its last leg’s bar. A cancel placed on an earlier leg’s bar at an instant T, once the strategy has seen that leg’s close at T, would otherwise dodge a fill at T’s opens, which came earlier, and a combo cancelled and replaced on every bar would never fill. So the simulator evaluates T first:
- the cancel is answered
pending(CancelOutcomePending, statuspending_cancel); - when T fills the combo, the fill wins: its leg fills end the attempt, and the cancel came too late;
- otherwise the cancel applies once T is evaluated, an
OrderCancel(EXPLICIT) carrying the request’s id, stamped T; - when T never completes (a leg has no bar at it), the cancel applies as soon as the run moves past T, before the next bar or timer, still stamped T. A pending cancel left at the end of the run applies before the expiry and shutdown passes;
- whatever else ends the combo meanwhile (an expiry, a roll) answers the request too: its cancel carries the request’s id.
A replacement placed beside the cancel, under the same label, is held by the race guard behind the pending cancel (Lifecycle turns). It is released at T when the cancel applies, and evaluated from the next instant. It is denied cancel_race: … when T fills the attempt it waited on, so the strategy never has two combos working. A cancel placed when no leg’s bar at the clock is in yet, or after the instant completed, applies at once, as before. calspread decides on the bar that completes an instant, so it never meets the rule.
A leg’s fill carries the combo’s ClientID and attempt, the leg’s Symbol and executed Side, its contracts (ratio × units), ComboLeg (the leg’s 1-based index), a leg-unique ExecID, RemainingQuantity, the combo units still working: the combo’s quantity until its last leg, then 0, and the combo’s Name when it has one (GLE-666). The position of each contract moves with its leg; ctx.Position reads it per contract.
Priced at the exchange’s spread (GLE-487). A leg that trades thinly can have an open or a close stale by tens of points, where the exchange’s own calendar spread shows where the pair traded. marketfeed keeps ES’s spreads (GLE-414, fut:XCME:ES:H26-M26, listed front first and priced as the deferred contract minus the front). On a run that negotiated combo orders, the engine reads, for each pair of the run’s dated ES series at one construction, interval and session, that pair’s spread over the run’s window and hands it to the simulator. It reaches neither the strategy nor the bar count. A combo of exactly those two legs, one unit each on opposite sides, in either order, is then evaluated at the spread’s price:
- it is evaluated on the earlier-expiring leg’s bar at each instant after it was placed; the other leg’s price is derived, so that leg needs no bar of its own, and a thinly traded one rarely has one;
- the spread’s price at the instant is its bar’s open, then its close, when it traded then, else its last close before the instant at both, which is what it was last known to trade at; before the spread’s first bar the combo is priced at its legs’ own bars, as any combo is;
- at each point the earlier-expiring leg fills at its own open (or close) and the other at that price plus the spread’s, so the combo’s net is the spread’s. A limit is tested against the spread’s price itself, so one at exactly that price fills. A market combo’s legs are still slipped per leg;
- each evaluation is the instant’s window, so a
Day,IOCorFOKcombo not filled there expires as any order does.
A pair priced so is not a note: Summary.ComboSpreadFills counts the combos it priced. A spread the adapter does not serve, or one with no bar in the window, is left out, and combos of its legs fill at their own bars. So is one whose bars fail validation, or, on an intraday grid, one whose grid the adapter does not probe. Each of those is a combo pricing line of the run’s data notes (GLE-1360), which says why:
combo pricing fut:XCME:ES:H26-M26 no intraday grid; combos fill at their legs' own bars
``` A run that holds the legs at several
intervals reads the spread once, at the first pair of series. Another root's
spreads are not used until its sign convention is checked, since the sign is
the listing's.
**Limits of the model.** A combo that is not exactly a kept spread's two
legs (a butterfly, a 1:2 ratio, two contracts of different roots) fills at
its legs' own opens and closes. A spread-priced combo is anchored on its
earlier-expiring leg's own price: its net is the spread's, but when that leg
is the thin one (an M26/U26 pair in January), both legs' prices are as stale
as that leg's. The second leg's price can also fall between the outright's
ticks, since a spread ticks finer. Open positions are still marked at each
contract's own close. Under `--margin-model enforce` a combo is admitted when the initial margin of
every position after all its legs fill fits the net liquidation; the model has
no spread credit, so it is stricter than an exchange. Among the lifetime
limits a combo is one working order on the run and one on each leg's
contract, and each leg's contracts (ratio × units) meet the order-quantity
cap.
**Where combos run.** A combo needs order lifetime v2 (a backtest's
default) and the `combo-orders` capability, which the engine offers on a backtest on the
pb wire with no continuous series; a combo from a strategy that did not
accept it, or on a run with a continuous series, is denied. A v1 run denies
every combo, a live run refuses one (the IBKR venue has no combo ticket
yet), the CSV strategy wire has no place for legs, and `kit.Controller` does
not manage combos: return them from the callback.
**In the report.** Each leg is a fill of its own contract and pairs into
that contract's trades. The run also writes **combo trades**: the units of a
combo execution paired, first in first out, with a later execution of the
reversed legs (a two-unit entry closed by two one-unit exits makes two), with
the cash each paid and the profit. A combo closed by other orders, or by a
leg's expiry, stays open in this view. They are in `result.json`
(`ComboTrades`), `combo_trades.csv` and the HTML report's "Combo trades"
table, written only on a run with combos. The CSV's columns are
`client_id,combo,units,entry_time,exit_time,entry_cost,exit_cost,profit_currency,commission,open`:
`combo` names the legs per unit as entered
(`B1@fut:XCME:ES:M26|S1@fut:XCME:ES:H26`), the times are RFC 3339 UTC,
the costs are the cash the trade's units paid at entry and at exit in the
base currency (negative when received), `profit_currency` is gross of
commission and slippage, and an open trade has an empty `exit_time`, is
marked at each leg's last close and reads `open` `true`. The portfolio
output has no combo trades: its `trades.csv` lists the legs' trades of
each contract. The lifecycle trace's `submit`
record lists the legs and each leg's `fill` record its `combo_leg`.
**The example.** `strategies/demo/go/calspread` mean-reverts the E-mini
March/June 2026 calendar spread on the two dated contracts: on each instant
with both bars it takes the spread (June − March) and its z-score over 20
instants, buys the spread at −1.5, sells it at +1.5 and closes it within 0.5
of zero, each a market combo.
```sh
make run-calspread # --lifetime v2, fut:XCME:ES:H26 + fut:XCME:ES:M26, Dec 2025 to Mar 2026Over December 2025 to mid-March 2026 on the archive it places 7 combos, whose 14 leg fills pair into four combo trades, all priced at the exchange’s H26-M26 spread: three round trips and an entry on 10 March still open when the window ends. It ends at $100,190.00 on $100,000. A thinner window shows why the spread matters. In October and November 2025 M26 traded tens of lots a day, and on the days calspread acted the two contracts’ own closes implied spreads from 49.75 to 107.50. The run’s six combos fill at the exchange spread’s opens, 52.20 to 54.80, or, on Sunday 23 November, when the spread did not trade, at its last close, 50.15.
make run-calspread CALSPREAD_START=2025-10-01T00:00:00Z CALSPREAD_END=2025-12-01T00:00:00Zmake test-golden pins both runs. Spreads on continuous series (two ranks of one root) are not combos: see Contract curves.
GTC quarter-end cancellation
Interactive Brokers offers no order that is immune to expiry: a good-till-cancelled order is cancelled at the close of the last trading day of the calendar quarter following the quarter in which it was placed (placed in Q3 2026, cancelled at the end of Q4 2026; placed on 2026-10-01, cancelled at the end of Q1 2027), and a modified order gets a new deadline. A backtest that ignores this shows protection a live account does not have. --gtc-expiry selects whether the simulator models it (the order-lifetime programme’s increment I13a, GLE-374):
| Value | Meaning |
|---|---|
never (default) | No age-based GTC expiry. The order rests until a fill, a cancellation or the run’s end; OCO, corporate-action and contract-expiry rules still apply under their respective profiles. The quarter-expiry model records no anchor or counts and adds no events. |
ibkr-quarter | A working GTC order is cancelled, reason GTC_EXPIRED, before the first bar whose trade date falls after the end of the calendar quarter following the quarter of its submission’s trade date. Under lifetime v2 with the root’s exchange calendar, at the calendar’s close of the quarter’s final trading day instead (At the calendar’s close, below). |
It is a command-line option only, like --lifecycle-json: no run-config key sets it, so a --config run keeps never. Any other value (--gtc-expiry quarter, say) is refused naming both values.
The rule. Every physical submission is anchored at the exchange trade date of the bar the strategy just decided on: BarSession.TradeDate when the bar carries a session block (a session-keyed daily or weekly series), else the bar’s economic date, the date on the exchange’s clock (the symbol’s zone, The date range; UTC when the adapter gives none) of the instant one nanosecond before its close (a bar closing exactly at the exchange’s midnight belongs to the day that midnight ends). The deadline is the last calendar day of the quarter after the anchor’s: anchored 2026-09-30, due after 2026-12-31; anchored 2026-10-01, due after 2027-03-31. No exchange calendar is needed, because on trade dates no date lies between a quarter’s final trading day and its last calendar day, so “before any bar whose trade date is past the deadline” is the same test either way. The anchor and the submission instant are stored side by side, so a bar keyed 2026-09-30 whose close is 2026-10-01T01:00:00Z anchors in Q3.
Before each bar is walked, after the previous close’s queued events are delivered and before anything is matched against the bar, the simulator cancels every working GTC order, of any symbol, whose deadline is strictly before the bar’s trade date: the venue’s deadline is a clock event, not a property of the bar’s instrument, so another symbol’s bar advances it too and an illiquid symbol does not keep a dead order alive. A bar keyed on the deadline’s own date is still walked and can fill the order. The cancel is stamped at the simulation clock, the last observed close, and reaches the strategy as an OnCancel with reason GTC_EXPIRED (CancelReasonGTCExpired) ahead of that bar’s fills. A due order’s OCO group settles as a fill would: its still-inactive children are cancelled ParentCancelled, a sibling that is itself due is GTC_EXPIRED in its own right, and any other live sibling is cancelled OCOTriggered by it. An order already expired is not swept again at the end of data; one whose deadline is still ahead is swept with Shutdown, as before. A continuous roll runs the same pass at its trade date before it reads the working book (Simulator.ExpireGTC), so an order the venue has already ended is not rolled (Order lifetime v2 across a roll); under lifetime v2 the contract-expiry pass runs it too, at the bar’s or the timer’s trade date, before it expires a dated futures contract, so an order due under both reasons is GTC_EXPIRED (Contract expiry (lifetime v2)).
Paths and coarse bars. With --include-path (and a path on the bar) the deadline is resolved inside the bar: each constituent is tested before it is walked, so an order fills on the constituents up to and including the deadline’s trade date and is cancelled before the first one after it, the cancel stamped at the parent bar’s close. Without a path a bar is resolved no finer than itself: a weekly bar straddling a mid-week quarter end cancels the order before the bar, although the bar’s range may cross the order’s level, and a post-deadline fill is not admitted. That approximation is counted: Summary.GTCExpiredCoarse is the number of expiries produced before a bar whose close is more than 24 hours after its open (a CME session, an equity day and an epoch day are not coarse; a week is) and whose span contains the deadline. When the model is on, the report’s simulator: line gains gtc_expiry=ibkr-quarter gtc_expired=N gtc_expired_coarse=M; a default run’s line is unchanged.
What resets the anchor. Each physical submission is a fresh anchor: a cancel-and-replace under the same client id restarts the deadline from the replacement’s trade date, and the replaced order’s cancel keeps the reason the strategy’s cancel gave it (Explicit). A bracket child anchors at its activation, the bar or constituent on which its parent filled, the simulation’s stand-in for the instant the venue would release it. A continuous roll re-places a resting order on the incoming contract as a new physical submission, so it resets the anchor too, and every order a roll re-places anchors at the roll’s trade date, the synthetic incoming bar’s (since I15 unit 2b, GLE-459): a re-submission at the cut explicitly (Simulator.SubmitRolled), because the simulation clock still stands at the outgoing contract’s last bar when the roll places it; a re-submission after the synthetic bars through the clock, which the bars have moved to the roll’s date; a re-established bracket child at its activation on the synthetic incoming bar. A GTC order rolled every quarter therefore does not expire in a :cont backtest. The deadline is applied before the roll reads the book, so an order due at the roll’s trade date expires and is not rolled, while one whose deadline is that date is rolled (The GTC rule at a roll). A GTC order submitted before any bar was observed (direct simulator use) anchors at the first bar’s trade date, the parent’s on a path bar. Only GTC carries a deadline; Day, IOC, FOK and an unspecified time in force (a CSV order, an engine roll leg) are untouched.
The lifecycle trace labels the reason gtc_expired and counts it among the unsolicited_cancels; the CSV strategy wire renders it gtc_expired as well. A run that keeps the default emits the reason nowhere, so its trace and its CSV lines are unchanged.
At the calendar’s close (lifetime v2). Since I13b (GLE-468, 2026-10-10) a run under lifetime v2 that holds the root’s exchange calendar cancels the order at the DAY-cancel close of the quarter’s final trading day, the last trading day at or before the deadline above (a weekend or a holiday stepped back over, an early close applied), rather than before the next bar: the deadline day’s bar is walked in full, a fill on it wins, and the cancel goes out in that bar’s events ahead of the strategy’s decision, stamped at the close and carrying the calendar’s basis; when no bar closes at the instant, the cancel comes before the first bar of any symbol closing after it, at a timer, at a roll’s cut or at the run’s end. The instant is placed when the order is anchored, from the same deadline, and only when the calendar is complete there; an order the calendar cannot place keeps the rule above and is counted (calendar_fallbacks=F). Such a cancel counts among gtc_expired and among the calendar counts; gtc_expired_coarse stays this rule’s count. The rule above is unchanged for v1, for a run without calendars and for the live loop. See Calendar cancellation instants (lifetime v2).
Known limits. The cancel instant is the last observed close, the latest instant known to precede the deadline, not IBKR’s closing time on the quarter’s final trading day: after a data gap the stamp is earlier than the venue’s (visible in the trace, and not a fill), and a sub-daily bar without a session block takes its economic date on the exchange’s clock, which puts the evening hours of a CME trading day (from 17:00 CT) on the calendar date before its trade date. The coarse condition is mechanical: it reads the open’s plain calendar date on the exchange’s clock (an instant at midnight starts that day, so a weekly bar opening exactly at the exchange’s midnight starting 1 October is exact for a 2026-09-30 deadline, while a close at midnight ends the previous day) and flags the bar when the deadline is on or after it. It over-reports when a bar’s ts_open is the previous session’s close: a daily feed stamped that way spans a weekend (Friday 21:00Z to Monday 21:00Z is 72 hours) and is flagged coarse when the deadline is that Friday, although the bar’s trading is all after it. Harmless, because it is a count and not a fill. Under lifetime v2 with the root’s exchange calendar, I13b replaces both approximations with the calendar’s close (above); an order the calendar cannot place is left under this rule and reported as a calendar fallback.
Contract expiry (lifetime v2)
A dated futures contract stops trading at its expiration, and Interactive Brokers ends it there: its working orders are gone, and a position held through it is cash-settled at the contract’s final settlement price. Since increment I14 unit 2a of the order-lifetime programme (GLE-479, 2026-10-09; engine/sim/expiry.go and engine/contexpiry.go) a backtest under lifetime v2, the default since I22, does the same, and since its follow-up (GLE-481, 2026-10-10; engine/finalsettle.go and engine/sim/finalsettle.go) the price is the exchange’s own final settlement, read from the data adapter’s statistics stream. When the loop’s clock passes a contract’s expiration, the contract’s working orders are cancelled with a reason of their own, CANCEL_REASON_CONTRACT_EXPIRED, its position is closed by one fill at the final settlement price, the contract is marked expired so that a later submission on it is denied, the lifecycle trace records the expiry ahead of its events, the report counts it, and the engine’s race guard follows. The pass is automatic under v2 and has no flag.
v1 is unchanged, byte for byte. The legacy profile knows nothing of expiry: on a backtest of a dated contract the strategy’s working orders rest past the expiration until the end of the data (then Shutdown), and a position held through it stays open, marked at the contract’s last close. A v1 run asks the adapter for no expiration and no final settlement, builds no pass, calls nothing on the simulator and produces no cancel with the new reason, so the KBD masters and every golden are unchanged.
Where the expirations come from. Before the loop, under v2 only, the engine asks the data adapter for each venue symbol’s InstrumentInfo.expiration (Protocol reference): the contract’s last-trade instant, in UTC, which marketfeed reads from the exchange’s definitions. A plain dated contract is asked for by its own name, and a continuous series’ contracts by their dated feed symbols (fut:XCME:ES:H26 for the engine’s ESH26), one round trip per live contract, so that the continuous diagnostics below have their facts. The instants go to the simulator’s venue config (sim.VenueConfig.Expirations, read back as Simulator.ContractExpiries, sorted by instant and then by symbol). With them, since GLE-481, go the final settlements of the contracts expiring within the run (sim.VenueConfig.FinalSettlements, read back as Simulator.FinalSettle; how they are found is under The price below). A symbol the adapter gives no expiration for is left out and behaves as before: an equity, a futures root, or an adapter that predates the field (the proto promises older adapters stay compatible, so there is no refusal). When the adapter describes such a symbol as a future, the engine notes it once, because the contract’s orders and position will then outlive it in the simulator. A backtest’s note is an expiry line of its data notes (GLE-1360), and its degradation.json holds it in full:
expiry fut:XCME:ES:H26 none from the adapter; the simulator does not expire its orders or positionA live run writes it on stderr as it finds it:
algo: ESH26: the data adapter gives no expiration; the simulator does not expire its orders or position (GLE-200 I14 unit 2a)When a contract is due. The expiration is an instant and is compared with instants (bar closes, a timer’s instant, a roll’s cut, the run’s end), not with trade dates: a trade-date key would move a 14:30Z expiry to the day’s end and admit fills the venue could not have given. The pass runs at three points of the bar loop:
- at the top of every bar, after the deferred lifetime-v2 outcomes and the corporate-action passes and before the continuous rolls due before the bar, every plain contract whose expiration is strictly before the bar’s close expires, before the bar is advanced;
- before a timer’s decision (Scheduled decision points), every plain contract whose expiration is strictly before the timer’s instant expires, ahead of the rolls due before it, so the decision sees the post-expiry state;
- after the last bar, every contract whose expiration is at or before the run’s end (
--date-to, resolved as the latest end over the run’s series, The date range; the last bar’s close when a run has no end) expires, before the held orders are refused and the shutdown sweep runs. The run’s end is never later than the instant the run was made, unless the last bar closes later still: a run with no--date-to, or one that reaches today, does not expire a contract whose expiration is still to come. It ends at its newest bar with the position open, valued at the last price, as a run ending at that bar would (GLE-1350).
The asymmetry is deliberate: a bar closing exactly at the expiration is advanced in full and a timer at the expiration fires nothing, while a run ending exactly at the expiration fires. Both read “the venue stopped trading before this instant” at the instant, and at the run’s end the run has ended. A bar whose span straddles the expiration (a daily epoch bar on the expiration day, an intraday bar around it) closes after it, so the pass fires before that bar is advanced and the orders do not see the bar’s pre-expiry window: the same approximation the GTC model makes, a venue termination being resolved no finer than a bar, and not counted here. A session bar keyed on the expiration’s trade date closes at its last constituent, at or before the expiration, so it is advanced in full and the pass fires on the next bar (another symbol’s) or at the run’s end. A contract that expired before the run started fires at the first bar, with nothing to cancel or close unless a position was seeded; the point is the mark, so that an order on it is denied. Two contracts due at one instant fire in the queue’s order.
What the expiry does. Simulator.ExpireContract, in order:
- The cancels. Every live working order on the contract, walked in submission order, is cancelled through the common cancel path a strategy’s own cancel takes, with
CANCEL_REASON_CONTRACT_EXPIRED; each of its unactivated children follows it withPARENT_CANCELLED, as when any parent is cancelled. The activated children of a filled entry are live orders of their own and are each cancelled for the expiry, as is each member of a standalone OCO group: a group does not span symbols, so every live member is reached and noOCO_TRIGGEREDcancel is produced. Each cancel echoes the attempt and carries the top-level order’s broker id as its origin. A working combo order with a leg on the contract is cancelled the same way, whole: a combo goes with its first leg to expire (Combo orders). Orders on other contracts, and orders already done, are untouched. - The settlement. When the position is not flat, one closing fill settles it: a long sells and a short buys the whole quantity at the settlement price, with no commission and no identity (
ClientID,ParentClientID,ExecIDandOrderRefempty,AttemptandRemainingQuantity0). The notional moves the cash of the contract’s currency as a fill’s does, the P&L is realised against the average cost and the lot is flattened. The fill belongs to no order: the--fills-jsonblotter and the trace’s blotter carry it with an empty broker id, as the cash merger’s close leg is carried, and the performance recorder sees a market execution with no slippage. - The mark. The contract is marked expired before the cancels, the close and any callback the close makes, so a submission made while the strategy hears the closing fill is already denied, and a second expiry of the same contract is a no-op. From then on every submission on the contract is denied with positive evidence, as the venue would deny it,
contract ESH26 expired at 2026-03-20T13:30:00Z and no longer trades, which the engine surfaces as aDeniedupdate and aREJECTEDcancel, as any denial; a submission on another symbol is accepted as before.
The events are stamped at the expiration instant, which is known exactly and lies between the last observed close and the next, or at the simulation clock when the clock is already past it (a multi-series run whose other series moved the clock on), so the simulator’s stamps do not run backwards. A close stamped on the previous day’s bar would misdate the P&L. The trade-date GTC cancels of the coincidence below keep their clock stamp; a cancel at an exchange-calendar instant carries that instant.
The price. The settlement price is, in this order of precedence:
- the exchange’s final settlement (
settle_source "final_settlement", since GLE-481): the settlement the exchange published for the contract’s expiration date, read from the data adapter’s statistics stream before the run starts (below); - else the contract’s last served settlement (
"settlement"):BarSession.settlewithhas_settleon a session-keyed bar (Session bars), which the simulator records as it observes each bar; - else the contract’s last close (
"close"): intraday bars, an epoch bar, a feed without settlements.
The trace’s expiry record (settle_source), the operator line’s tail and the report’s expiry_fallbacks=F say which was used. A position with none of the three fails the run rather than settle at a made-up price (unreachable through the simulator’s API, since every path that opens a position records a last price; kept as a guard). A flat contract needs no price. A finite negative settlement is a price (CL settled at -37.63 in April 2020) and is accepted, and so is a final settlement of 0; a NaN or infinite one refuses the expiry before anything changes, as does a position with no magnitude in 64 bits.
Why the bars cannot carry it. The adapter attaches a settlement to a bar only when the settlement was published by the bar’s close, and a contract’s final settlement is published after its last bar closes (so is a thin contract’s daily settlement whenever its last trade comes before the settlement time). Checked on the wire on 2026-10-09: the last daily session bar of ES H24 (2024-03-15) is served with no settle and a close of 5116.25, against the exchange’s final settlement of 5101.67, a difference of 14.58 points, 729 dollars a contract; ZC H24 closed at 423 against a final settlement of 422.5, and CL G24 at 75.01 against 75.19. Until GLE-481 every real run settled at the last close. The statistics stream does carry the final settlement (Statistics and instrument definitions): ES H24’s is one STAT_SETTLEMENT_PRICE record dated 2024-03-15 and published at 13:56Z, twenty-six minutes after the 13:30Z expiration.
How the final settlement is found. Before the loop, under v2 only, beside the expirations, the engine makes one settlement-price statistics request per contract expiring within the run, at run start, while the adapter is up (the data client is shut down before the bar loop, so nothing can be fetched at the pass). A contract is due when the adapter gave it an expiration at or before the run’s end (--date-to; with no end, every contract that has one). The request names the contract’s dated feed symbol (fut:XCME:ES:H24 for the engine’s ESH24; a plain contract by its own name) and the one kind, STAT_SETTLEMENT_PRICE, and its window holds the publications after the UTC midnight starting the expiration’s UTC date and up to seven days later, (2024-03-15T00:00:00Z, 2024-03-22T00:00:00Z] for ES H24 (a record owns its instant, as a bar owns its close: The date range); the adapter filters on publication, so the window catches the same-day publication, a weekend republish and a Monday correction. Among the records served, the final settlement is the record whose reference date (ts_ref, the settlement’s trade date) is the expiration’s UTC date, the latest published among them (ts_recv, else ts_event, else ts_ref; two published at one instant resolve to the later on the wire). The archive explains the rule: a daily settlement is published two or three times a day with the same value, so the latest publication is the right tie-break and a restatement wins; the day before’s settlement is republished after midnight UTC, on a Sunday too, so the date match keeps it out. A record of another day, another contract or another kind, a deletion, or one with no finite price or no reference date is ignored. No exchange calendar is consulted: every CME last-trade time falls inside the Chicago business day, so the expiration’s UTC date is its trade date. The prices found go to the simulator’s venue config (sim.VenueConfig.FinalSettlements, keyed by the venue symbol and read back as Simulator.FinalSettle), and the pass reads them there.
Through the pinned marketfeed adapter against the live store (2026-10-09, repeated with the integrated code on 2026-10-10), each of the three contracts above answered the request with exactly one record, dated the expiration’s UTC date and published minutes after the expiration instant (ES H24 twenty-six minutes after, ZC H24 twenty-two seconds, CL G24 sixty-nine seconds), and a position held to expiry under v2 closed at it: ES H24 at 5101.67, ZC H24 at 422.5 and CL G24 at 75.19, each with the final-settlement line below and no fallback on the report. Under the default auto wire a lifetime-v2 run holding a dated futures contract prefers stdio-pb-v1 (since GLE-489; before it the auto wire took DBN first and the settlement was reached only with --data-protocol pb), so the run negotiates pb with marketfeed and no wire notice is written; --data-protocol forced to another wire falls back with the line below.
The knowledge-time rule. The final settlement is published after the expiration instant, so no served bar and no declared statistics series carries it before the position is closed, and the run-start fetch reads it ahead of every bar. The venue closes the position at it all the same: the final settlement is the contract’s own terms, the price the clearing house settles every open position at, not information a strategy could act on. No strategy decision precedes the forced close; the strategy hears the price only through the venue’s closing fill (the OnFill with no ClientID below), after the position is gone. The run’s bars, statistics series and declared events are untouched: the price reaches the simulator through VenueConfig.FinalSettlements alone and leaves it through the closing fill alone.
Errors and fallbacks. The fetch warns and falls back; it refuses no run, since the fallback is what I14 unit 2a did, now labelled as a fallback. A backtest’s warnings are final settlement lines of its data notes (GLE-1360), each in full in its degradation.json; a live run writes them on stderr, as quoted here.
An adapter that does not advertise
STATISTICS(a fixture adapter,file-csv, an adapter that predates the schema) is asked nothing, silently, whatever its wire.On a data wire other than
stdio-pb-v1(the one wire that carries statistics; under the defaultautoa v2 run holding a dated contract prefers pb, so this is--data-protocolforced todbnorcsv, or an adapter that offers no pb) nothing is asked, and one line is written when a contract is due, none otherwise. The remedy is the defaultautowire, or--data-protocol pb, with an adapter that serves the schema on it:algo: the final settlements cannot be read: statistics need the stdio-pb-v1 data wire (negotiated stdio-dbn-v1); a position held to its expiry settles at the last settlement or close (GLE-481)A request that fails (an adapter error, a wire error) contributes nothing, whatever records came back beside the error; one line names the contract and the error, and the other contracts are still asked about, the prices already found kept:
algo: ESH24: the final settlement could not be read from the data adapter: <error>; a position held to its expiry settles at the last settlement or close (GLE-481)A request that finds nothing usable (no record dated the expiration’s UTC date) is silent at run start; the pass labels the fallback.
Whether nothing could be asked or nothing was found, the pass treats the contract alike: a position without a final settlement settles at the last served settlement, else the last close, and the fallback shows in three places: the record’s settle_source (settlement or close), the operator line’s tail (“the statistics stream carried no final settlement” or “the feed carried no settlement price”) and the report’s expiry_fallbacks=F, the positions settled at expiry without the final settlement.
What the strategy hears. Each cancel reaches it as an OnCancel whose Reason is CancelReasonContractExpired, and its working view retires the attempt as for any cancel (The working view under lifetime v2). The settlement reaches it as an OnFill with no ClientID: an OnFill with no identity is the venue’s settlement of the position. The SDK applies it to ctx.Position as it applies every fill (the quantity, the realized P&L against the average cost, the average cost and OpenedAt cleared when flat), the attempt-indexed working view ignores a fill it cannot attribute, and the v1 map has no entry under the empty label, so a strategy indexing its fills by ClientID sees the empty key once and nothing else moves. The SDK is unchanged by this unit. A held attempt’s refusal (below) follows the cancels, and a submission the strategy makes on the expired contract afterwards is denied as above.
Held attempts. An attempt the race guard holds on the contract (admitted but not sent, waiting behind a pending cancellation; The engine race guard) is not at the venue, so the cancel does not reach it, and released it would go onto a contract that no longer trades. It is refused instead, after the working orders’ cancels: an OrderUpdate with status Denied and the reason hold_contract_expired: the contract <symbol> expired while order "<client id>" attempt <n> (<side> <symbol>) was held, stamped at the simulation clock, its children ended with it, the guard’s own denial line on stderr, and no turn granted. Holds on other symbols stay held, in their order. The guard’s position of the contract follows the closing fill, which it observes as it observes every fill, so a position cap reads the settled position.
The pass refuses by book: every attempt held on the book the contract maps to, which on a continuous run is the series’ logical symbol, and the text names that book (on a lone rank hold_contract_expired: the contract fut:XCME:ES expired while ...); on a continuous run it takes the contract’s own book, then each holding rank’s. Where order-taking ranks share the contract’s chain (Contract curves, GLE-484) those books name frames by chain order and by residue, not by the contract, and the pass refused a holder’s attempt on its own logical symbol, bound for its active contract, under a text naming the wrong contract. Since GLE-491 (2026-10-11) the pass there refuses only the attempts pinned to the expiring contract, the ones whose order names it, whatever book each was admitted on, with the contract named: hold_contract_expired: the contract ESM26 expired while order "b1-held" attempt 1 (buy fut:XCME:ES:cont:ofs=B1) was held; a holder’s attempt on its own logical symbol stays held, in its order. On a lone rank and on a plain contract the pass refuses by book exactly as before (the by-book refusal of a lone rank’s logical held attempts at a late roll, bound for the incoming contract, is recorded as a candidate for the same by-pin treatment; nothing is filed). At a late roll the expiry’s refusals come before the roll’s own pass over the held attempts, so an attempt both would refuse is hold_contract_expired (Order lifetime v2 across a roll).
The coincidence order. When a GTC quarter-end, a contract expiry and a roll fall together they go in that order, as I15 unit 2b froze: the venue’s quarter-end pass, then the expiry, then the roll (Order lifetime v2 across a roll). On the plain path, when an expiry is due before a bar or a timer, the pass itself runs the venue’s GTC deadline pass first (Simulator.ExpireGTC at the bar’s trade date, the raw bar’s session date when it carries one, else the economic date of the bar’s close or of the timer’s instant) and delivers its cancels, so an order due under both reasons is GTC_EXPIRED and is not counted among the expiry’s cancels; the simulator’s own pre-walk GTC pass then finds the date swept. On that one bar the deadline is resolved at the date rather than inside a path-walked bar’s constituents, with no coarse count, a deviation of one bar per contract. Since I13b (GLE-468) the pre-sweep begins with the calendar sweep, Simulator.ExpireCalendar at the bar’s close or the timer’s instant, exclusive: every order whose calendar instant (a Day order’s session close, a GTC order’s quarter close) precedes it is cancelled with its own reason, stamped at the instant, ahead of the trade-date pass and of the contract’s end, while a bar closing at an instant is still walked in full, so an order whose instant is at or after the bar’s close when the contract expired before it is CONTRACT_EXPIRED (Calendar cancellation instants (lifetime v2)). At a roll the roll’s own calendar sweep and GTC pass precede the expiry; at the run’s end the deferred outcomes and the calendar sweep at the run’s end precede the pass, and the shutdown sweep follows.
Continuous runs. A contract a continuous series holds is left to its roll: the served schedule rolls before expiry (GLE-274), and the roll owns the contract’s end, so the pass does not fire the series’ contract at a bar. It expires in two cases only, each a schedule anomaly reported as such:
- A late roll, whose cut comes strictly after the outgoing contract’s expiration. The expiry fires in the roll’s frozen slot, after the roll’s GTC pass and before it reads the book: the outgoing contract’s working orders, the logical ones translated onto it included, are cancelled
contract_expiredand listed in the roll account’sexpired; the position is cash-settled by a fill the strategy hears on the logical symbol; and the roll then finds a flat book and re-places nothing. The strategy re-places the orders itself if it wants them, after the roll’s notice. - The run’s end, when the expired contract is still the series’ active contract. It fires there as a plain contract does, with the series named.
A contract the series rolled out of in time is left alone, at a bar and at the end. The outcome is the venue’s (the venue settled the position; the roll cannot carry it) and the diagnostic is loud: the operator line says the schedule rolled late or the contract was not rolled, the trace’s expiry record carries the series and late: true, and the report’s simulator: line gains expiry_unrolled=N. A cut exactly at the expiration is in time.
Diagnostics.
One stderr line per expiring contract, even a flat one with nothing working (the contract can no longer be traded), after its events are delivered, counting the orders cancelled with the reason (their
PARENT_CANCELLEDchildren are not counted) and saying what became of the position: none, closed at the final settlement, closed at the last served settlement, or closed at the last close:algo: contract expiry: ESH26 expired at 2026-03-20T13:30:00.000000000Z: cancelled 4 working order(s) of instance demo; position +2 closed at the final settlement price 5101.67 (order lifetime v2; reason contract_expired)with
position +2 closed at the last settlement price 5153.75 (the statistics stream carried no final settlement)when the statistics stream gave no final settlement and a bar’s settlement was served,position +2 closed at the last close 5116.25 (the feed carried no settlement price)when neither was, andno positionwhen flat. A continuous series’ late expiry names the series and says why it is late:algo: continuous: ESH26, a contract of fut:XCME:ES, expired at 2026-03-20T13:30:00.000000000Z before its roll at 2026-03-23T21:00:00.000000000Z (the schedule rolled late): cancelled 2 working order(s) of instance demo; position +1 closed at the last close 5116.25 (the feed carried no settlement price) (order lifetime v2; reason contract_expired) algo: continuous: ESM26, a contract of fut:XCME:ES, expired at 2026-06-19T13:30:00.000000000Z and was not rolled before the run's end: cancelled 1 working order(s) of instance demo; no position (order lifetime v2; reason contract_expired)The lifecycle trace records an
expiryrecord ahead of the expiry’s cancels and closing fill (the contract, the series, the position settled, the price and its source, the client ids cancelled and whether it came late), labels each cancelcontract_expiredand counts it among theunsolicited_cancels, and writescontract_expiriesin the summary when it is not zero (The lifecycle trace schema).The report’s
simulator:line gainscontract_expiries=N contract_expiry_cancels=M(Summary.ContractExpiriesandSummary.ContractExpiryCancels) when N is above zero,expiry_unrolled=Uwhen U is, and, since GLE-481,expiry_fallbacks=Fwhen F is (the positions settled at expiry without the exchange’s final settlement, at the last served settlement or the last close), so every other run’s line is unchanged.At run start, the final-settlement fetch’s two lines (Errors and fallbacks above): the wire notice, once, and one line per contract whose request failed.
A refused held attempt prints the guard’s denial line,
algo: order "<client id>" (<symbol>) from instance <label> denied: hold_contract_expired: ....
The reason on each wire. CANCEL_REASON_CONTRACT_EXPIRED is 10 in the proto’s CancelReason (Protocol reference), the value I15 unit 2a reserved for it, and the SDK’s CancelReasonContractExpired. stdio-csv-v2 writes it cancelled REASON contract_expired (The v2 line catalogue), the stdio-csv-v1 cancel line has the same token, though only a lifetime-v2 run produces the reason and such a run does not speak v1, and the lifecycle trace labels it contract_expired too. A reader built before the value receives it as the number 10.
Known limits.
- The final settlement is looked for once, at run start, within seven days of the expiration’s UTC date; a restatement published later is not seen, and nothing is fetched at the pass (the adapter is shut down before the loop). A product whose last-trade instant crossed midnight UTC would find no record dated its trade date and fall back, labelled; no CME product does.
- The final settlement travels on the pb data wire only: an adapter negotiating DBN or CSV (under the default
autoa v2 run holding a dated contract prefers pb, so that is a forced--data-protocol dbnorcsv, or an adapter that offers no pb), or one without theSTATISTICSschema, leaves every expiry at the last served settlement or the last close, labelled. - The expiry is bar-granular: a bar straddling the expiration is cut off before it, and the lost pre-expiry window is not counted. I13b (GLE-468) moved the Day and GTC cancellations to their calendar instants and left the expiry at the bar.
- Every expiry is modelled as a cash settlement at the price above; a physically delivered contract is settled the same way.
- The ledger’s position-event line for an expiry and the execution fold’s replay of it (the live path’s recovery, which no backtest opens a ledger for), how IBKR treats resting orders near the last trading time and how an expiry appears on its trades endpoint (unknown; its Web API reference is silent) are the rest of I14 unit 2 (GLE-456).
Tests. engine/sim/aa00_cx14_tournament_spec_test.go (5 tests) pins the venue facts (the sorted list, the lookups, the last settlement following only the bars that carry one, every method on a nil simulator) and ExpireContract’s walk, children and OCO members, stamp, closing fill (side, quantity, price, zero commission, empty identity, the cash and realized P&L, the blotter and the observer), counters, idempotence, denial text, a short, a flat contract and a non-finite settle. engine/aa00_cx14_tournament_spec_test.go (20) drives runBarLoop: the cancels and the close before the first bar after the expiration with and without a served settlement, the trace record and the report, the operator lines verbatim, the race guard’s position and refused holds, the run’s end, the GTC-then-expiry order and a GTC delivery error, two contracts due at one instant, the timer hook, the late roll, the in-time roll left alone and the contract unrolled at the run’s end, and the same runs on v1 unchanged. internal/wire/aa00_cx14_tournament_spec_test.go pins the token on both CSV grammars and sdk/strategy/aa00_cx14_tournament_spec_test.go the SDK’s tolerance of the identity-less fill on both profiles. The review panel’s regression tests, in engine/cx14_panel_test.go and engine/sim/cx14_panel_test.go, pin the mark ahead of the callbacks, the refused position of no magnitude, the trade date built only when an expiry is due and the head over the queue’s terminal entries; its gap tests, in engine/cx14_review_test.go and engine/sim/cx14_review_test.go, the expirations loaded through the adapter on v2 and nothing asked on v1, a settlement charging no commission, a present zero settlement, an expiration before the run’s start with a seeded position, a delivery failure stopping the pass, a second continuous frame owning the expiring contract, and the signed cash of a short covered and a long settled at a negative price. GLE-481’s spec tests, engine/sim/aa00_fs81_tournament_spec_test.go (1 test) and engine/aa00_fs81_tournament_spec_test.go (7), pin FinalSettle (present, 0 included, absent, a nil map, a nil simulator, independent of the bars observed); the selection over the ES H24, ZC H24 and CL G24 records of the archive with their republished prior-day settlements, an expiration in another zone, a prior-day record republished after the final, a next-day record, revisions in either order, a tie resolved by wire order, and every ignored record; the fetch with a fake client (one request per due contract in venue order, the feed symbol, the one kind, the window and the batch size, the end inclusive, a zero end, each absence and error with its line or its silence, a failed request’s records contributing nothing); the precedence and the line’s tails; the plain v2 run closing at 5101.67 ahead of the bar’s settlement and the last close, with the record, the line, no fallback counted and the realized P&L, the two fallbacks with their count, another contract’s final settlement not applying, and v1 unchanged; and, end to end through a fixture adapter serving the statistics schema and a holder strategy process, a contract held to its expiry settling at 5101.67 by one statistics request, v1 making none, and a run whose statistics carry no final settlement settling at the last close with expiry_fallbacks=1 and no warning.