A trend using an aligned economic panel
The previous chapter used the latest known report. Now suppose you want a daily table with price, positioning, GDP and another market, all as known at each historical daily close. alignpanel builds exactly that:
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/alignpanel --symbols fut:XCME:ES --bar-interval 1d \
--inputs Peer=fut:XCME:NQ \
--date-from 2025-07-01 --date-to 2025-12-31 \
--commission-per-share 2.50 --slippage-ticks 1 \
--results-dir results/learning/panelIts daily trend is gated by COT positioning, positive quarter-on-quarter GDP growth and, with Peer set, an upward NQ trend. NQ remains a reference; the orders trade ES. The strategy declares COT, GDP and the optional peer, then declares views on the primary grid:
func (s *AlignPanel) AlignedSeries() []algolang.AlignedSeries {
views := []algolang.AlignedSeries{
{SeriesID: "cot_d", Source: "cot"},
{SeriesID: "gdp_d", Source: "gdp"},
}
if s.Peer != "" {
views = append(views, algolang.AlignedSeries{
SeriesID: "peer_d", Source: "peer",
})
}
return views
}An empty Grid selects the primary. ctx.Series("cot") indexes releases; ctx.Series("cot_d") indexes daily decisions and carries the COT value available at each one. These are different statistical samples. A 20-row average of the latter is a daily average of carried values, not an average of 20 independent reports.
Avoid false alignment
Do not zip the last 20 raw rows of ES, GDP and COT. They cover different times and counts. Use aligned views for grid-based comparisons, and release views for calculations whose unit is a report or reference period. The demo computes GDP growth by quarter on its release view, while the daily panel records what was known each day.
The primary lookback sizes an aligned view’s grid history. The source’s own lookback controls the release view. Check the available lengths and missing values; a carried value has not become a fresh observation merely because another daily row was added. Bar(0).Updates identifies newly incorporated source releases. kit.StaleSeries checks the underlying observation’s age; MaxAge=240h is the demo’s COT freshness limit.
Inspect the first printed panel and a publication day. Find the same release in the raw report history and verify the first primary decision that can see it. Then inspect a long publication gap. A stale-data rule should change the decision for an explicit reason, rather than silently backfilling later knowledge.
For revision-sensitive research, the gdprevision demo declares Observations and reacts to the publication of vintages. A first-release bar and a later revision answer different questions. Decide which is the input before interpreting a macro backtest. Source to study: strategies/demo/go/alignpanel/main.go and strategies/demo/go/gdprevision/main.go.
Complete source: alignpanel
The numbered reading notes below explain the complete program; the inline comments describe individual steps. Keep all the listed files together. MODULE means the module path printed by go list -m in this checkout.
The declarations identify raw reference series and aligned views separately. A view samples the information available at each primary-grid instant.
Read the length and validity guards before the indicators. Filling missing values indiscriminately would manufacture a longer economic history.
The strategy combines the aligned filters only at its decision clock. The logging and plots let you compare raw release timing with the sampled panel.
Build the supplied files directly:
go build -o bin/alignpanel ./strategies/demo/go/alignpanel
bin/alignpanel --algolang-describeThis program requires engine capabilities. The current standalone --algolang-selftest offers none, so it intentionally refuses this program during negotiation. Inspect its inputs with --algolang-describe and use the chapter’s engine run to exercise it; do not remove the capability requirement to make a standalone probe pass.
alignpanel/main.go
// Command alignpanel is the worked example for "Aligned series" in
// docs/algolang.md (GLE-353): a daily strategy on its primary (an ES contract
// in the examples) that lines a weekly COT report and quarterly GDP up with
// its own bars, one row per daily close.
//
// - Aligned views (stretch slow onto fast, declared). AlignedSeries carries
// the newest COT report and the newest GDP release known at each daily
// close onto that close, so ctx.Series("cot_d"), ctx.Series("gdp_d") and
// the primary line up index for index: Bar(i) of each is the same day.
// A value is repeated until the next release; a release stamped at
// exactly a daily close is first carried by the next daily bar.
// - Release views for statistics. The COT index (where the newest report
// sits between the lowest and highest of the last COTWindow reports) and
// quarter-on-quarter GDP growth are computed on the series' own release
// history, never on the repeated daily values, which would weight a
// report by how many days it stayed current.
// - Staleness from the source, not the grid. Each sample carries the
// instant its value was published (SourceCloseTime), so kit.StaleSeries
// on an aligned view measures how old the COT report is, not the daily
// bar. During a long COT gap (the 2025 shutdown) the strategy stays flat.
//
// It holds one contract long while the daily close is above its Window-day
// SMA, the COT index known at the close is at or above MinIndex, the newest
// GDP release known at the close showed growth on the previous quarter, and
// the COT report is no older than MaxAge; it is flat otherwise. The first
// daily decision that carries each new COT report or GDP release logs one
// line, which the engine prints on stderr and the regression test reads:
//
// alignpanel: 2025-11-20T00:00:00Z carries cot 2025-09-30 released 2025-11-19T21:00:00Z updates=1 value=-437245 index=0.1301 rows=21
//
// On a continuous primary (fut:XCME:ES) the panel's grid is the continuous
// series, and Peer names a second continuous series (fut:XCME:NQ) declared
// beside it and lined up with it as peer_d (GLE-394): the peer must trend up
// too, read from the aligned view index for index with the primary, and each
// decision that first carries a new peer contract logs the sample's adjusted
// and raw close. The view's samples are in the run's one adjusted frame, so
// the peer's roll moves its raw close and not its adjusted one.
//
// It declares data series and aligned series, so it runs on the protobuf
// wire (`make run-alignpanel` runs it against the marketfeed adapter, and
// `make run-alignpanel-continuous` on the continuous ES with NQ as its peer).
package main
import (
"fmt"
"math"
"os"
"time"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
)
var buildID string
type AlignPanel struct {
COT string `algolang:"default=cot:CFTC:13874A:LF,desc=Release-stamped COT series (E-mini S&P 500 leveraged funds net)"`
GDP string `algolang:"default=macro:FRED:GDP,desc=Release-stamped quarterly GDP series"`
Window int `algolang:"default=20,min=2,max=500,desc=Daily rows in the panel and the trend SMA"`
COTWindow int `algolang:"default=52,min=4,max=520,desc=COT reports in the COT index"`
MinIndex float64 `algolang:"default=0.5,min=0,max=1,by=0.05,desc=Trade only while the COT index known at the close is at or above this"`
MaxAge time.Duration `algolang:"default=240h,desc=Stay flat when the newest COT report known at the close is older than this"`
Peer string `algolang:"desc=A second continuous series (fut:XCME:NQ) lined up with the primary as peer_d; it must trend up too (empty: none)"`
started bool // the first decision has logged the panel
peerLast string // the peer contract the previous decision's peer_d sample carried
}
func (s *AlignPanel) Name() string { return "AlignPanel" }
// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. Its orders are market orders alone, so the
// one-bar rule (OneBarRule) ends none of them.
func (s *AlignPanel) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does; it exempts market orders.
func (s *AlignPanel) OneBarRule() bool { return true }
func (s *AlignPanel) Description() string {
return "Daily SMA trend gated on COT positioning and GDP growth lined up bar for bar with aligned series (Aligned series example)."
}
// Lookback sizes the primary's buffer, and so every aligned view on it: a view
// buffers as many samples as its grid buffers bars.
func (s *AlignPanel) Lookback() int { return s.Window + 1 }
// DataRequirements declares the two release series at 1w, as release-stamped
// series are declared. Their Lookback counts releases and sizes their release
// views; the aligned views below need nothing from it, because the engine
// fetches whatever older releases the views need to fill the primary's warm-up.
//
// A Peer is declared daily with one bar of its own lookback: its aligned view
// is as deep as the primary whatever the peer's own buffer holds, because the
// engine reaches back through the peer's composite for the samples the
// primary's warm-up needs.
func (s *AlignPanel) DataRequirements() []algolang.DataRequirement {
weekly := algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1w"}
reqs := []algolang.DataRequirement{
{SeriesID: "cot", Symbol: s.COT, Lookback: s.COTWindow, Schema: weekly},
{SeriesID: "gdp", Symbol: s.GDP, Lookback: 2, Schema: weekly},
}
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})
}
return reqs
}
// AlignedSeries lines both release series, and the Peer when set, up with the
// primary (Grid "").
func (s *AlignPanel) AlignedSeries() []algolang.AlignedSeries {
views := []algolang.AlignedSeries{
{SeriesID: "cot_d", Source: "cot"},
{SeriesID: "gdp_d", Source: "gdp"},
}
if s.Peer != "" {
views = append(views, algolang.AlignedSeries{SeriesID: "peer_d", Source: "peer"})
}
return views
}
func (s *AlignPanel) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.IsPrimary(bar) {
return nil, nil // a COT or GDP release bar: the views already 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")
// The panel: the last `rows` daily closes with the COT and GDP values
// known at each. Every view is right-aligned with the primary, so the
// newest row of each is today; a view can be shorter than the primary
// when its source has no release before the oldest daily bar.
rows := min(prim.Len(), cotD.Len(), gdpD.Len(), s.Window+1)
peerD := ctx.Series("peer_d")
if s.Peer != "" {
rows = min(rows, peerD.Len())
}
index := cotIndex(cot, s.COTWindow)
if !s.started {
s.started = true
s.logPanel(ctx, bar, prim, cotD, gdpD, rows)
}
s.logNew(ctx, bar, "cot", cotD, rows, index)
s.logNew(ctx, bar, "gdp", gdpD, rows, index)
s.logPeer(ctx, bar, peerD)
if rows < s.Window+1 {
return s.flatten(ctx, bar), nil // not enough lined-up history yet
}
// Levels and gates at this close, read from the aligned views: the
// newest row. Index i of prim, cotD and gdpD is the same daily bar.
closes := indicators.Closes(prim)
trendUp := prim.Close(0) > closes.SMA(s.Window).Value()
growth := math.NaN()
if g0, _, ok0 := kit.PeriodsAgo(gdp, kit.PeriodQuarter, 0); ok0 {
if g1, _, ok1 := kit.PeriodsAgo(gdp, kit.PeriodQuarter, 1); ok1 && g1 != 0 {
growth = g0/g1 - 1 // quarter on quarter, by Ref, from the release view
}
}
stale := len(kit.StaleSeries(ctx, s.MaxAge, "cot_d")) > 0 // the report's age, not the bar's
// The peer's trend, on its aligned view: Bar(i) is the peer as known at
// the primary's i-th close, so its SMA lines up with the primary's.
peerUp := true
if s.Peer != "" {
peerUp = peerD.Close(0) > indicators.Closes(peerD).SMA(s.Window).Value()
}
long := trendUp && peerUp && index >= s.MinIndex && growth > 0 && !stale // false when index or growth is NaN
if qty := ctx.Position(bar.Symbol).Quantity; long && qty == 0 {
return []algolang.Order{algolang.MarketBuy(bar.Symbol, 1).Named("LE")}, nil
} else if !long {
return s.flatten(ctx, bar), nil
}
return nil, nil
}
// cotIndex places the newest report between the lowest and highest of the
// last n reports, on the release view: 0 at the low, 1 at the high. NaN until
// n reports are known or when they are all equal.
func cotIndex(cot algolang.Series, n int) float64 {
if cot.Len() < n {
return math.NaN()
}
lo, hi := math.Inf(1), math.Inf(-1)
for i := range n {
lo, hi = min(lo, cot.Close(i)), max(hi, cot.Close(i))
}
if hi == lo {
return math.NaN()
}
return (cot.Close(0) - lo) / (hi - lo)
}
// logNew logs one line when the view's newest sample carries a source bar it
// did not carry at the previous daily close (Updates > 0), naming the period
// (Ref), when it was published, how many releases arrived since the previous
// close (2 or more is a catch-up), the value, and the panel's depth.
func (s *AlignPanel) logNew(ctx *algolang.Context, bar algolang.Bar, name string, view algolang.Series, rows int, index float64) {
if view.Len() == 0 || view.Bar(0).Updates == 0 {
return
}
b := view.Bar(0)
ctx.Logf("alignpanel: %s carries %s %s released %s updates=%d value=%g index=%.4f rows=%d",
bar.CloseTime.UTC().Format(time.RFC3339), name, b.Ref.Format(time.DateOnly),
b.SourceCloseTime.UTC().Format(time.RFC3339), b.Updates, b.Close, index, rows)
}
// logPeer logs one line when the peer's newest sample carries a contract the
// previous decision's did not: the sample's adjusted close, in the run's
// frame, and its raw close, the contract's own price. At the first decision
// it names the contract of the oldest row too, which may be one the peer
// rolled out of during the warm-up.
func (s *AlignPanel) logPeer(ctx *algolang.Context, bar algolang.Bar, peerD algolang.Series) {
if s.Peer == "" || peerD.Len() == 0 {
return
}
b := peerD.Bar(0)
if b.ActiveContract == s.peerLast {
return
}
first := s.peerLast == ""
s.peerLast = b.ActiveContract
line := fmt.Sprintf("alignpanel: %s peer %s carries %s close=%g raw=%g rows=%d",
bar.CloseTime.UTC().Format(time.RFC3339), s.Peer, b.ActiveContract, b.Close, b.RawPrice(algolang.FieldClose), peerD.Len())
if first {
o := peerD.Bar(peerD.Len() - 1)
line += fmt.Sprintf(" oldest=%s@%s", o.ActiveContract, o.SourceCloseTime.UTC().Format(time.DateOnly))
}
ctx.Logf("%s", line)
}
// logPanel logs, at the first decision, how many lined-up rows the warm-up
// gave and which release each view carries in its oldest row: with enough
// history every view is as deep as the primary from the first bar, because
// the engine fetched the releases the warm-up needed, while the release views
// (cot, gdp) hold only their own Lookback.
func (s *AlignPanel) logPanel(ctx *algolang.Context, bar algolang.Bar, prim, cotD, gdpD algolang.Series, rows int) {
oldest := func(v algolang.Series) string {
if v.Len() == 0 {
return "none"
}
return v.Bar(v.Len() - 1).SourceCloseTime.UTC().Format(time.RFC3339)
}
ctx.Logf("alignpanel: %s panel rows=%d primary=%d cot_d=%d gdp_d=%d cot=%d gdp=%d oldest_cot=%s oldest_gdp=%s",
bar.CloseTime.UTC().Format(time.RFC3339), rows, prim.Len(), cotD.Len(), gdpD.Len(),
ctx.Series("cot").Len(), ctx.Series("gdp").Len(), oldest(cotD), oldest(gdpD))
}
func (s *AlignPanel) flatten(ctx *algolang.Context, bar algolang.Bar) []algolang.Order {
if qty := ctx.Position(bar.Symbol).Quantity; qty > 0 {
return []algolang.Order{algolang.MarketSell(bar.Symbol, qty).Named("LX")}
}
return nil
}
func main() {
if err := algolang.Run(&AlignPanel{}); err != nil {
fmt.Fprintln(os.Stderr, "alignpanel:", err)
os.Exit(1)
}
}Complete source: gdprevision
The numbered reading notes below explain the complete program; the inline comments describe individual steps. Keep all the listed files together. MODULE means the module path printed by go list -m in this checkout.
DataRequirementsasks for observations, preserving reference period, publication time, vintage, revision and withdrawal information.The strategy constructs its GDP signal from the values known at the current decision. A revised past period may change today’s signal without changing the original past decision.
The lookups and guards distinguish an unavailable value from zero growth. This matters when a vintage withdraws a value.
Build the supplied files directly:
go build -o bin/gdprevision ./strategies/demo/go/gdprevision
bin/gdprevision --algolang-describeThis program requires engine capabilities. The current standalone --algolang-selftest offers none, so it intentionally refuses this program during negotiation. Inspect its inputs with --algolang-describe and use the chapter’s engine run to exercise it; do not remove the capability requirement to make a standalone probe pass.
gdprevision/main.go
// Command gdprevision is a runnable example of revision-aware observations
// (GLE-408): it trades ES on GDP growth as it was known before each close,
// revisions applied.
//
// Besides its daily bars the strategy declares one market-event series, "gdp":
// the OBSERVATIONS of macro:FRED:GDP, every published value of every quarter,
// first releases and revisions alike, each delivered at the instant it became
// public (strictly before the first bar whose close follows it). At each close
// the strategy takes the latest quarter whose value is known, and its growth
// over the quarter before as both stood in the same vintage, annualised. It is
// long when that growth is at or above Threshold percent and flat otherwise.
//
// A first-release series (the BARS read of macro:FRED:GDP) would keep each
// quarter at its advance estimate for ever. Here every revision moves the
// estimate the strategy sees from the instant it was published, and the
// annual update, which revises years of quarters at once, reaches it in one
// delivery. The log line of each close records the quarter, its revision, the
// growth and the latest revision's surprise.
//
// Run it with make run-gdprevision, which replays the daily bars of a dated ES
// contract and GDP's vintages from the marketfeed archive.
package main
import (
"errors"
"fmt"
"math"
"os"
"time"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
)
// GDPRevision is long ES while the latest known quarter's annualised GDP growth
// is at least Threshold percent.
type GDPRevision struct {
Threshold float64 `algolang:"default=2,min=-50,max=50,desc=Annualised GDP growth (percent) at or above which the strategy is long"`
Qty int `algolang:"default=1,min=1,max=1000,desc=Contracts when long"`
// symbol is the contract being traded, recorded by OnInit.
symbol string
// The signal of the delivered history, and the history's length when it was computed. At a
// bar every delivered observation is already public, so the signal changes only when the
// history grows: it is recomputed then, not on every bar.
known int
point kit.ObsPoint
growth, surprise float64
growthOK, surpriseOK bool
}
// Name returns the display name of the strategy.
func (s *GDPRevision) Name() string { return "GDP Revision" }
// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. Its orders are market orders alone, so the
// one-bar rule (OneBarRule) ends none of them.
func (s *GDPRevision) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does; it exempts market orders.
func (s *GDPRevision) OneBarRule() bool { return true }
// Description returns a one-sentence summary of the strategy.
func (s *GDPRevision) Description() string {
return "Long ES while GDP growth as known before the close, revisions applied, is at or above a threshold."
}
// OnInit records the traded contract, the first configured instrument.
func (s *GDPRevision) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
if len(cfg.Instruments) == 0 {
return errors.New("gdprevision: no instrument configured")
}
s.symbol = cfg.Instruments[0].Symbol
return nil
}
// Lookback is the number of bars the strategy needs: the current one.
func (s *GDPRevision) Lookback() int { return 1 }
// DataRequirements declares GDP's observations ("gdp"). The buffer keeps the
// last 8 delivered; the strategy reads the whole delivered history through
// ctx.Observations.
func (s *GDPRevision) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{
{SeriesID: "gdp", Symbol: "macro:FRED:GDP", Schema: algolang.DataSchemaSpec{Kind: algolang.Observations}, Lookback: 8},
}
}
// signal is the series as known at t: the latest quarter with a known value,
// its annualised growth over the quarter before in the same vintage (percent),
// and the latest revision's surprise. ok is false until a quarter and the one
// before it are both known.
func signal(h algolang.ObservationHistory, t time.Time) (p kit.ObsPoint, growthPct float64, ok bool, surprise float64, surpriseOK bool) {
p, ok = kit.ObsLatestKnown(h, t)
if !ok {
return p, 0, false, 0, false
}
surprise, surpriseOK = kit.ObsRevisionSurprise(h, p.Ref, t)
g, gok := kit.ObsGrowth(h, kit.PeriodQuarter, p.Ref, 1, t)
if !gok {
return p, 0, false, surprise, surpriseOK
}
return p, (math.Pow(1+g, 4) - 1) * 100, true, surprise, surpriseOK
}
// decide is the pure decision: qty when the growth is known and at or above
// threshold, else flat.
func decide(qty int64, growthPct float64, ok bool, threshold float64) int64 {
if ok && growthPct >= threshold {
return qty
}
return 0
}
// OnBar works out the wanted position from GDP as known before this close and
// returns one market order when that differs from the current position.
func (s *GDPRevision) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if bar.Symbol != s.symbol {
return nil, nil
}
h, _ := ctx.Observations("gdp")
if h.Len() != s.known {
s.point, s.growth, s.growthOK, s.surprise, s.surpriseOK = signal(h, bar.CloseTime)
s.known = h.Len()
}
p, growth, ok, surprise, surpriseOK := s.point, s.growth, s.growthOK, s.surprise, s.surpriseOK
pos := ctx.Position(bar.Symbol).Quantity
want := decide(int64(s.Qty), growth, ok, s.Threshold)
ref := ""
if !p.Ref.IsZero() {
ref = p.Ref.Format("2006-01-02")
}
ctx.Logf("gdprevision: %s close=%.2f ref=%s rev=%d gdp=%.3f growth_pct=%.4f ok=%t surprise=%.3f surprise_ok=%t known=%d pos=%d target=%d",
bar.CloseTime.Format(time.RFC3339), bar.Close, ref, p.Revision, p.Value, growth, ok, surprise, surpriseOK, h.Len(), pos, want)
if want == pos {
return nil, nil
}
var order algolang.Order
if want > pos {
order = algolang.MarketBuy(bar.Symbol, want-pos).Named("LE")
} else {
order = algolang.MarketSell(bar.Symbol, pos-want).Named("LX")
}
order.ClientID = fmt.Sprintf("gdprevision_%d", bar.CloseTime.UnixNano())
return []algolang.Order{order}, nil
}
func main() {
if err := algolang.Run(&GDPRevision{}); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}Previous: A trend filtered by positioning and unemployment · Next: A cross-exchange trend: New York and London clocks