Aligning series
nseries works on plain []float64 vectors. It has no timestamps, and its two-series methods pair values from the newest end (GLE-253). A strategy that combines series therefore has to put them on one clock before it calls nseries: a 1h primary with a FRED series, 1h with a declared 1d, or two 1h futures legs. This section sets out the rules and the strategies/kit helpers that apply them. The worked examples at the end assume a 1h primary.
The clock and the “as known at” rule
The engine merges every series of a run into one stream ordered by close time, and every bar, primary or declared, calls OnBar (Backtest event ordering). That gives one rule for every series: a decision at time t may use a value only if its bar closed at or before t (CloseTime <= t; GLE-221 specification §3.15, rules 1-5). ctx.Series(id).Close(0) already follows it: on any bar it is that series’ newest value closed by now, the value as known at the decision. kit.AsOfClose(series, cutoff) applies the same rule at an earlier cutoff.
Bars that close at the same instant follow the co-close order: other price series first, then the primary, then releases (cot:, macro:, fx:RBA:). On the primary’s bar a co-closing price leg is already current, so a spread never pairs this hour’s primary with last hour’s leg. A release stamped at the same instant is not yet visible: it is first seen at the next primary bar, because a release stamped at a bar’s close came after that close’s price.
Fresh() is true when a series’ newest bar closed at the current instant, on every OnBar call at that instant: when several bars close together, a co-closing series stays fresh through all of their calls. To act once per new value, test the delivered bar (bar.SeriesID == "cpi"), or remember the close time you last acted on, as cpigate does below. A series that is not fresh still has a value; measure how old it is with kit.AgeAt.
Each buffer counts its own bars. ctx.Series("d1").Close(3) is three daily bars back; Close(3) on a 1h primary is three bars back, which is more than three hours of clock when bars are missing. Never index one series by another series’ position.
Three patterns
| Pattern | What it does | Use it for | kit |
|---|---|---|---|
| Per leg | Compute each series on its own clock, then combine the results at the decision | indicators on each leg: a daily trend, an hourly RSI | none: run nseries on ctx.Series(id).Closes() |
| Stretch slow onto fast | Carry the slow series’ latest value onto each primary close | levels and gates | AsOfCloses(aux, prim, n), AsOfClose; declared once, as an aligned series |
| Sample fast on the slow clock | Record the primary’s last close at or before each release | correlations and regressions against a release series | ReleaseClock |
Stretching repeats each slow value across many fast bars. Do not compute paired-window statistics (correlation, beta, regression) on stretched values: the repeats bias them towards zero (the Epps effect). Sample on the slow clock instead. Each kit helper’s doc comment names its pairing class: as-of (carried forward), same-clock (exact close-time match) or release clock (event-sampled).
A ReleaseClock records one pair per release. Call Observe(aux, prim) at the end of every OnBar, for every series, so a primary bar closing at exactly a release instant is paired with it whichever of the two the engine delivers first. Series() returns the recorded release values and primary closes, oldest first, ready for Correlation or a regression on their changes.
Aligned series: one row per grid bar
The kit helpers above rebuild their windows on every call, from whatever each buffer still holds. A strategy that wants all its series on one clock, so that row i of every series is the same bar, declares aligned series instead (GLE-353). An aligned series is a view the SDK maintains bar by bar: at every bar of a grid series (usually the primary, the finest series of the run) it appends one sample carrying the newest value of a source series known at that bar’s close. Between two source bars the value is repeated, so a weekly series lined up on a daily grid repeats each report on every day until the next one. The view is the declared form of “stretch slow onto fast”.
Take a strategy that trades daily ES and reads the weekly COT report and quarterly GDP. It declares the two release series as usual, then one view for each:
func (s *Panel) Lookback() int { return 21 } // the primary, and so each view on it, buffers 21 bars
func (s *Panel) DataRequirements() []algolang.DataRequirement {
weekly := algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1w"}
return []algolang.DataRequirement{
{SeriesID: "cot", Symbol: "cot:CFTC:13874A:LF", Lookback: 52, Schema: weekly},
{SeriesID: "gdp", Symbol: "macro:FRED:GDP", Lookback: 2, Schema: weekly},
}
}
func (s *Panel) AlignedSeries() []algolang.AlignedSeries {
return []algolang.AlignedSeries{
{SeriesID: "cot_d", Source: "cot"}, // Grid "" is the primary
{SeriesID: "gdp_d", Source: "gdp"},
}
}On every daily bar, ctx.Series("cot_d").Bar(i), ctx.Series("gdp_d").Bar(i) and the primary’s Bar(i) describe the same day, from the newest end:
prim, cotD, gdpD := ctx.Series(ctx.PrimarySymbol()), ctx.Series("cot_d"), ctx.Series("gdp_d")
n := min(prim.Len(), cotD.Len(), gdpD.Len())
for i := range n { // newest row first
ctx.Logf("%s ES=%g COT=%g (published %s) GDP=%g", prim.Bar(i).CloseTime.Format(time.DateOnly),
prim.Close(i), cotD.Close(i), cotD.Bar(i).SourceCloseTime.Format(time.DateOnly), gdpD.Close(i))
}strategies/demo/go/alignpanel is the complete example; see Worked examples.
Declaring a view
SeriesAligner is an optional interface, probed like DataRequirer. Each AlignedSeries has three fields:
| Field | Meaning |
|---|---|
SeriesID | The view’s id: read it with ctx.Series(SeriesID). It must differ from every series id in the run and from the other views. |
Source | The canonical id (SeriesID, else symbol) of the series whose values the view carries: a configured or declared series of any kind, price or release. |
Grid | The canonical id of the clock series. "" means the primary. |
Views are built in the strategy process. The engine never sees a sample: it validates each declaration, fetches the source’s history far enough back to fill the view’s warm-up (below), and otherwise delivers bars exactly as before. The source and the grid still call OnBar for each of their own bars; a view calls nothing. With no SeriesAligner a run is byte-identical to a run before this feature.
What a sample holds
At each grid bar the view appends the newest source bar that is visible at the grid bar’s close:
- a source bar that closed before the grid bar is visible;
- one that closed at the same instant is visible, unless the source is a release (
cot:,macro:,fx:RBA:) and the grid is a price series.
| Source bar closing at the grid close | Grid is a price series | Grid is a release series |
|---|---|---|
| a price bar | visible | visible |
| a release | not visible: carried from the next grid bar | visible |
Two price bars that close together describe trading up to the same instant, so a daily bar closing at the same midnight as an hourly grid bar is in that hour’s sample. A release stamped at exactly a price bar’s close was published after that close’s price, which is GLE-259’s tie rule: it is first carried by the next grid bar. These are the rules the co-close order already applies to ctx.Series(id).Close(0) on the primary’s bar (The clock and the “as known at” rule); a view applies them to every grid, not just the primary, and whatever order the engine delivers co-closing bars in.
The ticket’s example: weekly bars that close at 17:00 New York on Friday, lined up on daily bars that close at 16:00. Friday’s daily bar closes an hour before this week’s weekly bar, so every day of the week carries last week’s:
daily close, 16:00 New York Mon Tue Wed Thu Fri | Mon Tue ...
weekly bar W closes 17:00 Fri
sample carries W-1 W-1 W-1 W-1 W-1 | W W ...
Updates 1 0 0 0 0 | 1 0 ...A sample is a copy of the source bar with the grid bar’s times:
| Field | On a sample |
|---|---|
OpenTime, CloseTime | the grid bar’s, so the view lines up index for index with its grid and Fresh() follows the grid’s clock |
Open, High, Low, Close, Volume | the source bar’s (a completed bar: never a developing one) |
Symbol | the source’s symbol |
SeriesID | the view’s id |
Ref, Session, raw prices, CumulativeAdjustment, CumulativePriceRatio, ActiveContract, seam fields | the source bar’s |
SourceOpenTime, SourceCloseTime | the source bar’s own times. SourceCloseTime is when its value became known: its release stamp, or a price bar’s close |
Updates | how many source bars became visible since the view’s previous sample: 0 the value is carried forward, 1 a new value, 2 or more a catch-up whose intermediate values the view does not show. The view’s first sample has 1 |
Path | nil |
The three provenance fields are zero on every bar that is not a sample.
Reading a view
Len(),Bar(i),Close(i)and the bulk views (Closes()and so on) work as on any series; index 0 is the current grid bar.- New value or repeat:
Bar(0).Updates > 0means the current grid bar carries a source bar the previous one did not.Fresh()cannot tell you: it compares the sample’sCloseTime, the grid’s, with now, so a view is fresh at every grid close. - Age of the information:
ctx.Now().Sub(view.Bar(0).SourceCloseTime).kit.AgeAt,kit.StaleLegsandkit.StaleSeriesuseSourceCloseTimewhen it is set, sokit.StaleSeries(ctx, 10*24*time.Hour, "cot_d")reports a COT report more than ten days old, not a daily bar. - Grid-clocked helpers:
kit.AsOfCloses,kit.JoinCloses,kit.Cadence,kit.CompareLegsandkit.AllFreshreadCloseTime, so on a view they see the grid’s clock. - Periods:
Refpasses through, soview.Bar(0).Refnames the period of the value carried (the COT as-of date, the FRED observation date). Period arithmetic (kit.PeriodsAgo,kit.RefValue) belongs on the source’s own release series, where each period has one bar.
How long a view is
A view buffers as many samples as its grid buffers bars: the grid’s declared Lookback when a requirement names it, else the global Lookback(). To hold more samples, deepen the grid. The source’s own Lookback does not limit the view. The view holds what the grid actually holds: an epoch daily grid warms up Lookback calendar days, not trading days (only session daily series widen their window), so an ES grid with Lookback() = 21 starts the run with 19 bars (18 warm-up bars and the first decision; see the worked example) and its views with as many samples. They fill as the run goes on.
Warm-up. Before the first decision, the view is built from the grid’s warm-up bars, each with the newest source bar visible at it. The source’s own warm-up covers only its own depth (a declared COT series with Lookback: 2 warms up two reports), which may not reach back to the grid’s oldest warm-up bar. The engine therefore fetches the source’s older history itself, back to the newest bar visible at the grid’s oldest held bar, and sends those bars tagged with the view’s id: they reach only that view and never the source’s own buffer, so ctx.Series("cot") is unchanged by declaring a view on it. With enough history, every view holds its grid’s depth at the first decision.
When the source starts later. A grid bar with no visible source bar gets no sample. A view is therefore shorter than its grid until the source’s first bar: a FRED series that starts in 1990 lined up on a grid that starts in 1985 holds nothing for the first five years. Every grid bar from then on gets a sample, so the view stays right-aligned with its grid: view.Bar(i) and grid.Bar(i) are the same bar for every i < view.Len(). Guard reads with Len(). When the source’s archive starts after the grid’s oldest warm-up bar, the engine records an aligned_shortfall degradation naming the view (“cot_d: aligned series holds 80 of the 104 grid bars in its warm-up …”) in degradation.json, and the run’s data notes say aligned 80 of 104 grid bars under short warm-up; it never refuses the run.
Repeats, catch-ups and gaps
- A stall repeats the last value, with
SourceCloseTimeunchanged andUpdates == 0. In the 2025 shutdown the E-mini COT report published on 2025-09-26 (as of 2025-09-23) was the newest until 2025-11-19, when the report as of 2025-09-30 came out: a daily view repeats the 26 September report for 54 days, whichkit.StaleSerieson the view reports. - A catch-up of several releases between two grid bars (reports published together close a second apart) shows only the newest, with
Updatescounting them. The intermediate values are in the source’s own release view. - A missing grid bar (an hour with no trades: marketfeed never fills gaps) gets no sample. The grid is the clock: the view skips what the grid skips, and stays aligned with it.
- A missing source period has no bar to carry.
CPIAUCSLhas no October 2025, so a daily CPI view carries September 2025’s value until November’s release;Refsays which month the value describes. - Volume and other totals repeat with the value. Never sum a view’s volume across repeats.
When to use which view
A slow series declared once has two views: its own series (the release view: one bar per release, or per source bar) and any aligned view on it.
| Task | Use |
|---|---|
| A level or gate at the decision: the newest COT, the newest GDP | the aligned view’s Bar(0), or the release view’s Close(0) |
| A table of rows on the grid’s clock, state built bar by bar, printing a panel | the aligned view |
| How old the newest value is; whether this bar brought a new one | the aligned view’s SourceCloseTime and Updates |
| Statistics over the data’s own history: COT index, percentiles, z-scores, changes between reports | the release view |
| Anything keyed by period: year on year, quarter on quarter | the release view with kit.PeriodsAgo / kit.RefValue |
| Correlations and regressions against the slow series | kit.ReleaseClock, or a view whose grid is the release series (below) |
| Two same-interval legs with missing bars, for statistics | kit.JoinCloses |
Do not compute paired-window statistics, averages or volatilities on an aligned view of a slower series. Its repeats weight each value by how long it stayed current and bias correlations towards zero (the Epps effect): a 20-day average of a daily COT view is not an average of reports.
A faster source on a slower grid
A view can also line a faster series up on a slower one: a daily grid sampling an hourly source carries the last hourly bar at or before each daily close. That is the last bar, not an aggregate: its High is that hour’s high, not the day’s. For daily bars built from hourly ones use kit.Resample, or declare the daily interval.
With the grid set to a release series, a view records the primary’s last close at or before each release, which is the release clock as a view:
{SeriesID: "es_at_cpi", Source: "fut:XCME:ES:U26", Grid: "cpi"}Each sample holds the ES bar at or before one CPI release (an ES bar closing exactly at the release instant is included), and the view buffers as many samples as the CPI series buffers releases. ctx.Series("es_at_cpi").Closes() and ctx.Series("cpi").Closes() then pair release by release for ReturnCorrelation. Unlike kit.ReleaseClock, the view is full from the first decision (it is built from the warm-up) and needs no Observe call.
Within one instant
The SDK updates every view before it calls OnBar for the grid bar, so the grid bar’s own OnBar already sees that bar’s sample. When several bars close at the same instant, a co-closing source bar can be delivered after the grid bar; the view then revises its newest sample to carry it. This happens when the grid is a declared price series and the source is the primary (or a later series of the same class): at midnight the declared 1d grid bar is delivered before the primary’s hourly bar that also closes at midnight, and the daily sample is completed when the hourly bar arrives. Read views on the primary’s bar: by then every co-closing price bar has been delivered, so its samples are final for that instant. On the grid’s own OnBar, when the grid is not the primary, the newest sample can still change within the instant.
Where daily and weekly bars close
A sample is decided by close times, so the grid’s close times matter:
- Epoch daily bars (no session) close at the exchange’s local midnight (GLE-1344), so Friday’s ES bar closes at Saturday 00:00 Chicago time and carries a COT report published at 16:00 New York that Friday.
- Epoch weekly bars (
1wwith no session) run from Monday 00:00 to Monday 00:00 in the exchange’s zone. A Friday COT report lined up on them is first carried at the week’s close, the next Monday 00:00, and on ES that bar also holds Sunday evening’s trading. That is late, never look-ahead, but it is rarely what a strategy wants: use a session weekly grid, which closes at the end of the week’s last trading session, through a configured series with its ownsessionor a run with--session. - Session daily bars close at the session end, which can tie a 16:00 or 17:00 New York release stamp: a COT report stamped at 16:00 New York ties a 16:00 equity close and is carried from the next day; the five FRED series stamped 17:00 New York tie a 17:00 futures close the same way.
- Every stamp and close is an instant, so daylight-saving changes need no special handling.
Choosing the grid
""is the primary. When the primary’s series id is not its symbol (a multi-interval config derives ids such asfut:XCME:ES:U26@1h), the engine refuses""and names the id to write instead.- Any configured or declared series can be a grid, including a release series (one sample per release, above). A view cannot be a grid or a source.
- The finest series is the natural grid for a panel: on it, a source value is skipped only when two source bars fall between the same pair of grid bars, and
Updatesreports it. Declaring several views on one grid gives a panel whose rows all line up.
On a continuous run
Views work on a continuous run as on any other (GLE-394), in both directions:
- A continuous grid. On
fut:XCME:ESthe primary is the continuous series, andGrid: ""lines a view up with its bars. A daily continuous series reads trade-date session bars, which close at the session’s end (16:00 Chicago, 21:00 or 22:00 UTC), not at midnight. A COT report published at 20:00 UTC on a Friday is therefore carried by that Friday’s own session bar, where an epoch daily grid carries it from the bar closing at Saturday 00:00 Chicago time. The grid’s warm-up is the series’ own (Lookback and the Series API), so the views are as deep as it is from the first decision. - A continuous source. A view’s
Sourcecan be a continuous series, configured or declared:fut:XCME:NQknown at each ES close, say. A sample is a copy of the source bar as the strategy receives it inctx.Series(source): adjusted prices,RawPrice(the contract’s own price),ActiveContract,Sessionand the adjustment fields. - The frame of a continuous sample. Every continuous bar of a run is in one adjusted frame: the composite’s, anchored at the run’s end. That holds for the live bars, the warm-up, the source’s own series and every sample, so a view and its source agree value for value, and a roll after a sample re-adjusts nothing the strategy holds. The price known when the sample was taken is its raw price; the adjusted one is in the run’s frame, the frame every indicator on the series reads.
- On a run that rebases (the default since GLE-1502) the frame is the held contract’s instead: the warm-up, the source’s series and every sample are on the basis of the contract the series holds, and at each roll the view is rebuilt from the source’s rebased history, so a view and its source still agree value for value (Aligned views across a roll, GLE-1504).
- The reach-back. When the grid’s warm-up reaches past the source’s own warm-up, the engine reads the source’s composite again from earlier, pinned to the run’s snapshot token, generation and adjustment anchor. It keeps a wider read only if that reproduces the bars already held, adjusted and original alike. It never fetches the root as a plain series. When the feed cannot serve the older window, the view starts short and the run records an
aligned_shortfall, as on a plain run. - A declared continuous series by its id. Its bars carry the declared
SeriesID, as a declared plain series’ do. A view names it by that id (Source: "nq"),ctx.Series("nq")reads it, and its ownLookbacksizes its buffer.
Two continuous roots on one exchange can still close a second apart. ES and NQ daily session bars end at 21:59:59 or 22:00:00 UTC, set by each root’s last trade. On 40 of 430 ES decisions from January 2025 to August 2026, NQ’s session bar closed a second after ES’s, so the view carried the previous trade date’s NQ. That is exactly what was known at the ES close. When a decision wants both roots’ same session, check view.Bar(0).Session.TradeDate against bar.Session.TradeDate, or pair the bars by trade date as strategies/demo/go/esnqspread does.
Limits and refusals
The SDK refuses at Init: an empty SeriesID or Source; a SeriesID used twice, equal to a declared series id or to the primary; a Source equal to the grid; a view used as another view’s source or grid; Grid: "" with no primary. The engine refuses, before fetching anything for the view:
- an unknown source or grid id, and
Grid: ""on a derived primary id; - a source that is a corporate-action-adjusted equity (
eq:V:T:adj=splitoradj=splitdiv; keyed on the qualifier since GLE-328): the reach-back would fetch bars older than the run’s corporate-action window (a CA equity as the grid is fine); --replicateabove 1;- live mode, until live delivery of declared series exists (GLE-295);
- an event-bar run (below);
- the CSV strategy wire, which cannot carry the declaration: run the strategy on
stdio-pb-v1(declaring strategies need it already). A raw CSV replay with no engine builds views from the bars it is given, without a warm-up.
Event-bar runs (volume, tick, range and the other activity bars) are refused too: views are defined over time-bar grids only.
Each view costs one sample per grid bar and memory for its grid’s depth. The reach-back adds a fetch or two per view at startup, widening backwards only until it finds the bar it needs (two views of one source fetch its history twice).
Missing bars
Marketfeed never fills gaps: an hour with no trades has no bar. Two 1h series therefore drift apart by position, and Close(5) can be a different hour on each leg. Pair same-interval legs by CloseTime:
- Statistics: keep matching hours only.
kit.JoinCloses(a, b, n)returns the last n hours present in both legs (an inner join on exact close time), as two equal-length series. - Levels: carry forward, with a staleness check. Carry each leg’s latest value with
kit.AsOfCloses, and refuse a stale leg withkit.AgeAt,kit.StaleLegsorkit.StaleSeries(ctx, maxAge, ids...), which generaliseskit.AllFreshfrom “closed exactly now” to “closed within maxAge”.
Daily legs can also end their sessions at different times. kit.Cadence summarises a leg’s interval and close time of day, and kit.CompareLegs(a, b, loc) reports whether two legs share both, or the offset between them: GLD closes at 16:00 New York while GC and DX close at 17:00, so GLD paired with GC by date lacks the last hour of GC’s information. Close time of day is compared only for daily-or-slower legs; two intraday legs are aligned when they share an interval.
Release-stamped series
Release-stamped series: COT, FRED and RBA has the stamping rules. What matters for lining them up:
- Publication time, not the period. A FRED bar closes at the instant its value was first public, and
Bar.Refis the period it describes. The delay differs by series. DGS10 for 23 September 2026 closes on 24 September at 16:15 New York. August 2026 payrolls close on 4 September (the first Friday of the next month) at 08:30. CPI arrives in the middle of the next month (August 2026 CPI on 11 September at 08:30), and GDP about a month after its quarter ends (the first quarter of 2026 on 30 April). - Released together, a second apart. Observations published together close a second apart in observation order, so a catch-up after a shutdown arrives as consecutive bars.
- First-release values on the bars. A bar read of a FRED series serves each observation’s value as first published (First-release values, not revisions). The revisions are a separate read, the OBSERVATIONS schema (Revisions: the OBSERVATIONS schema), which a strategy declares as market events (Observations as events).
- Spreads clocked by a report. A synthetic spread whose first plain leg is release-stamped, such as
spr:1*macro:EIA:WCESTUS1,1*macro:EIA:WGTSTUS1, closes at that leg’s releases and carries itsRef; a later leg not yet published holds its previous value (Synthetic spreads). - Estimated stamps. Before a series’ ALFRED record starts, its stamps are estimated (Estimated release dates in early FRED history).
- Missing periods. A period that was never published has no bar: CPIAUCSL has no October 2025.
Bar(k)counts releases, so key anything by period onRef:kit.PeriodsAgo(cpi, kit.PeriodMonth, 12)is year on year. On the August 2026 row it returns August 2025, and it reportsokfalse for a period that has no bar rather than returning a neighbour.kit.RefValue(s, ref)looks up one period;kit.ShiftRef(ref, p, k)does the calendar arithmetic.kit.PairByRef(a, b, n)pairs two release series by period, with the instant each pair became known: the later of the two releases.
- Warm-up counts releases. A declared release series warms up to its
Lookbackin releases, not in time (How a release reaches a strategy).
Higher timeframes from base bars
There are two ways to see daily bars beside a 1h primary.
- Declare them (
Interval: "1d"). Marketfeed stamps each daily bar at its close, and the co-close order delivers it before a primary bar that closes at the same instant. - Build them from the primary’s own bars.
kit.Resample(prim, kit.TimeframeDay, loc)returns the completed periods only, those whose end is at or before the newest base bar’s close, plus the developing period built from its base bars to date. The developing bar is rebuilt from base bars on every call, so a completed bar never changes.kit.HTFCloses(completed)gives nseries the closes. ISO weeks (TimeframeWeek), months and years work the same way.
A base bar belongs to the period that contains its last instant, so a daily bar stamped at the next midnight belongs to the day it covers. Periods are calendar periods in loc, not exchange trade dates: in New York, a Sunday-evening Globex bar belongs to Sunday and so to the previous ISO week. Completion is strict and needs no holiday calendar: a week completes on the first base bar that closes at or after the following Monday 00:00. kit.WeeklyOHLCCompleted instead treats Friday’s daily bar as the end of the week; with Resample, read the week to date from the developing bar.
kit.PeriodStarts(prim, tf, loc) returns one flag per bar, 1 on the first bar of a new period compared with the bar before it and 0 otherwise. A week starts at an ISO-week change, and a day, month or year at a calendar change. The flags are causal, and the oldest buffered bar is not flagged.
A higher-timeframe series must be stamped at its close. A weekly bar stamped at the Monday that starts its week would put the whole week’s prices on the week’s first base bar. kit.RequireCloseStamped(series) returns an error for a series with any bar whose close is not after its open; call it once on a declared higher-timeframe series before trusting it. The engine itself refuses only a bar that closes before it opens.
Calendar and session keys
nseries holds no timestamps, so its seasonal and calendar rules read the calendar from key series the caller supplies: one value per bar, paired with the prices by position (the nseries manual’s “Calendar keys” introduction, in its Comparison category). strategies/kit generates those keys, and the session flags the higher-timeframe rules need, from the exchange calendar the engine pushes (Exchange calendar facts). The keys belong to the exchange’s trade date, not to the calendar date of a bar’s clock: a Globex bar that closes at 18:00 CT on a Sunday is Monday’s (GLE-524).
The index. A strategy that implements CalendarObserver receives each root’s Calendar before its first warm-up bar. kit.NewCalendarIndex(cal, kit.CalendarIndexOptions{}) reads the facts once and computes every key of every served day; the index is immutable and safe to share between goroutines, and idx.Bar(bar) or idx.At(t) costs one binary search and allocates nothing. kit.KeysAt(cal, t) is the one-shot form for a hook or a log line: it copies the facts on every call.
func (s *Seasonal) OnCalendar(_ *algolang.Context, cal algolang.Calendar) error {
s.keys = kit.NewCalendarIndex(cal, kit.CalendarIndexOptions{})
return nil
}
func (s *Seasonal) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
prim := kit.Series(ctx, bar)
tdm := kit.KeySeries(prim, s.keys, kit.KeyTDM) // one value per bar, oldest first
tdr := kit.KeySeries(prim, s.keys, kit.KeyTDR)
turnOfMonth := tdr.LTE(1).Add(tdm.LTE(3)).GT(0) // the nseries page's gate
...
}kit.Keys holds the keys of one bar, each a whole number in a float64, NaN when unknown, as nseries reads them. CalendarKey names a field for Keys.Value and KeySeries.
| Key | Keys field | Values |
|---|---|---|
month, dom, doy, year | Month, DOM, DOY, Year | of the trade date |
weekday | Weekday | ISO, Monday 1 to Sunday 7 |
| week | Week | ISO year times 100 plus ISO week (202415) |
| session key | SessionKey | the trade date as YYYYMMDD (20240408) |
| session | Session | 1 on a session, 0 on a closure |
tdm | TDM | trading day of the month, 1 on its first session |
tdr | TDR | trading days left in the month, 0 on its last session |
tdy | TDY | trading day of the year, 1 on its first session |
tdw | TDW | trading day of the ISO week, 1 on its first session |
tdh | TDH | trading days left before the next holiday, 0 on the last session before it |
| expiration week | ExpWeek | 1 in the ISO week that holds the month’s third Friday |
| expiration day | ExpDay | 1 on the month’s equity-index expiration session |
| time of day | TOD | minutes since midnight of the bar’s close, exchange-local (a 16:00:01 close reads 960) |
These are the nseries page’s keys (month, ISO weekday, dom, doy, tdm, tdr 0 on the month’s last session so that tdm + tdr is the month’s number of sessions, tdy and tdh), with the ones its later recipes asked for. A half day is an ordinary session, and intraday bars repeat their session’s keys, differing only in TOD. The first session of the week is TDW == 1; on intraday bars its first bar is flagged by TradeDateStarts(s, cal, kit.TimeframeWeek) (below).
A bar’s trade date is the trade date whose span holds the bar’s last instant, CloseTime less one nanosecond, the rule Resample uses for calendar periods. A session bar’s close lies inside its own date’s span, and a weekly session bar takes its last session’s keys; a grid bar lies inside one window of its date. An epoch bar that straddles a span’s end takes the later date: a plain 1d ES bar, closing at Chicago midnight, seven hours into the next trade date’s evening session, is keyed to the next trade date, so give daily futures bars a session (--session eth or rth). A bar that no served span holds has every key NaN.
Unknown keys. The counts refuse rather than guess, as the calendar’s lookups do. A count is NaN on a day that is not a session (a closure, or a date the holiday table does not know), when a day it would count over has unknown facts, and when the served days do not reach the edge of its period: TDM, TDW and TDY need the month’s, the ISO week’s or the year’s first date to be served (or an earlier day), TDR the month’s last date (or a later day). The engine serves the calendar from 14 days before the run’s earliest bar, warm-up included, to two quarters after its last (--calendar-margin-quarters raises it). So TDY is NaN until the first 1 January inside that window unless the strategy’s Lookback asks for about a year of warm-up, and TDR, TDH and ExpDay are NaN where they would need a day past the horizon.
tdh and its holiday set. TDH counts the sessions strictly between the bar’s trade date and the next day of a holiday set. The default, kit.WeekdayClosure, is every full closure the holiday table knows on a Monday to Friday trade date, other than a closed weekday of a per-weekday era. On ES that is New Year’s Day, Good Friday in most years and Christmas (and the closure of 11 June 2004, before the archive’s bars): Martin Luther King Day, Presidents’ Day, Independence Day, Labor Day and Thanksgiving are early-close sessions with their own trade dates. On a run’s last bars TDH is NaN when the next closure lies past the served horizon: for an ES run that ends in April, Christmas is more than two quarters ahead. The calendar carries no holiday names, so another set (an equity rule’s, for example) is a predicate on the TradingDay record passed as CalendarIndexOptions.Holiday, usually a set of dates; the index calls it once per served day while it is built.
Expiration. ExpWeek and ExpDay follow the equity-index options rule: the third Friday of the trade date’s month, or the latest earlier session of the month when that Friday is closed. In April 2025 the third Friday, the 18th, was Good Friday, so ExpDay is 1 on Thursday the 17th; idx.ExpirationDate(year, month) returns the date. ExpWeek is the week nseries’s recipes call optx. A futures contract’s own last trading day is not this key: the contract listings carry it (Contract listings).
Session flags and session bars. kit.SessionStarts(s, cal) flags 1 on the first bar of each trade date and kit.TradeDateStarts(s, cal, tf) the first bar of a new trade-date week, month or year (TimeframeWeek, TimeframeMonth, TimeframeYear), one value per bar, oldest first, like PeriodStarts, the oldest bar never flagged. kit.ResampleSessions(s, cal) builds one HTFBar per trade date, its Start and End the date’s span and its TradeDate set, completed once the span has ended, with Resample’s completed and developing results. These differ from the calendar periods of PeriodStarts and Resample exactly where the trade date and the clock disagree: a Sunday-evening Globex bar starts Monday’s session and Monday’s week, and a session that opens in the evening is not split at midnight.
The demo. strategies/demo/go/printkeys prints every bar’s keys and places no order (it declares optional lifetime-v2 support); its History input widens the warm-up, and so the calendar the engine serves backwards:
$ bin/algo run --adapter bin/marketfeed-adapter --adapter-inputs Dir=/usr/local/marketfeed \
--data-protocol pb --strategy bin/printkeys --inputs History=260 \
--symbol fut:XCME:ES:M24 --bar-interval 1d --session eth \
--date-from 2024-03-27T00:00:00Z --date-to 2024-04-02T00:00:00Z
[printkeys] [keys 1] fut:XCME:ES:M24 close=2024-03-27T16:00:00 CDT date=2024-03-27 month=3 weekday=3 dom=27 doy=87 year=2024 week=202413 session=1 skey=20240327 tdm=19 tdr=1 tdy=62 tdw=3 tdh=1 expweek=0 expday=0 tod=960
[printkeys] [keys 2] fut:XCME:ES:M24 close=2024-03-28T16:00:00 CDT date=2024-03-28 month=3 weekday=4 dom=28 doy=88 year=2024 week=202413 session=1 skey=20240328 tdm=20 tdr=0 tdy=63 tdw=4 tdh=0 expweek=0 expday=0 tod=960
[printkeys] [keys 3] fut:XCME:ES:M24 close=2024-04-01T16:00:00 CDT date=2024-04-01 month=4 weekday=1 dom=1 doy=92 year=2024 week=202414 session=1 skey=20240401 tdm=1 tdr=21 tdy=64 tdw=1 tdh=NaN expweek=0 expday=0 tod=960Good Friday, 29 March 2024, has no session, so the 28th is March’s last (tdr=0) and the last before the holiday (tdh=0), and tdh is NaN on 1 April because no later full weekday closure lies within the served horizon. make test-golden runs TestGoldenPrintkeysCalendarKeys over the archive: a Sunday-evening grid bar keyed to Monday, Good Friday 2024 on daily bars, the month’s turn, Thanksgiving’s 12:00 CT close and the April 2025 expiration on the Thursday, the same lines under both order lifetimes.
Parity with nseries. The kit’s spec tests build a daytime calendar of 2002 to 2004 with the NYSE closures and a predicate on Kaeppel’s eight holidays, and reproduce nseries’s reference keys (month, weekday, dom, doy, tdm, tdr, tdy and tdh of 568 sessions, from its WP0.9 fixture) exactly. Implementation anchors: strategies/kit/calkeys.go, tournament_calkeys_spec_test.go and the review tests beside it, strategies/demo/go/printkeys.
Prior sessions and weeks on base bars
Some rules read the last finished session or week on finer bars: Andrea Unger filters his 15-minute breakouts by the prior session’s body against its range and his 30-minute platinum breakouts by a daily ADX, Elder’s Triple Screen takes daily entries in the direction of the last finished week’s MACD histogram, and Bruce Babcock’s opening-gap continuation measures the gap from the prior session’s close. nseries holds no timestamps, so it cannot tell where a session or a week ends; its recipes emulate the weekly screen by length (the “x5” form) and leave the rest to the caller. strategies/kit/sessions.go and three demos (GLE-524, rows 27 and 30 of the register’s V-867) do it on the strategy side, with no engine change. nseries’s PriorPeriodLast, PriorPeriodHighest and PriorPeriodLowest (GLE-258 WP4.30, nseries PR 191, pinned since GLE-524’s WP3) give the series form of this map on a caller’s period-start flags, such as kit.SessionStarts; a cross-check pins the two forms bit for bit (Tests).
The rule. The prior session of a bar is the newest higher-timeframe bar whose trade date precedes the bar’s own trade date (each bar’s trade date is that of its last instant, as in Calendar and session keys). It is not “the newest bar that closed before this one”: a declared 1d rth gold bar closes at 12:30:01 CT, with the last 15-minute grid bar of its session, and is delivered before it (the co-close order), and an ES 1d rth bar closes one second before the grid’s last bar ends, so a test on instants would hand a session’s last bar its own session.
Two routes, one answer.
- An aligned view. Declare a
1dsession series of the strategy’s own symbol and an aligned view of it on the primary grid;kit.LastBefore(view, cal, date)returns the newest sample whose source bar (SourceCloseTime) belongs to an earlier trade date. On a session’s last grid bar the newest sample carries that session, so it takes the sample before; from the next session’s first bar, the newest.LastBeforereads a declared series the same way. - The kit’s trade-date resample.
kit.PriorSession(grid, cal)returns the newest barResampleSessionscompletes from the grid buffer before the newest bar’s trade date. A session is complete only when its trade-date span ends (17:00 CT for gold, after the 12:30 rth close), so on every bar of a session the newest completed one is the prior session. The buffer must hold the whole prior session: give the strategy aLookbackof at least two sessions of bars (21 a session on gold’s 15-minute rth grid, 46 on platinum’s 30-minute eth grid).
On the June 2024 gold contract’s 15-minute rth grid, 1 February to 23 May 2024, the two agree on all 1,678 bars, and on the July 2024 platinum contract’s 30-minute rth grid, March to June 2024, on all 780. A continuous run refuses a second series of its own root (a run takes each root once), so there only the kit route works; a dated contract of the same root can be declared beside a continuous primary, but its raw prices are not the continuous series’ adjusted ones. Weeks follow the same rule: a declared 1w session bar closes at its last session’s close (Thursday 28 March 2024, before Good Friday) and is carried from that bar, and kit.Resample(daily, kit.TimeframeWeek, time.UTC) completes a week on the next week’s first bar; by the trade-date rule both give, on every day, the week before the bar’s own.
kit.SessionWindow(cal, date, boundary) returns the window an intraday grid boundary names on a trade date (rth: the RTH window; eth and session: the first ETH leg’s open to the last leg’s close, the early close applied). A grid cuts a session’s last bar at the close and ends it one second after, so a bar whose close is at or after the window’s close is the session’s last. kit.StopEntry(symbol, side, qty, level, last) builds a stop entry, the plain stop or, at or through the last price, where a plain stop is refused, its first-touch form (backtest-only).
Resting orders on an intraday grid. Under lifetime v2 with a calendar a Day order rests until its session’s DAY-cancel close; under v1 it lives one bar. Returning Day orders again on every bar therefore stacks them under v2. The intraday demos rest GTC orders and keep them right themselves, with one code path for both profiles: sessionbreak compares the stops it wants with its working orders on every bar, cancels the rest (ctx.Cancel; the engine processes a bar’s cancels before its new orders) and submits what is missing; openinggap places one entry with an attached stop loss and cancels by name when the session ends. It names the stop loss rather than sweeping ctx.WorkingOrders(), because a v1 working view does not list an attached child once it has activated: a sweep leaves it working into the next session, where it fills. The exit at a session’s close is a market-on-close order on the bar kit.CloseOutAt names: under v1 the session’s last bar, as the MOC settles at the close it was decided on; under v2 the pre-close bar, the last that closes at least kit.MOCLead (5 minutes) before the RTH close, so the MOC is in before the send-time window opens and goes out the same session (Market-on-close orders). On that bar the demo cancels what rests, by name, and sends the MOC; after it, the session’s last bars place nothing. At bar resolution the MOC fills at the last bar’s close under both profiles, but under v2 the stop loss stops working a bar earlier, so the profiles’ fills differ on the sessions where it would have filled in the last bar. Their conformance claim is conform.Expect.CloseOut: the fills agree outside each session’s end, from the earliest MOC submission that day to the latest MOC fill, and each profile is flat once it is over. Under Session eth the MOC still targets the RTH close, so roundnumbers exits there under v2, not at the ETH close as under v1. A live strategy would re-price through kit.Controller (The desired-order controller).
The order of touches inside a bar (V-867 row 30). When one bar reaches openinggap’s entry and then its stop loss, the bar-resolution simulator enters and stops out in that bar; --path-heuristic midpoint takes the extreme nearer the open first; --path-interval 1m (which implies --include-path) decides from the minute bars (Path resolution). On the June 2024 E-mini contract’s 5-minute rth grid, 18 March to 13 June 2024, 4 of the 25 trades are entered and stopped out in one bar at bar resolution (net 1,337.50 before costs), 4 with the midpoint heuristic at other prices (1,087.50), and 1 with the minute path (7,225.00). The engine is unchanged. Babcock’s opening range is taken from the rth grid and the calendar’s window rather than a custom:HHMM-HHMM session window because custom windows refuse bare roots and :cont composites (Custom session windows). Two entry stops in one OCO group tie at bar resolution, and the one submitted first fills: tdrebo and roundnumbers below show it, and Which level a bar reached first sets out the four resolutions.
The demos. Five examples under strategies/demo/go/, each built by make build, with spec tests on constructed bars (on synthetic calendars, algolang.NewCalendar, where a helper reads one), review tests, and a conformance claim under both lifetimes:
| Demo | Source and rules | Orders and lifetime | Departures |
|---|---|---|---|
sessionbreak | Unger, “Filters On The Test Bench” (Stocks & Commodities V40:12, 2022): from bar StartBar to bar EndBar of a session (3 and 15 of gold’s 21 rth bars), a buy stop at the session’s high so far and a sell stop at its low, both resting, so a fill can be reversed; out at the close; no stop-loss; Factor f gates entries on the prior session’s |O − C| < f(H − L), strict and without a division (2, the default, is off; 0.5 is his indecision pattern). Levels prior with ADXGate is his platinum system (“Intraday Breakout Strategy On Platinum Futures”, V43:10, 2025): stops at the prior session’s high and low while the daily ADX(6) of the sessions before is below 40. Route both computes the prior session both ways and logs prior-session checks N, disagreements M at shutdown | GTC stops (kit.StopEntry), OCO-joined while flat, reconciled every bar; MOC exit on kit.CloseOutAt’s bar (v1 the session’s last bar, v2 the pre-close bar); a position met on a session’s first bar (its close-out bar was missing) is closed at market; supports lifetime v2 (one code path); needs the calendar (pb wire); Route kit on a continuous symbol | the bar counter is the calendar’s ordinal from the session’s first bar; a bar that reaches both stops fills the buy (submitted first) and the reversal rests from the next bar, where TradeStation would reverse in that bar; the gold window is not printed (3 and 15 scale his DAX 10 and 40); the 2025 article’s daily-factor level is not built |
openinggap | Babcock (Le Beau and Lucas, Day Trading Systems & Methods, ch. 8): a gap of at least GapMin from the prior session’s close to the open; a stop FollowThrough beyond the first RangeMinutes minutes’ range in the gap’s direction; a stop loss of StopDollars (500) a contract; out on the close. His “75 points” and “25 points” are hundredths of a 1992 S&P point (about 0.19% and 0.06% of the index); the defaults 10 and 3 are those fractions of an E-mini near 5,300 | one GTC entry a session with an attached GTC stop loss; the stop loss (or the unfilled entry) cancelled by name and an MOC exit on kit.CloseOutAt’s bar (v1 the last bar, v2 the pre-close bar), or on the next session’s first bar, with a market exit, when that bar is missing; supports lifetime v2 (one code path); needs the calendar; declares no series, so it serves continuous symbols | the opening range is the grid’s first minutes (his “opening price range” is a pit-era term); the gap is inclusive; no re-entry after a stop |
triplescreen | Penfold, The Universal Tactics of Successful Trend Trading (2021), ch. 6, testing Elder’s Triple Screen: the slope of the weekly MACD(12, 26, 9) histogram of the last finished week (the signal seeded on the MACD’s valid part); bear power (low − EMA13) below zero and rising for a long, bull power above zero and falling for a short; a stop one tick beyond the setup bar’s extreme for the next bar only; a first-touch protective stop a tick below the lower of the setup and entry bars’ lows, raised to the entry price after a close in profit and to a tick below each confirmed swing low that is higher | the entry a kit.PendingEntry with MaxBars 1, its stop returned while it rests, and the protective stop returned each bar, both through kit.OneBar, which gives each a life of one bar under both profiles; supports lifetime v2; Weeks kit (default) needs no calendar, Weeks declared reads a 1w session series of a dated contract | “break” is a tick beyond and the entry lives one bar (unprinted); open profit is read on the close; swings are strict pivots of SwingLen bars; no exit on a trend change; Penfold’s re-entry is the next setup after a stop-out; his “Variables” list keeps a 50% trailing stop that his text replaces with the swing, which is built; Aspray’s and Star’s daily MACD-Mo signals on the same weekly screen are another base system, not built |
tdrebo | Perl, DeMark Indicators (2008), ch. 9, TD Range Expansion Breakout: at the close of a session’s first grid bar, a buy stop strictly beyond its open plus 0.382 (Break) of the prior session’s true range and a sell stop strictly beyond the open less it, one OCO pair; each with a limit target at 0.618 (Extend) and a stop loss at the opposite 0.382 level (Protect); out at the close. Qualify takes Perl’s qualified breakout: the buy only after a down close, the sell only after an up close. With Scenarios it classifies each session by DeMark’s four TD Range Projection tolerance scenarios (the projected high and low from the prior session, the tolerance levels at 0.15 of its true range from the open), logs them and counts at shutdown how many held and were right | GTC entries with hand-built GTC children (<entry>_tp, <entry>_sl); what is left cancelled by name and an MOC exit on kit.CloseOutAt’s bar (v1 the last bar, v2 the pre-close bar), or a market exit on the next session’s first bar when that bar is missing; supports lifetime v2 (one code path); needs the calendar; declares no series, so it serves continuous symbols | the stops work from the session’s second bar (the open is known at the first bar’s close); the 0.618 extension is read as the target and “until a signal occurs in the opposite direction” as the stop loss at the opposite level, with one trade a session and no reversal; Perl’s fades are not built; the scenarios’ “within” is inclusive and their events strict; under v1, after a missing last bar, a session on whose first bar an entry left working from the last session filled places no pair (under v2 the pre-close bar cancels it: on the 3 July 2020 early close the 30-minute rth grid has no bar at the window close, but has the pre-close bar) |
roundnumbers | Unger, “Round Numbers And Price Behavior” (Stocks & Commodities V44:9, September 2026): the round numbers of Step (50) above and below the prior session’s last close, in whole ticks, so decimal steps are exact; a buy stop at the upper and a sell stop at the lower as one OCO pair, placed at the close of the first bar inside his window (OpenDelay 15 minutes after the open to CloseLead 15 minutes before the close: his 17:15 to 15:45 on Session eth 15-minute bars); a stop loss of StopDollars (1,500) a contract and an optional target; out at the close | GTC entries with GTC children; the unfilled pair cancelled by name when the window ends; what is left cancelled and an MOC exit on kit.CloseOutAt’s bar (v1 the last bar, v2 the pre-close bar: under Session eth the bar before the RTH close, not the ETH close); supports lifetime v2 (one code path); needs the calendar; logs once when a bar carries an adjustment (a continuous series from its first roll in the run with --roll-rebase=false; under the default roll rebase its bars are the held contract’s own and carry none), as its levels are then not the traded contract’s round numbers | the stop loss and target are measured from the level, not the fill; breakeven is not built; a trade opened and closed inside one bar does not re-arm the pair; the prior close is the grid’s last trade, not a settlement; under v1, after a missing last bar, a session on whose first bar an entry left working from the last session filled places no pair |
Unger’s and Penfold’s printed results (Unger’s average trade with the filter off and on: DAX 48.36 → 63.96, gold 41.93 → 88.47; platinum 29.98 → 50.07; Penfold’s 24 futures from 1980, $29 a trade after $51 of costs; Unger’s round numbers on 15-minute E-mini bars from 2010 to 2025, $200,762.50 net and $80.14 a trade, about 2,505 trades by division, with his optimised stop and target) depend on their base systems, contracts and costs; they are cited, not targets. Babcock printed no results, and Perl only charts.
Tests. strategies/kit/tournament_sessions_spec_test.go pins the four helpers on a synthetic gold-like calendar (a closed Wednesday, an early close) and its 15-minute grid, including a bar that closes exactly at its span’s end. Each demo’s tournament_*_spec_test.go pins its pure helpers (the session state, the two routes, the gates, the wanted orders and the reconciliation; the gap, the opening range and the close-out; the weekly histogram, the setups and the stop; the TD REBO and projection levels, their tick snapping, the entries and the scenario classification; the round-number levels, Unger’s window and the entries). The tdrebo and roundnumbers spec tests also run each demo’s orders through the fill simulator three ways on the same constructed bars, as Which level a bar reached first describes. triplescreen runs through the engine on a 600-bar weekday walk against an independent loop and pins its v1 blotter (cf21_conform_test.go); a review test pins its one-bar PendingEntry under lifetime v2. The calendar-driven demos cannot run through the file-csv adapter, which serves no calendar (their cf21_conform_test.go checks that they place no order there); their golden tests run them over the archive under both lifetimes (make test-golden): equal fills and counts, the subsets the filters trade, one entry a session under its OCO tag, the window’s cancellations, the scenario lines, the order of touches at the three resolutions, the stop loss’s dollars and the exit’s timing, and the no-calendar line logged once. strategies/kit/sessions_nseries_crosscheck_test.go (GLE-524’s WP3) compares PriorSession and LastBefore with nseries’s PriorPeriodLast, PriorPeriodHighest and PriorPeriodLowest on SessionStarts flags, bit for bit, on the spec tests’ synthetic calendars; its golden form, TestGoldenXcPriorSessionAgreesWithNseriesOnGold, does the same over the archive’s June 2024 gold contract (the 15-minute rth grid of 8 to 19 April 2024: the last price on 189 of its 210 bars, the high and low on 168) in make test-golden. Review tests beside the spec tests (*_review_test.go, *_mutation_review_test.go) close the gaps the review panel and the mutation sweep found.
Worked examples
1h ES with CPIAUCSL. strategies/demo/go/cpigate is a complete example. make run-cpigate runs it on an hourly ES contract against the marketfeed adapter, and engine/gle265_cpigate_e2e_test.go runs it through the file-csv adapter on the lake’s CPIAUCSL rows. It declares the CPI series and reads it all three ways:
func (s *CPIGate) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "cpi", Symbol: s.CPI, Lookback: max(36, s.CorrWindow+14),
Schema: algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1w"},
}}
}
func (s *CPIGate) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
prim, cpi := ctx.Series(ctx.PrimarySymbol()), ctx.Series("cpi")
defer s.clock.Observe(cpi, prim) // the release clock: every bar, every series
if !ctx.IsPrimary(bar) {
return nil, nil
}
// The gate: the newest CPI known at this close. Year on year by Ref,
// across the missing October 2025.
latest, ref, ok := kit.PeriodsAgo(cpi, kit.PeriodMonth, 0)
yearAgo, _, ok12 := kit.PeriodsAgo(cpi, kit.PeriodMonth, 12)
...
// The correlation of ES returns between releases with CPI changes, on
// the release clock.
cpiVals, esCloses := s.clock.Series()
corr := esCloses.ReturnCorrelation(cpiVals, s.CorrWindow, 1).Value()
...
}The first decision that sees each release logs one line per release (several when a catch-up arrives between two hourly bars). On the lake, August 2026 CPI, released at 08:30 New York (12:30 UTC), is first seen by the 13:00 UTC bar, and its year on year uses August 2025, not the July 2025 row twelve releases back:
cpigate: 2026-09-11T13:00:00Z sees CPI 2026-08 released 2026-09-11T12:30:00Z yoy=0.033297 corr=0.0649 n=12The correlation needs CorrWindow+1 releases observed during the run (warm-up bars do not call OnBar), so it reads NaN for the first year of a run. The CPI series is declared, so the run needs --data-protocol pb (see Declaring extra data). Since the order-lifetime programme’s I21 (GLE-467) the demo declares optional lifetime-v2 support, and cf21_conform_test.go beside it runs it under both profiles over the GLE-265 fixture on a shorter window, four fills equal under each, the last the gate’s flatten (Conformance under both lifetimes).
1d ES with weekly COT and quarterly GDP, lined up. strategies/demo/go/alignpanel is the aligned series example. make run-alignpanel runs it on a daily ES contract against the marketfeed adapter, and engine/gle353_alignpanel_e2e_test.go runs it through the file-csv adapter on the lake’s COT and GDP rows (since the order-lifetime programme’s I21, GLE-467, so does cf21_conform_test.go beside it, under both profiles at the defaults, four fills equal under each; Conformance under both lifetimes). It declares both release series, then a view of each on the primary, and reads each kind of question from the view that answers it:
func (s *AlignPanel) Lookback() int { return s.Window + 1 } // the primary's depth, and so each view's
func (s *AlignPanel) DataRequirements() []algolang.DataRequirement {
weekly := algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1w"}
return []algolang.DataRequirement{
{SeriesID: "cot", Symbol: s.COT, Lookback: s.COTWindow, Schema: weekly}, // the release views
{SeriesID: "gdp", Symbol: s.GDP, Lookback: 2, Schema: weekly},
}
}
func (s *AlignPanel) AlignedSeries() []algolang.AlignedSeries {
return []algolang.AlignedSeries{
{SeriesID: "cot_d", Source: "cot"}, // one sample per daily bar
{SeriesID: "gdp_d", Source: "gdp"},
}
}
func (s *AlignPanel) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.IsPrimary(bar) {
return nil, nil // a release bar: the views carry it from the next daily close
}
prim, cotD, gdpD := ctx.Series(ctx.PrimarySymbol()), ctx.Series("cot_d"), ctx.Series("gdp_d")
cot, gdp := ctx.Series("cot"), ctx.Series("gdp")
rows := min(prim.Len(), cotD.Len(), gdpD.Len(), s.Window+1) // right-aligned: row 0 is today in each
if cotD.Len() > 0 && cotD.Bar(0).Updates > 0 {
// a report this close carries for the first time: Ref is its as-of date,
// SourceCloseTime its publication, Updates > 1 a catch-up
}
...
index := cotIndex(cot, s.COTWindow) // statistics: on the release view
g0, _, ok0 := kit.PeriodsAgo(gdp, kit.PeriodQuarter, 0) // periods: on the release view, by Ref
g1, _, ok1 := kit.PeriodsAgo(gdp, kit.PeriodQuarter, 1)
stale := len(kit.StaleSeries(ctx, s.MaxAge, "cot_d")) > 0 // age of the report, not of the bar
...
}make run-alignpanel runs the December 2025 contract while it was the front, from 15 September to 12 December 2025. At its first decision it logs the panel its warm-up built, and then one line for each daily close that carries a new release:
alignpanel: 2025-09-15T05:00:00Z panel rows=19 primary=19 cot_d=19 gdp_d=19 cot=52 gdp=2 oldest_cot=2025-08-22T20:00:00Z oldest_gdp=2025-07-30T12:30:00Z
alignpanel: 2025-09-20T05:00:00Z carries cot 2025-09-16 released 2025-09-19T20:00:00Z updates=1 value=-472904 index=0.0000 rows=21
alignpanel: 2025-09-27T05:00:00Z carries cot 2025-09-23 released 2025-09-26T20:00:00Z updates=1 value=-442953 index=0.1092 rows=21
alignpanel: 2025-11-20T06:00:00Z carries cot 2025-09-30 released 2025-11-19T21:00:00Z updates=1 value=-437245 index=0.1301 rows=21
alignpanel: 2025-11-22T06:00:00Z carries cot 2025-10-07 released 2025-11-21T21:00:00Z updates=1 value=-456477 index=0.0599 rows=21
alignpanel: 2025-11-26T06:00:00Z carries cot 2025-10-14 released 2025-11-25T21:00:00Z updates=1 value=-409269 index=0.2321 rows=21
...
Data notes 2 notes
short warm-up fut:XCME:ES:Z25@1d 18 of 21 bars
fill path bar, not tick: tick resolution is single-series only (one trade stream per replay)
cache served 0 of 6 bar fetches from /home/you/algolang/cacheRead it from the top:
- The panel at the first decision. Each view holds as many rows as the primary: 19, because an epoch daily warm-up spans 21 calendar days (18 bars, hence the run’s
short warm-upnote,18 of 21 barson the primary, not on the views) plus the first decision. Its oldest COT row carries the report published on 22 August, the newest one before the oldest daily bar. The release views hold their own depth: 52 reports and 2 GDP releases. - Each report on its first close. The report published at 20:00 UTC on Friday 19 September is first carried by Friday’s daily bar, which closes at Saturday 00:00 Chicago time (05:00 UTC); the bar’s close is after the release, so it is visible.
- The shutdown. No report appears between 27 September and 20 November: the view repeats the 26 September report on every daily bar for 54 days (
Updates == 0),kit.StaleSeriesreports it stale once it is older thanMaxAge(ten days), and the strategy stays flat. - The catch-up. The delayed reports, published a few days apart from 19 November, are each carried by the first daily close after their release, with their own as-of date in
Ref. When two land between the same pair of daily bars (a missing day on a thin contract, for instance) the line saysupdates=2and the view shows only the newer.
The same panel on the continuous series, with a continuous peer. On a continuous primary the panel’s grid is the continuous series. The Peer input declares a second continuous series beside it, with one bar of its own lookback, and lines it up as peer_d (On a continuous run):
if s.Peer != "" {
daily := algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1d"}
reqs = append(reqs, algolang.DataRequirement{SeriesID: "peer", Symbol: s.Peer, Lookback: 1, Schema: daily})
}
...
views = append(views, algolang.AlignedSeries{SeriesID: "peer_d", Source: "peer"})
...
peerUp = peerD.Close(0) > indicators.Closes(peerD).SMA(s.Window).Value() // the peer's trend, row for row
The strategy goes long only while the peer trends up too. Each decision that first carries a new peer contract logs the sample’s adjusted and raw close. make run-alignpanel-continuous runs it on fut:XCME:ES with fut:XCME:NQ as the peer, from July to December 2025 (excerpt):
alignpanel: 2025-07-01T21:00:00Z panel rows=21 primary=21 cot_d=21 gdp_d=21 cot=52 gdp=2 oldest_cot=2025-05-30T20:00:00Z oldest_gdp=2025-04-30T12:30:00Z
alignpanel: 2025-07-01T21:00:00Z peer fut:XCME:NQ carries NQU25 close=23185.5 raw=22691.75 rows=21 oldest=NQM25@2025-06-03
alignpanel: 2025-07-07T20:59:59Z carries cot 2025-07-01 released 2025-07-07T20:00:00Z updates=1 value=-302016 index=0.4879 rows=21
alignpanel: 2025-07-11T21:00:00Z carries cot 2025-07-08 released 2025-07-11T20:00:00Z updates=1 value=-340689 index=0.2962 rows=21
...
alignpanel: 2025-09-15T21:00:00Z peer fut:XCME:NQ carries NQZ25 close=24794 raw=24538 rows=21
...
alignpanel: 2025-12-15T21:59:59Z peer fut:XCME:NQ carries NQH26 close=25348.75 raw=25348.75 rows=21
...
bars: 290 main after replicate (+ 96 warmup), 290 loop, 2 orders
2 fills, commission 0.00, realized PnL 737.50Read it from the top:
- A full panel from the first decision. The continuous series warms up (Lookback and the Series API), so every view holds 21 rows on 1 July, where the dated contract’s held 19.
- The peer reached back across its roll. NQ’s own lookback is one bar, yet
peer_dholds 21 rows. Its oldest row carries NQM25, the contract NQ rolled out of in June, read through NQ’s composite under the run’s snapshot. - Reports on their own session. The report published at 20:00 UTC is carried by that day’s session bar, which closes at 20:59:59 or 21:00:00 UTC in summer.
- The peer’s rolls. At the September roll the sample moves to NQZ25. Its adjusted close (24794) sits 256 points above its raw one (24538), the gap still ahead at the December roll in the run’s frame. From 15 December the sample carries NQH26, the contract held at the anchor, so the two agree.
1h with a declared 1d. Compute each leg on its own clock and combine at the decision. A daily bar that closes at the same instant as an hourly bar is delivered first, so it is already in ctx.Series("d1") on that hourly bar:
d1 := ctx.Series("d1")
up := d1.Len() >= 50 && d1.Close(0) > indicators.Closes(d1).SMA(50).Value()To build the daily bars from the hourly primary instead, use kit.Resample(prim, kit.TimeframeDay, ny) and read the completed days; kit.PeriodStarts(prim, kit.TimeframeDay, ny) marks each day’s first hour.
Two 1h legs. Statistics use matching hours only; levels carry forward with a staleness check:
a, b, ok := kit.JoinCloses(ctx.Series("es"), ctx.Series("nq"), 100)
if ok {
beta := ... // regression on a and b: the same 100 hours on both legs
}
if stale := kit.StaleSeries(ctx, 2*time.Hour, "es", "nq"); len(stale) > 0 {
return nil, nil // a leg has not traded for two hours
}