Term structure and carry: add a tradeable symbol

Term structure and carry: add a tradeable symbol

termcarry observes the front and deferred contract of one futures root. It computes annualized roll yield from raw closes and delivery spacing, and holds the front while the yield’s fast average is above its slow average. The deferred composite is loaded by the strategy:

bin/algo run \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/termcarry --symbols fut:XCME:ES --bar-interval 1d \
  --date-from 2020-01-01 --date-to 2024-12-31 \
  --inputs Log=true \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --results-dir results/learning/carry

The default Next is fut:XCME:ES:cont:ofs=B1:adj=none. B1 is the rank behind the feed’s held front, not simply whichever unexpired contract looks nearest today. Pair the observations by trade date and inspect their ActiveContract values. Adjusted trend history must not be substituted for raw curve levels when calculating carry.

This two-point term-structure model computes log(F/N) * 12/m, where F and N are positive raw closes and m is their positive delivery-month spacing. With three months between contracts, 5000 against 5050 gives about -3.98% annualized; 5000 against 4950 gives +4.02%. Contango gives negative carry; backwardation gives positive carry. This curve statistic is neither a realized return nor an exact day-count financing calculation.

The signal compares five trade dates’ average carry with 60 dates’ average. It can buy improving but still-negative carry. Invalid prices or contract spacing yield no sample. Inspect the logged pair and yield around rolls.

Turn the reference into a second holding

Set Spread=true and explicitly allow tradeable expansion in a config file. universe-expansion is a key inside data, not an algo run flag. Save this as examples/learning/carry-spread.json:

{
  "global": {
    "data": {
      "adapter": "bin/marketfeed-adapter",
      "data-protocol": "pb",
      "universe-expansion": "full"
    },
    "strategy": "bin/termcarry",
    "bar-interval": "1d",
    "date-from": "2020-01-01",
    "date-to": "2024-12-31",
    "commission-mode": "per-unit",
    "commission-amount": 2.50,
    "slippage-ticks": 1,
    "results-dir": "results/learning/carry-spread"
  },
  "runs": [{
    "id": "carry-spread", "symbol": "fut:XCME:ES",
    "inputs": {"Spread": true, "Log": true}
  }]
}
bin/algo run --config examples/learning/carry-spread.json --verify
bin/algo run --config examples/learning/carry-spread.json

The strategy already declares the deferred bar series. This method adds venue eligibility only in spread mode:

func (s *TermCarry) TradeableSymbols() []string {
    if s.Spread {
        return []string{s.Next}
    }
    return nil
}

DataRequirements provides observations; TradeableSymbols requests trading eligibility; the run policy admits it. The data-only default cannot become a hedge holding. These initialization declarations do not provide arbitrary mid-run subscriptions.

Two deferred ranks when the archive serves them

The term-structure strategy can trade contracts beyond the default front holding. termcarry uses the configured primary as its nearer leg; the input named Next supplies the farther leg. Neither role has to be the front. Use B1 as the primary and B2 as Next to buy/sell the first and second deferred ranks. The program is the same complete source printed below.

An illustrative upward-sloping ES curve with the front untraded, a buy in B1 and a sell in B2. Actual contract names at each rank come from the served schedules.{width=“100%”}

This is a coverage-dependent variation, not a command that every archive can run. The archive used to check this book currently serves ES at F and B1, but not B2; it refuses this request with “a composite held at B2 is not served”. Marketfeed must first derive the requested extra rank (its contract.extra_ranks product setting). Algolang cannot manufacture that missing composite by changing a strategy input. The dated December/March example below is the tested way to trade two deferred contracts using the available archive.

For an archive with both products, save this complete configuration as examples/learning/deferred-carry.json:

{
  "global": {
    "data": {
      "adapter": "bin/marketfeed-adapter",
      "data-protocol": "pb",
      "universe-expansion": "full"
    },
    "strategy": "bin/termcarry",
    "bar-interval": "1d",
    "date-from": "2026-01-01",
    "date-to": "2026-09-30",
    "commission-mode": "per-unit",
    "commission-amount": 2.50,
    "slippage-ticks": 1,
    "results-dir": "results/learning/deferred-carry"
  },
  "runs": [{
    "id": "b1-b2-carry",
    "symbol": "fut:XCME:ES:cont:ofs=B1:adj=none",
    "inputs": {
      "Next": "fut:XCME:ES:cont:ofs=B2:adj=none",
      "Fast": 5,
      "Window": 20,
      "Spread": true,
      "Log": true
    }
  }]
}
bin/algo run --config examples/learning/deferred-carry.json --verify
bin/algo run --config examples/learning/deferred-carry.json \
  --plate full --color never --chart lines \
  --export results/learning/deferred-carry.algorun

When its carry condition is true, this configuration holds +1 B1 and −1 B2; otherwise it closes those holdings. It does not buy the front as an intermediate step. “B1” and “B2” describe held ranks, not fixed month names: after a roll, each series holds its successor. For example, while the served front is ESU26, the illustrative B1/B2 pair can be ESZ26/ESH27. Use the actual ActiveContract fields and roll audit to establish the pair in your run; do not hard-code the diagram’s mapping for every date.

--verify validates the expanded run plan; it does not establish that every archive product is populated. Check the data fetch and run result as well.

The calculation uses the two held contracts’ raw closes and their delivery month separation to form an annualized roll yield. It compares that yield’s short and long averages; it does not simply buy whichever outright price is lower. On an upward curve the computed yield can be negative and still be above its recent average. The strategy buys the nearer leg and sells the farther on that relative condition; it does not implement a symmetric short spread on the opposite condition.

Require archive coverage for both deferred composites. Each roll adds leg executions and costs, and the two independent orders are not atomic. The demo also uses simplified position checks; production treatment of partial or denied legs needs explicit reconciliation. To hold fixed months rather than moving ranks, use the dated-contract combo in the next chapter.

A held rank and a listed curve answer different questions

The deferred composite follows marketfeed’s stored held-rank schedule. ctx.Curve(root) instead examines a declared contract listing, with maturity and instrument information as of the decision. See curvewatch for the listing interface when designing maturity-based selection. That API is currently a backtest facility, with its own data and performance restrictions.

Each rank rolls separately, without automatic netting, spread margin credit or a combined exposure cap. Include every leg’s costs and inspect both books. As with ES/NQ, these are separate market orders, not a combo. Source to study: strategies/demo/go/termcarry/ and strategies/demo/go/curvewatch/main.go.

Complete source: termcarry

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.

  1. main.go declares the deferred continuous series. TradeableSymbols additionally admits it when the Spread input is enabled.

  2. carry.go contains the entire pairing, contract-month parsing and annualized roll-yield model. The calculation uses raw held-contract prices rather than comparing independently back-adjusted levels.

  3. hold returns either the front order alone or both spread legs. Each logical series rolls independently, and a pair of market orders still needs leg-risk controls for live use.

Build the supplied files directly:

go build -o bin/termcarry ./strategies/demo/go/termcarry
bin/termcarry --algolang-describe

This 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.

termcarry/main.go

// Command termcarry is the example of a deferred composite beside the front
// (docs/algolang.md, "Contract curves", GLE-410). It trades the continuous
// E-mini S&P 500 daily series fut:XCME:ES and declares, for reference, the
// same root held one contract further out: fut:XCME:ES:cont:ofs=B1:adj=none,
// the composite marketfeed stores for ES at B1.
//
// On each trade date for which both series have a bar it reads the raw close
// of the contract the front series holds and of the one behind it, and from
// the months between their deliveries the annualised roll yield (carry.go):
// what a long held in the front earns, positive, or pays, negative, as it
// rolls up the curve. It holds one ES lot while the roll yield's Fast-day
// average is above its Window-day average, the curve having flattened or
// tilted towards backwardation against its recent shape, and is flat
// otherwise.
//
// The two bars of one trade date can close a second or two apart, so they
// pair by trade date. Every order is a market order on the logical symbol
// fut:XCME:ES; the engine fills it on the held contract and rolls it. The
// deferred series takes no orders: it is declared for reference only.
//
// With Spread set it holds the calendar spread instead of the outright (GLE-484):
// long one front lot and short one of the deferred series, which it then
// declares tradeable as well. Each order is a market order on its series'
// logical symbol, and each series rolls its own lot at the root's cut, with legs
// of its own: the front's from the contract the deferred series is leaving.
package main

import (
    "fmt"
    "os"

    algolang "MODULE/sdk/strategy"
)

var buildID string

// TermCarry is the strategy: its inputs, and the model and pairing state.
type TermCarry struct {
    Next   string `algolang:"default=fut:XCME:ES:cont:ofs=B1:adj=none,desc=The deferred composite held one contract behind the front (unadjusted)"`
    Fast   int    `algolang:"default=5,min=1,max=100,desc=Trade dates in the roll yield's fast average"`
    Window int    `algolang:"default=60,min=2,max=500,desc=Trade dates in the roll yield's slow average"`
    Spread bool   `algolang:"default=false,desc=Hold the calendar spread (long the front and short Next) instead of the front alone"`
    Log    bool   `algolang:"default=false,desc=Print each trade date's roll yield and decision to stderr"`

    model *Model
    pair  Pairer
}

func (s *TermCarry) Name() string { return "Term carry" }

func (s *TermCarry) Description() string {
    return "Continuous ES held while its roll yield against the next contract (a deferred composite) is above its average."
}

// 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 *TermCarry) 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 *TermCarry) OneBarRule() bool { return true }

// OnInit builds the model.
func (s *TermCarry) OnInit(_ *algolang.Context, _ algolang.InitConfig) error {
    if s.Fast >= s.Window {
        return fmt.Errorf("Fast %d must be below Window %d", s.Fast, s.Window)
    }
    s.model = NewModel(s.Fast, s.Window)
    return nil
}

// DataRequirements declares the deferred composite as a daily series; it is
// not declared tradeable, so it is reference-only.
func (s *TermCarry) DataRequirements() []algolang.DataRequirement {
    return []algolang.DataRequirement{{SeriesID: "next", Symbol: s.Next, Lookback: 1,
        Schema: algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: "1d"}}}
}

// TradeableSymbols declares the deferred composite tradeable when the strategy
// holds the spread.
func (s *TermCarry) TradeableSymbols() []string {
    if s.Spread {
        return []string{s.Next}
    }
    return nil
}

// OnBar pairs the bar with its trade date's other leg and, once both are in,
// observes the roll yield and holds or flattens one lot.
func (s *TermCarry) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    leg := Front
    switch {
    case ctx.IsPrimary(bar):
    case bar.Symbol == s.Next || bar.SeriesID == "next":
        leg = Next
    default:
        return nil, nil
    }
    date := bar.CloseTime.UTC().Format("2006-01-02")
    if bar.Session != nil && bar.Session.TradeDate != "" {
        date = bar.Session.TradeDate
    }
    front, next, ok := s.pair.Add(leg, date, Quote{Close: bar.RawClose, Contract: bar.ActiveContract})
    if !ok {
        return nil, nil
    }
    y, ok := RollYield(front, next)
    if !ok {
        return nil, nil
    }
    above, ok := s.model.Observe(y)
    if !ok {
        return nil, nil
    }
    sym := ctx.PrimarySymbol()
    qty := ctx.Position(sym).Quantity
    s.logf("%s %s/%s roll yield %+.4f above-average=%v", date, front.Contract, next.Contract, y, above)
    switch {
    case above && qty == 0:
        return s.hold("LE", algolang.MarketBuy(sym, 1), algolang.MarketSell(s.Next, 1)), nil
    case !above && qty > 0:
        return s.hold("LX", algolang.MarketSell(sym, qty), algolang.MarketBuy(s.Next, -ctx.Position(s.Next).Quantity)), nil
    }
    return nil, nil
}

// hold returns the front's order, and with Spread the deferred series' too,
// named for the action: name for the outright, "Spread " and name for both legs
// of the spread.
func (s *TermCarry) hold(name string, front, next algolang.Order) []algolang.Order {
    if !s.Spread {
        return []algolang.Order{front.Named(name)}
    }
    if next.Quantity <= 0 {
        return []algolang.Order{front.Named("Spread " + name)}
    }
    return []algolang.Order{front.Named("Spread " + name), next.Named("Spread " + name)}
}

func (s *TermCarry) logf(format string, args ...any) {
    if s.Log {
        fmt.Fprintf(os.Stderr, format+"\n", args...)
    }
}

func main() {
    if err := algolang.Run(&TermCarry{}); err != nil {
        fmt.Fprintf(os.Stderr, "termcarry %s: %v\n", buildID, err)
        os.Exit(1)
    }
}

termcarry/carry.go

package main

// The roll-yield model. It is plain Go with no SDK types, no I/O and no
// clock, so it is tested on its own (carry_test.go).

import (
    "math"
    "strings"
)

// monthCodes are the futures delivery-month letters, January to December.
const monthCodes = "FGHJKMNQUVXZ"

// Delivery reads a dated contract's delivery month from the last three
// characters of its code, a month letter and a two-digit year (ESH26 and
// fut:XCME:ES:H26 are both March 2026), as a count of months. ok is false
// for any other code.
func Delivery(contract string) (months int, ok bool) {
    if len(contract) < 3 {
        return 0, false
    }
    tail := contract[len(contract)-3:]
    m := strings.IndexByte(monthCodes, tail[0])
    d1, d2 := tail[1], tail[2]
    if m < 0 || d1 < '0' || d1 > '9' || d2 < '0' || d2 > '9' {
        return 0, false
    }
    year := 2000 + int(d1-'0')*10 + int(d2-'0')
    return year*12 + m, true
}

// Quote is one leg's raw close on a trade date and the dated contract it is
// a close of.
type Quote struct {
    Close    float64
    Contract string
}

// RollYield is the annualised roll yield of holding the front contract
// against the next one: ln(front/next) over the months between their
// deliveries, scaled to a year. Positive is backwardation (the next contract
// trades below the front, so a long held in the front gains as it rolls up
// the curve); negative is contango. ok is false unless both closes are
// positive and finite and the next contract delivers after the front.
func RollYield(front, next Quote) (float64, bool) {
    fm, ok1 := Delivery(front.Contract)
    nm, ok2 := Delivery(next.Contract)
    if !ok1 || !ok2 || nm <= fm {
        return 0, false
    }
    if !(front.Close > 0) || !(next.Close > 0) || math.IsInf(front.Close, 0) || math.IsInf(next.Close, 0) {
        return 0, false
    }
    return math.Log(front.Close/next.Close) * 12 / float64(nm-fm), true
}

// Leg names which series a bar belongs to.
type Leg int

const (
    Front Leg = iota // the series that trades: the front
    Next             // the deferred composite held one contract behind it
)

// Pairer matches the two legs' quotes by trade date. Two series' bars of one
// trade date can close a second or two apart and arrive in either order. A
// Pairer assembles one date at a time: a later date discards whatever was
// incomplete, a bar for an earlier date is stale and ignored, and a date
// completes once. The zero value is ready to use.
type Pairer struct {
    date        string
    front, next Quote
    has         [2]bool
    done        bool
}

// Add feeds one leg's quote for tradeDate (YYYY-MM-DD, which orders
// lexically). It returns both quotes and ok=true on the bar that completes a
// date; until then the latest quote of each leg wins.
func (p *Pairer) Add(leg Leg, tradeDate string, q Quote) (front, next Quote, ok bool) {
    if leg != Front && leg != Next {
        return Quote{}, Quote{}, false
    }
    switch {
    case tradeDate < p.date:
        return Quote{}, Quote{}, false
    case tradeDate > p.date:
        *p = Pairer{date: tradeDate}
    }
    if p.done {
        return Quote{}, Quote{}, false
    }
    if leg == Front {
        p.front = q
    } else {
        p.next = q
    }
    p.has[leg] = true
    if !p.has[Front] || !p.has[Next] {
        return Quote{}, Quote{}, false
    }
    p.done = true
    return p.front, p.next, true
}

// Model keeps the last Slow roll yields and compares the average of the
// newest Fast of them with the average of all Slow: a daily roll yield is
// noisy (the two contracts' closes are not simultaneous and the deferred one
// trades thinly), and the fast average is what the decision reads.
type Model struct {
    fast, slow int
    ys         []float64
}

// NewModel returns a model over fast and slow yields; fast is at least 1 and
// slow at least fast+1.
func NewModel(fast, slow int) *Model {
    fast = max(fast, 1)
    return &Model{fast: fast, slow: max(slow, fast+1)}
}

// Observe records y and reports whether the average of the newest Fast
// yields is above the average of the newest Slow, y among both. ok is false
// until Slow yields are known.
func (m *Model) Observe(y float64) (above, ok bool) {
    m.ys = append(m.ys, y)
    if len(m.ys) > m.slow {
        m.ys = m.ys[len(m.ys)-m.slow:]
    }
    if len(m.ys) < m.slow {
        return false, false
    }
    return mean(m.ys[len(m.ys)-m.fast:]) > mean(m.ys), true
}

func mean(xs []float64) float64 {
    sum := 0.0
    for _, v := range xs {
        sum += v
    }
    return sum / float64(len(xs))
}

Complete source: curvewatch

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.

  1. DataRequirements subscribes to the root’s contract listings. The curve is the set known at the current decision, not a hindsight list of all eventual contracts.

  2. main.go compares successive curves and identifies the held contract. watch.go supplies the complete Diff and Held helpers.

  3. The program logs listing changes without placing orders. Its purpose is to audit which contracts and metadata the carry strategy could have selected.

Build the supplied files directly:

go build -o bin/curvewatch ./strategies/demo/go/curvewatch
bin/curvewatch --algolang-describe

This 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.

curvewatch/main.go

// Command curvewatch is the example of a strategy reading a futures curve point in time
// (docs/algolang.md, "Contract curves", GLE-410). On a continuous run of a futures root it
// declares the root's contract listing and, at each bar of the run's series, compares
// ctx.Curve with the curve at the bar before. It prints each contract that joined the curve
// (activated, first traded and known by the bar's close) and each that left it (expired), with
// the contract the continuous series holds and the days that contract has before it expires.
// It places no orders.
//
// The curve is point in time: a contract listed after a bar is never in that bar's curve,
// although the archive holds it today.
package main

import (
    "fmt"
    "os"
    "strings"

    algolang "MODULE/sdk/strategy"
)

var buildID string

// CurveWatch is the strategy: its input and the curve at the previous bar.
type CurveWatch struct {
    Root string `algolang:"default=fut:XCME:ES,desc=The futures root whose listed contracts are watched (fut:<venue>:<root>)"`

    prev []algolang.MarketListing
}

func (s *CurveWatch) Name() string { return "Curve watch" }

// 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 (s *CurveWatch) 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 (s *CurveWatch) OneBarRule() bool { return true }

func (s *CurveWatch) Description() string {
    return "Prints each contract that joins or leaves a futures root's point-in-time curve."
}

// DataRequirements declares the root's contract listing.
func (s *CurveWatch) DataRequirements() []algolang.DataRequirement {
    return []algolang.DataRequirement{{SeriesID: "curve", Symbol: s.Root, Schema: algolang.DataSchemaSpec{Kind: algolang.ContractListing}}}
}

// OnBar reports how the curve changed since the previous bar of the run's series.
func (s *CurveWatch) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !ctx.IsPrimary(bar) {
        return nil, nil
    }
    curve := ctx.Curve(s.Root)
    changes := Diff(s.prev, curve)
    s.prev = curve
    if len(changes) == 0 {
        return nil, nil
    }
    date := bar.CloseTime.UTC().Format("2006-01-02")
    if bar.Session != nil && bar.Session.TradeDate != "" {
        date = bar.Session.TradeDate
    }
    var parts []string
    for _, c := range changes {
        if c.Joined {
            parts = append(parts, fmt.Sprintf("+%s (first traded %s)", c.Listing.Contract, c.Listing.FirstBar.UTC().Format("2006-01-02")))
        } else {
            parts = append(parts, fmt.Sprintf("-%s (expired %s)", c.Listing.Contract, c.Listing.Expiration.UTC().Format("2006-01-02")))
        }
    }
    codes := make([]string, len(curve))
    for i, l := range curve {
        codes[i] = l.Contract
    }
    held := bar.ActiveContract
    if h, ok := Held(curve, bar.ActiveContract); ok {
        held += fmt.Sprintf(", %d days to expiry", int(h.Expiration.Sub(ctx.Now()).Hours()/24))
    }
    fmt.Fprintf(os.Stderr, "%s %s; curve %s; holding %s\n", date, strings.Join(parts, " "), strings.Join(codes, " "), held)
    return nil, nil
}

func main() {
    if err := algolang.Run(&CurveWatch{}); err != nil {
        fmt.Fprintf(os.Stderr, "curvewatch %s: %v\n", buildID, err)
        os.Exit(1)
    }
}

curvewatch/watch.go

package main

import (
    "strings"

    algolang "MODULE/sdk/strategy"
)

// Change is one contract that joined or left a curve between two bars.
type Change struct {
    Joined  bool                   // true: listed now and not before; false: listed before and not now
    Listing algolang.MarketListing // the contract's record: the current one when it joined, the last one when it left
}

// Diff returns the changes from the curve before to the curve now: the contracts of now that
// before lacks, which joined, then those of before that now lacks, which left, each group in
// curve order, front first. Contracts are matched by Symbol.
func Diff(before, now []algolang.MarketListing) []Change {
    in := func(curve []algolang.MarketListing, sym string) bool {
        for _, l := range curve {
            if l.Symbol == sym {
                return true
            }
        }
        return false
    }
    var out []Change
    for _, l := range now {
        if !in(before, l.Symbol) {
            out = append(out, Change{Joined: true, Listing: l})
        }
    }
    for _, l := range before {
        if !in(now, l.Symbol) {
            out = append(out, Change{Joined: false, Listing: l})
        }
    }
    return out
}

// Held returns the curve's record of the contract a continuous series holds, given as an
// engine code such as "ESM26" (Bar.ActiveContract): the record whose contract code ("M26")
// ends the held code. It reports false when the curve has no such contract.
func Held(curve []algolang.MarketListing, active string) (algolang.MarketListing, bool) {
    for _, l := range curve {
        if l.Contract != "" && strings.HasSuffix(active, l.Contract) {
            return l, true
        }
    }
    return algolang.MarketListing{}, false
}

Previous: ES/NQ relative value: one strategy, two traded symbols · Next: A dated calendar spread with combo orders