Market events
Bars summarise the tape; sometimes a strategy wants the prints themselves. Declare a TRADES series and the engine delivers every trade of that instrument to the strategy between bars (GLE-389):
func (s *TapeReader) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "tape", Symbol: s.symbol, Lookback: s.Lookback,
Schema: algolang.DataSchemaSpec{Kind: algolang.Trades},
}}
}Each trade arrives as an algolang.MarketTrade:
| Field | Meaning |
|---|---|
SeriesID | the declared series’ id (its Symbol when the declaration gave none) |
Symbol, Price, Size | the instrument, price and size of the print |
Aggressor | AggressorBuy when the buyer lifted the offer, AggressorSell when the seller hit the bid, AggressorNone when the feed does not say |
TsEvent | the matching engine’s instant |
TsRecv | when the data provider received the trade: the instant it became visible |
BadTsRecv | the provider flags TsRecv as unreliable |
Read them two ways:
ctx.MarketTrades("tape")returns the newestLookbacktrades of the series, oldest first, as a copy you own. A declaration without aLookbackkeeps one trade. Each call copies the whole buffer, so sizeLookbackto what you read, or accumulate inOnMarketTradeinstead.- The optional
MarketTradeHandlerinterface,OnMarketTrade(ctx, t), is called once per trade in replay order, after the trade has joined the buffer and withctx.Now()at itsTsRecv. It is observe-only: it returns nothing, and orders still come only fromOnBar.
Visibility. A trade becomes visible at its TsRecv. Before each bar the engine sends every trade received strictly before that bar’s close that it has not sent yet. A trade received at exactly a close is sent before the next bar, the same rule as a release stamped at a bar’s close: the bar [open, close) does not contain its close instant. So in OnBar the trades since the previous decision are those with prevClose <= TsRecv < bar.CloseTime. Several declared series merge into one replay: ascending TsRecv, ties in declaration order, then in the adapter’s order within a series.
Limits.
- Declared trades are backtest-only; a live run refuses them.
- The adapter must serve the TRADES schema. The Databento adapter does. marketfeed advertises TRADES for dated futures contracts, but the current archive holds no trade tapes (its futures are 1s/1m/1h/1d bars), so a declared tape there is refused with “no trades coverage”.
- The strategy must speak the protobuf wire, which every declaring strategy does already.
- The engine fetches each tape over the bar loop’s window, from the first bar’s open to the last bar’s close. There is no trade warm-up before the first bar, and the whole tape is held in memory for the run.
- A trade series’ id must not be a bar series’ id. A declaration with no
SeriesIDtakes its symbol, which is the id of that symbol’s configured bar series, so give the tape its own id.
Example. strategies/demo/go/tapereader reads the MSFT tape between one-minute bar closes. At each close it counts the trades since the previous close and splits their size by aggressor. With at least MinTrades trades and a net aggressor share (buy - sell) / (buy + sell) of at least Imbalance it wants a long of Qty shares, at most -Imbalance a short, and otherwise keeps what it holds. It reads its position from the engine and sends one market order for the difference. Since the order-lifetime programme’s I21 (GLE-467) it declares optional lifetime-v2 support, and cf21_conform_test.go beside it runs it under both profiles over the bundled sample through the Databento adapter, the declared tape included, seven fills equal under each (Conformance under both lifetimes).
$ make run-tapereader
[tapereader] INFO: tapereader: first trade tape MSFT price=265.76 size=14 recv=2022-06-10T12:30:01.100858345Z
[tapereader] INFO: tapereader: 2022-06-10T12:31:00Z trades=146 buy=260 sell=622 pos=0 target=-100
[tapereader] INFO: tapereader: 2022-06-10T12:32:00Z trades=68 buy=114 sell=417 pos=-100 target=-100
[tapereader] INFO: tapereader: 2022-06-10T12:33:00Z trades=70 buy=972 sell=1997 pos=-100 target=-100
[tapereader] INFO: tapereader: 2022-06-10T12:34:00Z trades=89 buy=1126 sell=211 pos=-100 target=100
...
[tapereader] INFO: tapereader: 2022-06-10T12:53:00Z trades=5 buy=0 sell=3 pos=-100 target=-100
bars: 23 main after replicate (+ 0 warmup), 23 loop, 7 ordersThe 23 windows hold all 1,000 trades of the sample. Trades with no aggressor (N) count in a window’s trades but in neither side, so buy + sell can be well below the window’s volume.
Statistics and definitions as events
A futures strategy can declare two more market-event kinds the same way (GLE-406): a contract’s venue statistics (Kind: algolang.Statistics: settlement price, open interest, cleared volume) and its point-in-time definitions (Kind: algolang.InstrumentDefinition: expiration, tick, maturity). They need an adapter that serves the schemas; marketfeed does (see Statistics and instrument definitions).
func (s *OIConfirm) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{
{SeriesID: "stats", Symbol: s.symbol, Lookback: 400, Schema: algolang.DataSchemaSpec{Kind: algolang.Statistics}},
{SeriesID: "defs", Symbol: s.symbol, Lookback: 1, Schema: algolang.DataSchemaSpec{Kind: algolang.InstrumentDefinition}},
}
}When they are visible. A statistic becomes visible when it was published: its TsRecv, else its TsEvent, else its TsRef (MarketStatistic.VisibleAt). A definition becomes visible at its TsEvent. Both then follow the trade rule: an event is sent before the first bar whose close is strictly after its visibility instant. A settlement for Monday’s session, published Monday evening, is therefore first seen by the bar that closes after it, never by an earlier one. The engine sorts each statistics series by visibility instant, because adapters serve statistics in trading-date order, not publication order. It fetches statistics from 10 days before the run’s first bar and definitions from 1 day before, so the latest settlement, open interest and definition are already known at the first bar.
Reading them.
| Call | Returns |
|---|---|
ctx.MarketStatistics("stats") | the newest Lookback statistics delivered, oldest first, as a copy |
ctx.LatestStatistic("stats", sym, algolang.StatSettlementPrice) | the latest of a contract and kind |
ctx.Definition("defs", sym) | the definition in force for a contract |
ctx.Definitions("defs") | every contract’s definition in force, sorted by symbol |
OnStatistic(ctx, s) / OnDefinition(ctx, d) | optional observers, once per event, with ctx.Now() at its visibility instant |
A statistic is revised: one contract, kind and trading date can have several records published at different times, such as a preliminary and a final settlement, or an open interest restated the next morning. Each revision arrives as its own MarketStatistic. “Latest” means the record with the greatest trading date (TsRef), and among records for the same date, the last one delivered. A late correction of an older date never displaces a newer date’s value, and a deleted record (Deleted) never becomes the latest. A statistic the venue did not date (CME before 2015) has a zero TsRef, so its visibility instant stands in for its date. Venues resend definitions daily, and the definition in force is the last one delivered.
strategies/kit has pure helpers over ctx.MarketStatistics. OpenInterestChange gives the open-interest change between a contract’s two most recent trading dates, taking the latest revision of each date. SettlementGap gives a price minus the latest settlement. DaysToExpiry gives the days left before a definition’s expiration.
Example. strategies/demo/go/oiconfirm trades a dated ES contract’s daily bars:
- It buys a close above the previous
Breakouthighs when open interest rose into the bar. - It exits when the close falls
StopPointsbelow the latest settlement. - It flattens
ExitDaysbefore the contract’s expiration, which it reads from the definition in force.
Since the order-lifetime programme’s I21 (GLE-467) it declares optional lifetime-v2 support, and golden_test.go beside it runs it under both profiles over the archive window of make run-oiconfirm through the marketfeed adapter (make test-golden), the fills equal under each (Conformance under both lifetimes).
$ make run-oiconfirm
[oiconfirm] INFO: oiconfirm: 2025-11-17T06:00:00Z close=6843.25 breakout=false oi_change=2360 oi_ok=true settle_gap=27.75 gap_ok=true days_left=123.3 pos=0 target=0
...
[oiconfirm] INFO: oiconfirm: 2025-11-27T06:00:00Z close=6891.00 breakout=true oi_change=118 oi_ok=true settle_gap=4.75 gap_ok=true days_left=113.3 pos=0 target=1
...
[oiconfirm] INFO: oiconfirm: 2026-01-19T06:00:00Z close=6916.75 breakout=false oi_change=27426 oi_ok=true settle_gap=-60.00 gap_ok=true days_left=60.3 pos=1 target=0
...
[oiconfirm] INFO: oiconfirm: 2026-01-28T06:00:00Z close=7031.75 breakout=true oi_change=2147 oi_ok=true settle_gap=23.25 gap_ok=true days_left=51.3 pos=0 target=1
...
[oiconfirm] INFO: oiconfirm: 2026-02-02T06:00:00Z close=6880.75 breakout=false oi_change=4794 oi_ok=true settle_gap=-85.00 gap_ok=true days_left=46.3 pos=1 target=0
...
[oiconfirm] INFO: oiconfirm: 2026-02-26T06:00:00Z close=6947.00 breakout=true oi_change=34082 oi_ok=true settle_gap=-12.75 gap_ok=true days_left=22.3 pos=0 target=1
...
[oiconfirm] INFO: oiconfirm: 2026-03-02T06:00:00Z close=6815.25 breakout=false oi_change=-29402 oi_ok=true settle_gap=-73.75 gap_ok=true days_left=18.3 pos=1 target=0
...
bars: 101 main after replicate (+ 9 warmup), 101 loop, 6 orders
6 fills, commission 0.00, realized PnL -12725.00The pre-roll shows on the first bar: open interest, the settlement gap and the days to expiry are all known before the window’s first close. The daily bars close at Chicago midnight, after the session settles (CME publishes the settlement at about 15:00 Chicago time), so the latest settlement a weekday bar sees is its own day’s. With Breakout=10 the window has seven breakouts; three came while flat with open interest rising, and all three positions left on the settlement-anchored exit (in January, February and March, 60.00, 85.00 and 73.75 points below the latest settlement), before the expiry exit could arm. The example illustrates the API, not an edge.
Declared statistics and definitions are backtest-only and refused on a continuous run, like declared trades.
Observations as events
A strategy can declare a release-stamped series’ revisions as a market-event series (GLE-408): Kind: algolang.Observations on a macro:FRED:<ID> symbol. Every published value of every reference period is then an event: the first release and each later revision, withdrawals included. It needs an adapter that serves OBSERVATIONS. Marketfeed does for its alfred-kind FRED series, and so does the file-csv adapter from a vintages file (Revisions: the OBSERVATIONS schema).
func (s *GDPRevision) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{
{SeriesID: "gdp", Symbol: "macro:FRED:GDP", Lookback: 8, Schema: algolang.DataSchemaSpec{Kind: algolang.Observations}},
}
}When they are visible. An observation becomes visible at its AvailableAt, the instant it was published, and follows the trade rule: it is sent before the first bar whose close is strictly after that instant. The engine fetches the series’ whole revision history up to the run’s end, so everything published before the first bar arrives before it, and the strategy’s view of each period is exact from its first decision. A series’ vintages are few (GDP’s whole history is about 3,300 records).
Reading them.
| Call | Returns |
|---|---|
ctx.MarketObservations("gdp") | the newest Lookback observations delivered, oldest first, as a copy |
ctx.Observations("gdp") | an ObservationHistory: every observation delivered so far, as an immutable view |
h.AsKnownAt(t) | the series as known at t: each period’s last observation available at or before t, by period, withdrawals included |
h.ValueAt(ref, t) | a period’s value as known at t; false when unknown or withdrawn |
h.Latest(ref), h.Revisions(ref), h.Refs() | a period’s newest observation, all of its observations, the periods |
OnObservation(ctx, o) | an optional observer, once per observation, with ctx.Now() at its AvailableAt |
A view never changes: an observation delivered later is in the next view ctx.Observations returns, not in the one a strategy already holds. algolang.NewObservationHistory builds one from a slice, for a strategy’s own tests.
strategies/kit has pure helpers over a history: - ObsLatestKnown(h, t): the latest period whose value is known at t. A withdrawn latest period falls back to the one before it. - ObsKnownBefore(h, closes): the same for each of a list of bar closes, counting only observations strictly before each close, the engine’s delivery rule. Pairing class: as-of (carried forward). - ObsRevisionSurprise(h, ref, t): how much the latest revision moved a period’s estimate. - ObsGrowth(h, p, ref, k, t): a period’s growth over the period k before it, both as known at t, so both come from the same vintage.
The helpers read the whole history on each call. A macro series is small, but ANFCI’s history is a million observations, so on fine bars compute a signal when the history grows (ctx.Observations(id).Len() changes) rather than on every bar. At a bar every delivered observation is already public, so nothing else changes the answer; the example does this.
Example. strategies/demo/go/gdprevision trades a dated ES contract’s daily bars. At each close it takes the latest quarter whose GDP is known and that quarter’s annualised growth over the one before, both as they stood in one vintage. It is long while the growth is at or above Threshold percent, and flat otherwise. Since the order-lifetime programme’s I21 (GLE-467) it declares optional lifetime-v2 support, and cf21_conform_test.go beside it runs it under both profiles over the GLE-408 fixture’s bars and vintages at a threshold the vintages cross four times, two round trips equal under each (Conformance under both lifetimes).
$ make run-gdprevision
[gdprevision] INFO: gdprevision: 2025-06-02T05:00:00Z close=5992.50 ref=2025-01-01 rev=1 gdp=29976.638 growth_pct=3.4453 ok=true surprise=-0.994 surprise_ok=true known=3206 pos=0 target=0
...
[gdprevision] INFO: gdprevision: 2025-07-31T05:00:00Z close=6513.50 ref=2025-04-01 rev=0 gdp=30331.117 growth_pct=5.0190 ok=true surprise=0.000 surprise_ok=false known=3208 pos=0 target=0
...
[gdprevision] INFO: gdprevision: 2025-08-29T05:00:00Z close=6565.75 ref=2025-04-01 rev=1 gdp=30353.902 growth_pct=5.3349 ok=true surprise=22.785 surprise_ok=true known=3209 pos=0 target=0
...
[gdprevision] INFO: gdprevision: 2025-09-26T05:00:00Z close=6653.75 ref=2025-04-01 rev=2 gdp=30485.729 growth_pct=6.0387 ok=true surprise=131.827 surprise_ok=true known=3231 pos=0 target=1
...
bars: 171 main after replicate (+ 0 warmup), 171 loop, 1 orders
1 fills, commission 0.00, realized PnL 0.00What the run shows: - The first bar. GDP’s whole history (3,206 observations) is known: the first quarter of 2025 at its second estimate. - Revisions. The third estimate (26 June), the second quarter’s advance estimate (30 July) and its second estimate (28 August) each move the signal from the next close. - The annual update. The 2025 annual update, published at 08:30 New York on 25 September, revised 22 quarters at one instant, and all 22 arrive before the next close (known goes from 3,209 to 3,231). It lifts the second quarter’s annualised growth from 5.33% to 6.04%, over the 5.5% threshold, and the strategy goes long on that close. - Against first releases. A first-release series (the BARS read of macro:FRED:GDP) keeps the quarter at its advance estimate of 5.02%, so the same rule would never trade.
The example illustrates the API, not an edge.
Declared observations are backtest-only and refused on a continuous run, like declared trades.
Contract listings as events
A futures root’s contract listing is a market-event series too (GLE-410): Kind: algolang.ContractListing on a bare root such as fut:XCME:ES. Each record is a contract of the root, delivered at its known_at and again when a daily listing restates it, and ctx.Curve(root) reads the contracts listed now. Unlike the other kinds, it is served on a continuous run. See The listed curve.