An intraday crossover with an hourly trend
The next strategy still trades one symbol, but watches two clocks. multiseries trades primary-bar SMA crosses only while its coarser series has an upward slope. It is long-or-flat, unlike our first long/short example.
First exercise the declaration with the bundled tape:
bin/algo run \
--adapter bin/databento-adapter \
--adapter-inputs Path=testdata/xnas-sample/xnas-itch-20220610.trades.csv \
--data-protocol pb --strategy bin/multiseries \
--symbols MSFT --bar-interval 1m \
--inputs Symbol=MSFT,Trend=5m,Fast=3,Slow=8 \
--commission-per-share 0.005 --slippage-ticks 1 --cache offThis short sample is a visibility exercise and may not produce useful trades. On a populated archive, use eq:XNAS:MSFT for both --symbols and the Symbol input, a 5m primary, Trend=1h, --session rth, explicit dates, and bin/marketfeed-adapter. Supplying matching symbols is necessary: the demo’s default input is the fixture name MSFT.
Declare the second interval inside the strategy
The implemented method is:
func (m *MultiSeries) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "trend", Symbol: m.Symbol, Lookback: m.Slow + 1,
Schema: algolang.DataSchemaSpec{
Kind: algolang.Bars, BarKind: algolang.BarsTime,
Interval: m.Trend,
},
}}
}The engine loads it before trading starts and makes it available as ctx.Series("trend"). This is strategy-driven loading: a declaration during initialization, not an arbitrary fetch from inside OnBar. A second interval for an already configured symbol is a refinement, so it does not require permission to add a new tradeable instrument.
Lookback() sizes the primary; each declaration sizes its own buffer. Schema.Session can select a different session; empty inherits the run’s. Set BarKind: BarsTime explicitly when declaring time bars beside a run using another construction.
The important callback guard is:
if !ctx.IsPrimary(bar) {
return nil, nil
}
primary := ctx.Series(ctx.PrimarySymbol())
trend := ctx.Series("trend")
if primary.Len() < m.Slow+1 || trend.Len() < 2 {
return nil, nil
}
up := trend.Close(0) >= trend.Close(1)A coarser bar updates history; it does not independently trigger an entry. Between hourly closes, the latest completed hour remains the filter. Requiring trend.Fresh() on every five-minute decision would instead allow trades only when an hourly bar also closes. Choose deliberately between “use the latest completed value” and “act only on a new reference value”.
Configure multiple intervals outside the strategy
A run’s series list is the other way to specify multiple clocks:
{
"global": {
"strategy": "bin/printbars",
"data": {
"adapter": "bin/databento-adapter",
"inputs": {"Path": "testdata/xnas-sample/xnas-itch-20220610.trades.csv"},
"data-protocol": "pb"
}
},
"runs": [{
"id": "two-clocks",
"series": [
{"symbol": "MSFT", "bar-interval": "1m"},
{"symbol": "MSFT", "bar-interval": "5m"}
]
}]
}Save as examples/learning/two-clocks.json; run bin/algo run --config examples/learning/two-clocks.json to inspect delivery. Use a strategy designed for these series: the original crossover would trade both clocks. Avoid duplicate declarations and use named IDs where possible. This pattern works on equities and dated futures. Two clocks of the same continuous holding have extra restrictions; Triple Screen demonstrates the resampling alternative. Source to study: strategies/demo/go/multiseries/main.go.
Complete source: multiseries
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.
DataRequirementsdeclares the additional hourly series with its own identity and history depth. The primary and reference clocks are independent.OnBargates decisions on the intended primary and checks the reference before using its trend. A buffered reference close is not automatically fresh at this decision.The final orders reconcile the desired direction with actual position. The shared
kithelpers are imported library code, not missing files from this program.
Build the supplied files directly:
go build -o bin/multiseries ./strategies/demo/go/multiseries
bin/multiseries --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.
multiseries/main.go
// Command multiseries is the reference DataRequirer demo (Section 7.13). It
// declares a coarser "trend" bar series for its symbol IN ADDITION to the
// config-provided primary series, then trades the primary gated on the trend's
// direction -- exercising the init-driven data-declaration path end to end:
// the engine fetches and folds in the declared series, delivers both with their
// series_id, and (because the strategy declares data) pushes the resolved
// instrument universe so ctx.Instrument is populated and OnUniverseResolved fires.
//
// The declared trend interval defaults to 5m; the config primary is whatever the
// run requests (the demo target uses MSFT @ 1m). The trend series shares the
// primary's symbol, so it is a REFINEMENT (a new interval of a configured symbol),
// not a universe expansion -- it runs under any universe-expansion policy.
package main
import (
"fmt"
"os"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
)
var buildID string
type MultiSeries struct {
Symbol string `algolang:"default=MSFT,desc=Symbol to trade (must match the run's configured symbol)"`
Trend string `algolang:"default=1h,desc=Interval of the declared coarser trend series"`
Fast int `algolang:"default=3,min=2,max=200,desc=Fast SMA period on the primary series"`
Slow int `algolang:"default=8,min=3,max=400,desc=Slow SMA period on the primary series"`
resolved bool
bars int
traded int
}
func (m *MultiSeries) Name() string { return "MultiSeries" }
// 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 (m *MultiSeries) 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 (m *MultiSeries) OneBarRule() bool { return true }
func (m *MultiSeries) Description() string {
return "Declares a coarser trend series and trades the primary series gated on it (DataRequirer demo)."
}
// DataRequirements declares the extra coarser trend series (Section 7.13.3).
// Implementing DataRequirer sets InitAck.needs_instruments, so the engine pushes
// the resolved universe and OnUniverseResolved fires.
func (m *MultiSeries) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "trend",
Symbol: m.Symbol,
Lookback: m.Slow + 1,
Schema: algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: m.Trend},
}}
}
// Lookback sizes the PRIMARY (config) series buffer.
func (m *MultiSeries) Lookback() int { return m.Slow + 1 }
// OnUniverseResolved confirms the resolved-universe push arrived and ctx.Instrument
// is populated (Section 7.13.5). Informational; returning nil accepts the run.
func (m *MultiSeries) OnUniverseResolved(ctx *algolang.Context) error {
ii := ctx.Instrument(m.Symbol)
ctx.Logf("multiseries: universe resolved; %s exchange=%q asset=%q tick=%v", m.Symbol, ii.ExchangeMIC, ii.AssetClass, ii.TickSize)
m.resolved = true
return nil
}
func (m *MultiSeries) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
m.bars++
// A trend bar only updates its series: decisions are made on primary
// bars. The primary series is keyed by its symbol (a primary bar carries
// no series id of its own, so ctx.Series(bar.SeriesID) would read an
// empty buffer and the demo would never trade, GLE-467 B8).
if !ctx.IsPrimary(bar) {
return nil, nil
}
prim := ctx.Series(ctx.PrimarySymbol())
trend := ctx.Series("trend")
if prim.Len() < m.Slow+1 || trend.Len() < 2 {
return nil, nil
}
// Trade the primary only on a fresh primary bar; gate on the trend's slope.
if !prim.Fresh() {
return nil, nil
}
closes := indicators.Closes(prim)
fast := closes.SMA(m.Fast)
slow := closes.SMA(m.Slow)
up := trend.Close(0) >= trend.Close(1) // coarse-series uptrend
dir := ctx.Position(bar.Symbol).Quantity
switch {
case up && fast.CrossesAbove(slow) && dir <= 0:
m.traded++
return []algolang.Order{algolang.MarketBuy(bar.Symbol, 1).Named("LE")}, nil
case (!up || fast.CrossesBelow(slow)) && dir > 0 && !kit.Exiting(ctx, bar.Symbol): // the exit-once gate (GLE-467)
m.traded++
return []algolang.Order{algolang.MarketSell(bar.Symbol, 1).Named("LX")}, nil
}
return nil, nil
}
func (m *MultiSeries) OnShutdown(ctx *algolang.Context) {
fmt.Fprintf(os.Stderr, "[multiseries] bars=%d trades=%d universe_resolved=%v\n", m.bars, m.traded, m.resolved)
}
func main() {
if err := algolang.Run(&MultiSeries{}); err != nil {
fmt.Fprintln(os.Stderr, "multiseries:", err)
os.Exit(1)
}
}Complete source: printbars
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.
This is the complete observer used by the two-clock configuration. It exposes what arrived without adding trading rules.
symbolExchangeMICandexchangeTZselect a display zone; the underlying timestamps still represent absolute instants. The mapping is a demonstration, not an exhaustive exchange registry.barLinecontrols display, including settlement information when requested.OnShutdownreports the count of decision bars, excluding warm-up decisions that never ran.
Build the supplied files directly:
go build -o bin/printbars ./strategies/demo/go/printbars
bin/printbars --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.
printbars/main.go
// Command printbars is the hello-world Algolang strategy: it prints every
// bar it receives to stderr and never trades. Stdout belongs to the wire
// protocol; all human output goes to stderr.
package main
import (
"fmt"
"os"
"strings"
"time"
_ "time/tzdata" // embed the IANA tz database so time.LoadLocation works anywhere
algolang "MODULE/sdk/strategy"
)
// buildID is stamped by the Makefile via -ldflags.
var buildID string
type PrintBars struct {
Print bool `algolang:"default=true,desc=Print each bar to stderr"`
Every int `algolang:"default=1,min=1,desc=Print every Nth bar"`
Settle bool `algolang:"default=false,desc=Append a session bar's exchange settlement (settle=<price>, or settle=none when the bar arrived without one)"`
n int
}
func (p *PrintBars) Name() string { return "Print Bars" }
func (p *PrintBars) Description() string {
return "Prints every bar it receives; the hello-world strategy."
}
// 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 (p *PrintBars) 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 (p *PrintBars) OneBarRule() bool { return true }
// exchangeTZ maps an exchange MIC to its IANA trading timezone. CME Group venues
// (Globex, CBOT, NYMEX, COMEX) keep Central Time; the major US equity / ICE-US
// venues Eastern; a few others as noted. The publishers of release-stamped
// series (cot:CFTC:..., macro:FRED:..., fx:RBA:...) map to the zone they
// release in. An unknown or empty MIC falls back to UTC.
func exchangeTZ(mic string) *time.Location {
var name string
switch strings.ToUpper(mic) {
case "XCME", "XCBT", "XNYM", "XCEC", "GLBX", "CMES":
name = "America/Chicago"
case "XNYS", "XNAS", "ARCX", "BATS", "XASE", "IEXG", "IFUS", "CFTC", "FRED":
name = "America/New_York"
case "RBA":
name = "Australia/Sydney"
case "IFEU", "XLON":
name = "Europe/London"
case "XEUR", "XETR":
name = "Europe/Berlin"
default:
return time.UTC
}
loc, err := time.LoadLocation(name)
if err != nil {
return time.UTC
}
return loc
}
// symbolExchangeMIC resolves the exchange MIC for a bar: the resolved
// InstrumentInfo when the engine populated it, else the venue parsed from a
// namespaced futures symbol "class:VENUE:ticker[:qualifier]" (e.g. "fut:XCME:ES",
// the logical symbol of a bare-root continuous-futures run).
func symbolExchangeMIC(ctx *algolang.Context, bar algolang.Bar) string {
if mic := ctx.Instrument(bar.Symbol).ExchangeMIC; mic != "" {
return mic
}
if parts := strings.Split(bar.Symbol, ":"); len(parts) >= 3 && parts[1] != "" {
return parts[1]
}
return ""
}
func (p *PrintBars) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
p.n++
every := p.Every
if every < 1 {
every = 1
}
if p.Print && p.n%every == 0 {
// On a continuous-futures run the strategy trades the logical root (bar.Symbol,
// e.g. "fut:XCME:ES") but each bar names the underlying DATED contract live for
// that session in bar.ActiveContract (e.g. "ESM26"). Print the dated contract
// when present, falling back to the logical/plain symbol otherwise.
sym := bar.ActiveContract
if sym == "" {
sym = bar.Symbol
}
fmt.Fprintln(os.Stderr, barLine(p.n, sym, bar, exchangeTZ(symbolExchangeMIC(ctx, bar)), p.Settle))
}
return nil, nil
}
// barLine formats one bar: its open and close in the TIMEZONE OF THE SYMBOL'S
// EXCHANGE (e.g. America/Chicago for CME's XCME), showing the zone
// abbreviation + offset, then OHLCV and, with settle, the session settlement.
func barLine(n int, sym string, bar algolang.Bar, loc *time.Location, settle bool) string {
const stamp = "2006-01-02T15:04:05 MST (-07:00)"
line := fmt.Sprintf("[bar %d] %s open=%s close=%s O=%g H=%g L=%g C=%g V=%g",
n, sym, bar.OpenTime.In(loc).Format(stamp), bar.CloseTime.In(loc).Format(stamp),
bar.Open, bar.High, bar.Low, bar.Close, bar.Volume)
if settle && bar.Session != nil {
// The settlement rides on the bar only when it had been published by
// the bar's close (GLE-415); otherwise the bar carries none.
if bar.Session.HasSettle {
line += fmt.Sprintf(" settle=%g", bar.Session.Settle)
} else {
line += " settle=none"
}
}
if !bar.Ref.IsZero() {
// A release-stamped bar (COT, FRED, RBA) closes when its value was first
// public; Ref is the period the value describes (GLE-261). lag is the
// calendar days between them, so a late release (a holiday week, a
// shutdown catch-up) stands out against the series' usual lag.
c := bar.CloseTime.In(loc)
day := time.Date(c.Year(), c.Month(), c.Day(), 0, 0, 0, 0, time.UTC)
line += fmt.Sprintf(" ref=%s lag=%dd", bar.Ref.Format("2006-01-02"), int(day.Sub(bar.Ref).Hours()/24))
}
return line
}
func (p *PrintBars) OnShutdown(ctx *algolang.Context) {
fmt.Fprintf(os.Stderr, "[printbars] received %d bars total\n", p.n)
}
func main() {
if err := algolang.Run(&PrintBars{}); err != nil {
fmt.Fprintln(os.Stderr, "printbars:", err)
os.Exit(1)
}
}Previous: The crossover with a drawdown brake · Next: A trend filtered by positioning and unemployment