The crossover with a drawdown brake
Now let the strategy ask about its own results. ddbrake uses the same crossover, but flattens and pauses when drawdown breaches a threshold:
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/ddbrake --symbols eq:ARCX:SPY:adj=split \
--bar-interval 1d --session rth \
--inputs Fast=20,Slow=200,MaxDrawdown=0.05,Cooldown=20 \
--date-from 2015-01-01 --date-to 2024-12-31 \
--commission-per-share 0.005 --slippage-ticks 1 \
--results-dir results/learning/brakeThe threshold is a fraction of account equity, not of the instrument price. At one share and substantial idle cash, a 5% account drawdown may never occur. That is a useful result to notice before claiming that a risk overlay improved anything. For a small, deliberately exaggerated mechanics experiment, lower the threshold; do not choose a research threshold to make a chart attractive.
Ask for the view you need
The strategy requests portfolio information explicitly:
func (s *DDBrake) PortfolioNeeds() algolang.PortfolioNeeds {
return algolang.PortfolioNeeds{Curve: algolang.CurvePortfolio}
}In a callback, inspect the view before using it:
if view := ctx.Portfolio(); view.Valid() {
me := view.Summary(view.Reader())
if me.HasStatistics {
ctx.Logf("equity %.2f, drawdown %.2f%%",
me.MarkedEquity, 100*me.DrawdownPct)
}
}The view contains only information available at the decision. Its next snapshot will reflect orders returned by this callback. Availability flags matter: a missing Sharpe ratio is not a Sharpe ratio of zero.
| Question | API or saved artifact |
|---|---|
| Am I long, flat or short? | ctx.Position(symbol).Quantity; positive, zero or negative |
| Can a new entry duplicate a pending one? | ctx.Flat(symbol) checks both position and working orders; also inspect ctx.Exposure(symbol) |
| What is my average entry price? | ctx.Position(symbol).AvgPrice |
| What is the marked account worth? | ctx.Account() and its HasNetLiquidation/NetLiquidation fields |
| What are my P&L and drawdown? | view.Summary(view.Reader()), with HasStatistics checked |
| What are my closed-trade statistics? | view.Stats(view.Reader(), algolang.AllTrades); also long/short subsets |
| What is the portfolio equity history? | Request CurvePortfolio, then view.Equity(""); CurveMembers requests member histories too |
| What positions and orders are visible? | view.Positions(), view.Orders(member), view.Total(symbol) |
| What were the individual historical trades? | trades.csv or the .algorun trade/fill tables; no general SDK trade-history query is provided |
If a strategy needs a history of individual trades during a run, implement an explicit fill-derived ledger with a stated pairing rule. Do not infer closed trades from attempted entries, and do not pretend a process-local ledger survives a restart. ctx.Trade(bar) provides current-trade lifecycle state; it is not a database of all prior round trips.
Give a brake a way to release
A rule saying “stay flat until my drawdown recovers” can remain flat forever: without positions, its own equity may stop changing. ddbrake pauses for Cooldown bars, then resumes. It requires a further step down before braking again unless equity has recovered under the original threshold. Read that state machine before changing it.
Compare the unbraked and braked runs over the same data, costs and capital. Inspect participation, avoided losses, missed recoveries and the number of brakes, as well as maximum drawdown. In an ordinary backtest the portfolio view is a one-member view; putting this run beside another run in a config does not give either strategy the other’s developing equity. Source to study: strategies/demo/go/ddbrake/main.go and sdk/strategy/portfolio.go.
Complete source: ddbrake
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.
PortfolioNeedsrequests portfolio statistics and the portfolio equity curve. This is a declaration made at initialization, rather than a new callback on each equity change.OnBarchecks the drawdown brake before the crossover. Once tripped, the strategy flattens and pauses for the configured cooldown; inspect the remaining pause and next threshold when explaining a missing later entry.OnShutdownprints the last supplied portfolio view and curve length. Closed-trade figures and marked equity answer different questions.
Build the supplied files directly:
go build -o bin/ddbrake ./strategies/demo/go/ddbrake
bin/ddbrake --algolang-describeThis 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.
ddbrake/main.go
// Command ddbrake is smacross with a drawdown brake (GLE-1372): the same
// SMA crossover, reading the portfolio view before each decision. When its
// own equity falls more than MaxDrawdown below its peak, the brake goes on:
// it closes the position it holds and stands aside for Cooldown bars, then
// trades the crosses again. The brake goes on again only at a further
// MaxDrawdown of drawdown, or, once the drawdown is back under MaxDrawdown,
// at MaxDrawdown again. (A brake held until the drawdown recovered would
// hold for good: standing aside, the strategy's equity does not move.)
//
// It is the manual's example for "Reading the portfolio": the view comes
// from the engine (in a backtest, a one-member portfolio of the strategy
// itself), so ctx.Portfolio().Summary(reader) holds the figures the run's
// report would show if it ended at this bar.
package main
import (
"fmt"
"os"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
)
type DDBrake 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)"`
MaxDrawdown float64 `algolang:"default=0.05,min=0,max=1,desc=Drawdown from peak equity (a fraction) at which the brake goes on"`
Cooldown int `algolang:"default=20,min=1,max=1000,desc=Bars the strategy stands aside once the brake goes on"`
next float64 // the drawdown at which the brake goes on next
pause int // bars still to stand aside
brakes int // times the brake went on, for the summary
braked int // bars decided with the brake on, for the summary
}
func (s *DDBrake) Name() string { return "SMA Crossover with a drawdown brake" }
func (s *DDBrake) Description() string {
return "Trades the SMA crossover, standing aside while its drawdown from peak equity exceeds MaxDrawdown."
}
// 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 *DDBrake) 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 *DDBrake) OneBarRule() bool { return true }
// PortfolioNeeds asks for the portfolio view, with the portfolio's equity
// curve for the summary at the end.
func (s *DDBrake) PortfolioNeeds() algolang.PortfolioNeeds {
return algolang.PortfolioNeeds{Curve: algolang.CurvePortfolio}
}
func (s *DDBrake) Lookback() int { return s.Slow + 1 }
func (s *DDBrake) 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)
}
return nil
}
func (s *DDBrake) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
id := bar.SeriesID
if id == "" {
id = bar.Symbol
}
series := ctx.Series(id)
if series.Len() < s.Slow+1 {
return nil, nil
}
pos := ctx.Position(bar.Symbol).Quantity
// The brake: the strategy's own drawdown, as of this bar.
view := ctx.Portfolio()
me := view.Summary(view.Reader())
if me.HasStatistics {
dd := me.DrawdownPct
if s.next == 0 || dd < s.MaxDrawdown {
s.next = s.MaxDrawdown
}
if dd > s.next {
ctx.Logf("ddbrake: drawdown %.1f%% is over %.1f%%; standing aside for %d bars",
100*dd, 100*s.next, s.Cooldown)
s.next = dd + s.MaxDrawdown
s.pause = s.Cooldown
s.brakes++
}
}
if s.pause > 0 {
s.pause--
s.braked++
if pos != 0 {
exit := algolang.MarketSell(bar.Symbol, pos)
if pos < 0 {
exit = algolang.MarketBuy(bar.Symbol, -pos)
}
return []algolang.Order{s.order(exit.Named("brake"), bar)}, nil
}
return nil, nil
}
closes := indicators.Closes(series)
fast := closes.SMA(s.Fast)
slow := closes.SMA(s.Slow)
switch {
case fast.CrossesAbove(slow) && pos < 1:
return []algolang.Order{s.order(algolang.MarketBuy(bar.Symbol, 1-pos).Named("LE"), bar)}, nil
case fast.CrossesBelow(slow) && pos > -1:
return []algolang.Order{s.order(algolang.MarketSell(bar.Symbol, 1+pos).Named("SE"), bar)}, nil
}
return nil, nil
}
func (s *DDBrake) order(o algolang.Order, bar algolang.Bar) algolang.Order {
o.ClientID = fmt.Sprintf("ddbrake_%d", bar.CloseTime.UnixNano())
return o
}
// OnShutdown prints what the last view held: the portfolio's figures and
// the length of the curve the SDK accumulated.
func (s *DDBrake) OnShutdown(ctx *algolang.Context) {
view := ctx.Portfolio()
if !view.Valid() {
fmt.Fprintln(os.Stderr, "[ddbrake] no portfolio view (live, visibility none, or a CSV wire)")
return
}
sum := view.Summary("")
all := view.Stats("", algolang.AllTrades)
perf := view.Performance("")
fmt.Fprintf(os.Stderr, "[ddbrake] as of %s: equity %.2f, net profit %.2f, max drawdown %.1f%%, %d closed trades\n",
view.AsOf().Format("2006-01-02"), sum.MarkedEquity, sum.NetProfit, 100*sum.MaxDrawdownPct, all.Trades)
if perf.HasSharpe {
fmt.Fprintf(os.Stderr, "[ddbrake] Sharpe %.2f over %d days\n", perf.Sharpe, perf.SharpeDays)
}
fmt.Fprintf(os.Stderr, "[ddbrake] %d curve points; the brake went on %d times, for %d bars\n",
len(view.Equity("")), s.brakes, s.braked)
}
func main() {
if err := algolang.Run(&DDBrake{}); err != nil {
fmt.Fprintln(os.Stderr, "ddbrake:", err)
os.Exit(1)
}
}Previous: A 20/200-day crossover · Next: An intraday crossover with an hourly trend