A 20/200-day crossover
Our first rule is deliberately small: go long one unit when the 20-day simple moving average crosses above the 200-day average; go short one unit on the opposite cross. It stays flat until an actual crossing occurs. It does not enter simply because the fast average is already above the slow one on the first day.
Run the bundled implementation first:
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/smacross --symbols eq:ARCX:SPY:adj=split \
--bar-interval 1d --session rth --inputs Fast=20,Slow=200 \
--date-from 2015-01-01 --date-to 2024-12-31 \
--commission-per-share 0.005 --slippage-ticks 1 \
--plate full --color never --chart lines \
--results-dir results/learning/cross-spyThis needs SPY daily RTH coverage and at least 201 earlier bars to start fully warm. The commission is illustrative and omits broker minimums. A one-share position makes the arithmetic easy, but its return on a USD 100,000 account is not a fully invested strategy return. Shorting also introduces borrow and financing assumptions the simple cost model does not establish.
Write the whole strategy
The following is a complete small equivalent of the signal logic. Save it as examples/learning/cross.go. As in the house manual, import algolang and import indicators are display shorthand. Run go list -m in the checkout and replace them with Go imports using the printed module path followed by /sdk/strategy and /indicators, respectively; give the SDK import the alias algolang. For example, the form is import algolang "MODULE/sdk/strategy". The supplied smoke target makes these substitutions automatically and compiles this exact block.
package main
import (
"fmt"
"os"
)
import algolang
import indicators
// 1. Tagged exported fields become strategy inputs.
type Cross struct {
Fast int `algolang:"default=20,min=2,max=200"`
Slow int `algolang:"default=200,min=3,max=400"`
}
func (s *Cross) Name() string { return "Learning crossover" }
func (s *Cross) Description() string {
return "Long or short one unit on a fast/slow SMA cross."
}
func (s *Cross) SupportedCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// 2. Retain one extra close to compare the previous and current averages.
func (s *Cross) Lookback() int { return s.Slow + 1 }
func (s *Cross) OnInit(ctx *algolang.Context,
cfg algolang.InitConfig) error {
if s.Fast >= s.Slow {
return fmt.Errorf("Fast must be less than Slow")
}
return nil
}
func (s *Cross) OnBar(ctx *algolang.Context,
bar algolang.Bar) ([]algolang.Order, error) {
id := bar.SeriesID
if id == "" {
id = bar.Symbol
}
// 3. Warm-up can be incomplete; never trade an unformed slow average.
series := ctx.Series(id)
if series.Len() < s.Slow+1 {
return nil, nil
}
closes := indicators.Closes(series)
fast, slow := closes.SMA(s.Fast), closes.SMA(s.Slow)
// 4. Size the change from the filled position, including reversals.
pos := ctx.Position(bar.Symbol).Quantity
switch {
case fast.CrossesAbove(slow) && pos < 1:
return []algolang.Order{
algolang.MarketBuy(bar.Symbol, 1-pos).Named("LE"),
}, nil
case fast.CrossesBelow(slow) && pos > -1:
return []algolang.Order{
algolang.MarketSell(bar.Symbol, 1+pos).Named("SE"),
}, nil
}
return nil, nil
}
func main() {
if err := algolang.Run(&Cross{}); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}After replacing the imports, compile and call it through the same engine:
go build -o bin/learning-cross examples/learning/cross.go
bin/learning-cross --algolang-selftestUse --strategy bin/learning-cross in the preceding run. There is no separate strategy installation step while using its bin/ path. If you want it with your installed strategies, copy that executable there; the root Makefile does not discover new examples placed under examples/learning/.
The optional interfaces provide inputs, history and initialization. The only trading callback here is OnBar. The SDK keeps position from actual fills. Going from short one to long one buys two, because the order quantity is the difference between target and actual position. Changing a private isLong flag when an order is submitted would confuse intention with a fill.
ctx.Series(id) uses SeriesID when present and the symbol otherwise. Index zero is the latest bar; index one is the preceding bar. Bulk column slices are oldest first and are borrowed views: copy a slice if retaining it. The indicator conversion helpers adapt those series to nseries. The length guard matters because an indicator’s initial values need not be fully formed.
Keep standard output free for the SDK protocol. Use ctx.Logf in callbacks, or standard error for process-level diagnostics. For a larger strategy, add stable client IDs, OnFill and order-update handling; the bundled smacross also plots both averages and logs fills.
Inspect one reversal
Repeat the run with --lifecycle-json results/learning/cross-life.json and --fills-json results/learning/cross-fills.json. Find a crossing in the bars, the resulting order, its next-bar fill, and the changed signed position. Check that commission was charged on the filled quantity and that there is no trade on a warm-up bar. Compare trade P&L with net account equity: trade statistics are gross while the equity curve includes commissions.
For a local exercise with enough daily bars, run make strategy-guide-smoke. It creates deterministic synthetic history, compiles the program above, checks 20/200 reversals and costs, and exercises the saved reports. That proves mechanics; it is not a market performance result. Source to study: strategies/demo/go/smacross/main.go.
Complete source: smacross
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.
The tagged fields expose CLI inputs.
OnInitvalidates their relationship, andLookbackretains the extra bar needed to detect an actual crossing.OnBarconverts the buffered closes into indicator series, plots the averages, then compares a crossing with the signed, filled position.Reversing from short one to long one requires buying two.
OnFillrecords what actually executed; returning an order does not itself change the position.
Build the supplied files directly:
go build -o bin/smacross ./strategies/demo/go/smacross
bin/smacross --algolang-selftestsmacross/main.go
// Command smacross is the Go reference SMA-crossover strategy (spec
// Appendix A.1, pinned to nseries cross semantics). It goes long one unit
// when the fast SMA crosses above the slow SMA and short one unit when it
// crosses below, reversing through flat: each cross trades the difference
// between one unit on its side and the REAL position from the Context
// (spec A.2: lifecycle state must be a pure function of bars and fills,
// never a private flag — that pattern is restart-correct by construction).
// From flat a cross trades one unit; from the other side, two.
//
// The other language ports must be decision-identical to this one bar for
// bar; the SMA summation order (newest to oldest, then one divide) and the
// cross definitions come from nseries and pin cross-language float parity.
// Every port keeps its position from the fill lines, as the SDK keeps
// ctx.Position, so they agree in replay mode (no fills ever arrive, the
// position stays 0, and every cross trades one unit) and engine-driven
// (GLE-533: the ports once gated on an intended position instead, and
// every implementation alternated between flat and the first cross's
// side, never reversing).
package main
import (
"fmt"
"os"
"sort"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
)
// buildID is stamped by the Makefile via -ldflags.
var buildID string
type SmaCross struct {
Fast int `algolang:"default=3,min=2,max=200,desc=Fast SMA period in bars"`
Slow int `algolang:"default=8,min=3,max=400,desc=Slow SMA period in bars (expected greater than Fast)"`
// Bookkeeping for the shutdown summary, not trading state: fill
// counts and the set of symbols that produced fills. Decisions never
// read these — the position gate queries ctx.Position instead.
buyFills int
sellFills int
traded map[string]bool
}
func (s *SmaCross) Name() string { return "SMA Crossover" }
// SupportedCapabilities declares order lifetime v2 (GLE-200 I21): the
// strategy's decisions are the same under either profile (market orders
// alone, gated on the real position), so it follows the run's profile.
func (s *SmaCross) SupportedCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
func (s *SmaCross) Description() string {
return "Goes long one unit when the fast SMA crosses above the slow SMA and short one unit on the cross below."
}
// Lookback requests Slow+1 bars of history: the slow SMA ending at the
// PREVIOUS bar needs Slow closes that exclude the current one.
func (s *SmaCross) Lookback() int { return s.Slow + 1 }
// OnInit enforces the cross-field constraint the tag layer cannot express
// (algolang tags carry only per-field min/max): Fast must be strictly
// less than Slow, or the SMAs coincide / invert and every "cross" is
// garbage. Rejecting at init turns that silent misconfiguration into an
// init_failed error.
func (s *SmaCross) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
if s.Fast >= s.Slow {
return fmt.Errorf("Fast (%d) must be less than Slow (%d)", s.Fast, s.Slow)
}
s.traded = map[string]bool{}
return nil
}
func (s *SmaCross) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
// The SDK buckets bars by SeriesID, falling back to the symbol only
// when it is empty (Section 7.12); mirror that rule or a
// SERIES_ID-tagged bar stream would leave this lookup empty forever.
id := bar.SeriesID
if id == "" {
id = bar.Symbol
}
series := ctx.Series(id)
// nseries' Average returns the RAW input values for indexes < n-1 (the
// warmup prefix), so the last two points of each SMA series — the ones
// CrossesAbove/CrossesBelow compare — are only real SMAs once the
// series holds at least Slow+1 closes. This guard is mandatory.
if series.Len() < s.Slow+1 {
return nil, nil
}
closes := indicators.Closes(series)
fast := closes.SMA(s.Fast)
slow := closes.SMA(s.Slow)
// The two averages, drawn over the prices (GLE-677).
ctx.Plot("fast", fast.Value(), algolang.PlotStyle{Color: "#2962ff"})
ctx.Plot("slow", slow.Value(), algolang.PlotStyle{Color: "#ff6d00"})
// The target is one unit on the cross's side; the order is the
// difference from the REAL position the SDK maintains from the fill
// stream, not a private intent flag (spec A.2, restart-correct). In
// replay mode no fills arrive, pos stays 0, and every cross trades one
// unit, as every other port's does.
pos := ctx.Position(bar.Symbol).Quantity
switch {
case fast.CrossesAbove(slow) && pos < 1:
ctx.Logf("smacross: fast SMA(%d) crossed above slow SMA(%d); buying %d %s", s.Fast, s.Slow, 1-pos, bar.Symbol)
return []algolang.Order{s.order(algolang.MarketBuy(bar.Symbol, 1-pos).Named("LE"), bar)}, nil
case fast.CrossesBelow(slow) && pos > -1:
ctx.Logf("smacross: fast SMA(%d) crossed below slow SMA(%d); selling %d %s", s.Fast, s.Slow, 1+pos, bar.Symbol)
return []algolang.Order{s.order(algolang.MarketSell(bar.Symbol, 1+pos).Named("SE"), bar)}, nil
}
return nil, nil
}
// order stamps a deterministic, restart-safe client ID from the bar
// timestamp (spec A.2): a private counter would collide across a live
// restart. The CSV wire drops client IDs; that is fine.
func (s *SmaCross) order(o algolang.Order, bar algolang.Bar) algolang.Order {
o.ClientID = fmt.Sprintf("smacross_%d", bar.CloseTime.UnixNano())
return o
}
// OnFill counts real fills (the SDK applies each fill to ctx.Position
// before dispatching here, Section 7.5) and records the symbol for the
// shutdown summary.
func (s *SmaCross) OnFill(ctx *algolang.Context, fill algolang.Fill) {
side := "bought"
if fill.Side == algolang.Sell {
side = "sold"
s.sellFills++
} else {
s.buyFills++
}
if s.traded == nil {
s.traded = map[string]bool{}
}
s.traded[fill.Symbol] = true
ctx.Logf("smacross: fill %s: %s %d %s @ %v", fill.ClientID, side, fill.Quantity, fill.Symbol, fill.Price)
}
// OnShutdown summarises what actually happened at the venue: fills (not
// orders) and the final REAL position per traded symbol via ctx.Position.
func (s *SmaCross) OnShutdown(ctx *algolang.Context) {
fmt.Fprintf(os.Stderr, "[smacross] %d fills (%d buys, %d sells)\n",
s.buyFills+s.sellFills, s.buyFills, s.sellFills)
symbols := make([]string, 0, len(s.traded))
for sym := range s.traded {
symbols = append(symbols, sym)
}
sort.Strings(symbols)
for _, sym := range symbols {
p := ctx.Position(sym)
fmt.Fprintf(os.Stderr, "[smacross] final position %s %+d @ %v\n", sym, p.Quantity, p.AvgPrice)
}
}
func main() {
if err := algolang.Run(&SmaCross{}); err != nil {
fmt.Fprintln(os.Stderr, "smacross:", err)
os.Exit(1)
}
}Previous: Data, decisions, and fills · Next: The crossover with a drawdown brake