A continuous futures trend: contracts and rolls

A continuous futures trend: contracts and rolls

What a continuous contract represents

A dated futures contract has an expiry. ESZ26 is the December 2026 E-mini S&P 500 contract; the canonical data symbol is fut:XCME:ES:Z26. The quarterly month codes are H for March, M for June, U for September and Z for December. The continuous symbol fut:XCME:ES represents a sequence of held contracts chosen by marketfeed’s served roll schedule. It is a useful history for a trend calculation, but there is no exchange-listed “continuous ES” order book. Actual execution always reaches a dated contract.

The held contract changes at a roll cut, the schedule’s transition instant. This need not be expiry day or the instant your own volume comparison would choose. The engine consumes the served schedule and composite together. It does not independently elect another roll from the strategy’s bars.

The logical ES identity stays constant while its bars and execution contract change from September to December and then March. The cuts come from the served schedule.{width=“100%”}

The contract price can jump at a roll even when the underlying market has not moved: two maturities trade at different prices at the same instant. An adjustment removes that seam from the signal history. It does not book the difference as free trading profit.

ViewAt a hypothetical seam: outgoing 100, incoming 102
Panama / additiveMove earlier prices by +2 onto the incoming basis; an earlier 95 becomes 97.
RatioMultiply earlier prices by 1.02; an earlier 95 becomes 96.90.
Unadjusted (adj=none)Keep each contract’s raw history; the seam remains visible.

The bare root selects Panama; explicit composites can select :cont:adj=panama, :cont:adj=ratio or :cont:adj=none. With the default roll rebase enabled, the series history is restated onto the incoming contract’s basis at each cut. That changes historical indicator inputs as seen from the new decision, not the decisions already made. A static, end-anchored historical study with rebasing off has a different calculation frame; preserve the choice with the result.

The actual archived September 2026 roll makes the point concrete. The seam between ESU26 and ESZ26 is 67.75 points. After rebasing, the old series and any private price-valued indicator must be expressed on ESZ26’s basis.

The recorded September 2026 ES roll: the earlier history moves up by 67.75 points, then continues with ESZ26. Dashed lines show the old basis or the other contract, not an extra price history available to the earlier decision.{width=“100%”}

Choose the order identity deliberately

The signal’s data identity and an order’s destination can differ. There are three useful cases:

Order destinationPrice basis and holding behavior
Logical fut:XCME:ESUse the strategy’s adjusted price basis. The engine resolves the current held contract and translates levels. Eligible working orders follow the roll at corresponding levels.
The held code from ctx.ActiveContract(root), such as ESZ26Use raw contract prices. The order is pinned to that contract; a still-working order is cancelled at its roll and is not carried to the successor. Fills are attributed to the logical position.
Separately configured or admitted fut:XCME:ES:Z26This is a separate dated holding, even alongside continuous ES. It does not automatically roll with the continuous position. Its own series and admission are required.

A continuous signal can produce a logical order that follows the roll, a raw-priced order pinned to the currently held contract, or an order on a separately configured dated holding.{width=“100%”}

Use bar.Close and the continuous series for the signal; use bar.RawClose for a limit addressed to the held dated code. Market orders have no limit level to convert, but their destination still matters. Do not type an arbitrary future month into a continuous order and expect admission: that shortcut is for the currently held contract. To trade a different month, declare or configure it as another traded series, as the term-structure examples do.

An explicit contract address does not detach an already filled position from its continuous series. The engine still rolls that logical position. The pinning distinction governs the working order’s destination and carry-forward policy. A separate fully qualified dated holding is what you use when you intend to keep that month independently of the root’s roll.

Calculate on ES, submit to ESZ26

contracttrend is the small executable for this distinction. It holds one contract while the continuous close is above its 20-bar average. Every order uses ctx.ActiveContract(root), so in the following window it first names ESU26 and then ESZ26. It continues to query position and working exposure under the logical root. Its complete source appears later in this chapter.

go build -o bin/contracttrend ./strategies/demo/go/contracttrend
bin/algo run \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/contracttrend --symbols fut:XCME:ES --bar-interval 1d \
  --date-from 2026-09-01 --date-to 2026-10-01 \
  --inputs Window=20,Qty=1,EntryTicks=1 \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --fills-json results/learning/contract-fills.json \
  --lifecycle-json results/learning/contract-life.json \
  --plate full --color never --chart lines \
  --results-dir results/learning/contract

EntryTicks=1 makes the entry a one-bar limit bid one raw tick below the held contract’s latest close. Setting it to zero uses a market entry. With the limit, the strategy can have a valid trend and still fail to get filled; that is an execution outcome, not a missing signal. The logs show the logical signal symbol, held contract, adjusted and raw closes, average, position, target and actual order destination. Inspect those alongside the fill and lifecycle exports.

With default roll rebasing, the current bar’s adjusted and raw close usually agree: it is the earlier history that has moved into the held contract’s frame. That equality does not make the two fields interchangeable. For a diagnostic, rerun with --roll-rebase=false. In the checked September window, one ESU26 decision then has an adjusted close of 7,817 and a raw close of 7,749.25. Its one-tick bid is 7,749, addressed to ESU26. The resulting fill reaches the strategy’s OnFill under logical fut:XCME:ES, with raw price 7,749 and adjusted price 7,816.75; the execution blotter retains the dated destination. The 67.75-point difference is the price-frame translation, not an extra gain or an extra slippage charge.

The average is recomputed from SDK history at each decision, so this program has no private price-valued state to move in OnRebase. That makes it a useful first routing example. The more developed rolltrend below adds a running EMA, a protective stop and remembered price levels: those require explicit rebasing.

What the engine rolls and what the strategy restates

For an existing long continuous position, a successful roll transfers the holding by selling the outgoing contract and buying the incoming one. A short position uses the opposite legs. The engine also handles working-order cancellation/replacement and reports the lifecycle outcomes; the strategy must not submit a duplicate manual roll merely because it received OnRoll.

The conceptual sequence is:

served cut and seam
    -> roll notice and rebased strategy history
    -> cancel outgoing working orders
    -> close outgoing holding + open incoming holding
    -> restore eligible logical orders at translated levels
    -> continue decisions on the incoming contract

The simulator and supported live venue paths implement their own execution details and failure handling. Roll legs incur the applicable costs. A live roll can fail partway through; a smooth adjusted chart is not evidence of two successful broker fills. The run’s roll audit and actual exposure are the evidence.

The SDK restates the history, position cost and its working-order levels. The strategy owns any additional state it remembers: a running EMA, entry anchor, trailing high or volatility distance. Move levels and distances with the rebase helpers, or recompute them from the new history. The following strategy demonstrates that responsibility.

Our first crossover could already run on fut:XCME:ES. Now rolltrend adds a running EMA, ATR-based protection and a high-water mark, so we can see what a continuous strategy must preserve across a roll.

bin/algo run \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/rolltrend --symbols fut:XCME:ES \
  --bar-interval 1d --session eth --inputs Verbose=true \
  --date-from 2025-07-01 --date-to 2025-12-31 \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --roll-trades stitch \
  --results-dir results/learning/rolltrend

ES is a logical holding. Marketfeed supplies the continuous composite, adjustment constants and roll schedule. Algolang follows that schedule, routes orders to the held dated contract, and closes/reopens exposure at the scheduled cuts. The engine does not independently elect contracts from today’s volume or open interest.

Separate logical, raw and adjusted prices

bar.Symbol identifies the logical series. bar.ActiveContract identifies the contract that supplied that bar, and ctx.ActiveContract(symbol) answers which contract is currently held. bar.Close is in the strategy’s price frame; bar.RawClose is the underlying unadjusted observation.

An order addressed to the logical symbol uses the logical price frame. An order deliberately addressed to the held dated contract uses raw contract prices. Do not mix a raw limit with an adjusted symbol, or use a back-adjusted price as the cash cost of buying an actual historical contract.

adj=panama moves price levels additively; adj=ratio rescales them; adj=none leaves contract gaps visible. Adjustment choice is part of the hypothesis. Percentage returns and ratios can behave poorly on additive history, especially when old adjusted prices approach or cross zero.

Rebase strategy-owned memory

Roll rebasing is on by default. The engine/SDK restates the supported series, position and working-order state into the new held-contract frame. An indicator recomputed from that buffer follows the changed frame. A private running EMA or stored high must be moved by the strategy’s OnRebase:

func (s *RollTrend) move(r algolang.Rebase) {
    s.avg.Value = r.Level(s.avg.Value)
    if s.high != 0 {
        s.high = r.Level(s.high)
    }
}

This helper is called by the demo’s OnRebase. Use r.Level for prices and r.Distance for distances. Do not apply either to dimensionless ratios, quantities or timestamps. An additive roll moves a price level but not a price distance; a ratio roll changes both. OnRoll is an informational notification and cannot alter the feed’s election.

For a diagnostic experiment, rerun with --inputs MoveState=false,Verbose=true. The logs show stale private state against the new prices. This deliberately broken mode teaches why a seemingly harmless cached indicator can alter a strategy at a roll. --roll-rebase=false is a different experiment: it changes the run’s price-frame convention and is not a repair for forgotten state.

Audit the economic trade

--roll-trades stitch joins contract legs into an economic trade for reporting; split reports contract legs separately. The execution and roll costs still exist in either view. Inspect manifest.yaml, audit.jsonl, the fill blotter and data notes around a cut. Check which contracts filled, the roll prices, commissions, pending-order transfer and any degraded or provisional data.

A roll is not an ordinary strategy reversal. Do not count its close/open pair as a new alpha signal. Also do not assume every daily bar is a midnight UTC bucket: continuous daily bars normally use trade-date session composites, including session and settlement metadata. A settlement is usable only when it was published in time, not simply because the bar describes that date.

Session windows may be disjoint. The current calendar also handles an ETH definition whose evening and daytime legs straddle midnight with a gap at midnight. A preceding-evening leg still belongs to the following trade date; do not infer its date merely from which leg crosses midnight. The marketfeed update changes affected calendar/grid revisions, so historical session grouping may change. Use the served windows, not one continuous open-to-close span that would invent trading during a break.

A roll due before a live timer takes the streaming roll path first, restating the holding and strategy view before OnTimer. Read current positions and instrument identity there; do not cache the outgoing contract when arming it. Source to study: strategies/demo/go/rolltrend/main.go and sdk/strategy/rebase.go.

Complete source: contracttrend

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. Compute the SMA from the continuous series, but obtain the current dated destination from ctx.ActiveContract(root). The code never guesses a month from the calendar.

  2. Query Exposure(root) for both the logical position and working orders on its held contract. Fill notifications remain attributed to the logical root, even when an order names ESZ26.

  3. With EntryTicks greater than zero, construct the bid from bar.RawClose and the instrument tick size, then give it a one-bar expiry. Adjusted indicator values are not raw dated-contract limit prices.

  4. Recompute the SMA from SDK history after each rebase. This example keeps no private price-valued state; the next example shows how to restate a running EMA and protective levels.

Build the supplied files directly:

go build -o bin/contracttrend ./strategies/demo/go/contracttrend
bin/contracttrend --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.

contracttrend/main.go

// Command contracttrend calculates on continuous history but addresses orders
// to the dated contract that history currently holds. Its optional entry limit
// uses the contract's raw price, not the continuous adjusted price.
package main

import (
    "fmt"
    "os"

    "MODULE/indicators"
    algolang "MODULE/sdk/strategy"
)

var buildID string

type ContractTrend struct {
    Window     int `algolang:"default=20,min=2,max=500,desc=Continuous closes in the trend average"`
    Qty        int `algolang:"default=1,min=1,desc=Contracts to hold while the trend is up"`
    EntryTicks int `algolang:"default=0,min=0,desc=Zero for a market entry; otherwise bid this many ticks below the raw close for one bar"`
}

func (s *ContractTrend) Name() string { return "Continuous signal, dated order" }
func (s *ContractTrend) Description() string {
    return "Uses the continuous SMA but sends raw-priced orders to its currently held dated contract."
}
func (s *ContractTrend) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule lets the engine end eligible resting orders after the next bar.
func (s *ContractTrend) OneBarRule() bool { return true }
func (s *ContractTrend) Lookback() int    { return s.Window }

func (s *ContractTrend) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !ctx.IsPrimary(bar) {
        return nil, nil
    }
    root := bar.Symbol
    contract, ok := ctx.ActiveContract(root)
    if !ok {
        return nil, fmt.Errorf("contracttrend needs continuous bars with an active contract")
    }
    id := bar.SeriesID
    if id == "" {
        id = root
    }
    series := ctx.Series(id)
    if series.Len() < s.Window {
        return nil, nil
    }
    // These closes are the continuous signal view. Recompute from SDK history
    // each time, so there is no private EMA or price level to move on a rebase.
    average := indicators.Closes(series).SMA(s.Window).Value()
    target := int64(0)
    if bar.Close > average {
        target = int64(s.Qty)
    }
    // Positions and fills belong to the logical series. Exposure(root) also
    // includes a working order addressed to that series' active contract.
    exposure := ctx.Exposure(root)
    if len(exposure.WorkingOrders) != 0 {
        return nil, nil
    }
    delta := target - exposure.Position.Quantity
    if delta == 0 {
        return nil, nil
    }
    var order algolang.Order
    if delta > 0 {
        order = algolang.MarketBuy(contract, delta).Named("dated entry")
        if s.EntryTicks > 0 {
            tick := ctx.Instrument(root).TickSize
            if tick <= 0 {
                return nil, fmt.Errorf("no tick size for %s", root)
            }
            price := bar.RawClose - float64(s.EntryTicks)*tick
            order = algolang.LimitBuy(contract, delta, price).Named("dated bid")
            order.OneBar = true // Protobuf strategy wire; do not leave an old entry working.
        }
    } else {
        order = algolang.MarketSell(contract, -delta).Named("dated exit")
    }
    order.ClientID = fmt.Sprintf("contracttrend_%s_%d", contract, bar.CloseTime.UnixNano())
    ctx.Logf("signal=%s held=%s adjusted=%g raw=%g sma=%g position=%d target=%d order=%s limit=%g",
        root, contract, bar.Close, bar.RawClose, average, exposure.Position.Quantity,
        target, order.Symbol, order.Price)
    return []algolang.Order{order}, nil
}

func (s *ContractTrend) OnFill(ctx *algolang.Context, fill algolang.Fill) {
    ctx.Logf("fill logical=%s adjusted=%g raw=%g position=%d", fill.Symbol,
        fill.Price, fill.RawPrice(), ctx.Position(fill.Symbol).Quantity)
}
func (s *ContractTrend) OnCancel(ctx *algolang.Context, cancel algolang.OrderCancel) {
    ctx.Logf("cancel %s reason=%v", cancel.ClientID, cancel.Reason)
}

func main() {
    if err := algolang.Run(&ContractTrend{}); err != nil {
        fmt.Fprintln(os.Stderr, "contracttrend:", err)
        os.Exit(1)
    }
}

Complete source: rolltrend

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 owns SDK callbacks, the actual position and working orders. trend.go contains the running EMA, pure decision rule and tick-rounded stop calculation.

  2. OnRebase moves strategy-owned levels and distances onto the new contract basis. The SDK has already restated the series, position cost and working levels before this hook.

  3. The pure decide function distinguishes a pending entry, protective stop and pending exit. These are separate states even if the current quantity is unchanged.

Build the supplied files directly:

go build -o bin/rolltrend ./strategies/demo/go/rolltrend
bin/rolltrend --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.

rolltrend/main.go

// Command rolltrend is the demo for a strategy that keeps prices of its own
// across a continuous series' roll (the manual's "Contract rolls in a live
// strategy"). It follows the trend, long only, on one continuous future:
//
//   - flat, it buys Lots at the market when the close crosses above an EMA of
//     the closes, which it keeps as running state;
//   - once long, it places one protective GTC sell stop StopATR average true
//     ranges below its entry, and never moves it;
//   - it sells at the market when the close falls TrailATR average true
//     ranges below the highest close since the entry, which it remembers.
//
// The average true range is computed from the series on every bar, so it
// needs nothing at a roll. The EMA and the highest close are prices the
// strategy keeps itself. Under the roll rebase (on by default, GLE-1502) the
// SDK moves the series, the position and the working stop onto each new
// contract's prices, and OnRebase moves the EMA and the highest close the
// same way. With
// MoveState=false it leaves them where they were, to show what goes wrong:
// after the roll the strategy compares the new contract's prices with levels
// from the old one.
package main

import (
    "fmt"
    "os"

    "MODULE/indicators"
    algolang "MODULE/sdk/strategy"
)

var buildID string

// RollTrend is the strategy: its inputs and the prices it keeps.
type RollTrend struct {
    Lots      int     `algolang:"default=1,min=1,desc=Contracts to buy"`
    EMA       int     `algolang:"default=20,min=2,max=400,desc=The EMA's period in bars; the EMA is kept as running state"`
    ATR       int     `algolang:"default=14,min=1,max=400,desc=The average true range's period in bars; it is computed from the series on each bar"`
    StopATR   float64 `algolang:"default=4,min=0.1,desc=The protective stop's distance below the entry, in average true ranges"`
    TrailATR  float64 `algolang:"default=3,min=0.1,desc=The exit's distance below the highest close since the entry, in average true ranges"`
    Tick      float64 `algolang:"default=0,min=0,desc=The price increment for the stop; 0 takes the instrument's tick size"`
    MoveState bool    `algolang:"default=true,desc=Move the EMA and the highest close onto the new contract's prices at each roll; false shows what goes wrong"`
    Verbose   bool    `algolang:"default=false,desc=Log each bar's contract, close, EMA, ATR and exit level"`

    avg       ema     // the EMA of the closes: a price level
    prevAbove bool    // the last close was above the EMA as it stood then
    high      float64 // the highest close since the entry: a price level; 0 while flat
}

func (s *RollTrend) Name() string { return "Roll trend" }

func (s *RollTrend) Description() string {
    return "Buys when the close crosses above an EMA and trails the highest close; moves its own prices at each roll."
}

// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. Every order it rests is GTC, which the
// one-bar rule (OneBarRule) exempts, so the rule ends none of them.
func (s *RollTrend) 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 GTC and market orders.
func (s *RollTrend) OneBarRule() bool { return true }

// Lookback keeps three EMA periods of closes, from which the first bar seeds
// the EMA, and enough bars for the average true range.
func (s *RollTrend) Lookback() int {
    return max(3*s.EMA, s.ATR+1)
}

// OnBar decides on each bar of the primary symbol (decide, in trend.go).
func (s *RollTrend) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !ctx.IsPrimary(bar) {
        return nil, nil
    }
    sym := bar.Symbol
    id := bar.SeriesID
    if id == "" {
        id = sym
    }
    series := ctx.Series(id)
    s.step(series, bar.Close)
    if series.Len() < s.ATR+1 {
        return nil, nil
    }
    ohlc := indicators.FromSeries(series)
    atr := ohlc.Close.ATR(ohlc.High, ohlc.Low, ohlc.Close, s.ATR).Value()

    pos := ctx.Position(sym)
    if pos.Quantity > 0 {
        s.high = max(s.high, bar.Close)
    } else {
        s.high = 0
    }
    trail := s.high - s.TrailATR*atr
    date := tradeDate(bar)
    if s.Verbose {
        line := fmt.Sprintf("rolltrend: %s %s close %v EMA %.2f ATR %.2f", date, bar.ActiveContract, bar.Close, s.avg.Value, atr)
        if pos.Quantity > 0 {
            line += fmt.Sprintf(" long %d, exit below %.2f", pos.Quantity, trail)
        } else {
            line += " flat"
        }
        ctx.Logf("%s", line)
    }

    entry, exiting, stops := working(ctx, sym)
    st := state{
        Position:  pos.Quantity,
        Warm:      s.avg.warm(),
        PrevAbove: s.prevAbove,
        Above:     bar.Close > s.avg.Value,
        Trailed:   pos.Quantity > 0 && bar.Close < trail,
        Entry:     entry,
        Exit:      exiting,
        Stop:      len(stops) > 0,
    }
    s.prevAbove = st.Above

    switch decide(st) {
    case enter:
        ctx.Logf("rolltrend: %s close %v crossed above the EMA %.2f: buy %d", date, bar.Close, s.avg.Value, s.Lots)
        o := algolang.MarketBuy(sym, int64(s.Lots)).Named("Trend LE")
        o.ClientID = "entry-" + date
        return []algolang.Order{o}, nil
    case protect:
        tick := s.Tick
        if tick == 0 {
            tick = ctx.Instrument(sym).TickSize
        }
        level, err := stopLevel(pos.AvgPrice, s.StopATR*atr, tick)
        if err != nil {
            return nil, fmt.Errorf("rolltrend: %s: %w", sym, err)
        }
        ctx.Logf("rolltrend: %s long %d at %v: protective sell stop GTC at %v", date, pos.Quantity, pos.AvgPrice, level)
        o := algolang.StopSell(sym, pos.Quantity, level).Named("Trend stop")
        o.TIF = algolang.GTC
        o.ClientID = "stop-" + date
        return []algolang.Order{o}, nil
    case exit:
        ctx.Logf("rolltrend: %s close %v < %.2f, %v ATRs below the highest close %v: sell %d",
            date, bar.Close, trail, s.TrailATR, s.high, pos.Quantity)
        for _, id := range stops {
            ctx.Cancel(id)
        }
        o := algolang.MarketSell(sym, pos.Quantity).Named("Trend LX")
        o.ClientID = "exit-" + date
        return []algolang.Order{o}, nil
    case withdraw:
        for _, id := range stops {
            ctx.Logf("rolltrend: %s flat with the stop %s working: cancelling it", date, id)
            ctx.Cancel(id)
        }
    case short:
        return nil, fmt.Errorf("rolltrend: %s is short %d; the demo only holds a long position", sym, -pos.Quantity)
    }
    return nil, nil
}

// step moves the EMA on by one close. On the first bar it seeds the EMA from
// the warm-up history the series holds, oldest first, so the EMA starts warm.
func (s *RollTrend) step(series algolang.Series, close float64) {
    s.avg.N = s.EMA
    if s.avg.Seen > 0 {
        s.avg.add(close)
        return
    }
    closes := series.Closes()
    if len(closes) == 0 {
        closes = []float64{close}
    }
    for _, c := range closes[:len(closes)-1] {
        s.avg.add(c)
        s.prevAbove = c > s.avg.Value
    }
    s.avg.add(closes[len(closes)-1])
}

// OnRebase moves the prices the strategy keeps onto the incoming contract's
// basis (the roll rebase, on by default). The SDK has already moved the
// series, the position and the working stop. With MoveState=false it leaves
// them, and says so.
func (s *RollTrend) OnRebase(ctx *algolang.Context, r algolang.Rebase) {
    ema, high := s.avg.Value, s.high
    if s.MoveState {
        s.move(r)
    }
    note := fmt.Sprintf("rolltrend: %s rolled %s -> %s, gap %v:", r.At.UTC().Format("2006-01-02"), r.From, r.To, r.Gap)
    if s.MoveState {
        note += fmt.Sprintf(" EMA %.2f -> %.2f", ema, s.avg.Value)
        if high != 0 {
            note += fmt.Sprintf(", high %v -> %v", high, s.high)
        }
    } else {
        note += fmt.Sprintf(" EMA %.2f kept", ema)
        if high != 0 {
            note += fmt.Sprintf(", high %v kept", high)
        }
        note += " (MoveState=false)"
    }
    // The protective stop, as the SDK moved it.
    for _, w := range ctx.Exposure(r.Symbol).WorkingOrders {
        if w.Order.Side == algolang.Sell && w.Order.Type == algolang.Stop {
            note += fmt.Sprintf(", stop %v", w.Order.StopPrice)
        }
    }
    ctx.Logf("%s", note)
}

// move moves the two prices the strategy keeps by the rebase: both are price
// levels, so each moves by Level. The highest close is 0 while flat, and
// stays 0.
func (s *RollTrend) move(r algolang.Rebase) {
    s.avg.Value = r.Level(s.avg.Value)
    if s.high != 0 {
        s.high = r.Level(s.high)
    }
}

// OnFill logs each fill.
func (s *RollTrend) OnFill(ctx *algolang.Context, f algolang.Fill) {
    side := "bought"
    if f.Side == algolang.Sell {
        side = "sold"
    }
    ctx.Logf("rolltrend: %s %d %s at %v (%s)", side, f.Quantity, f.Symbol, f.Price, f.ClientID)
}

// OnCancel logs each cancel the strategy sees.
func (s *RollTrend) OnCancel(ctx *algolang.Context, c algolang.OrderCancel) {
    ctx.Logf("rolltrend: %s cancelled (reason %d)", c.ClientID, c.Reason)
}

// working reports what is working on symbol: whether a buy (the entry) or a
// market sell (the exit) is, and the labels of the sell stops (the
// protective stop). It reads each order's side and type, not its label: a
// roll places the stop again on the incoming contract, and a restart adopts
// it.
func working(ctx *algolang.Context, symbol string) (entry, exiting bool, stops []string) {
    for _, w := range ctx.Exposure(symbol).WorkingOrders {
        o := w.Order
        switch {
        case o.Side == algolang.Buy:
            entry = true
        case o.Side == algolang.Sell && o.Type == algolang.Market:
            exiting = true
        case o.Side == algolang.Sell && (o.Type == algolang.Stop || o.Type == algolang.StopLimit):
            stops = append(stops, o.ClientID)
        }
    }
    return entry, exiting, stops
}

// tradeDate is the bar's exchange trade date, else its close's UTC date.
func tradeDate(bar algolang.Bar) string {
    if bar.Session != nil && bar.Session.TradeDate != "" {
        return bar.Session.TradeDate
    }
    return bar.CloseTime.UTC().Format("2006-01-02")
}

func main() {
    if err := algolang.Run(&RollTrend{}); err != nil {
        fmt.Fprintln(os.Stderr, "rolltrend:", err)
        os.Exit(1)
    }
}

rolltrend/trend.go

package main

import (
    "errors"
    "fmt"
    "math"
    "strconv"
    "strings"
)

// ema is an exponential moving average of the closes, kept as running state:
// one update per close, alpha = 2/(N+1), seeded with the first close. Its
// value is a price level, so a roll moves it by the rebase's Level.
type ema struct {
    N     int     // the period, in bars
    Value float64 // the average after the last close
    Seen  int     // the closes it has taken
}

// add takes one close.
func (e *ema) add(close float64) {
    if e.Seen == 0 {
        e.Value = close
    } else {
        e.Value += 2 / float64(e.N+1) * (close - e.Value)
    }
    e.Seen++
}

// warm reports whether the average has taken at least N closes.
func (e ema) warm() bool { return e.Seen >= e.N }

// state is what the decision reads on each bar.
type state struct {
    Position  int64 // the symbol's position, signed
    Warm      bool  // the EMA has taken its period of closes
    PrevAbove bool  // the previous close was above the EMA as it stood then
    Above     bool  // this close is above the EMA
    Trailed   bool  // this close is TrailATR ATRs or more below the highest close since the entry
    Entry     bool  // a buy is working
    Exit      bool  // a market sell is working
    Stop      bool  // the protective sell stop is working
}

// action is the decision: at most one order, and what it is for.
type action int

const (
    hold     action = iota // nothing to send
    enter                  // buy Lots at the market
    protect                // place the protective stop below the entry
    exit                   // sell the position at the market and cancel the stop
    withdraw               // flat with the stop working: cancel it
    short                  // short: the demo never sells short, so it stops
)

// decide is the demo's whole rule. Flat, it buys when the close crosses above
// the EMA. Long, it places one protective stop and sells when the close falls
// far enough below the highest close since the entry. A stop left working
// while flat protects nothing and is cancelled.
func decide(s state) action {
    switch {
    case s.Position < 0:
        return short
    case s.Position == 0 && s.Stop:
        return withdraw
    case s.Position == 0 && !s.Entry && s.Warm && !s.PrevAbove && s.Above:
        return enter
    case s.Position > 0 && !s.Exit && s.Trailed:
        return exit
    case s.Position > 0 && !s.Exit && !s.Stop:
        return protect
    }
    return hold
}

// stopLevel is the protective stop's price: dist below entry, rounded down to
// a whole tick so the venue takes it as it stands.
func stopLevel(entry, dist, tick float64) (float64, error) {
    if tick <= 0 || math.IsNaN(tick) || math.IsInf(tick, 0) {
        return 0, errors.New("no tick size for the symbol: set the Tick input")
    }
    raw := entry - dist
    if !(raw > 0) || math.IsInf(raw, 0) {
        return 0, fmt.Errorf("a stop %v below %v is not a positive price", dist, entry)
    }
    // The small allowance keeps a level already on a tick on that tick.
    n := math.Floor(raw/tick + 1e-9)
    decimals := 0
    if s := strconv.FormatFloat(tick, 'f', -1, 64); strings.Contains(s, ".") {
        decimals = len(s) - strings.IndexByte(s, '.') - 1
    }
    return strconv.ParseFloat(strconv.FormatFloat(n*tick, 'f', decimals, 64), 64)
}

Previous: A random exit in the final five minutes of RTH · Next: ES/NQ relative value: one strategy, two traded symbols