A trend filtered by positioning and unemployment
cotcarry adds other symbols inside the strategy. It holds one ES lot when the daily close is above its 50-day SMA, the latest leveraged-funds COT positioning is in the lower half of its 26-report range, and unemployment is no higher than three releases earlier. Otherwise it is flat.
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/cotcarry --symbols fut:XCME:ES --bar-interval 1d \
--date-from 2018-01-01 --date-to 2024-12-31 \
--commission-per-share 2.50 --slippage-ticks 1 \
--results-dir results/learning/cotcarryThe primary is a continuous future; for now, treat it as a logical instrument. The roll chapter explains what happens underneath it. This run also requires macro:FRED:UNRATE and cot:CFTC:13874A:LF history.
Reference symbols are not automatically tradeable
In the default net-positioning mode the declarations are equivalent to:
weekly := algolang.DataSchemaSpec{
Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1w",
}
reqs := []algolang.DataRequirement{
{SeriesID: "jobless", Symbol: s.Jobless, Lookback: 4,
Schema: weekly},
{SeriesID: "cot", Symbol: s.COT, Lookback: s.COTWindow,
Schema: weekly},
}Here 1w is the declaration convention for release-stamped series. It does not turn monthly unemployment into fabricated weekly observations. Lookback counts actual releases. Force the protobuf data wire: automatic negotiation happens before declarations, and DBN cannot carry this declared 1w series.
Algolang separates the data universe from the venue universe. By default, universe-expansion=reference-only permits these extra references but denies orders on them. off refuses new-symbol expansion. full permits a new tradeable symbol only when the strategy also declares it as tradeable and provides its bar series. Term carry demonstrates that step.
For an archive-free inspection of reference loading, make run-refexpand uses the supplied AAA/BBB daily fixture. refexpand logs the newly loaded reference and places no orders. Its OnUniverseResolved callback illustrates when ctx.Instrument(reference) becomes available. Keep such validation out of callbacks that run before the resolved metadata arrives.
Publication time versus the period described
A report may describe Tuesday’s positions and arrive on Friday. Friday is the information boundary. A monthly observation similarly has a publication timestamp and a Ref identifying the month it describes. Strategies must not move the value back to that month when constructing signals.
cotcarry also accepts --inputs Crowding=ratio. It then loads the long and short report components and ranks their ratio instead of net positioning. The example demonstrates that two related symbols can express a different economic hypothesis even when their timestamps match.
When comparing annual changes, use reference periods, not “twelve rows ago”. Missing reports and delayed releases break that equivalence. The cpigate demo uses kit.RefValue and kit.ShiftRef to match CPI months a year apart, and declines to invent a value for a missing month. The archive’s historical release dates and first-release coverage still matter: an estimated date is not proof of the exact instant the market learned a number. Source to study: strategies/demo/go/cotcarry/main.go, strategies/demo/go/refexpand/main.go and strategies/demo/go/cpigate/main.go.
Complete source: cotcarry
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.
DataRequirementsadds positioning and unemployment data while the primary remains the traded instrument. The declaration makes those inputs part of the reproducible run.OnBarfirst checks usable history, then combines the primary trend with the latest available reference values. Release availability determines what the strategy can know.The order logic targets the primary only. Loading another symbol’s data does not grant permission to trade it.
Build the supplied files directly:
go build -o bin/cotcarry ./strategies/demo/go/cotcarry
bin/cotcarry --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.
cotcarry/main.go
// Command cotcarry is the example of declarations on a continuous run
// (docs/algolang.md, "Declaring extra data on a continuous run", GLE-392):
// it trades the continuous E-mini S&P 500 daily series fut:XCME:ES and
// declares two release-stamped references beside it, the weekly CFTC
// leveraged-funds positioning in E-mini S&P 500 futures and the monthly US
// unemployment rate.
//
// It holds one ES lot while the adjusted daily close is above its Window-day
// SMA, the newest COT report sits in the lower half of its range over the
// last COTWindow reports (leveraged funds are not crowded long), and the
// newest unemployment release is no higher than the one three releases
// before it. It is flat otherwise. Every order is a market order on the
// logical symbol; the engine fills it on the held contract and rolls it.
//
// Each release reaches the strategy as a bar of its own series at its
// release time, so a decision on a daily close sees only the releases known
// by then. A run on a dated contract would do the same; on the continuous
// series it no longer needs to be one contract at a time.
//
// With Crowding=ratio (GLE-413) the positioning test reads the category's
// long and short positions instead of its net: it declares the two legs of
// the COT group (cot:CFTC:13874A:LF-L and LF-S) and places the newest
// long/short ratio (kit.LongShortRatio) in its range over COTWindow reports.
// The net says how far leveraged funds lean; the ratio says how one-sided
// they are, which the net hides when both legs grow together.
package main
import (
"fmt"
"math"
"os"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
)
var buildID string
// COTCarry is the strategy's inputs and state.
type COTCarry struct {
COT string `algolang:"default=cot:CFTC:13874A:LF,desc=Release-stamped COT series (E-mini S&P 500 leveraged funds net)"`
Jobless string `algolang:"default=macro:FRED:UNRATE,desc=Release-stamped monthly unemployment rate"`
Window int `algolang:"default=50,min=2,max=500,desc=Daily closes in the trend SMA"`
COTWindow int `algolang:"default=26,min=4,max=520,desc=COT reports in the positioning range"`
Crowding string `algolang:"default=net,desc=Positioning measure: net (the group's net) or ratio (its long/short ratio from the two legs)"`
}
func (s *COTCarry) Name() string { return "COT carry" }
// 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 *COTCarry) 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 *COTCarry) OneBarRule() bool { return true }
func (s *COTCarry) Description() string {
return "Continuous ES trend gated on COT positioning and the unemployment trend (declarations on a continuous run)."
}
// Lookback sizes the primary's buffer for the SMA.
func (s *COTCarry) Lookback() int { return s.Window + 1 }
// OnInit checks the positioning measure.
func (s *COTCarry) OnInit(_ *algolang.Context, _ algolang.InitConfig) error {
if s.Crowding != "net" && s.Crowding != "ratio" {
return fmt.Errorf("Crowding %q: want net or ratio", s.Crowding)
}
return nil
}
// DataRequirements declares the release series at 1w, as release-stamped
// series are declared; each Lookback counts releases. Under Crowding=ratio
// the COT group's long and short legs replace its net.
func (s *COTCarry) DataRequirements() []algolang.DataRequirement {
weekly := algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1w"}
reqs := []algolang.DataRequirement{{SeriesID: "jobless", Symbol: s.Jobless, Lookback: 4, Schema: weekly}}
if s.Crowding == "ratio" {
return append(reqs,
algolang.DataRequirement{SeriesID: "cotlong", Symbol: s.COT + "-L", Lookback: s.COTWindow, Schema: weekly},
algolang.DataRequirement{SeriesID: "cotshort", Symbol: s.COT + "-S", Lookback: s.COTWindow, Schema: weekly},
)
}
return append(reqs, algolang.DataRequirement{SeriesID: "cot", Symbol: s.COT, Lookback: s.COTWindow, Schema: weekly})
}
// OnBar decides on each daily ES close; a release bar only updates its
// series, which the next daily decision reads.
func (s *COTCarry) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.IsPrimary(bar) {
return nil, nil
}
prim := ctx.Series(ctx.PrimarySymbol())
if prim.Len() < s.Window {
return nil, nil
}
trendUp := prim.Close(0) > indicators.Closes(prim).SMA(s.Window).Value()
var index float64
if s.Crowding == "ratio" {
index = ratioRangeIndex(ctx.Series("cotlong"), ctx.Series("cotshort"), s.COTWindow)
} else {
index = rangeIndex(ctx.Series("cot"), s.COTWindow)
}
jobless := ctx.Series("jobless")
easing := jobless.Len() >= 4 && jobless.Close(0) <= jobless.Close(3)
long := trendUp && index <= 0.5 && easing // false while index is NaN
qty := ctx.Position(bar.Symbol).Quantity
switch {
case long && qty == 0:
return []algolang.Order{algolang.MarketBuy(bar.Symbol, 1).Named("LE")}, nil
case !long && qty > 0:
return []algolang.Order{algolang.MarketSell(bar.Symbol, qty).Named("LX")}, nil
}
return nil, nil
}
// rangeIndex places the newest value between the lowest and highest of the
// last n: 0 at the low, 1 at the high. NaN until n values are known or when
// they are all equal.
func rangeIndex(s algolang.Series, n int) float64 {
if s.Len() < n {
return math.NaN()
}
lo, hi := math.Inf(1), math.Inf(-1)
for i := range n {
v := s.Close(i)
lo, hi = math.Min(lo, v), math.Max(hi, v)
}
if hi == lo {
return math.NaN()
}
return (s.Close(0) - lo) / (hi - lo)
}
// ratioRangeIndex places the newest long/short ratio between the lowest and
// highest of the last n reports, as rangeIndex does for a net. The two legs
// are released together, so their i-th values are the same report's. NaN
// until n reports of both are known, when a report's short is not positive,
// or when the ratios are all equal.
func ratioRangeIndex(long, short algolang.Series, n int) float64 {
if long.Len() < n || short.Len() < n {
return math.NaN()
}
lo, hi, newest := math.Inf(1), math.Inf(-1), math.NaN()
for i := range n {
r, ok := kit.LongShortRatio(long.Close(i), short.Close(i))
if !ok {
return math.NaN()
}
if i == 0 {
newest = r
}
lo, hi = math.Min(lo, r), math.Max(hi, r)
}
if hi == lo {
return math.NaN()
}
return (newest - lo) / (hi - lo)
}
func main() {
if err := algolang.Run(&COTCarry{}); err != nil {
fmt.Fprintln(os.Stderr, "cotcarry:", err)
os.Exit(1)
}
}Complete source: refexpand
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
Referenceinput names a symbol absent from the configured universe.DataRequirementsrequests it under the stable series IDref.OnUniverseResolvedreads the resulting instrument metadata before bars arrive. This is where a strategy can reject unsuitable resolved data.OnBarandOnShutdownmake the expansion observable. There are no orders: the extra symbol remains data-only under reference-only expansion.
Build the supplied files directly:
go build -o bin/refexpand ./strategies/demo/go/refexpand
bin/refexpand --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.
refexpand/main.go
// Command refexpand is the reference-universe-EXPANSION demo (Section 7.13.2,
// 7.13.11). It declares a data-only "ref" bar series for a symbol that is NOT in
// the run's configured universe -- the modern analogue of the old div50csv
// pattern (a strategy reading extra symbols' data while trading only its
// configured primary). The engine expands the DATA universe to fetch and deliver
// the reference series (so ctx.Series("ref") is populated), but the reference
// symbol is NEVER admitted to the VENUE universe, so orders on it are denied:
// it is data-only. This runs under universe-expansion = reference-only (the
// default) or full; under "off" the engine rejects the expansion at startup.
package main
import (
"fmt"
"os"
algolang "MODULE/sdk/strategy"
)
var buildID string
type RefExpand struct {
Reference string `algolang:"default=BBB,desc=A data-only symbol to pull in that is NOT in the run config (a universe expansion)"`
bars int
refBars int
resolved bool
}
func (r *RefExpand) Name() string { return "RefExpand" }
// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. It places no order, so the one-bar rule
// (OneBarRule) has nothing to end.
func (r *RefExpand) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does.
func (r *RefExpand) OneBarRule() bool { return true }
func (r *RefExpand) Description() string {
return "Reference universe-expansion demo: declares a data-only series for a symbol not in the run config (div50csv-style)."
}
// DataRequirements declares a data-only series for a NEW symbol (Section 7.13.11).
// The symbol is not configured, so this is an EXPANSION (gated by the
// universe-expansion policy); because it is not declared tradeable, it stays
// data-only (orders on it are denied by the venue gate).
func (r *RefExpand) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "ref",
Symbol: r.Reference,
Lookback: 2,
Schema: algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1d"},
}}
}
func (r *RefExpand) OnUniverseResolved(ctx *algolang.Context) error {
r.resolved = true
ii := ctx.Instrument(r.Reference)
ctx.Logf("refexpand: universe resolved; reference %s exchange=%q asset=%q", r.Reference, ii.ExchangeMIC, ii.AssetClass)
return nil
}
func (r *RefExpand) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
r.bars++
ref := ctx.Series("ref")
if ref.Len() > 0 {
r.refBars++
ctx.Logf("refexpand: primary %s close=%.2f | reference %s close=%.2f (len %d)",
bar.Symbol, bar.Close, r.Reference, ref.Close(0), ref.Len())
}
// Data-only: this demo never trades the reference symbol (and the engine would
// deny such an order anyway, since it is not in the venue universe).
return nil, nil
}
func (r *RefExpand) OnShutdown(ctx *algolang.Context) {
fmt.Fprintf(os.Stderr, "[refexpand] bars=%d ref_bars=%d universe_resolved=%v\n", r.bars, r.refBars, r.resolved)
}
func main() {
if err := algolang.Run(&RefExpand{}); err != nil {
fmt.Fprintln(os.Stderr, "refexpand:", err)
os.Exit(1)
}
}Complete source: cpigate
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 CPI requirement is release-stamped data.
yearOnYearlocates the matching reference month a year earlier instead of assuming that twelve received records equal twelve calendar months.OnBarcombines the economic gate with the moving-average signal and flattens when the gate requires it.logNewReleasesrecords releases once, andreleaseCorrelationuses those release observations. Repeating a carried value on every price bar would change the sample being measured.
Build the supplied files directly:
go build -o bin/cpigate ./strategies/demo/go/cpigate
bin/cpigate --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.
cpigate/main.go
// Command cpigate is the worked example for "Lining up series" in
// docs/algolang.md (GLE-250, GLE-265): an hourly strategy on its primary (ES
// in the examples) that reads FRED's CPIAUCSL three ways.
//
// - Gate (stretch slow onto fast). At each hourly close it uses only the
// newest CPI release that closed at or before that close. A release
// stamped at exactly an hourly close is first seen at the next hourly
// bar, because the co-close order puts releases after the primary.
// - Release clock (sample fast on the slow clock). At each release it
// records the primary's last close at or before the release, and
// correlates the primary's returns between releases with CPI's changes.
// It never correlates carried-forward values.
// - Reference period. Year-on-year inflation divides the newest CPI by the
// value whose Ref is twelve months earlier, so the missing October 2025
// (never published) cannot shift the comparison by a month.
//
// It holds one contract long while the fast SMA is above the slow SMA and
// year-on-year CPI, as known at the close, is at or below MaxYoY, and is flat
// otherwise. The first hourly decision that sees each CPI release logs one
// line per release (several when a catch-up arrives between two hourly
// bars), which the engine prints on stderr and the regression test reads:
//
// cpigate: 2026-09-11T13:00:00Z sees CPI 2026-08 released 2026-09-11T12:30:00Z yoy=0.033297 corr=0.0649 n=12
//
// When last year's month has no row, yoy is NaN and the line names the
// missing month (year_ago=2025-10 missing); the strategy stays flat until a
// comparable month arrives.
//
// It declares a data series, so it runs on the protobuf wire (`make
// run-cpigate` runs it against the marketfeed adapter).
package main
import (
"fmt"
"math"
"os"
"time"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
)
var buildID string
type CPIGate struct {
CPI string `algolang:"default=macro:FRED:CPIAUCSL,desc=Release-stamped CPI series (its Ref is the month it describes)"`
MaxYoY float64 `algolang:"default=0.04,min=0,max=0.2,by=0.005,desc=Trade only while year-on-year CPI known at the close is at or below this"`
Fast int `algolang:"default=10,min=2,max=200,desc=Fast SMA period in primary bars"`
Slow int `algolang:"default=50,min=3,max=1000,desc=Slow SMA period in primary bars"`
CorrWindow int `algolang:"default=12,min=3,max=120,desc=Releases in the release-clock return correlation"`
clock *kit.ReleaseClock
lastLogged time.Time // CloseTime of the newest CPI release a primary decision has logged
}
func (s *CPIGate) Name() string { return "CPIGate" }
// 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 *CPIGate) 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 *CPIGate) OneBarRule() bool { return true }
func (s *CPIGate) Description() string {
return "Hourly SMA trend gated on year-on-year CPI as known at each close; logs the release-clock correlation (Lining up series example)."
}
// Lookback sizes the primary series buffer to the longer SMA.
func (s *CPIGate) Lookback() int { return max(s.Fast, s.Slow) + 1 }
// DataRequirements declares the CPI series at 1w, as release-stamped series
// are declared. Its Lookback counts releases (warm-up fetches that many
// rows): thirteen cover year on year, and the rest leave room for missing
// months and the correlation window.
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")
if s.clock == nil {
s.clock = kit.NewReleaseClock(s.CorrWindow + 1)
}
// The release clock observes at the end of every OnBar, for every
// series, so a primary bar closing at exactly a release instant is
// paired with that release whichever of the two the engine delivers
// first.
defer s.clock.Observe(cpi, prim)
if !ctx.IsPrimary(bar) {
return nil, nil
}
// Year on year by reference period: the newest CPI known at this close
// and the one describing the same month a year earlier. PeriodsAgo
// reports a missing month (naming it) instead of returning a neighbour.
latest, _, ok := kit.PeriodsAgo(cpi, kit.PeriodMonth, 0)
if !ok {
return s.flatten(ctx, bar), nil // no CPI release known yet
}
yoy := math.NaN() // the gate: year on year of the newest CPI known at this close
if yearAgo, _, ok12 := kit.PeriodsAgo(cpi, kit.PeriodMonth, 12); ok12 && yearAgo != 0 {
yoy = latest/yearAgo - 1
}
s.logNewReleases(ctx, bar, cpi)
if prim.Len() < max(s.Fast, s.Slow)+1 {
return nil, nil
}
closes := indicators.Closes(prim)
long := closes.SMA(s.Fast).Value() > closes.SMA(s.Slow).Value() && yoy <= s.MaxYoY // false when yoy 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
}
// yearOnYear is the CPI for ref divided by the CPI for the same month a year
// earlier, less one, both looked up by Ref. NaN when either month has no
// bar; yearAgo is then the year-ago month that is missing.
func yearOnYear(cpi algolang.Series, ref time.Time) (yoy float64, missing time.Time) {
now, ok := kit.RefValue(cpi, ref)
yearAgo, okShift := kit.ShiftRef(ref, kit.PeriodMonth, 12)
then, ok12 := kit.RefValue(cpi, yearAgo)
if !ok || !okShift || !ok12 || then == 0 {
if ok && okShift && !ok12 {
return math.NaN(), yearAgo
}
return math.NaN(), time.Time{}
}
return now/then - 1, time.Time{}
}
// logNewReleases logs one line for each CPI release this decision is the
// first to see, oldest first. Several can arrive between two primary bars
// (a catch-up after a shutdown is stamped a second apart, and the primary
// has no bar in an hour without trades). The first decision of a run logs
// only the newest release, the one it gates on.
func (s *CPIGate) logNewReleases(ctx *algolang.Context, bar algolang.Bar, cpi algolang.Series) {
if s.lastLogged.IsZero() && cpi.Len() > 1 {
s.lastLogged = cpi.Bar(1).CloseTime
}
corr, n := s.releaseCorrelation()
for i := cpi.Len() - 1; i >= 0; i-- { // oldest first
rel := cpi.Bar(i)
if !rel.CloseTime.After(s.lastLogged) {
continue
}
yoy, missing := yearOnYear(cpi, rel.Ref)
note := ""
if !missing.IsZero() {
note = " year_ago=" + missing.Format("2006-01") + " missing"
}
ctx.Logf("cpigate: %s sees CPI %s released %s yoy=%.6f corr=%.4f n=%d%s",
bar.CloseTime.UTC().Format(time.RFC3339), rel.Ref.Format("2006-01"),
rel.CloseTime.UTC().Format(time.RFC3339), yoy, corr, n, note)
}
s.lastLogged = cpi.Bar(0).CloseTime
}
// releaseCorrelation is the correlation of the primary's returns between
// consecutive releases with CPI's changes over the last CorrWindow releases,
// sampled on the release clock. NaN (and n = 0) until the clock holds
// CorrWindow+1 releases.
func (s *CPIGate) releaseCorrelation() (float64, int) {
if s.clock.Len() < s.CorrWindow+1 {
return math.NaN(), 0
}
cpiVals, primCloses := s.clock.Series()
return primCloses.ReturnCorrelation(cpiVals, s.CorrWindow, 1).Value(), s.CorrWindow
}
func (s *CPIGate) 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(&CPIGate{}); err != nil {
fmt.Fprintln(os.Stderr, "cpigate:", err)
os.Exit(1)
}
}Previous: An intraday crossover with an hourly trend · Next: A trend using an aligned economic panel