A dated calendar spread with combo orders
calspread trades the difference between two dated ES contracts. It pairs bars at the same instant, calculates a rolling z-score and returns a single combo order whose legs fill together in the simulator.
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/calspread --lifetime v2 \
--symbols fut:XCME:ES:H26,fut:XCME:ES:M26 --bar-interval 1d \
--inputs Front=fut:XCME:ES:H26,Next=fut:XCME:ES:M26 \
--date-from 2025-12-15 --date-to 2026-03-13 \
--commission-per-share 2.50 --slippage-ticks 1 \
--results-dir results/learning/calspreadUse common coverage before expiry unless testing expiry handling. The model warms from paired main observations; SDK series warm-up does not seed its private rolling window.
The spread is next minus front. Its buy side is:
legs := []algolang.ComboLeg{
algolang.BuyLeg(s.Next, 1),
algolang.SellLeg(s.Front, 1),
}
order := algolang.ComboMarket(algolang.Buy, int64(s.Units), legs...)The strategy requires CapabilityLifetimeV2 and CapabilityComboOrders. This differs from returning two independent orders. Inspect leg fills, combo trades and costs together.
Support requires a lifetime-v2 protobuf backtest with dated futures legs, no continuous series and no live combo ticket. Margin has no spread credit. Pricing uses a supported kept exchange spread, otherwise the legs’ observations; atomic simulation does not establish liquidity at that price.
Marketfeed spr: expressions and exchange spread series are data references. Trade admitted legs or an eligible combo. Check units: a crack spread can mix dollars per barrel and per gallon. Source to study: strategies/demo/go/calspread/.
Select December and March explicitly
This is a complete, archive-tested example of trading two contracts beyond the default front holding, using the same annotated calspread source below. It requires their dated histories, not a derived B2 composite.
Front and Next are input names for the two legs; they do not constrain the nearer leg to the market’s current front month. The following run selects December 2026 and March 2027 while the continuous root’s served holding is still September. Both traded legs therefore lie beyond that default holding.
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/calspread --lifetime v2 \
--symbols fut:XCME:ES:Z26,fut:XCME:ES:H27 --bar-interval 1d \
--inputs Front=fut:XCME:ES:Z26,Next=fut:XCME:ES:H27,Window=20,Log=true \
--date-from 2026-08-03 --date-to 2026-09-11 \
--commission-per-share 2.50 --slippage-ticks 1 \
--plate full --color never --chart lines \
--fills-json results/learning/deferred-combo-fills.json \
--results-dir results/learning/deferred-comboThe spread here is March minus December. Buying it buys one March contract and sells one December; selling it reverses those sides. This sign convention differs from termcarry’s long-near/short-far carry position. The complete ComboLeg construction below makes the convention explicit. Match it to the report before comparing the two strategies’ P&L.
These contracts remain December and March for the whole run; there is no automatic selection of the next pair. The window must contain sufficient overlapping data for both legs, and a study extending toward expiry needs an explicit exit or pair-selection policy. Combo execution here is a supported backtest facility, not a claim of continuous-series or live combo support.
Complete source: calspread
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.
RequiredCapabilitiesmakes combo support a startup requirement.main.gobuilds one combo from dated legs, whilespread.godefines the pairing and z-score model.Pairercompletes each instant once. The model observes next minus front and applies entry and exit bands after enough varying observations exist.The pure model advances its own side when it decides, as though the action filled. That is an explicit demo assumption: a production implementation must reconcile rejection and actual fills.
Build the supplied files directly:
go build -o bin/calspread ./strategies/demo/go/calspread
bin/calspread --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.
calspread/main.go
// Command calspread is the example of a combo order (docs/algolang.md,
// "Combo orders", GLE-409): an E-mini S&P 500 calendar-spread mean reversion
// on two dated contracts, the front fut:XCME:ES:H26 and the next
// fut:XCME:ES:M26, traded as one IBKR-style combo so that both legs fill
// together or not at all.
//
// On each instant at which both contracts have a bar it takes the spread
// (next close - front close) and its z-score over Window instants
// (spread.go). It buys the spread (buy the next, sell the front) when the
// z-score falls to -EntryZ, sells it when it rises to +EntryZ, and closes
// the open spread when the z-score returns within ExitZ of zero. Each is one
// market combo order; the simulator fills its two legs at the next instant's
// opens, together.
//
// A combo needs order lifetime v2 and the combo-orders capability, which the
// strategy requires: run it with --lifetime v2 (make run-calspread).
package main
import (
"fmt"
"os"
algolang "MODULE/sdk/strategy"
)
var buildID string
// CalSpread is the strategy: its inputs, and the model and pairing state.
type CalSpread struct {
Front string `algolang:"default=fut:XCME:ES:H26,desc=The front leg (a dated contract)"`
Next string `algolang:"default=fut:XCME:ES:M26,desc=The next leg (a dated contract)"`
Window int `algolang:"default=20,min=2,max=500,desc=Instants in the spread's rolling z-score"`
EntryZ float64 `algolang:"default=1.5,min=0,desc=Enter when the z-score reaches this either side"`
ExitZ float64 `algolang:"default=0.5,min=0,desc=Close the spread when the z-score is within this of zero"`
Units int `algolang:"default=1,min=1,desc=Combo units per spread (one contract of each leg per unit)"`
Log bool `algolang:"default=false,desc=Print each decision to stderr"`
model *Model
pair Pairer
seq int
}
func (s *CalSpread) Name() string { return "Calendar spread" }
func (s *CalSpread) Description() string {
return "ES front/next calendar-spread mean reversion, traded as one combo order (GLE-409)."
}
// RequiredCapabilities asks for order lifetime v2, the one order lifetime
// (GLE-1906), and combo orders.
func (s *CalSpread) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2, algolang.CapabilityComboOrders}
}
// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does. Its orders are combo market orders, which the rule
// exempts, so it ends none of them.
func (s *CalSpread) OneBarRule() bool { return true }
// OnInit builds the model.
func (s *CalSpread) OnInit(_ *algolang.Context, _ algolang.InitConfig) error {
if s.Front == s.Next {
return fmt.Errorf("calspread: the front and the next are both %s", s.Front)
}
s.model = NewModel(s.Window, s.EntryZ, s.ExitZ)
return nil
}
// OnBar pairs the bar with its instant's other leg and, once both are in,
// acts on the model's decision with one combo order.
func (s *CalSpread) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
leg := -1
switch bar.Symbol {
case s.Front:
leg = 0
case s.Next:
leg = 1
default:
return nil, nil
}
at := bar.CloseTime.UTC().Format("2006-01-02T15:04:05")
front, next, ok := s.pair.Add(leg, at, bar.Close)
if !ok {
return nil, nil
}
z, ok := s.model.Observe(next - front)
if !ok {
return nil, nil
}
spread := []algolang.ComboLeg{algolang.BuyLeg(s.Next, 1), algolang.SellLeg(s.Front, 1)}
var side algolang.Side
var name string
switch s.model.Decide(z) {
case BuySpread:
side, name = algolang.Buy, "Spread LE"
case SellSpread:
side, name = algolang.Sell, "Spread SE"
case Flatten:
// Close what the account holds: long the next leg is a long spread.
switch q := ctx.Position(s.Next).Quantity; {
case q > 0:
side, name = algolang.Sell, "Spread LX"
case q < 0:
side, name = algolang.Buy, "Spread SX"
default:
return nil, nil
}
default:
return nil, nil
}
s.seq++
o := algolang.ComboMarket(side, int64(s.Units), spread...).Named(name)
o.ClientID = fmt.Sprintf("spread-%d", s.seq)
s.logf("%s spread %.2f z=%+.2f -> %s %d unit(s) of %s", at, next-front, z, sideName(side), s.Units, o.Symbol)
return []algolang.Order{o}, nil
}
func sideName(s algolang.Side) string {
if s == algolang.Sell {
return "sell"
}
return "buy"
}
func (s *CalSpread) logf(format string, args ...any) {
if s.Log {
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
}
func main() {
if err := algolang.Run(&CalSpread{}); err != nil {
fmt.Fprintf(os.Stderr, "calspread %s: %v\n", buildID, err)
os.Exit(1)
}
}calspread/spread.go
package main
// The calendar-spread model. It is plain Go with no SDK types, no I/O and no
// clock, so it is tested on its own (spread_test.go).
import "math"
// Pairer matches the two legs' closes by bar close time. The two contracts'
// bars of one instant arrive in either order; a later instant discards
// whatever was incomplete, an earlier one is stale, and an instant completes
// once. The zero value is ready to use.
type Pairer struct {
at string
front, next float64
has [2]bool
done bool
}
// Add feeds leg 0 (the front) or 1 (the next) at instant at (an ordered
// string). It returns both closes and ok=true on the bar that completes it.
func (p *Pairer) Add(leg int, at string, close float64) (front, next float64, ok bool) {
if leg != 0 && leg != 1 {
return 0, 0, false
}
switch {
case at < p.at:
return 0, 0, false
case at > p.at:
*p = Pairer{at: at}
}
if p.done {
return 0, 0, false
}
if leg == 0 {
p.front = close
} else {
p.next = close
}
p.has[leg] = true
if !p.has[0] || !p.has[1] {
return 0, 0, false
}
p.done = true
return p.front, p.next, true
}
// Action is the model's decision on one instant.
type Action int
const (
Hold Action = iota
BuySpread // the spread is cheap: buy the next, sell the front
SellSpread // the spread is rich: sell the next, buy the front
Flatten // the spread has reverted: close the open spread
)
// Model is a rolling z-score of the calendar spread (next - front) with an
// entry and an exit band.
type Model struct {
window int
entryZ, exitZ float64
spreads []float64
side int // +1 long the spread, -1 short, 0 flat
}
// NewModel returns a model over window spreads (at least 2).
func NewModel(window int, entryZ, exitZ float64) *Model {
return &Model{window: max(window, 2), entryZ: entryZ, exitZ: exitZ}
}
// Observe records the instant's spread and returns its z-score against the
// window ending with it; ok is false until the window is full or when the
// spreads do not vary.
func (m *Model) Observe(spread float64) (z float64, ok bool) {
m.spreads = append(m.spreads, spread)
if len(m.spreads) > m.window {
m.spreads = m.spreads[len(m.spreads)-m.window:]
}
if len(m.spreads) < m.window {
return 0, false
}
mean, sq := 0.0, 0.0
for _, s := range m.spreads {
mean += s
}
mean /= float64(len(m.spreads))
for _, s := range m.spreads {
sq += (s - mean) * (s - mean)
}
sd := math.Sqrt(sq / float64(len(m.spreads)))
if sd == 0 {
return 0, false
}
return (spread - mean) / sd, true
}
// Decide turns a z-score into an action against the model's side, and moves
// the side as if the action filled.
func (m *Model) Decide(z float64) Action {
switch {
case m.side == 0 && z <= -m.entryZ:
m.side = 1
return BuySpread
case m.side == 0 && z >= m.entryZ:
m.side = -1
return SellSpread
case m.side != 0 && math.Abs(z) <= m.exitZ:
m.side = 0
return Flatten
}
return Hold
}
// Side is the spread the model holds: +1 long, -1 short, 0 flat.
func (m *Model) Side() int { return m.side }Previous: Term structure and carry: add a tradeable symbol · Next: Momentum ranking: daily and intraday ETF baskets