A portfolio of crossover strategies

A portfolio of crossover strategies

We now return to the simple strategy and run several independent instances. Each instance has its own parameters, holdings and capital share. Save this as examples/learning/portfolio.json:

{
  "global": {
    "data": {"adapter": "bin/marketfeed-adapter", "data-protocol": "pb"},
    "strategy": "bin/smacross",
    "bar-interval": "1d",
    "date-from": "2020-01-01",
    "date-to": "2024-12-31",
    "initial-capital": "USD200000",
    "commission-mode": "per-unit",
    "commission-amount": 2.50,
    "slippage-ticks": 1,
    "results-dir": "results/learning/portfolio",
    "report": {"equity-sampling": "bar"}
  },
  "runs": [
    {"id": "es-slow", "symbol": "fut:XCME:ES", "capital-units": 1,
      "inputs": {"Fast": 20, "Slow": 200}},
    {"id": "nq-medium", "symbol": "fut:XCME:NQ", "capital-units": 1,
      "inputs": {"Fast": 10, "Slow": 100}}
  ]
}

Run the preflight and then the study:

bin/algo run --config examples/learning/portfolio.json --verify
bin/algo run --config examples/learning/portfolio.json \
  --plate full --color never --chart lines \
  --export results/learning/portfolio.algorun
bin/algo report results/learning/portfolio --runs es-slow

--verify expands and checks the plan and adapter prerequisites without fetching bars or trades. It does not prove that a strategy will never fail later, that every session has every bar, or that a hypothesis is profitable.

Understand capital and execution scope

The explicit global pool is USD 200,000. With equal capital-units, each configured run receives USD 100,000. Without an explicit pool, each expanded run independently gets the default capital. Doubling the number of runs can therefore double the apparent starting capital unless you specify it.

This config executes runs sequentially, each with its own account, then combines the curves. It is a portfolio report, not a simulation of shared cash, contemporaneous cross-strategy decisions or competition for one margin pool. A strategy’s ctx.Portfolio() during these backtests sees its own one-member portfolio. Keep that limitation attached to any combined result.

Config vocabulary differs slightly from single-run flags: it uses commission-mode (per-unit or per-trade) and commission-amount. Protocol and universe-expansion keys belong inside data; read warnings about unknown fields even when verification exits successfully. symbols inside a config run is slash-separated, whereas CLI --symbols is comma-separated. A series array is clearer for mixed intervals. To use different strategy executables, set strategy on each run or group them under the top-level strategies array.

Add governed orders, then distinguish a shared desk

A trade director is a gate between a strategy’s proposed order and admission. For an executable example, save the following as examples/learning/director.json:

{
  "director": {
    "version": 1,
    "rules": [
      {"rule": "max-directional-exposure",
        "symbol": "fut:XCME:ES", "max-short-quantity": 0},
      {"rule": "entry-rate", "max": 1, "window": "720h"}
    ]
  }
}

Run the preceding portfolio command with --director examples/learning/director.json. In this backtest the director is applied separately to each run. The ES-specific rule disallows opening short ES; the entry-rate rule limits openings per run. The results directory supplies somewhere to write director-decisions.jsonl.

The crossover can request a sell of two to reverse a long. The director may allow the reducing unit and trim the opening unit. Strategy state must follow the accepted quantities and actual fills. Inspect both the decision log and the final position; counting requested orders is not an exposure measure.

Other director rules cover position counts, deployed value, margin, drawdown, liquidity, historical risk and conviction ranking. rankedcross demonstrates conviction-bearing orders. A ranking rule only makes sense when candidates share a meaningful scale and missing values have an explicit policy.

A concurrently governed multi-member portfolio belongs to the desk/deployment workflow (algo run --deploy), with visibility and director ownership set there. It needs the separate desk setup and its supported clock/venue configuration. A portfolio.director field in a research config does not magically produce that shared backtest; the ordinary backtest notes that it does not apply that portfolio director. Treat shared-account research as a separate requirement, not a stronger interpretation of this report.

Resume a member with an explicit adoption policy

A live run with recovery now refuses to start by default if the strategy’s own book contains a non-flat position or a working order, before handing either to the strategy. The refusal exits with status 78, and a deployment supervisor does not keep restarting that member. Other members can continue.

Use --allow-open-positions only when the strategy is ready to adopt those holdings. The config equivalent is "open-positions": "adopt" inside data; a deployment member uses "start": "adopt", with refuse the default. A supervisor-level flag applies to every member and restart. This permits OnAdoptedState delivery; it does not reconstruct a private signal history, campaign counter or event EMA. Adopted desk positions now retain the desk’s opening time, which helps time-in-trade logic, but an accurate timestamp is not a complete strategy-state checkpoint.

Before the start check, recovery handles adopted orders whose engine expiry passed while the process was down. On the ordinary live clock it cancels them and waits up to two minutes for confirmation; unconfirmed cancellations refuse the start. A fill that wins that race is adopted. On a desk’s SIM clock, restart cannot infer its instant before the first bar, so it keeps the adopted expiries for subsequent processing. Reconnecting an existing member session is not a new process start and does not repeat the adoption gate.

Evaluate the combination

Read the aggregate marked equity, drawdown and overlap in losses, then inspect each member and long/short contribution. Check whether diversification survives equalized risk and realistic costs. Missing or failed members must not silently improve the portfolio; inspect index.json and require the intended run set. algo report --partial is an explicit partial-results choice, not a remedy for unexplained failures. Source to study: strategies/demo/go/rankedcross/main.go, the run-config implementation, and the technical manual’s Trade director chapter.

Complete source: rankedcross

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. The strategy requires the order-lifetime capability and enables the one-bar rule. It additionally accepts order conviction when offered.

  2. It derives a signal-strength score from the crossover and attaches conviction to the order. A score is an input to the director’s admission policy, not an instruction that guarantees execution.

  3. The ordinary position and crossing guards still apply. Compare accepted and denied intents with the configured ranking and limits when interpreting a portfolio run.

Build the supplied files directly:

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

rankedcross/main.go

// Command rankedcross trades a moving-average crossover on every symbol of
// its run and ranks one close's entries by conviction for the trade director.
// It is the demo of the manual's Trade director chapter.
package main

import (
    "fmt"
    "math"
    "os"
    "strings"

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

type RankedCross struct {
    Fast int `algolang:"default=10,min=2,max=200,desc=Fast SMA period in bars"`
    Slow int `algolang:"default=40,min=3,max=400,desc=Slow SMA period in bars"`
    Qty  int `algolang:"default=1,min=1,max=100000,desc=Units per entry"`

    symbols []string
}

func (s *RankedCross) Name() string { return "Ranked crossover" }
func (s *RankedCross) Description() string {
    return "SMA crossover on every symbol, ranked by conviction"
}
func (s *RankedCross) Lookback() int { return s.Slow + 1 }

// RequiredCapabilities declares the one order lifetime (GLE-1906), which the
// director needs as well: the strategy requires lifetime v2. Its orders are
// market orders alone, so the one-bar rule (OneBarRule) ends none of them.
func (s *RankedCross) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// SupportedCapabilities asks for conviction on orders, when the engine offers
// it.
func (s *RankedCross) SupportedCapabilities() []string {
    return []string{algolang.CapabilityOrderConviction}
}

// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does; it exempts market orders.
func (s *RankedCross) OneBarRule() bool { return true }

func (s *RankedCross) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
    for _, in := range cfg.Instruments {
        s.symbols = append(s.symbols, in.Symbol)
    }
    return nil
}

// OnBar decides once per close, on the primary series' bar, so every
// symbol's entry of that close is in one response: the director ranks
// them together.
func (s *RankedCross) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !ctx.IsPrimary(bar) {
        return nil, nil
    }
    var orders []algolang.Order
    for _, sym := range s.symbols {
        series := ctx.Series(sym)
        if series.Len() < s.Slow+1 || !series.Fresh() {
            continue
        }
        closes := indicators.Closes(series)
        fast, slow := closes.SMA(s.Fast), closes.SMA(s.Slow)
        // Conviction: the fast average's distance from the slow one,
        // in units of 5%, clipped to [0, 1].
        strength := math.Min(1, math.Abs(fast.Value()-slow.Value())/slow.Value()/0.05)
        pos := ctx.Position(sym).Quantity
        var o algolang.Order
        switch {
        case fast.CrossesAbove(slow) && pos <= 0:
            o = algolang.MarketBuy(sym, int64(s.Qty)-pos).Named("LE")
        case fast.CrossesBelow(slow) && pos >= 0:
            o = algolang.MarketSell(sym, int64(s.Qty)+pos).Named("SE")
            strength = -strength // a sell's conviction is zero or negative
        default:
            continue
        }
        o.ClientID = fmt.Sprintf("%s_%d", sym, bar.CloseTime.Unix())
        if ctx.OrderConviction() {
            o.Conviction = &strength
        }
        orders = append(orders, o)
    }
    return orders, nil
}

// OnOrderUpdate reads the director's answer. A refusal is Denied with a
// reason that starts with a director_* token; a trim is the ordinary
// acceptance update, its Quantity the accepted quantity and its reason
// led by director_trimmed.
func (s *RankedCross) OnOrderUpdate(ctx *algolang.Context, u algolang.OrderUpdate) {
    switch {
    case u.Status == algolang.OrderStatusDenied && strings.HasPrefix(u.Reason, "director_"):
        code, _, _ := strings.Cut(u.Reason, ":")
        ctx.Logf("refused %s %s: %s", u.ClientID, u.Symbol, code)
    case strings.HasPrefix(u.Reason, algolang.DirectorTrimmed+":"):
        // The working view already holds the accepted quantity.
        ctx.Logf("trimmed %s %s to %d", u.ClientID, u.Symbol, u.Quantity)
    }
}

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

Previous: An event journal: every strategy callback · Next: A crossover family under research discipline