Triple Screen: completed weeks and resting stops

Triple Screen: completed weeks and resting stops

triplescreen combines a weekly MACD-histogram trend, a daily Elder-ray retracement and a stop entry beyond the setup bar. It adds two ideas: deriving a higher timeframe from base bars, and managing orders that wait for price to reach a level.

bin/algo run \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/triplescreen --symbols fut:XCME:ES \
  --bar-interval 1d --session rth --inputs Weeks=kit \
  --date-from 2020-01-01 --date-to 2024-12-31 \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --results-dir results/learning/triplescreen

The weekly trend uses the last complete week; the developing week does not leak its eventual close into Monday’s signal. With the default 12/26/9 weekly MACD, at least 35 completed weeks are needed for the comparison. Warm-up therefore has to cover much more than 35 daily bars.

Choose where the weekly bars come from

Weeks=kit resamples the daily history held by the strategy into completed ISO weeks. Weeks=declared reads a declared weekly session series, requests the exchange calendar and excludes the current daily bar’s week. The declared route is demonstrated on a dated contract; the current continuous path refuses another series of the same holding. The kit route is the working continuous example above.

Keep session definitions and warm-up lengths consistent when comparing the two routes. Different history starts can change recursive indicators even after their first finite value. A weekly series is not always just five daily rows: holidays and calendar boundaries determine the grouping.

A signal is not a position

When flat and a setup exists, the strategy rests a stop one tick beyond the setup bar’s extreme. kit.PendingEntry records whether that attempt filled, was withdrawn or expired. The protective stop is installed at the close of the bar where the entry fill is first observed, then may tighten to breakeven or a confirmed swing. This demo therefore has no protective stop inside its entry bar. The bracket strategy demonstrates protection that activates with the fill.

The entry lasts one bar through kit.OneBar. Under lifetime v2 a Day order means the exchange session’s day, not “one callback”. The helper uses GTC plus explicit cancellation to express the intended one-bar life. For an order that should remain working, a controller can express desired entries and exits and reconcile acknowledgements, replacements and cancellations.

The useful order idioms are:

IntentionTechnique
Enter only once while waitingRead position and working-order state; ctx.Flat for self-managed entries
Keep a stop until the next decisionkit.OneBar with an explicit one-bar policy
Protect the moment an entry fillsAttached orders; group competing exits with OCO
Move a persistent protective orderkit.Controller and its lifecycle handling
Avoid sending another exit while one is pendingkit.Exiting for the self-managed exit pattern
Maintain an entry/exit campaignkit.BaseTrade; define restart adoption explicitly
Track overlapping per-signal holdingskit.LotBook; account and report pairing still impose limits

For new lifetime-v2 strategies, the engine also offers a one-bar expiry. Set OneBar: true on an eligible Day resting order, or implement OneBarRule() bool returning true to apply it to such orders throughout the run. The declaration defaults to off; ctx.OneBarRule() reports it. Use the protobuf strategy wire. This is separate from kit.OneBar, which the shipped Triple Screen still uses with GTC and explicit cancellation.

The engine’s one-bar instant is the next delivered close of the deciding series strictly after the decision, not the next callback from any series. A 5-minute decision beside a 1-minute series therefore expires on the next 5-minute close. Missing intervals move it to the next bar present. A fill on that bar wins; an earlier Day session expiry wins instead. With no later bar it rests until the run ends. Market orders, GTC orders, combos and attached children are exempt; OneBar: true on GTC is an expiry_conflict.

The controller has its own ownership rules: do not layer a generic “no working order” gate over the very entry it owns, or the desired state can oscillate between submit and cancel. Follow the controller’s documented recipe rather than mixing the two ownership models.

At bar resolution, OHLC cannot establish whether a stop or target was hit first. Compare conservative ambiguity settings with a real finer path when available. --include-path --path-interval 1m asks for minute constituents; it does not turn a daily strategy into a minute-by-minute decision process. Source to study: strategies/demo/go/triplescreen/ and strategies/kit/.

Complete source: triplescreen

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 weekly and daily screens have different completion clocks. Trace the completed-week construction before following the daily entry condition.

  2. The entry is a resting stop rather than an immediate market purchase. The order controller and kit.OneBar manage cancellation and replacement across decision turns.

  3. Protective exits and close-out rules use the filled position. The helpers near the end keep price levels, ticks and session state separate from the signal.

Build the supplied files directly:

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

triplescreen/main.go

// Command triplescreen is the algolang demonstration of Alexander Elder's Triple Screen (1985) as Brent Penfold
// tested it: daily bars traded in the direction of a weekly trend. The series library nseries cannot write it, for it
// holds no timestamps (so it cannot tell which daily bars make a week) and sees no fills (on which the stops depend);
// algolang can, with its weekly closes taken either from the daily bars themselves or from a declared weekly series.
//
// # Source
//
// Brent Penfold, The Universal Tactics of Successful Trend Trading (Wiley, 2021), chapter 6, "Elder's TSTS (1985)",
// pp. 223-227, testing Elder's Triple Screen (1985; Alexander Elder, Trading for a Living, 1993). Penfold's rules,
// verbatim:
//
//  Buy Rules
//    Trend:          Up—weekly MACD histogram bar is rising
//                    Last weekly histogram bar is above previous weekly histogram bar
//    Retracement:    Down—Elder-Ray Bear Power declines below zero & then ticks back up towards the centre line
//    Entry:          Buy break of the previous bar's high
//    Initial Stop:   Sell break of the lowest low of either the setup or entry bar
//    Breakeven Stop: Move to breakeven at first open profit
//    Trailing Stop:  Sell break of the closest swing low
//  Sell Rules
//    Trend:          Down—weekly MACD histogram bar is falling
//                    Last weekly histogram bar is below previous weekly histogram bar
//    Retracement:    Up—Elder-Ray Bull Power rallies above zero & then ticks back down towards the centre line
//    Entry:          Sell a break of the previous bar's low
//    Initial Stop:   Buy break of the highest high of either the setup or entry bar
//    Breakeven Stop: Move to breakeven at first open profit
//    Trailing Stop:  Buy break of closest swing high
//
// with the parameters MACD (12, 26, 9) and Elder-ray (13). Penfold transposes the weekly MACD histogram into a daily
// representation, each day reading "the weekly histogram bar for the last complete week".
//
// # The rules as built
//
// The weekly closes (input Weeks). The kit route, the default, resamples the daily bars into ISO weeks with
// kit.Resample (in UTC, a daily bar falling in the week of its last instant) and keeps the closes of the completed
// weeks; it needs no calendar and serves continuous futures. The declared route reads a declared 1w session series
// (session WeekSession) and keeps the closes of its bars whose trade date, read through the exchange calendar,
// precedes the daily bar's own. Either way a day reads the complete weeks before its own: a week is complete from the
// first daily bar of the next week.
//
// The weekly trend. The weekly MACD histogram is the MACD (the Fast-week EMA of the weekly closes less the Slow-week
// one) less its signal line, the Signal-week EMA of the MACD sliced from its first full value (TA-Lib's seed); its
// first value is at week Slow+Signal-2. The trend is up when the last complete week's histogram is above the week
// before's and down when it is below; it is neither when the two are equal or either is undefined, so Slow+Signal
// weeks (35 by default) come before any trade.
//
// The retracement. The Elder-ray powers stand on the EMALen-day (13 by default) exponential average of the daily
// close, seeded with the simple average: the bear power is the low less the average and the bull power the high less
// it. With the trend up, a bar whose bear power is below zero and above the bar before's is a buy setup; with the
// trend down, a bar whose bull power is above zero and below the bar before's is a sell setup. A power of exactly zero
// is not past the centre line, and an unchanged power neither rises nor falls.
//
// The entry. While flat, a setup bar places a stop entry for the next bar only, a tick beyond the setup bar's
// extreme: a buy stop a tick above its high, a sell stop a tick below its low. The entry is a kit.PendingEntry with
// MaxBars 1, armed on the setup bar and observed on every daily bar, so it ends filled, withdrawn or expired on the
// next one.
//
// The protective stop. A filled entry is protected by a first-touch stop, placed at the close of the bar on which the
// fill is first seen, kept from bar to bar and moved at each close in three steps: the initial stop, set when the
// fill is seen, a tick beyond the extreme of the setup and entry bars (below the lower of their lows for a long,
// above the higher of their highs for a short); breakeven, the entry price, once a close is in profit; and the trail,
// a tick beyond the closest confirmed swing low (swing high for a short) when that is tighter. The stop is only ever
// tightened. The position is held until the stop fills: there is no exit on a change of trend and no reversal, a setup
// while in a position is ignored, and after a stop-out the next setup enters again.
//
// Side. Input Side trades both sides (the default), longs only or shorts only; with both, at most one entry rests at a
// time, as the weekly slope cannot be up and down at once.
//
// Orders. Every order is built as a Day order (the constructors' default), stamped by a kit.IDStamper with
// the prefix triplescreen and given its one-bar life by the engine's one-bar rule: no market orders, no attached orders, no OCO groups and no kit.Controller.
//
// # Departures
//
// Penfold does not print the entry's life or the size of a break, so the entry's one-bar life and "break" as a tick
// beyond the level are readings. "Open profit" is read on the close; a close equal to the entry is not profit. The
// swing is a strict pivot of SwingLen bars each side (an equal low or high is no swing), confirmed SwingLen bars
// later; SwingLen 0 turns the trail off. The stops are placed at the close of the bar on which the fill is seen, so
// they are never tested on the entry bar. The averages read the whole history kept (MaxBars daily bars, and the weeks
// made of them). With an unresolved tick (0) the entry rests at the setup bar's extreme itself, as a first-touch stop
// (backtest-only) when that extreme is also the close, since a plain stop there is refused at submission. Penfold's
// re-entries are simply the next setup after a stop-out (no base-trade latch). Elder's own book is not available
// here; Penfold is the source.
//
// # The two routes
//
// The kit and declared routes give the same weekly closes, the complete weeks before the bar's own: on daily session
// bars whose last instant falls on their own trade date in UTC (every US futures daily session bar), a week is
// complete from the next week's first bar under both, and a week whose Friday is a holiday ends on its last session.
// The histogram's averages read the weeks each route holds, so where the two histories start differently (the
// declared series' Lookback of Slow+Signal+25 weeks against the primary's MaxBars daily bars) the histogram's early
// values, and so the trades, can differ.
//
// # Evidence (cited, not a target)
//
// Penfold's P24 portfolio of 24 US futures from 1980 made $336,473 over 11,633 trades, $29 a trade after $51 a trade
// of costs: positive, but with a 100% simulated risk of ruin, so he rejects it.
//
// # Lifetime
//
// The strategy is on the one order lifetime (GLE-1906): it requires lifetime v2 and turns the one-bar rule on.
// Every resting order is a Day order, returned again on each primary bar while it should rest, and the engine
// cancels it at the close of the next bar when it is still unfilled. The kit route needs no calendar; the declared route needs the exchange calendar (pb wire) and
// a dated contract, since a continuous run refuses a second series of its own root.
package main

import (
    "errors"
    "fmt"
    "math"
    "os"
    "time"

    "MODULE/indicators"
    algolang "MODULE/sdk/strategy"
    "MODULE/strategies/kit"
    "nseries"
)

// strategyName is the strategy's name and the prefix of the client IDs stamped on its orders.
const strategyName = "triplescreen"

// weeksDeclared is the Weeks input that reads the weekly closes from the declared weekly series; any other value (the
// default, "kit") resamples the daily bars.
const weeksDeclared = "declared"

// weeklyID is the series id of the declared weekly series.
const weeklyID = "weekly"

// sideLong is the Side input that trades longs only.
const sideLong = "long"

// sideShort is the Side input that trades shorts only.
const sideShort = "short"

// The interfaces the engine and the SDK read the strategy through, checked at compile time. CalendarObserver is
// deliberately not among them: implementing it would request the calendar on every run.
var (
    _ algolang.Strategy           = (*TripleScreen)(nil)
    _ algolang.Initializer        = (*TripleScreen)(nil)
    _ algolang.Lookbacker         = (*TripleScreen)(nil)
    _ algolang.CapabilityRequirer = (*TripleScreen)(nil)
    _ algolang.OneBarDeclarer     = (*TripleScreen)(nil)
    _ algolang.DataRequirer       = (*TripleScreen)(nil)
    _ algolang.CalendarRequirer   = (*TripleScreen)(nil)
)

// TripleScreen is the Triple Screen strategy. Its exported fields are the inputs, which the SDK sets from their tags;
// its unexported fields are the state of one session, which OnInit resets so that one value may serve several
// sessions.
type TripleScreen struct {
    // Fast is the length in weeks of the fast EMA of the weekly MACD.
    Fast int `algolang:"default=12,min=1,max=200,desc=Fast EMA of the weekly MACD in weeks"`

    // Slow is the length in weeks of the slow EMA of the weekly MACD; it must exceed Fast.
    Slow int `algolang:"default=26,min=2,max=400,desc=Slow EMA of the weekly MACD in weeks"`

    // Signal is the length in weeks of the EMA of the weekly MACD that is its signal line.
    Signal int `algolang:"default=9,min=2,max=200,desc=EMA of the weekly MACD that is its signal line in weeks"`

    // EMALen is the length in days of the EMA of the daily close under the Elder-ray powers.
    EMALen int `algolang:"default=13,min=2,max=500,desc=EMA of the daily close under the Elder-ray powers"`

    // SwingLen is the number of bars each side of a swing low or high that trails the stop; 0 turns the trail off.
    SwingLen int `algolang:"default=2,min=0,max=50,desc=Bars each side of a swing low or high that trails the stop (0 off)"`

    // Weeks is where the weekly closes come from: "kit" resamples the daily bars into ISO weeks; "declared" reads the
    // declared weekly session series through the exchange calendar.
    Weeks string `algolang:"default=kit,values=[kit,declared],desc=Where the weekly closes come from"`

    // WeekSession is the session of the declared weekly series (read only when Weeks is "declared").
    WeekSession string `algolang:"default=rth,desc=Session of the declared weekly series"`

    // Side is the sides traded: "both", "long" or "short".
    Side string `algolang:"default=both,values=[both,long,short],desc=Sides to trade"`

    // Qty is the number of units per trade.
    Qty int `algolang:"default=1,min=1,max=1000000,desc=Units per trade"`

    // MaxBars is the number of daily bars of history kept; the averages read all of it.
    MaxBars int `algolang:"default=4096,min=64,max=100000,desc=Daily bars of history kept (the averages read all of it)"`

    // ids stamps the client ID of every order returned (Prefix "triplescreen").
    ids kit.IDStamper

    // symbol is the first instrument's symbol recorded by OnInit: the symbol of the declared weekly series.
    symbol string

    // stop is the open trade's protective stop level, NaN when there is none.
    stop float64

    // entry is the pending break entry: armed on a setup bar, it rests for the next bar only (MaxBars 1).
    entry kit.PendingEntry
}

// Name returns the strategy's name, "triplescreen".
func (s *TripleScreen) Name() string { return strategyName }

// Description returns one sentence on what the strategy does.
func (s *TripleScreen) Description() string {
    return "Elder's Triple Screen as Penfold tested it: a one-bar stop entry on a daily Elder-ray retracement in " +
        "the direction of the weekly MACD histogram's slope, protected by a first-touch stop moved to breakeven " +
        "and trailed beyond swings."
}

// RequiredCapabilities declares the one order lifetime (GLE-1906): the strategy requires lifetime v2.
func (s *TripleScreen) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule turns the engine's one-bar rule on: a resting order still unfilled at the close of the next bar is
// cancelled by the engine.
func (s *TripleScreen) OneBarRule() bool { return true }

// Lookback returns the daily bars of history the SDK keeps for the primary series: MaxBars, all of which the averages
// read.
func (s *TripleScreen) Lookback() int { return s.MaxBars }

// OnInit validates the inputs and resets the session state, so one value may serve several sessions. It returns an
// error, its text starting "triplescreen: ", when Fast is not below Slow or when Weeks is "declared" and there is no
// instrument whose weekly series to declare. It records the first instrument's symbol when there is one, gives the
// IDStamper a fresh sequence with the Prefix "triplescreen", clears the protective stop (NaN) and resets the pending
// entry to a kit.PendingEntry with MaxBars 1. It reads nothing from ctx.
func (s *TripleScreen) OnInit(_ *algolang.Context, cfg algolang.InitConfig) error {
    if s.Fast >= s.Slow {
        return fmt.Errorf("triplescreen: Fast (%d) must be below Slow (%d)", s.Fast, s.Slow)
    }
    if s.Weeks == weeksDeclared && len(cfg.Instruments) == 0 {
        return errors.New("triplescreen: Weeks declared needs an instrument whose weekly series to declare")
    }
    s.symbol = ""
    if len(cfg.Instruments) > 0 {
        s.symbol = cfg.Instruments[0].Symbol
    }
    s.ids = kit.IDStamper{Prefix: strategyName}
    s.stop = math.NaN()
    s.entry = kit.PendingEntry{MaxBars: 1}
    return nil
}

// DataRequirements declares the weekly series of the declared route: none for Weeks "kit"; for Weeks "declared" one
// series "weekly" of 1w time bars of the recorded symbol in the session WeekSession, with Slow+Signal+25 weeks of
// history pre-buffered (the histogram needs Slow+Signal).
func (s *TripleScreen) DataRequirements() []algolang.DataRequirement {
    if s.Weeks != weeksDeclared {
        return nil
    }
    return []algolang.DataRequirement{{
        SeriesID: weeklyID,
        Symbol:   s.symbol,
        Schema: algolang.DataSchemaSpec{
            Kind:     algolang.Bars,
            BarKind:  algolang.BarsTime,
            Interval: "1w",
            Session:  s.WeekSession,
        },
        Lookback: s.Slow + s.Signal + 25,
    }}
}

// NeedsCalendar asks the engine for the exchange calendar when the weekly closes come from the declared series
// (Weeks "declared"), whose bars and the daily bar it dates; the kit route needs none. TripleScreen deliberately does
// not implement OnCalendar, which would request the calendar on every run.
func (s *TripleScreen) NeedsCalendar() bool { return s.Weeks == weeksDeclared }

// OnBar runs once per bar. A declared weekly bar is data only and returns at once. On a daily (primary) bar it
// advances the trade state, folds it into the pending entry (kit.PendingEntry.Observe) and reads the kept history;
// holding a position it moves the protective stop (tsStop) and returns it again, a first-touch stop for the next
// bar; flat it forgets the stop and, on a setup (tsSetup) in the direction of the weekly slope (tsWeeklySlope) on a
// side that Side allows, arms the pending entry a tick beyond the setup bar's extreme and, while it rests, returns
// the stop entry for the next bar: a plain stop at its level, or a first-touch one when that level is at or through
// the close. Every order is stamped before it is returned. It never returns an error.
func (s *TripleScreen) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !ctx.IsPrimary(bar) {
        return nil, nil
    }
    st := ctx.Trade(bar)
    s.entry.Observe(st)
    ser := kit.Series(ctx, bar)
    h, l, c := indicators.Highs(ser), indicators.Lows(ser), indicators.Closes(ser)
    n := min(len(h), len(l), len(c))
    h, l, c = h[len(h)-n:], l[len(l)-n:], c[len(c)-n:]
    if n == 0 {
        return s.emit(ctx, bar), nil
    }
    k := n - 1
    sym := bar.Symbol
    pos := ctx.Position(sym).Quantity
    tick := kit.Tick(ctx, sym)
    qty := int64(s.Qty)

    switch {
    case pos > 0:
        s.stop = tsStop(+1, s.stop, st.JustEntered, st.EntryPrice, h, l, c, s.SwingLen, tick)
        return s.emit(ctx, bar, algolang.TouchSell(sym, pos, s.stop).Named("LX Stop")), nil
    case pos < 0:
        s.stop = tsStop(-1, s.stop, st.JustEntered, st.EntryPrice, h, l, c, s.SwingLen, tick)
        return s.emit(ctx, bar, algolang.TouchBuy(sym, -pos, s.stop).Named("SX Stop")), nil
    }

    s.stop = math.NaN()
    var wc nseries.Series
    if s.Weeks == weeksDeclared {
        cal, ok := ctx.Calendar(sym)
        if !ok {
            return s.emit(ctx, bar), nil
        }
        date, ok := cal.TradeDate(bar.CloseTime.Add(-time.Nanosecond))
        if !ok {
            return s.emit(ctx, bar), nil
        }
        wc = tsDeclaredWeeklyCloses(ctx.Series(weeklyID), cal, date)
    } else {
        wc = tsKitWeeklyCloses(ser)
    }
    slope := tsWeeklySlope(wc, s.Fast, s.Slow, s.Signal)
    set := tsSetup(h, l, c, s.EMALen, slope)
    switch {
    case set == +1 && s.Side != sideShort:
        s.entry.Arm(+1, h[k]+tick)
    case set == -1 && s.Side != sideLong:
        s.entry.Arm(-1, l[k]-tick)
    }
    if s.entry.Resting() {
        // The plain stop beyond the close, or its first-touch form at or through it (kit.StopEntry).
        name := "LE"
        if s.entry.Side < 0 {
            name = "SE"
        }
        return s.emit(ctx, bar, kit.StopEntry(sym, s.entry.Side, qty, s.entry.Level, c[k]).Named(name)), nil
    }
    return s.emit(ctx, bar), nil
}

// emit stamps the bar's orders (none or one) with the strategy's IDStamper and returns them; the engine's one-bar
// rule ends each at the close of the next bar when it is still unfilled.
func (s *TripleScreen) emit(_ *algolang.Context, bar algolang.Bar, orders ...algolang.Order) []algolang.Order {
    for i := range orders {
        orders[i] = s.ids.Stamp(orders[i], bar)
    }
    return orders
}

// tsKitWeeklyCloses returns the closes of the complete ISO weeks of the daily series, oldest first. It resamples the
// daily bars with kit.Resample into ISO weeks in UTC (a bar belongs to the week holding its last instant, CloseTime
// less a nanosecond; a week runs from Monday 00:00 to the next Monday 00:00) and keeps the completed weeks, those
// ending at or before the newest bar's close, so the developing week (the newest bar's own) is left out. An empty or
// nil series gives an empty, non-nil series. On daily session bars whose last instant falls on their own trade date in
// UTC (every US futures daily session bar) a week is complete from the next week's first bar, and a week whose Friday
// is a holiday ends on its last session.
func tsKitWeeklyCloses(daily algolang.Series) nseries.Series {
    if daily == nil {
        return nseries.Series{}
    }
    completed, _, _ := kit.Resample(daily, kit.TimeframeWeek, time.UTC)
    return nonNil(kit.HTFCloses(completed))
}

// tsDeclaredWeeklyCloses returns the closes of the bars of a declared weekly series whose trade date precedes date,
// oldest first. It walks the series from its oldest bar to its newest and keeps a bar's Close when the calendar dates
// the bar's last instant (CloseTime less a nanosecond) and that trade date is less than date: the dates are YYYY-MM-DD
// strings, so string order is date order. A nil weekly, an empty one, or no bar kept gives an empty, non-nil series. A
// weekly session bar closes at its last session's close and so carries that session's trade date; the daily bar of
// that session is not after it, so on a week's last session this gives the week before, as the kit route does.
func tsDeclaredWeeklyCloses(weekly algolang.Series, cal algolang.Calendar, date string) nseries.Series {
    if weekly == nil {
        return nseries.Series{}
    }
    n := weekly.Len()
    closes := make(nseries.Series, 0, max(n, 0))
    for i := n - 1; i >= 0; i-- {
        b := weekly.Bar(i)
        if d, ok := cal.TradeDate(b.CloseTime.Add(-time.Nanosecond)); ok && d < date {
            closes = append(closes, b.Close)
        }
    }
    return closes
}

// tsWeeklyHistogram returns the weekly MACD histogram of the weekly closes: the MACD less its signal line. It has a
// value for each close, all NaN when there are fewer than slow+signal-1 closes. Otherwise the MACD is the closes'
// MACD of fast and slow weeks, whose first full value is at index slow-1, and the signal line is the signal-week EMA
// of the MACD's valid part from that index (TA-Lib's seed; the whole-series average would seed on the MACD's
// warm-up), so the first value of the histogram is at index slow+signal-2 (33 for 12, 26 and 9) and every value
// before it is NaN. An empty wc gives an empty series.
func tsWeeklyHistogram(wc nseries.Series, fast, slow, signal int) nseries.Series {
    hist := make(nseries.Series, len(wc))
    for i := range hist {
        hist[i] = math.NaN()
    }
    if slow < 1 || signal < 1 || len(wc) < slow+signal-1 {
        return hist
    }
    m := wc.MACD(fast, slow)
    if len(m) < len(wc) {
        return hist
    }
    sig := m[slow-1:].XAverage(signal)
    for j := signal - 1; j < len(sig) && slow-1+j < len(hist); j++ {
        hist[slow-1+j] = m[slow-1+j] - sig[j]
    }
    return hist
}

// tsWeeklySlope returns +1 when the newest weekly histogram value is above the one before, -1 when below, else 0.
// It is 0 when the histogram has fewer than two values, when either of the two is NaN (so it needs slow+signal weekly
// closes, 35 for 12, 26 and 9, to be non-zero) and when they are equal.
func tsWeeklySlope(wc nseries.Series, fast, slow, signal int) int {
    h := tsWeeklyHistogram(wc, fast, slow, signal)
    n := len(h)
    if n < 2 || math.IsNaN(h[n-1]) || math.IsNaN(h[n-2]) {
        return 0
    }
    switch {
    case h[n-1] > h[n-2]:
        return +1
    case h[n-1] < h[n-2]:
        return -1
    default:
        return 0
    }
}

// tsSetup returns the Elder-ray setup on the newest daily bar in the direction of the weekly slope. h, l and c are the
// daily highs, lows and closes, of equal length and oldest first, and the powers stand on e, the emaLen-bar
// exponential average of the close, seeded at bar emaLen-1 with the simple average and NaN before it. It returns 0
// when the newest bar's index is below emaLen or the slope is 0. With an up slope it returns +1 when the newest bar's
// bear power (low less e) is strictly below zero and strictly above the bar before's: the retracement "declines below
// zero & then ticks back up towards the centre line". With a down slope it returns -1 when the newest bar's bull power
// (high less e) is strictly above zero and strictly below the bar before's. Otherwise it returns 0; a NaN operand
// makes no setup.
func tsSetup(h, l, c nseries.Series, emaLen, slope int) int {
    if slope == 0 || emaLen < 1 {
        return 0
    }
    if slope > 0 {
        low, cl := alignPair(l, c)
        k := len(cl) - 1
        if k < emaLen {
            return 0
        }
        e := elderAverage(cl, emaLen)
        bear0 := low[k] - e[k]
        bear1 := low[k-1] - e[k-1]
        if bear0 < 0 && bear0 > bear1 {
            return +1
        }
        return 0
    }
    high, cl := alignPair(h, c)
    k := len(cl) - 1
    if k < emaLen {
        return 0
    }
    e := elderAverage(cl, emaLen)
    bull0 := high[k] - e[k]
    bull1 := high[k-1] - e[k-1]
    if bull0 > 0 && bull0 < bull1 {
        return -1
    }
    return 0
}

// tsStop returns the protective stop level of an open trade at the newest daily bar's close. side is +1 for a long
// and -1 for a short; stop is the level kept from the bar before (NaN when there is none); fresh reports that the
// entry's fill is first seen on this bar; entry is the entry's average fill price; h, l and c are the daily highs,
// lows and closes, of equal length (at least one) and oldest first; tick is the instrument's tick (0 when unresolved).
// For a long, in this order: when fresh or stop is NaN, the initial stop replaces any kept one, a tick below the lower
// of the lows of the newest bar (the entry bar) and the bar before it (the setup bar); breakeven, when the newest
// close is above the entry (an equal close is not profit), raises the stop to the entry; and the trail, when swingLen
// is positive and the low swingLen bars back is strictly below every other low within swingLen bars either side of it
// (a confirmed swing low), raises the stop to a tick below that low when that is higher. A short mirrors it. Breakeven
// and the trail never loosen the stop, so a kept stop is only tightened. A swing low confirmed before the entry bar
// has the setup and entry bars inside its window, so it lies below the initial stop and cannot tighten it: only
// swings confirmed on or after the entry bar move the stop.
func tsStop(side int, stop float64, fresh bool, entry float64, h, l, c nseries.Series, swingLen int, tick float64) float64 {
    switch {
    case side > 0:
        low, cl := alignPair(l, c)
        if len(cl) == 0 {
            return stop
        }
        k := len(cl) - 1
        p := max(k-1, 0)
        if fresh || math.IsNaN(stop) {
            stop = min(low[k], low[p]) - tick
        }
        if cl[k] > entry {
            stop = max(stop, entry)
        }
        if swingLen > 0 && k >= 2*swingLen {
            pv := k - swingLen
            if swingLow(low, pv, k-2*swingLen, k) && low[pv]-tick > stop {
                stop = low[pv] - tick
            }
        }
    case side < 0:
        high, cl := alignPair(h, c)
        if len(cl) == 0 {
            return stop
        }
        k := len(cl) - 1
        p := max(k-1, 0)
        if fresh || math.IsNaN(stop) {
            stop = max(high[k], high[p]) + tick
        }
        if cl[k] < entry {
            stop = min(stop, entry)
        }
        if swingLen > 0 && k >= 2*swingLen {
            pv := k - swingLen
            if swingHigh(high, pv, k-2*swingLen, k) && high[pv]+tick < stop {
                stop = high[pv] + tick
            }
        }
    }
    return stop
}

// alignPair trims a and b, both oldest first, to their common length, keeping the newest values of each. It
// re-slices and neither copies nor modifies.
func alignPair(a, b nseries.Series) (nseries.Series, nseries.Series) {
    n := min(len(a), len(b))
    return a[len(a)-n:], b[len(b)-n:]
}

// nonNil returns s, or an empty non-nil series when s is nil.
func nonNil(s nseries.Series) nseries.Series {
    if s == nil {
        return nseries.Series{}
    }
    return s
}

// elderAverage returns the emaLen-bar exponential average of the close that the Elder-ray powers stand on: seeded at
// bar emaLen-1 with the simple average, and NaN before it.
func elderAverage(c nseries.Series, emaLen int) nseries.Series {
    return c.XAverage(emaLen).SetN(emaLen-1, math.NaN())
}

// swingLow reports whether low[pv] is strictly below every other low in low[from..to], both ends included: a
// confirmed swing low. An equal low, or a NaN, makes it no swing.
func swingLow(low nseries.Series, pv, from, to int) bool {
    for j := from; j <= to; j++ {
        if j != pv && !(low[pv] < low[j]) {
            return false
        }
    }
    return true
}

// swingHigh reports whether high[pv] is strictly above every other high in high[from..to], both ends included: a
// confirmed swing high. An equal high, or a NaN, makes it no swing.
func swingHigh(high nseries.Series, pv, from, to int) bool {
    for j := from; j <= to; j++ {
        if j != pv && !(high[pv] > high[j]) {
            return false
        }
    }
    return true
}

// main serves TripleScreen on the wire the engine starts it on; on error it prints "triplescreen: <err>" to standard
// error and exits 1.
func main() {
    if err := algolang.Run(&TripleScreen{}); err != nil {
        fmt.Fprintf(os.Stderr, "triplescreen: %v\n", err)
        os.Exit(1)
    }
}

Previous: A cross-exchange trend: New York and London clocks · Next: A channel breakout with an attached bracket