ES/NQ relative value: one strategy, two traded symbols
esnqspread observes the log ratio of ES and NQ adjusted closes, standardizes it over a rolling window, sells ES/buys NQ when ES is relatively rich, and does the reverse when ES is relatively cheap. It exits when the score returns toward zero. Both symbols are configured tradeable:
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/esnqspread \
--symbols fut:XCME:ES,fut:XCME:NQ --bar-interval 1d \
--date-from 2020-01-01 --date-to 2024-12-31 \
--commission-per-share 2.50 --slippage-ticks 1 \
--results-dir results/learning/esnqThere is one process, one account and two holdings. Each root has its own active contract and served roll schedule. The strategy can return an order for either symbol from either symbol’s callback; routing uses the order’s symbol, not the bar that happened to trigger the decision.
Pair observations before deciding
The two daily bars may close seconds apart. The demo buffers them by trade date, using bar.Session.TradeDate when present, and calls its model once both sides are available. Pairing the latest ES and latest NQ indiscriminately can compare today with yesterday. For other instruments, choose an explicit as-of alignment and maximum age instead of assuming trade-date equivalence.
The central order pattern, from the short-spread branch, is:
lots := s.params.NQLots(es, nq)
add(algolang.MarketSell(s.ES, s.params.ESLots).Named("Spread SE"),
"short-es")
add(algolang.MarketBuy(s.NQ, lots).Named("Spread SE"), "short-nq")Here the demo’s add helper assigns a trade-date-and-leg client ID and appends to the returned orders. NQ quantity approximates ES notional using point values and integer contract quantities. One ES against one NQ is not generally notional neutral. A notional match is not a fitted hedge ratio either.
Two orders are not an atomic spread
Returning both orders together does not guarantee simultaneous execution or acceptance. One can be denied or remain unfilled. The demo is a backtest example with model state; a hardened version must reconcile both actual positions and unresolved orders before assuming it owns a complete spread. Define what to do with a lone leg and include that policy in testing.
At exit, size each reducing order from ctx.Position(leg).Quantity, not from the originally requested hedge quantity. Check gross exposure, per-leg costs, different session hours and contract roll events. A low net exposure can hide large gross holdings. The next chapters contrast strategy-declared holdings and atomic dated-contract combos.
For research using log ratios, require positive inputs and understand that Panama adjustment and rebasing can change ratios. Do not attribute a roll-frame effect to mean reversion. Compare suitable raw or ratio-adjusted definitions and review how model-owned history is restated before extending the demo. Source to study: strategies/demo/go/esnqspread/.
Complete source: esnqspread
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.
main.goconnects paired observations to orders on both logical symbols.spread.gocontains all pairing, validation, statistics and sizing code used by that executable.Pairermatches the trade date once, discards an incomplete earlier date and rejects stale observations. It does not assume that daily closes share an exact timestamp.The model standardizes the log-price ratio and sizes the NQ hedge using point values. Separate leg orders are not atomic; model intentions must be checked against fills before adapting this demo for live trading.
Build the supplied files directly:
go build -o bin/esnqspread ./strategies/demo/go/esnqspread
bin/esnqspread --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.
esnqspread/main.go
// Command esnqspread is the example of a run with two continuous futures
// series (docs/algolang.md, "Several continuous series in one run",
// GLE-426): an E-mini S&P 500 / E-mini Nasdaq-100 relative-value strategy
// on the back-adjusted daily series fut:XCME:ES and fut:XCME:NQ.
//
// On each trade date for which both legs have a bar it standardises the log
// ratio of the two adjusted closes over a rolling window (spread.go). It sells
// the spread (ES short, NQ long) when ES is rich and buys it when ES is cheap,
// sizing NQ to ES's notional, and flattens both legs when the ratio reverts.
// The two bars of one trade date can close a second or two apart, so the legs
// pair by trade date. An order for either leg can be placed on either leg's
// bar: the engine routes each by its symbol (GLE-424).
//
// Every order is a market order on the logical symbol; the engine fills it
// on the leg's active contract and rolls the position at each served roll.
package main
import (
"fmt"
"os"
algolang "MODULE/sdk/strategy"
)
var buildID string
// ESNQSpread is the strategy: its inputs, and the model and pairing state.
type ESNQSpread struct {
ES string `algolang:"default=fut:XCME:ES,desc=The ES leg's symbol (a continuous series)"`
NQ string `algolang:"default=fut:XCME:NQ,desc=The NQ leg's symbol (a continuous series)"`
Lookback int `algolang:"default=20,min=2,desc=Trade dates in the rolling window of the log ratio"`
EntryZ float64 `algolang:"default=2,min=0,desc=Enter when the ratio's z-score reaches this, either side"`
ExitZ float64 `algolang:"default=0.5,min=0,desc=Flatten when the z-score reverts to within this of zero"`
ESLots int `algolang:"default=1,min=1,desc=ES contracts per spread; NQ is sized to their notional"`
Log bool `algolang:"default=true,desc=Print each decision to stderr"`
params Params
model *Model
pair Pairer
}
func (s *ESNQSpread) Name() string { return "ES/NQ spread" }
// 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 *ESNQSpread) 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 *ESNQSpread) OneBarRule() bool { return true }
func (s *ESNQSpread) Description() string {
return "Relative value between the continuous E-mini S&P 500 and Nasdaq-100 daily series."
}
// OnInit builds the model from the inputs; a bad input fails the run before
// its first bar.
func (s *ESNQSpread) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
s.params = Params{Lookback: s.Lookback, EntryZ: s.EntryZ, ExitZ: s.ExitZ, ESLots: int64(s.ESLots), ESPoint: 50, NQPoint: 20}
// The Init's instruments carry the legs' point values (the continuous
// series' definitions); the defaults stand when an instrument has none.
for _, in := range cfg.Instruments {
switch {
case in.Symbol == s.ES && in.PointValue > 0:
s.params.ESPoint = in.PointValue
case in.Symbol == s.NQ && in.PointValue > 0:
s.params.NQPoint = in.PointValue
}
}
if err := s.params.Validate(); err != nil {
return fmt.Errorf("esnqspread: %w", err)
}
s.model = NewModel(s.params)
return nil
}
// OnBar pairs the bar with its trade date's other leg and, once both are in,
// observes the ratio and acts on the model's decision.
func (s *ESNQSpread) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
leg := ""
switch bar.Symbol {
case s.ES:
leg = "ES"
case s.NQ:
leg = "NQ"
default:
return nil, nil
}
date := bar.CloseTime.UTC().Format("2006-01-02")
if bar.Session != nil && bar.Session.TradeDate != "" {
date = bar.Session.TradeDate
}
es, nq, ok := s.pair.Add(leg, date, bar.Close)
if !ok {
return nil, nil
}
z, ok := s.model.Observe(es, nq)
if !ok {
return nil, nil
}
var orders []algolang.Order
add := func(o algolang.Order, id string) {
o.ClientID = date + "-" + id
orders = append(orders, o)
}
switch s.model.Decide(z) {
case EnterShort:
lots := s.params.NQLots(es, nq)
add(algolang.MarketSell(s.ES, s.params.ESLots).Named("Spread SE"), "short-es")
add(algolang.MarketBuy(s.NQ, lots).Named("Spread SE"), "short-nq")
s.logf("%s z=%+.2f sell the spread: sell %d ES, buy %d NQ", date, z, s.params.ESLots, lots)
case EnterLong:
lots := s.params.NQLots(es, nq)
add(algolang.MarketBuy(s.ES, s.params.ESLots).Named("Spread LE"), "long-es")
add(algolang.MarketSell(s.NQ, lots).Named("Spread LE"), "long-nq")
s.logf("%s z=%+.2f buy the spread: buy %d ES, sell %d NQ", date, z, s.params.ESLots, lots)
case Exit:
for _, l := range []struct {
sym, id string
long int64 // the sign of the leg's position in a long spread
}{{s.ES, "exit-es", 1}, {s.NQ, "exit-nq", -1}} {
q := ctx.Position(l.sym).Quantity
name := "Spread LX"
if q*l.long < 0 {
name = "Spread SX"
}
switch {
case q > 0:
add(algolang.MarketSell(l.sym, q).Named(name), l.id)
case q < 0:
add(algolang.MarketBuy(l.sym, -q).Named(name), l.id)
}
}
s.logf("%s z=%+.2f flatten the spread", date, z)
}
return orders, nil
}
func (s *ESNQSpread) logf(format string, args ...any) {
if s.Log {
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
}
func main() {
if err := algolang.Run(&ESNQSpread{}); err != nil {
fmt.Fprintln(os.Stderr, "esnqspread:", err)
os.Exit(1)
}
}esnqspread/spread.go
// spread.go is the pure decision model of the esnqspread example, a
// relative-value strategy on the E-mini S&P 500 (ES) and E-mini Nasdaq-100
// (NQ) futures. It tracks the log ratio of the two back-adjusted daily
// closes, standardises it over a rolling window and trades the spread: short
// it when ES is rich, long it when ES is cheap, flat once it reverts.
//
// The model is plain Go with no SDK types, no I/O, no clock and no
// goroutines, so it is deterministic and testable on its own. main.go owns
// the wiring from these decisions to market orders.
package main
import (
"fmt"
"math"
)
// Params are the model's inputs.
//
// The z thresholds are measured in standard deviations of the rolling log
// ratio, so they are unitless and need no per-symbol tuning.
type Params struct {
Lookback int // rolling window length, >= 2
EntryZ float64 // |z| at or beyond which a flat spread is entered, > 0
ExitZ float64 // the z at which an open spread is closed, 0 <= ExitZ < EntryZ
ESLots int64 // ES contracts per spread, >= 1
ESPoint float64 // ES point value (50)
NQPoint float64 // NQ point value (20)
}
// Validate reports whether every bound documented on Params holds. It returns
// nil when they do and otherwise an error naming the first bad field in field
// order (Lookback, EntryZ, ExitZ, ESLots, ESPoint, NQPoint), so a given
// mistake always produces the same message.
//
// The float bounds are written as negated comparisons so that a NaN, which
// satisfies no comparison, is rejected instead of slipping through. Each
// message names only the field at fault.
func (p Params) Validate() error {
switch {
case p.Lookback < 2:
return fmt.Errorf("invalid params: Lookback must be at least 2, got %d", p.Lookback)
case !(p.EntryZ > 0):
return fmt.Errorf("invalid params: EntryZ must be greater than 0, got %v", p.EntryZ)
case !(p.ExitZ >= 0 && p.ExitZ < p.EntryZ):
return fmt.Errorf("invalid params: ExitZ must be at least 0 and below %v, got %v", p.EntryZ, p.ExitZ)
case p.ESLots < 1:
return fmt.Errorf("invalid params: ESLots must be at least 1, got %d", p.ESLots)
case !(p.ESPoint > 0):
return fmt.Errorf("invalid params: ESPoint must be greater than 0, got %v", p.ESPoint)
case !(p.NQPoint > 0):
return fmt.Errorf("invalid params: NQPoint must be greater than 0, got %v", p.NQPoint)
}
return nil
}
// Side is the spread's position.
type Side int
// The positions a spread can hold, named after the ES leg: Long is long ES
// against short NQ and profits when ES outperforms NQ, Short is the mirror
// image. Flat holds nothing and is the zero value, so a new Model starts flat.
const (
Flat Side = iota
Long // long ES, short NQ
Short // short ES, long NQ
)
// Action is a decision.
type Action int
// The decisions the model can make for one trade date. Hold leaves the
// position alone; the other three each name the orders the caller places on
// both legs. Hold is the zero value, so an unset Action never trades.
const (
Hold Action = iota
EnterLong // buy ES, sell NQ
EnterShort // sell ES, buy NQ
Exit // flatten both legs
)
// Pairer pairs the ES and NQ bars of one trade date.
//
// The two bars of a date arrive in no guaranteed order and their closes can
// be a second or two apart, so legs are matched by trade date rather than by
// timestamp. A Pairer assembles one date at a time. When a later date starts,
// whatever was incomplete is discarded for good, so a date missing a leg is
// skipped rather than patched from a neighbouring day, and a bar for an
// earlier date is stale and ignored. The zero value is ready to use.
type Pairer struct {
// date is the trade date being assembled; empty before the first bar.
date string
// es and nq are the latest closes seen for date. They are meaningful
// only while the matching flag below is set.
es, nq float64
// hasES and hasNQ record which legs of date have arrived.
hasES, hasNQ bool
// done is set once date has been handed out as a pair, so a date
// completes exactly once however many more bars arrive for it.
done bool
}
// Add feeds one bar into the Pairer. leg is "ES" or "NQ"; any other leg is
// rejected and changes nothing. tradeDate is a YYYY-MM-DD string, which
// orders lexically, and close is the leg's close for that date.
//
// Add returns both closes and ok=true on the bar that completes a trade date,
// and zeros with ok=false otherwise. Until a date completes, the latest close
// of each leg wins; afterwards the date is closed and further bars for it
// return ok=false.
func (p *Pairer) Add(leg string, tradeDate string, close float64) (es, nq float64, ok bool) {
if p == nil || (leg != "ES" && leg != "NQ") { // a nil Pairer pairs nothing
return 0, 0, false
}
switch {
case tradeDate < p.date:
// A stale bar for a date already left behind.
return 0, 0, false
case tradeDate > p.date:
// A later date has started: drop whatever was being assembled,
// complete or not, and begin again from nothing.
*p = Pairer{date: tradeDate}
}
if p.done {
return 0, 0, false
}
if leg == "ES" {
p.es, p.hasES = close, true
} else {
p.nq, p.hasNQ = close, true
}
if !p.hasES || !p.hasNQ {
return 0, 0, false
}
p.done = true
return p.es, p.nq, true
}
// Model is the spread's rolling z-score and its state machine. It is not safe
// for concurrent use: the strategy feeds it one trade date at a time.
type Model struct {
// p holds the parameters. The model trusts them; callers run Validate
// before NewModel.
p Params
// window holds the last Lookback values of ln(es) - ln(nq), oldest first.
window []float64
// side is the spread's current position.
side Side
}
// NewModel returns a Model that is Flat and has seen no observations. It
// assumes p is valid; the caller is expected to have run p.Validate.
func NewModel(p Params) *Model {
return &Model{p: p}
}
// Observe records one trade date's closes and returns the z-score of the
// newest log ratio within the rolling window of the last Lookback values. ok
// is false while there is no usable z: when the closes are unusable, while
// the window is still filling, or when every value in it is identical.
//
// A close that is not positive and finite has no logarithm, and a
// back-adjusted series can hold such values far back, so such a date is
// dropped without being recorded and does not advance the window.
//
// The z uses the population standard deviation (divide by Lookback) and the
// newest value counts as part of its own window. That caps |z| at
// sqrt(Lookback-1), so an EntryZ above that can never fire.
func (m *Model) Observe(es, nq float64) (z float64, ok bool) {
if m == nil {
return 0, false // a nil Model observes nothing
}
// Negated comparisons reject a NaN along with zero and negative closes;
// infinities have no usable logarithm either.
if !(es > 0) || !(nq > 0) || math.IsInf(es, 0) || math.IsInf(nq, 0) {
return 0, false
}
n := m.p.Lookback
if n < 1 {
// Only reachable with unvalidated params: there is no window to fill.
// Guarding here keeps the slicing below safe for any input.
return 0, false
}
// Record the newest value, first evicting the oldest ones so that the
// window never holds more than Lookback values.
x := math.Log(es) - math.Log(nq)
if len(m.window) >= n {
keep := n - 1
kept := copy(m.window, m.window[len(m.window)-keep:])
m.window = m.window[:kept]
}
m.window = append(m.window, x)
if len(m.window) < n {
return 0, false
}
// Moments are taken of offsets from the oldest value, not of the raw
// values. That changes neither the sd nor the z, but it makes a window of
// identical values come out as offsets that are all exactly zero. Summing
// the raw values can instead leave the mean an ulp off the value, so the
// sd == 0 test below would miss and a rounding-noise sd would yield a
// meaningless, possibly huge, z. Everything is recomputed from the window
// on each call, so there is no running-sum drift either.
ref := m.window[0]
count := float64(len(m.window))
var sum float64
for _, v := range m.window {
sum += v - ref
}
mean := sum / count
var sumSq float64
for _, v := range m.window {
d := v - ref - mean
sumSq += d * d
}
sd := math.Sqrt(sumSq / count)
if sd == 0 {
return 0, false
}
return (x - ref - mean) / sd, true
}
// Decide applies the z-score of one trade date to the spread's state machine
// and returns the decision for that date. z should be a value reported ok by
// Observe.
//
// A flat spread is entered once |z| reaches EntryZ: a high z means ES is rich
// against NQ, so the spread is shorted, and a low z means ES is cheap, so the
// spread is bought. An open spread is closed once z has come back to ExitZ.
// Because ExitZ is below EntryZ the two thresholds leave a band in which an
// open position is simply held, which stops a z hovering around one level
// from churning in and out.
//
// Each call makes at most one decision: an exit never re-enters on the same
// call, even if z has already crossed the far entry threshold. The next trade
// date's z decides whether the reverse spread is opened.
func (m *Model) Decide(z float64) Action {
if m == nil {
return Hold // a nil Model never trades
}
switch m.side {
case Flat:
if z >= m.p.EntryZ {
// ES is rich against NQ: sell ES, buy NQ.
m.side = Short
return EnterShort
}
if z <= -m.p.EntryZ {
// ES is cheap against NQ: buy ES, sell NQ.
m.side = Long
return EnterLong
}
case Short:
// Entered at a high z, so it has reverted once z falls back to ExitZ,
// or past it.
if z <= m.p.ExitZ {
m.side = Flat
return Exit
}
case Long:
// Entered at a low z, so it has reverted once z rises back to -ExitZ,
// or past it.
if z >= -m.p.ExitZ {
m.side = Flat
return Exit
}
}
return Hold
}
// Side returns the spread's current position.
func (m *Model) Side() Side {
if m == nil {
return Flat
}
return m.side
}
// NQLots returns the number of NQ contracts that balance ESLots ES contracts
// by notional at the given closes, that is
// round(ESLots * es * ESPoint / (nq * NQPoint)), with halves rounded away
// from zero and a floor of one contract so that a leg is never dropped.
//
// A non-positive nq, or a result that is not finite (a NaN or infinite close,
// or invalid params), yields 1 rather than an error or a panic: the caller
// sizes orders from live prices, and a safe minimum beats halting the
// strategy.
func (p Params) NQLots(es, nq float64) int64 {
if nq <= 0 {
return 1
}
lots := float64(p.ESLots) * es * p.ESPoint / (nq * p.NQPoint)
if math.IsNaN(lots) || math.IsInf(lots, 0) {
return 1
}
// math.Round rounds half away from zero, as specified.
lots = math.Round(lots)
switch {
case lots < 1:
return 1
case lots >= float64(math.MaxInt64):
// float64(MaxInt64) rounds up to 2^63, which no int64 can hold, and
// converting an out-of-range float is implementation-defined, so
// saturate to keep the result deterministic on every platform.
return math.MaxInt64
}
return int64(lots)
}Previous: A continuous futures trend: contracts and rolls · Next: Term structure and carry: add a tradeable symbol