Momentum ranking: daily and intraday ETF baskets

Momentum ranking: daily and intraday ETF baskets

The spread strategies compare two instruments. Now let one strategy compare an entire basket, choose its holdings and send orders to several symbols. momentumrank goes long the strongest positive momentum and short the strongest negative momentum. We first run it on daily bars, then give the same ranking rule a five-minute clock and a New York trading window.

This is one multi-symbol strategy with one account. Twelve symbols do not mean twelve independent strategy runs, and the trade director’s ranking of orders from separate strategies is a different mechanism.

Define the rule before choosing the basket

For each symbol, calculate close_now / close_Window_bars_ago - 1. Thus a move from 100 to 112 has momentum +12%, and a move from 100 to 85 has momentum −15%. This compares returns rather than dollar price changes.

At a rebalance:

  1. Rank positive returns from greatest to least and select up to Longs.
  2. Rank negative returns from most negative toward zero and select up to Shorts. Zero momentum qualifies for neither side.
  3. Give each selected holding the same Notional dollar budget, rounded down to whole shares using its raw current price.
  4. Set every unselected symbol’s target to zero. Subtract each actual filled position from its target and submit the difference as a market order.

Equal scores are broken by symbol name, so callback order cannot break a tie. If only one symbol is falling, only one short slot is used: this is not a rule that shorts rising markets merely because they rose less. A selected share costing more than the slot’s budget gets zero shares; the demo does not replace it with the next-ranked candidate.

InputDefaultMeaning
Window63Momentum spans this many completed bar-to-bar returns; it needs 64 closes.
Longs, Shorts3 eachMaximum number of positive longs and negative shorts. Either may be zero, but not both.
Notional10000Fixed USD budget per selected holding, not a percentage of equity.
RebalanceEvery21Complete eligible basket observations between rebalances; the first ready observation rebalances immediately.
IntradayfalseEnable the five-minute clock and intraday entry/exit rules.
Start, End10:00, 14:00New York entry start and planned flat time in intraday mode.
CalendartrueIntraday mode requests served calendars and brings the exit forward for an earlier session close.
LogtruePrint the momentum, target and current position of every candidate at each rebalance.

At the default counts and budget, six filled slots represent approximately USD 60,000 gross exposure before price changes. With three slots on each side, net dollar exposure is approximately zero, but neither dollar nor market-beta neutrality is guaranteed: share rounding and unequal sign counts matter. Empty slots do not transfer their budgets to the other positions.

For example, a target of −10 shares against an actual +8-share position requires a sell of 18: eight to close and ten to open short. No isLong flag or remembered submission quantity can substitute for the filled position.

Run a twelve-ETF daily basket

The worked universe contains three broad equity proxies, gold, Treasuries and seven equity-sector funds:

SymbolsRole in this example
SPY, QQQ, IWMBroad US, Nasdaq-100 and smaller-company equities
GLD, TLTGold and longer-duration US Treasuries
XLE, XLF, XLKEnergy, financials and technology
XLV, XLI, XLP, XLUHealth care, industrials, consumer staples and utilities

This is a readable example universe, not twelve independent sources of risk. The equity funds overlap substantially. Membership is supplied by the run; you can replace it with another USD ETF basket without recompiling. The total requested long and short slots must fit within the configured basket.

Build the program, then run from the checkout root. The ordinary shell variables below keep the long symbol list readable. Give the run a short explicit ID: a generated ID containing twelve canonical symbols can exceed the filesystem’s directory-name limit.

go build -o bin/momentumrank ./strategies/demo/go/momentumrank
DAILY_ETFS=eq:ARCX:SPY:adj=split,eq:XNAS:QQQ:adj=split,eq:ARCX:IWM:adj=split
DAILY_ETFS=$DAILY_ETFS,eq:ARCX:GLD:adj=split,eq:XNAS:TLT:adj=split,eq:ARCX:XLE:adj=split
DAILY_ETFS=$DAILY_ETFS,eq:ARCX:XLF:adj=split,eq:ARCX:XLK:adj=split,eq:ARCX:XLV:adj=split
DAILY_ETFS=$DAILY_ETFS,eq:ARCX:XLI:adj=split,eq:ARCX:XLP:adj=split,eq:ARCX:XLU:adj=split
bin/algo run --run-id momentum-daily \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/momentumrank --symbols "$DAILY_ETFS" --bar-interval 1d \
  --inputs Window=63,Longs=3,Shorts=3,Notional=10000,RebalanceEvery=21 \
  --date-from 2025-01-02 --date-to 2025-12-31 --initial-capital 100000 \
  --commission-per-share 0.005 --slippage-ticks 1 \
  --plate full --color never --chart lines \
  --fills-json results/learning/momentum-daily-fills.json \
  --results-dir results/learning/momentum-daily

The 63/21 defaults are roughly a quarter’s momentum and a month’s rebalance spacing on complete daily data. They are bar counts, not calendar months or month-end scheduling. Use Longs=2,Shorts=2 for two holdings per side, or Shorts=0 for a long-only variation. Keep the rest of the inputs in the comma-separated --inputs value when changing them.

Daily signals use split-adjusted closes so a share split does not look like a large loss. Sizing uses Bar.RawPrice(FieldClose), which returns the actual share price even when the signal’s series is adjusted. The selected view is price momentum, not a claim to have measured reinvested total returns.

Rank a complete observation, then reconcile positions

A basket’s daily bars need not have identical timestamps. key uses each bar’s served trade date; for a plain fixture without session metadata, it uses the New York date. OnBar waits until every symbol has that date and until all dates across the entire lookback match. Each history must contain Window + 1 closes. The SDK’s historical warm-up can therefore prepare the first rank, but insufficient warm-up delays trading rather than producing a shorter, different signal.

The complete lookback check matters. If one symbol is missing Wednesday, “five bars ago” can mean a different date for it than for the other eleven. This implementation skips that observation instead of comparing unequal periods or silently carrying a stale price. With a missing bar, the affected window must pass out of history before the full panel becomes usable again. No valid panel means no new daily rebalance; existing holdings remain, so missing data is also a risk-management consideration.

There is one rebalance per eligible panel, not one per callback. On a due rebalance, any working order postpones the entire basket until another complete panel arrives with no unresolved orders. Orders target filled positions, including closing symbols that fall out of the selection and reversing those that change sides. Shares then remain unchanged until the next rebalance, apart from actual execution and engine corporate-action handling; the strategy does not keep private price or share targets that would need restating after a split.

The basket is not atomic. Fills occur separately on each instrument’s following eligible bar. A refusal or partial fill can leave fewer positions than intended; the next scheduled rebalance reads that actual state. This demo has no immediate retry loop or portfolio-wide transaction guarantee. Inspect positions, open orders, costs and equity as well as the ranking log.

Check the daily rule without an archive

docs/examples/momentum-daily.csv contains invented daily prices for twelve labels, M01 through M12. With a two-return window and two slots per side, its first selection can be checked by hand:

LabelMomentumTarget shares at USD 1,000 per slot
M01+20%+8
M02+10%+9
M03–M06+5%, +3%, +2%, +1%0
M070%0
M08–M10−1%, −2%, −5%0
M11−10%−11
M12−20%−12
bin/algo run --run-id momentum-fixture \
  --adapter bin/file-csv-adapter --data-protocol pb \
  --adapter-inputs Path=docs/examples/momentum-daily.csv,Interval=1d,TickSize=0.01,PointValue=1 \
  --strategy bin/momentumrank \
  --symbols M01,M02,M03,M04,M05,M06,M07,M08,M09,M10,M11,M12 --bar-interval 1d \
  --inputs Window=2,Longs=2,Shorts=2,Notional=1000,RebalanceEvery=2 \
  --commission-per-share 0.005 --slippage-ticks 1 \
  --cache off --plate full --color never --chart lines \
  --fills-json results/learning/momentum-fixture-fills.json \
  --results-dir results/learning/momentum-fixture

The 4 March decisions first fill on 5 March. On 6 March the leaders and laggards switch sides; those reversals fill on 9 March. A final switch fills on 11 March. There are twelve fills in all. The smoke check verifies exact share quantities, next-bar prices, slippage and commission, then reverses the input symbol order and verifies that the economic result is unchanged.

Trade five-minute momentum from 10:00 to 14:00 New York

The intraday variant keeps the ranking and sizing rules, but changes four things: the observation clock, the momentum horizon, the rebalance cadence and the holding window. Use the same twelve ETFs with raw symbols. Marketfeed’s current adjusted-equity path does not serve five-minute session grid bars; using :adj=split in this command is refused.

INTRADAY_ETFS=eq:ARCX:SPY,eq:XNAS:QQQ,eq:ARCX:IWM,eq:ARCX:GLD
INTRADAY_ETFS=$INTRADAY_ETFS,eq:XNAS:TLT,eq:ARCX:XLE,eq:ARCX:XLF,eq:ARCX:XLK
INTRADAY_ETFS=$INTRADAY_ETFS,eq:ARCX:XLV,eq:ARCX:XLI,eq:ARCX:XLP,eq:ARCX:XLU
bin/algo run --run-id momentum-intraday \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/momentumrank --symbols "$INTRADAY_ETFS" \
  --bar-interval 5m --session rth \
  --inputs Intraday=true,Window=5,Longs=3,Shorts=3,Notional=10000,RebalanceEvery=6,Start=10:00,End=14:00 \
  --date-from 2026-03-06 --date-to 2026-03-13 --initial-capital 100000 \
  --commission-per-share 0.005 --slippage-ticks 1 \
  --plate full --color never --chart lines \
  --fills-json results/learning/momentum-intraday-fills.json \
  --results-dir results/learning/momentum-intraday

Window=5 compares six closes, spanning 25 minutes of complete five-minute data. Regular-session closes from 09:35 through 10:00 make the first 10:00 ranking possible. RebalanceEvery=6 normally means every 30 minutes, starting at 10:00. A longer window delays the first eligible rank: Window=12 needs thirteen same-day closes and ordinarily becomes ready at 10:35.

Raw intraday momentum is deliberately confined to the current New York date. It does not compare this morning’s price with yesterday’s raw price across a split, distribution or overnight gap. Each morning the rebalance counter resets and the strategy waits for its new window. In this mode the whole basket must also share exact close instants across that window. A missing five-minute bar blocks a rank until the histories match again.

America/New_York supplies the clock, including daylight saving. In the example week, 10:00 is 15:00 UTC on 6 March and 14:00 UTC on 13 March. The code compares time instants; it does not encode either UTC offset as a permanent rule.

Make the end of the window executable

New York decision time on a normal full sessionBehavior
Before 10:00No entries. Flatten any residual position on that symbol’s own bar.
10:00 through 13:50Rebalance when a complete panel is ready and due. The most recent completed bar supplies the signal.
13:55Stop entries and submit market exits on each held symbol’s own bar.
14:00 and laterNo entries. Reconcile any residual exposure; report an unflattened holding at shutdown.

Under the ordinary next-bar model, an exit decided at 13:55 can execute on the 13:55–14:00 bar, normally its opening price. The fill record is stamped with that bar’s close. This is not an order first submitted at 14:00 and retroactively filled at 13:55, nor is it a promise of a 14:00 auction price. Submitting at the 14:00 callback would normally need the next bar and miss the intended window.

Calendar=true requests the served exchange calendars. The exit deadline is five minutes before the earlier of the configured end and the earliest basket RTH close. On a 13:00 half-day, the exit decisions therefore begin at 12:55. Missing calendar facts cause an error rather than an assumed session.

Exit handling runs before the lookback and complete-panel checks, so it can flatten a symbol even when another member’s data is missing. It cancels unresolved entry/rebalance orders first and waits for their outcome before submitting another order. Existing window-exit orders are left working.

The intended holding window is 10:00–14:00. A missing exit bar, delayed fill or unresolved cancellation can prevent being flat by 14:00. Recovery exits remain allowed outside the entry window, and UNFLATTENED in the final log identifies exposure left at shutdown. For a strict live deadline, combine calendar timers, sufficiently fine execution data and an explicit venue failure policy; a five-minute bar-only simulation cannot guarantee a broker fill at an exact clock instant.

Check the clock across daylight saving

The second invented fixture spans 6 and 13 March 2026 and deliberately omits M12’s 10:30 bar on the second date. Its prices change direction around midday. It checks ranking changes, a missing panel, both UTC offsets and the final flattening without needing a marketfeed archive.

bin/algo run --run-id momentum-clock-fixture \
  --adapter bin/file-csv-adapter --data-protocol pb \
  --adapter-inputs Path=docs/examples/momentum-intraday.csv,Interval=5m,TickSize=0.01,PointValue=1 \
  --strategy bin/momentumrank \
  --symbols M01,M02,M03,M04,M05,M06,M07,M08,M09,M10,M11,M12 --bar-interval 5m \
  --inputs Intraday=true,Calendar=false,Window=5,Longs=3,Shorts=3,Notional=1000,RebalanceEvery=6 \
  --commission-per-share 0.005 --slippage-ticks 1 \
  --cache off --plate full --color never --chart lines \
  --fills-json results/learning/momentum-clock-fixture-fills.json \
  --results-dir results/learning/momentum-clock-fixture

Calendar=false is specific to these invented, known full sessions: the CSV contains no calendar service. Keep the default calendar check for the archive example. The smoke check expects 36 fills, no position carried between the two dates, no entry decision before 10:00 or at/after 13:55, and every scheduled exit filled on the bar stamped 14:00 New York. This is an execution check on invented prices, not evidence of profitable intraday momentum.

Evaluate the basket and its assumptions

Compare turnover, net performance after costs, gross and net exposure, drawdown and the contribution of each symbol. Record how many long and short slots were actually filled, how often data prevented a rebalance and whether the result depended on one instrument or market period. The daily and intraday variants have very different turnover; the same commission and slippage settings should not imply equally realistic execution.

The commands include commission and slippage. They do not establish short borrow availability, borrow fees, financing costs, realistic market impact or guaranteed liquidity. A fixed dollar budget does not resize with equity, enforce a leverage ceiling, make correlated ETFs independent or implement an account drawdown stop. Add those mechanisms deliberately and test their interaction with closing old positions and opening new ones.

A fixed basket selected today can introduce universe-selection and survivorship bias. Preserve the membership rule and data vintage, and reserve out-of-sample periods before tuning the window, counts or cadence. Do not choose the universe simply because its members won in the test period.

For futures-group representatives, reuse the ranking idea but change the instrument model deliberately. This executable rejects futures and non-USD or non-unit point values. A futures version needs contract multipliers, currency conversion where applicable, margin-aware sizing and a documented continuous-price return convention. Percentage momentum on additive history can be distorted, especially near zero; raw held-contract price changes also include roll gaps. The continuous-futures chapter explains why this is more than replacing ETF tickers with ES, GC, CL and a softs contract.

Complete source: momentumrank

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. OnInit collects the configured traded universe, validates USD share metadata and slot counts, and sorts symbols. IsMultiSymbol advertises the basket interface; Lookback retains the extra close required for a return.

  2. key groups daily closes by trade date and five-minute closes by exact instant. OnBar checks the entire shared history before ranking, uses current-day history for intraday signals, and counts complete panels only.

  3. rankTargets sorts positive and negative returns separately, resolves ties by symbol, and sizes whole shares from raw prices. Missing sign candidates leave slots empty.

  4. A rebalance subtracts the actual position from each target, including zero targets for dropped symbols. Working orders postpone a new basket; independent market orders are not an atomic portfolio transaction.

  5. Intraday deadlines use New York time and the earliest served RTH close. flatten runs on each symbol before ranking checks, cancels unresolved entries, and keeps exit orders working. Shutdown logging exposes residual holdings.

Build the supplied files directly:

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

momentumrank/main.go

// Command momentumrank trades a basket of USD ETFs in one strategy instance.
// Rank split-adjusted returns, take only positive longs and negative shorts,
// and size each selected slot to the same raw-price dollar budget. Daily and
// five-minute variants share the rule; Intraday adds a New York entry window.
package main

import (
    "fmt"
    "math"
    "os"
    "sort"
    "strings"
    "time"
    _ "time/tzdata"

    algolang "MODULE/sdk/strategy"
)

var buildID string

type MomentumRank struct {
    Window         int     `algolang:"default=63,min=1,max=500,desc=Bars back for percentage momentum"`
    Longs          int     `algolang:"default=3,min=0,max=100,desc=Maximum positive-momentum long positions"`
    Shorts         int     `algolang:"default=3,min=0,max=100,desc=Maximum negative-momentum short positions"`
    Notional       float64 `algolang:"default=10000,min=1,max=1000000000,desc=USD budget per selected position"`
    RebalanceEvery int     `algolang:"default=21,min=1,max=1000,desc=Complete eligible basket panels between rebalances"`
    Intraday       bool    `algolang:"default=false,desc=Use synchronized five-minute bars and a New York entry window"`
    Calendar       bool    `algolang:"default=true,desc=Use served calendars to exit before an early session close; false for synthetic fixtures only"`
    Start          string  `algolang:"default=10:00,desc=New York start of intraday entries (HH:MM)"`
    End            string  `algolang:"default=14:00,desc=Planned intraday flat time; exit decisions start five minutes earlier"`
    Log            bool    `algolang:"default=true,desc=Log scores targets and incomplete execution"`

    symbols                  []string
    known                    map[string]bool
    zone                     *time.Location
    start, exit              int
    day, last                string
    panels, next, rebalances int
}

func (s *MomentumRank) Name() string        { return "Basket momentum ranking" }
func (s *MomentumRank) IsMultiSymbol() bool { return true }
func (s *MomentumRank) Description() string {
    return "Long the strongest positive returns and short the weakest negative returns in a synchronized USD ETF basket."
}
func (s *MomentumRank) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule lets the engine end eligible resting orders after the next bar.
func (s *MomentumRank) OneBarRule() bool    { return true }
func (s *MomentumRank) Lookback() int       { return s.Window + 1 }
func (s *MomentumRank) NeedsCalendar() bool { return s.Intraday && s.Calendar }

func (s *MomentumRank) OnInit(_ *algolang.Context, cfg algolang.InitConfig) error {
    if s.Window < 1 || s.RebalanceEvery < 1 || !positive(s.Notional) ||
        s.Longs < 0 || s.Shorts < 0 || s.Longs+s.Shorts == 0 {
        return fmt.Errorf("invalid momentum window, rebalance period, budget or slot counts")
    }
    s.symbols, s.known = nil, make(map[string]bool)
    for _, in := range cfg.Instruments {
        if in.Symbol == "" || s.known[in.Symbol] {
            return fmt.Errorf("basket needs distinct nonempty instrument symbols")
        }
        if strings.HasPrefix(in.Symbol, "fut:") || in.PointValue != 1 || in.Currency != "USD" {
            return fmt.Errorf("%s: this example needs USD share instruments with point value 1", in.Symbol)
        }
        s.symbols = append(s.symbols, in.Symbol)
        s.known[in.Symbol] = true
    }
    if len(s.symbols) < 2 || s.Longs+s.Shorts > len(s.symbols) {
        return fmt.Errorf("momentumrank needs a basket at least as large as Longs+Shorts (and at least two symbols)")
    }
    sort.Strings(s.symbols) // Stable ties, logs and order submission, independent of CLI ordering.
    var err error
    if s.zone, err = time.LoadLocation("America/New_York"); err != nil {
        return err
    }
    if s.start, err = minute(s.Start); err != nil {
        return err
    }
    end, err := minute(s.End)
    if err != nil {
        return err
    }
    s.exit = end - 5
    if s.start%5 != 0 || end%5 != 0 || s.start >= s.exit {
        return fmt.Errorf("Start and End need five-minute boundaries and at least ten minutes between them")
    }
    s.day, s.last, s.panels, s.next, s.rebalances = "", "", 0, 1, 0
    return nil
}

func minute(clock string) (int, error) {
    t, err := time.Parse("15:04", clock)
    if err != nil {
        return 0, fmt.Errorf("invalid New York clock %q: %w", clock, err)
    }
    return t.Hour()*60 + t.Minute(), nil
}

func (s *MomentumRank) key(b algolang.Bar) string {
    if s.Intraday {
        return b.CloseTime.UTC().Format(time.RFC3339Nano)
    }
    if b.Session != nil && b.Session.TradeDate != "" {
        return b.Session.TradeDate
    }
    return b.CloseTime.In(s.zone).Format("2006-01-02")
}

func (s *MomentumRank) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !s.known[bar.Symbol] {
        return nil, nil
    }
    if s.Intraday {
        local := bar.CloseTime.In(s.zone)
        date := local.Format("2006-01-02")
        if date != s.day {
            s.day, s.panels, s.next = date, 0, 1
        }
        m := local.Hour()*60 + local.Minute()
        exit := s.exit
        if s.Calendar {
            // Use the earliest basket session close, including shortened sessions.
            for _, symbol := range s.symbols {
                cal, ok := ctx.Calendar(symbol)
                day, exists := cal.Day(date)
                if !ok || !exists || day.RTH == nil {
                    return nil, fmt.Errorf("%s: no RTH calendar for %s", symbol, date)
                }
                close := day.RTH.Close.In(s.zone)
                exit = min(exit, close.Hour()*60+close.Minute()-5)
            }
        }
        if m < s.start || m >= exit {
            // Exits do not need a complete ranking panel or an indicator. Reconcile
            // each symbol on its own bar, including recovery outside the entry window.
            return s.flatten(ctx, bar), nil
        }
        if bar.CloseTime.Sub(bar.OpenTime) != 5*time.Minute {
            return nil, fmt.Errorf("intraday momentumrank requires five-minute decision bars")
        }
    }
    key := s.key(bar)
    if key == s.last {
        return nil, nil
    }
    // All symbols must have the same observation keys over the entire window.
    // Daily closes may differ by seconds. Intraday closes must be equal instants.
    // Missing bars skip the panel; never carry yesterday's loser into today's rank.
    anchor := ctx.Series(s.symbols[0])
    if anchor.Len() <= s.Window || s.key(anchor.Bar(0)) != key {
        return nil, nil
    }
    var candidates []candidate
    for _, symbol := range s.symbols {
        series := ctx.Series(symbol)
        if series.Len() <= s.Window {
            return nil, nil
        }
        for i := 0; i <= s.Window; i++ {
            b := series.Bar(i)
            // Raw intraday ETF bars must not compare across an overnight split
            // or dividend gap. Build this morning's window afresh every session.
            if s.Intraday && b.CloseTime.In(s.zone).Format("2006-01-02") != s.day {
                return nil, nil
            }
            if b.CloseTime.After(ctx.Now()) || s.key(b) != s.key(anchor.Bar(i)) {
                return nil, nil
            }
            if i > 0 && !b.CloseTime.Before(series.Bar(i-1).CloseTime) {
                return nil, fmt.Errorf("%s: bars must advance in time", symbol)
            }
            if !s.Intraday && i > 0 && s.key(b) == s.key(series.Bar(i-1)) {
                return nil, fmt.Errorf("daily momentumrank needs one bar per trade date")
            }
        }
        now, then := series.Close(0), series.Close(s.Window)
        raw := series.Bar(0).RawPrice(algolang.FieldClose)
        if !positive(now) || !positive(then) || !positive(raw) {
            return nil, fmt.Errorf("%s: momentum and sizing need positive finite prices", symbol)
        }
        candidates = append(candidates, candidate{symbol, now/then - 1, raw})
    }
    s.last = key
    s.panels++
    if s.panels < s.next {
        return nil, nil
    }
    // Do not stack another basket over unresolved earlier orders. A due rebalance
    // waits until the next complete panel with no working orders.
    if len(ctx.WorkingOrders()) != 0 {
        s.log(ctx, "rank at=%s waiting for working orders", key)
        return nil, nil
    }
    targets, err := rankTargets(candidates, s.Longs, s.Shorts, s.Notional)
    if err != nil {
        return nil, err
    }
    s.next = s.panels + s.RebalanceEvery
    s.rebalances++
    var orders []algolang.Order
    for _, c := range candidates {
        position := ctx.Position(c.symbol).Quantity
        target := targets[c.symbol] // Unselected symbols explicitly want flat.
        s.log(ctx, "rank at=%s symbol=%s momentum=%.6f target=%d position=%d",
            key, c.symbol, c.score, target, position)
        if delta := target - position; delta != 0 {
            orders = append(orders, rebalanceOrder(c.symbol, delta, bar.CloseTime, "rank rebalance"))
        }
    }
    return orders, nil
}

func (s *MomentumRank) flatten(ctx *algolang.Context, bar algolang.Bar) []algolang.Order {
    exposure := ctx.Exposure(bar.Symbol)
    if len(exposure.WorkingOrders) != 0 {
        for _, w := range exposure.WorkingOrders {
            if w.Order.Name != "window exit" && w.Status != algolang.OrderStatusPendingCancel {
                ctx.Cancel(w.Order.ClientID)
            }
        }
        s.log(ctx, "window exit at=%s symbol=%s waiting for working orders", bar.CloseTime, bar.Symbol)
        return nil
    }
    if exposure.Position.Quantity == 0 {
        return nil
    }
    s.log(ctx, "window exit at=%s symbol=%s position=%d", bar.CloseTime, bar.Symbol, exposure.Position.Quantity)
    return []algolang.Order{rebalanceOrder(bar.Symbol, -exposure.Position.Quantity, bar.CloseTime, "window exit")}
}

func rebalanceOrder(symbol string, delta int64, at time.Time, name string) algolang.Order {
    o := algolang.MarketBuy(symbol, delta).Named(name)
    if delta < 0 {
        o = algolang.MarketSell(symbol, -delta).Named(name)
    }
    o.ClientID = fmt.Sprintf("rank_%s_%d", symbol, at.UnixNano())
    return o
}

func (s *MomentumRank) log(ctx *algolang.Context, format string, args ...any) {
    if s.Log {
        ctx.Logf(format, args...)
    }
}

func (s *MomentumRank) OnShutdown(ctx *algolang.Context) {
    s.log(ctx, "momentumrank rebalances=%d", s.rebalances)
    for _, symbol := range s.symbols {
        if s.Intraday && ctx.Position(symbol).Quantity != 0 {
            s.log(ctx, "UNFLATTENED symbol=%s quantity=%d: inspect missing bars or execution outcomes",
                symbol, ctx.Position(symbol).Quantity)
        }
    }
}

type candidate struct {
    symbol string
    score  float64
    raw    float64
}

func positive(x float64) bool { return x > 0 && !math.IsInf(x, 0) }

// rankTargets uses independent sign filters and deterministic symbol tie breaks.
// Unused slots stay empty; a selected but unaffordable share is not substituted.
func rankTargets(values []candidate, longs, shorts int, budget float64) (map[string]int64, error) {
    values = append([]candidate(nil), values...)
    for _, c := range values {
        if math.IsNaN(c.score) || math.IsInf(c.score, 0) || !positive(c.raw) {
            return nil, fmt.Errorf("%s: invalid ranking price or return", c.symbol)
        }
    }
    targets := make(map[string]int64)
    for _, side := range []int64{1, -1} {
        sort.Slice(values, func(i, j int) bool {
            if values[i].score == values[j].score {
                return values[i].symbol < values[j].symbol
            }
            return float64(side)*values[i].score > float64(side)*values[j].score
        })
        count := longs
        if side < 0 {
            count = shorts
        }
        for i, c := range values {
            if i >= count || float64(side)*c.score <= 0 {
                break
            }
            shares := math.Floor(budget / c.raw)
            if shares >= float64(math.MaxInt64) {
                return nil, fmt.Errorf("%s: share quantity overflows", c.symbol)
            }
            targets[c.symbol] = side * int64(shares)
        }
    }
    return targets, nil
}

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

Previous: A dated calendar spread with combo orders · Next: A volume-bar trend with flow confirmation