A range-break filter on an event clock
Suppose a breakout strategy should compare price with the average close of the last 20 bars that broke a three-bar range. Those are selected events within a time-bar series, unlike the volume bars of the previous chapter. A quiet month might contribute no events. No fixed number of recent raw bars guarantees that it contains the last 20 events.
Before adding orders, use printbreaks to inspect this strategy input:
bin/algo run \
--adapter bin/file-csv-adapter \
--adapter-inputs Path=strategies/demo/go/printbreaks/testdata/cf21/sine_1d.csv \
--data-protocol pb --strategy bin/printbreaks --symbols TEST \
--bar-interval 1d --inputs N=3,K=20,History=40 --cache off \
--results-dir results/learning/breaksThis diagnostic strategy places no orders. Its committed sine-wave fixture has 96 bars and 77 events. After the first 40 bars, rebuilding the calculation from the sliding 40-bar buffer disagrees with the persistent holder on all 56 remaining bars, in the EMA. At bar 80 the holder’s EMA is 102.0765817; the rebuild gives 102.8174476. The two versions have reseeded from different histories, even though they read the same newest price.
Retain indicator state between decisions
kit.NewRangeBreak(N, K) returns a holder for one source series and parameter setting. An up event requires a high strictly above the previous N highs; a down event requires a low strictly below their lows. Ties do not count, and a bar breaking both sides is one event. Keep() identifies that union; SMA(), EMA() and VWMA() update on retained closes and hold between events. They are unavailable until K events have been classified. Invalid high/low comparisons produce unknown flags, not a quiet-bar signal.
The key adaptation for a single-series trading strategy is:
// OnInit: construct once, handling any invalid N or K.
s.breaks, err = kit.NewRangeBreak(s.N, s.K)
// OnBar: update before reading the signal.
if _, err := s.breaks.Update(kit.Series(ctx, bar)); err != nil {
return nil, err
}
ready := !math.IsNaN(s.breaks.EMA()) && !math.IsInf(s.breaks.EMA(), 0)
enter := ready && s.breaks.Up() == 1 && bar.Close > s.breaks.EMA()These are hook fragments, not another complete executable. Add a *kit.RangeBreak field, initialize it once, and feed enter into the position and order-reconciliation pattern already learned. Import kit from your module’s /strategies/kit package and math from Go’s standard library. Choose a separate exit policy; printbreaks itself makes no trading claim.
Request at least N+1 bars, and at least two. Bound N inside Lookback as well as validating it in OnInit: the engine can ask for history first. The demo caps it at 5000 before adding one. Its first update replays the available buffer, including warm-up, and later calls ingest only new bars.
With several series, retain one holder per series and update every holder from its own source on every callback. This catches a late secondary bar before it falls out of that source’s buffer. Do not feed an aligned view’s repeated samples into the holder. Update requires strictly increasing close times, so this recipe is for time bars; activity bars sharing a close timestamp do not satisfy that requirement. Keep the returned pointer rather than copying the holder value.
Make restart and rebase behavior explicit
If the last ingested bar has left the buffer, the holder cannot know whether it missed data and returns an error. Updating less frequently is not a safe optimization. A changed last bar is also refused; do not swallow that error and continue from inconsistent history.
On a roll rebase, call Reset() for the affected holder in OnRebase, then let the next update replay the restated buffer. There is no general in-place gap/ratio rebase for this holder. A restart also begins from the new process’s buffer. Flags can be ready immediately with sufficient history, but averages need K classified events; the EMA reseeds and need not exactly rejoin an uninterrupted run. A session reset is yet another hypothesis: the default holder carries across sessions. Record these choices in the study.
To add a frequency filter, keep a separate window of raw-bar flags. If u bars break up, d break down and b break both, the event count is e = u + d - b; frequency is e/window, and directional imbalance is (u-d)/e when e is nonzero. A two-sided bar must not be counted twice. If Update catches up several bars, only the newest flags are directly available: treat the skipped flag readings as unknown, as the kit recipe tests do, rather than fabricating their direction. Source to study: strategies/demo/go/printbreaks/main.go, strategies/kit/rangebreak.go and strategies/kit/rangebreak_recipe_test.go.
Complete source: printbreaks
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 persistent range-break holder is fed each source bar exactly once. Its events form a second clock on which the example computes SMA, EMA and VWMA.
The deliberately naive rebuild uses the currently retained source window. Comparing it with the persistent holder shows the EMA seed and lost-history problem.
The rebase and summary handling expose state resets and event counts. This observer places no trades; it makes the indicator state that a trading rule would use inspectable.
Build the supplied files directly:
go build -o bin/printbreaks ./strategies/demo/go/printbreaks
bin/printbreaks --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.
printbreaks/main.go
// Command printbreaks is a demo Algolang strategy: it keeps a kit.RangeBreak
// for each series it receives, updates every one of them on every callback,
// and prints, for every bar, the range-break flags and the event averages
// beside a naive rebuild from the lookback buffer. It places no order. Stdout
// belongs to the wire protocol; all human output goes to stderr.
package main
import (
"fmt"
"math"
"os"
"strconv"
"time"
"MODULE/indicators"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
"nseries"
)
// buildID is stamped by the Makefile via -ldflags.
var buildID string
// maxBars is the most bars of history the demo asks for through History, and
// the largest N it accepts: with N above it, N+1 bars of lookback are more than
// a demo should ask an engine to keep, and at the largest int the sum wraps.
const maxBars = 5000
// PrintBreaks prints one line of range-break state per bar.
type PrintBreaks struct {
N int `algolang:"default=3,min=1,max=5000,desc=Previous bars each bar is compared with"`
K int `algolang:"default=20,min=1,desc=Retained closes in each average"`
History int `algolang:"default=40,min=2,max=5000,desc=Bars of history asked for (at least N+1 are kept)"`
Every int `algolang:"default=1,min=1,desc=Bars from one printed line to the next (1 prints every bar)"`
n int
events int
differs int
holders map[string]*kit.RangeBreak
ids []string // the series with a holder, in the order their first bars arrived
}
// Name returns the display name of the strategy.
func (p *PrintBreaks) Name() string { return "Print Breaks" }
// Description returns a one-sentence summary of the strategy.
func (p *PrintBreaks) Description() string {
return "Prints the range-break flags and event averages of every bar beside a naive rebuild from the lookback, and places no order."
}
// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. It places no order, so the one-bar rule
// (OneBarRule) has nothing to end.
func (p *PrintBreaks) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does.
func (p *PrintBreaks) OneBarRule() bool { return true }
// Lookback returns the bars of history asked for: History, and at least N+1,
// so that a warmed-up buffer lets the holder classify the first bar it is
// called for (with fewer, the holder classifies from its (N+1)-th bar on).
// OnInit refuses an N above maxBars; the bound here keeps N+1 from wrapping
// when Lookback is asked before OnInit has run.
func (p *PrintBreaks) Lookback() int {
return max(p.History, min(p.N, maxBars)+1, 2)
}
// OnInit refuses a setting the holder refuses, and an N or a History above
// maxBars, whose lookback the demo does not ask for.
func (p *PrintBreaks) OnInit(_ *algolang.Context, _ algolang.InitConfig) error {
if _, err := kit.NewRangeBreak(p.N, p.K); err != nil {
return err
}
if p.N > maxBars || p.History > maxBars {
return fmt.Errorf("printbreaks: got N = %d and History = %d, and each must be at most %d; pass a smaller N or History", p.N, p.History, maxBars)
}
return nil
}
// OnBar updates every holder from its own series and, on one bar in every
// Every, prints the state of the bar's holder beside the naive rebuild.
func (p *PrintBreaks) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
line, err := p.onBar(ctx.Series, bar)
if err != nil {
return nil, err
}
if line != "" {
fmt.Fprintln(os.Stderr, line)
}
return nil, nil
}
// onBar is OnBar with the lookback series handed in (in a run, the Context's
// Series method); it returns the line to print, or "" on a bar that prints
// none. Every holder is updated on every callback, each from its own series,
// and not the bar's holder alone: a bar that joined another series' buffer
// without a callback of its own would otherwise have left that buffer before
// the series' next callback, and its holder would then refuse the gap. The
// comparison with the naive rebuild and the line are for the bar's series.
func (p *PrintBreaks) onBar(series func(id string) algolang.Series, bar algolang.Bar) (string, error) {
id := bar.SeriesID
if id == "" {
id = bar.Symbol
}
for _, other := range p.ids {
if other == id {
continue
}
if _, err := p.update(other, series(other)); err != nil {
return "", err
}
}
held, naive, err := p.step(id, series(id))
if err != nil {
return "", err
}
p.n++
if p.n%max(p.Every, 1) != 0 {
return "", nil
}
return breakLine(p.n, id, bar.CloseTime, held, naive), nil
}
// OnRebase drops the state of the rebased series: its history was restated, so
// the next bar replays the rebased buffer.
func (p *PrintBreaks) OnRebase(_ *algolang.Context, r algolang.Rebase) {
id := r.SeriesID
if id == "" {
id = r.Symbol
}
p.holders[id].Reset()
}
// OnShutdown reports the decision bars received, the events the holders
// counted (those of a warm-up buffer included, and those of a buffer replayed
// after a rebase counted again) and the bars on which the naive rebuild
// differed from the holder.
func (p *PrintBreaks) OnShutdown(ctx *algolang.Context) {
fmt.Fprintf(os.Stderr, "[printbreaks] received %d bars total, %d events; the naive rebuild differed on %d bars\n", p.n, p.events, p.differs)
}
// state is what the demo prints of one reading: the holder's, or the naive
// rebuild's.
type state struct {
Up, Down, Keep float64
SMA, EMA, VWMA float64
Bars, Events int
}
// update brings the holder of series id up to date from s, building it at the
// series' first bar, and adds the events of the bars it ingested to the count:
// each bar is ingested once, by whichever callback first finds it in the
// buffer, so no event is counted twice. An error names the series.
func (p *PrintBreaks) update(id string, s algolang.Series) (*kit.RangeBreak, error) {
h := p.holders[id]
if h == nil {
var err error
if h, err = kit.NewRangeBreak(p.N, p.K); err != nil {
return nil, err
}
if p.holders == nil {
p.holders = make(map[string]*kit.RangeBreak)
}
p.holders[id] = h
p.ids = append(p.ids, id)
}
before := h.Events()
if _, err := h.Update(s); err != nil {
return nil, fmt.Errorf("printbreaks: series %s: %w", id, err)
}
p.events += h.Events() - before
return h, nil
}
// step updates the holder of series id from s and returns its state and the
// naive rebuild's. The rebuild's nseries views of s are used inside this call
// only.
func (p *PrintBreaks) step(id string, s algolang.Series) (held, naive state, err error) {
h, err := p.update(id, s)
if err != nil {
return held, naive, err
}
held = state{h.Up(), h.Down(), h.Keep(), h.SMA(), h.EMA(), h.VWMA(), h.Bars(), h.Events()}
naive = rebuild(indicators.FromSeries(s), p.N, p.K)
if !sameValue(held.SMA, naive.SMA) || !sameValue(held.EMA, naive.EMA) || !sameValue(held.VWMA, naive.VWMA) {
p.differs++
}
return held, naive, nil
}
// rebuild is the naive form: the whole calculation again over the lookback
// buffer b, read at its newest bar. It loses every event that has left the
// buffer and those among the buffer's first n bars, which it cannot classify,
// and seeds its EMA afresh from the first k events it still classifies. Its
// flags are the plain Breakout composition, which has no unknown state: where
// the holder's flags are NaN (an unusable bar in the comparison) it reads 0
// or 1.
func rebuild(b indicators.OHLCV, n, k int) state {
m := len(b.Close)
if m == 0 {
return state{SMA: math.NaN(), EMA: math.NaN(), VWMA: math.NaN()}
}
up := b.High.Breakout(n, 1).EQ(1)
down := b.Low.Breakout(n, 1).EQ(-1)
keep := up.Add(down).GT(0)
sma := b.Close.AverageWhere(keep, k)
ema := b.Close.FuncWhere(keep, func(x nseries.Series) nseries.Series {
return x.EMA(k).SetN(min(k-1, len(x)), math.NaN())
})
ix := keep.EventIndex()
ec, ev := ix.Gather(b.Close), ix.Gather(b.Volume)
vwma := ix.Hold(ec.VWMA(ev, k).SetN(min(k-1, len(ec)), math.NaN()))
return state{up[m-1], down[m-1], keep[m-1], sma[m-1], ema[m-1], vwma[m-1], m, len(ix.Positions())}
}
// sameValue reports whether two readings agree: both NaN, or the same bits.
func sameValue(a, b float64) bool {
if math.IsNaN(a) || math.IsNaN(b) {
return math.IsNaN(a) && math.IsNaN(b)
}
return math.Float64bits(a) == math.Float64bits(b)
}
// breakLine formats one bar's holder state and the naive rebuild's bars,
// events and averages on a single line. The close is shown in UTC.
func breakLine(n int, id string, at time.Time, held, naive state) string {
num := func(x float64) string { return strconv.FormatFloat(x, 'g', 10, 64) }
return fmt.Sprintf("[break %d] %s close=%s up=%s down=%s keep=%s bars=%d events=%d sma=%s ema=%s vwma=%s | naive(%d bars) events=%d sma=%s ema=%s vwma=%s",
n, id, at.UTC().Format("2006-01-02T15:04:05Z"),
num(held.Up), num(held.Down), num(held.Keep), held.Bars, held.Events, num(held.SMA), num(held.EMA), num(held.VWMA),
naive.Bars, naive.Events, num(naive.SMA), num(naive.EMA), num(naive.VWMA))
}
func main() {
if err := algolang.Run(&PrintBreaks{}); err != nil {
fmt.Fprintln(os.Stderr, "printbreaks:", err)
os.Exit(1)
}
}Previous: A volume-bar trend with flow confirmation · Next: An event journal: every strategy callback