The strategy kit
strategies/kit is the shared toolkit beside the strategies: the helpers every port of a legacy strategy was writing again by hand, kept out of sdk/strategy, which stays a lean wire-protocol SDK (the reasoning that keeps the nseries bridge in indicators). Its package comment states three conversion rules and every helper follows them: protective exits are per-bar price-level checks that the strategy answers with plain market orders, not venue-side verbs; state is derived from ctx, the position’s transitions rather than private intent flags, so it survives a restart; and equity sizing reads ctx.Account() and degrades to a caller’s floor when the run reports no balances. This chapter lists every exported helper, what it does, what it assumes about the order lifetime and which profile it serves (the order-lifetime programme’s increment I21, PR8, GLE-467). The two profiles are the legacy one (--lifetime v1), under which a Day order lives one evaluation bar and ctx.Flat is the entry gate, and lifetime v2, a backtest’s default, under which an order rests until the strategy or the venue ends it and the SDK keeps the attempt-indexed view (Querying your own state). In the tables, both means the helper takes part in placing, sizing or gating orders and does the same under either profile; v2 means it needs lifetime v2; none means it reads data alone (bars, series, statistics, observations) and touches no order, so the profile does not reach it. A helper’s doc comment is its contract; the chapter follows it.
Orders and the position
| Helper | What it does | Order lifetime | Profile |
|---|---|---|---|
Series(ctx, bar) (kit.go) | the bar’s own lookback series: the SDK buckets bars by SeriesID, falling back to the symbol when it is empty, and every strategy must mirror that rule or a single-symbol run reads an empty series | none | both |
Flatten(symbol, qty) (kit.go) | the market order that closes a signed position, a sell of qty while long and a buy of -qty while short; since the constructor graduated into the SDK it delegates to algolang.Flatten and stays for source compatibility; qty must be non-zero | a Day market order consumed on its first eligible bar: the simulator fills it at the next bar’s open, before that bar’s decision; a venue can hold it across a decision, and then an exit gated on the position alone sends a second one (the duplicate-flatten window), which is why Exiting stands beside it | both |
Exiting(ctx, symbol) (exiting.go) | the exit-once gate: true when a working order on the symbol opposes the position, a sell while long or a buy while short; false on a nil context and while flat; each working entry counts by its side alone | reads the SDK’s working view as the run’s profile makes it (the legacy map until a fill, a cancel or an expiry removes the order; the attempt-indexed view until the attempt’s terminal event) and withholds a second flatten until the first ends; see The exit-once gate | both |
IDStamper (kit.go) | deterministic, restart-safe client ids, <prefix>_<symbol>_<barCloseUnixNano>_<seq>; Stamp(order, bar) sets ClientID and returns the order; the per-process sequence tells apart the orders of one bar (a reversal’s close and open) and the bar’s timestamp is what makes the id restart-safe | none: the id names the order and says nothing about its life. An order a Controller submits is labelled by the controller and its ClientID is not read, so the stamper is for orders a strategy submits itself | both |
StopEntry(symbol, side, qty, level, last) (sessions.go) | a stop entry of qty at level: the plain stop (StopBuy, StopSell) when the level is beyond the last price, else its first-touch form (TouchBuy, TouchSell, backtest-only), since a plain stop at or through the last price is refused at submission | none: it builds a Day order and the caller sets its time in force (the intraday demos of Prior sessions and weeks on base bars rest it GTC and keep it right themselves) | both |
CloseOutAt(bar, sessionClose, rthClose, v2), CloseOut (CloseOutNone, CloseOutNow, CloseOutDone), MOCLead (closeout.go) | the bar on which an intraday strategy closes out its session with a market-on-close order (GLE-1375): under v1 the session’s last bar (CloseOutNow once the bar closes at sessionClose); under v2 the pre-close bar, the last that closes at or before rthClose less MOCLead (5 minutes) and whose successor would cross it, so the MOC is in before the send-time window opens, and CloseOutDone for the bars after it; a bar with no open time is never the pre-close bar | none: it names the bar; the strategy cancels what rests and sends the MOC (Prior sessions and weeks on base bars) | both |
Tracker (tracker.go) | the position and bar state the legacy engine handed a strategy, rebuilt from ctx.Position transitions: Update(position, bar), once per primary bar, returns the signed quantity and maintains BarIdx, EntryBar, the entry snapshot (EntryPrice, EntryHigh, EntryLow, and EntryTime from Position.OpenedAt), Peak and Trough since entry, this bar’s JustEntered, JustExited, JustAdded and JustAdopted, and LastLossBar; BarsSinceEntry(), TimeInTrade(now), InCooldown(waitBars) and ReEntered() read and adjust it | one assumption, in its comments and its tests (kit_test.go, openedat_test.go): an order from OnBar on bar N fills on bar N+1, so the first bar of a backtest is flat and the entry snapshot is taken one bar after the signal, when the fill is first observable. That is the simulator’s next-open fill. Live, a market order may fill later; the snapshot is then taken on the bar the fill is first seen, with that bar’s high and low, while EntryTime stays exact through the SDK’s Position.OpenedAt, and BarsSinceEntry is a per-process count that restarts after a live restart (TimeInTrade is the restart-correct measure). The SDK’s ctx.Trade(bar), which returns a TradeState, is Update graduated into the SDK with the same fields and the same caveat, and is the replacement most strategies use; one production strategy still drives the Tracker as a pure state machine, which is what its Update signature is for | both |
LoserCooldown (tier2.go) | the exact realized-PnL loser test over ctx.Trade and ctx.Position(sym).Realized: Observe(tradeState, realized), once per primary bar, snapshots realized PnL on an entry and records a loss when a position closes with realized below its own snapshot (on a flip bar the closed side is judged against its own entry before the new side’s snapshot is taken), and InCooldown(barIdx, waitBars) blocks entries for waitBars bars after a loss; LastLossBar() reads the anchor. It replaces the close-against-average approximation the Tracker makes | none beyond the trade state’s transitions | both |
StopSuite (stops.go) | the protective-exit stack as pure price levels against the current bar: a hard stop at Entry less or plus ATR*StopMult (TightenedMult after TightenAfter bars), a break-even floor once the close has moved BreakEvenMult*ATR in favour, a target at ATR*TargetMult and a trailing stop at TrailDist from the Tracker’s Peak or Trough; a zero field disables its mechanism; Breached(mp, bar, barsSinceEntry) reports whether the bar touched any enabled level | none: it rests nothing. The exit the strategy answers a breach with is a market order, so it is Flatten’s and Exiting’s | both |
BaseTrade (basetrade.go) | the base-trade latch: a base system’s virtual position kept apart from the real one, so that a stop cuts the real position and a re-entry rule returns it while the base trade is still on; Decide(tradeState, bar, signals), once per primary bar after ctx.Trade, takes the base’s four flags and the strategy’s own stop test and returns Want, the direction the real position should hold after the decision; Armed(), BaseBarsSinceEntry() and the bar’s events (BaseEntered, BaseExited, JustCut, JustReEntered, Missed) read it, and Fires(x) reads an nseries flag; RoundTrip(dir, price), after Decide, reports a real entry and its exit that both filled inside the bar, which the trade state cannot show (the position is flat at both decisions), from the strategy’s own fill record: the wanted entry and its cut, or inside a cut base trade the re-entry and its cut; callers: the histopivot, startersystem and cyclechannel demos, none of which calls RoundTrip; see Re-entries inside a base trade | none: it rests nothing and reads no working order. The orders that carry the real position to Want are the strategy’s, market-on-close or market orders under either profile or controller intents under v2; it assumes, as the Tracker does, that a decision’s order is seen filled on the next bar or rests at the venue, and reads an exit it did not ask for as a cut, and a round trip the strategy reports as the entry and its cut | both |
SwitchedLevel(barsSinceEntry, after, early, late) (basetrade.go) | an exit level that changes after after bars in the trade: early before, late from then on (Ruggiero’s BarsSinceEntry < 10 exit), on the real trade’s TradeState.BarsSinceEntry() | none | both |
PendingEntry, EntryEnd (EntryOpen to EntryReplaced) (pending.go) | a stop entry that waits for its fill: Observe(tradeState), once per primary bar after ctx.Trade, ends a pending entry EntryFilled when the position opens, reverses or grows onto its side, EntryWithdrawn on any other change of the position, and EntryExpired after MaxBars unfilled bars (0 is no limit); Arm(side, level) rests it for the next bar (a same-side arm re-prices it and restarts its life, an opposite one replaces it, EntryReplaced); Fill() ends a pending entry as filled from the strategy’s own record of a fill the trade state cannot show (an entry whose attached stop filled inside the same bar leaves the position flat at both decisions), called after Observe and before the rules; Cancel, Resting(), Level, Bars, Armed, End; Through(last) says whether the level is at or through the last close, where a plain stop is refused; callers: the fourbarfear, mfidirection, forcepullback and triplescreen demos, none of which calls Fill; see Pending stop entries and resting exits | none: it rests nothing. The stop that carries the entry is the strategy’s: a stop returned at each primary bar’s close through kit.OneBar lives the next bar under either profile, or a controller intent under v2; it reads the position from the trade state’s transitions alone unless the strategy calls Fill | both |
OneBar (onebar.go) | the one-bar order life of a strategy that returns its orders afresh at every bar’s close (GLE-1362): Orders(ctx, orders), called at every primary decision with that decision’s orders (nil when there are none), returns them unchanged under v1; under v2 it sends each resting order (any but market, MOO and MOC) GTC and first cancels (ctx.Cancel) every order the previous call returned that is still working, matched in the working view by its decision instant and its terms; callers: dualdpo, forcepullback, fourbarfear, mfidirection, momentumfirst and triplescreen; see example 6 | it replaces the one-bar Day rule, which v2 does not apply: the simulator confirms its cancellation at the next decision, the close of the order’s one bar, so the fills are v1’s while the trace counts explicit cancellations where v1 counts TIF_EXPIRED ones (conform.Expect.OneBar); between the two calls ctx.Flat and ctx.Exposure still see the previous bar’s orders | both |
LotBook, Lot, LotExit, LotState (LotPending to LotWithdrawn) (lotbook.go) | one lot per signal on one symbol, each with its own exit: the strategy forwards its fills to OnFill(fill), then once per primary bar calls Observe(bar), Enter(side, qty, exit) per signal (the exit a hold in bars, a stop or target level tested on the close, or Close(tag) and CloseAll()) and Orders(symbol), which returns one order per due exit, oldest lot first, then one per new entry, so the report’s FIFO pairing gives one trade per lot; Lots() is the per-lot ledger, OutOfOrder counts exits ordered ahead of an older open lot, and Position(), Withdraw(tag) and Adopt(qty, price, exit) complete it; see Overlapping per-signal trades | Day market or market-on-close orders it builds itself, consumed on their first eligible bar under either profile; it reads fills through OnFill and no working order, and assumes, as the Tracker does, that an order is filled by the next decision: an entry still unfilled then is withdrawn and an incomplete exit re-issued for its remainder | both |
Controller (reconcile.go) | the desired-order controller: at each decision the strategy declares the orders it wants resting, each under a logical key, and the controller compares the declaration with the attempt-indexed view and produces the cancel requests and the submissions; see The desired-order controller | the v2 contract: it reads the attempt-indexed view and submits at the lifecycle turns, neither of which is authoritative on a legacy run | v2 |
Stall, LogStalls (stall.go) | one attempt whose cancel-request budget is spent while it is still live, with its label, attempt, symbol, side, remaining quantity, requests, round and last cancel outcome; LogStalls(ctx, name, stalls) writes each as one line of the strategy’s log; see The desired-order controller | a stall is a failure to cancel, never an expiry: the order stays live and counted | v2 |
Withdrawer (withdraw.go) | withdraws the working orders on one side of a symbol for a strategy without a controller, with the controller’s per-attempt request budget, recovery rounds and stalls; Withdrawn reports an order it took for withdrawal that is still live; see Orders that outlive a decision | keeps a withdrawn order counted until the view retires it | v2 |
ExitRecovery (withdraw.go) | the exit of a strategy with market entries of any size: withdraws the entry’s remainder, flattens the position, and holds later decisions (Step, Turn) until the remainder has ended and the position is flat; see Orders that outlive a decision | persistent orders; under the legacy profile Exit is the plain flatten | v2 (the flatten alone under v1) |
RestingSuite and RestingParams, the tier-2 counterpart to StopSuite, are gone since I21’s PR8 (2026-10-11). They built the Day orders a position re-rested every bar to protect itself, a first-touch stop (TouchSell or TouchBuy) and a profit-taking limit, OCO-joined under a tag the caller made unique per bar so that the pair retired with its one-bar Day life. That is the one-bar lifetime written into a helper: under the legacy profile the simulator expired the pair after one evaluation bar and the strategy re-emitted it, and under lifetime v2 a Day order rests to its session’s close (Calendar cancellation instants (lifetime v2)), so on an intraday grid the same call would stack a pair per bar. No strategy, demo or port called it, the legacy sources under strategies/to-migrate included, and the programme’s migrations rest an exit ladder as intents of a controller instead (the swing-breakout migration’s exit-ladder intent, I20a). The owner’s decision of 2026-10-10 (the plan’s Q4) was to delete it with its test rather than keep it as a legacy-only helper. A legacy-profile strategy that wants a per-bar resting pair builds it from the SDK’s constructors and Order.OCOGroup directly; since GLE-1362 it can pass the pair through kit.OneBar to keep that life under v2 as well, where a Day order the calendar cannot place is denied.
The account and sizing
| Helper | What it does | Order lifetime | Profile |
|---|---|---|---|
Equity(ctx) (kit.go) | the account equity from ctx.Account(): the net liquidation in the base currency when the account reports one (a backtest does, every currency converted at the rate in force), zero or negative included; otherwise the USD balance when one is reported, otherwise the sum of every balance; 0 when the account reports nothing, and callers fall back to a fixed size (Currencies) | none | both |
BuyingPower(ctx) (kit.go) | what the account can still commit at initial margin: the net liquidation less the initial margin the open positions require, when the account reports both (a backtest whose simulator holds margin requirements); otherwise Equity(ctx) (Margin) | none | both |
PointValue(ctx, symbol), Tick(ctx, symbol) (kit.go) | the instrument’s contract multiplier, 1 when the instrument is unresolved or the value unset; its tick size, 0 when unresolved, which is safe in price-level arithmetic (the offset vanishes) | none | both |
RiskPipsQty(ctx, symbol, riskPips) and its pure core RiskPipsQtyFrom(equity, pointValue, riskPips) (sizing.go) | the legacy risk-parity sizer four of the migrated strategies and the legacy family share: riskPips basis points of equity over the point value, floored at one contract and capped at four; 1 when the run reports no equity, the accepted degraded mode | none | both |
VolTargetConfig, VolTargetQty(ctx, symbol, price, closes, cfg) and its pure core VolTargetQtyFrom (sizing.go) | the vol-target and fractional-Kelly sizer two of the market-only production strategies share: a flat fraction of equity, or the annualised volatility target over the realised log-return volatility of closes across RealisedVolLen bars, capped at MaxLeverage and scaled by KellyFraction, converted to whole contracts at price; 0 when equity is unreported or the realised volatility is degenerate, and callers floor it with their minimum | none | both |
Regular-hours equity bars
Two data helpers in rth.go, with no order and no profile, for a daily strategy that trades an equity’s regular session (Session bars):
| Helper | What it does |
|---|---|
IsEquity(symbol) | whether the symbol’s class, the text before its first colon, is eq in any case (eq:ARCX:SPY:adj=splitdiv); a symbol with no class, such as a file-csv fixture’s B01, is not an equity. A strategy that declares a basket can declare its equity members at rth and leave the rest at the run’s session, which keeps a file-csv fixture runnable: that adapter serves no session |
RequireRTH(name, bar) | nil for a bar of any other class and for an equity bar whose Bar.Session is rth; otherwise an error prefixed with name and the symbol that tells the operator to run with --session rth. Only session-keyed daily and weekly bars carry a session, so an intraday equity bar is refused too. A strategy returns it from OnBar, which ends the run |
Series arithmetic
series.go holds small pure functions over nseries vectors, with no order and no profile: Finite(x), a usable number (neither NaN nor infinite); Clip(x, lo, hi); LogReturns(s) and SimpleReturns(s), the one-bar returns of a price series, 0 where undefined, built for nseries.Series.Func; and the weekly resamplers WeeklyOHLCCompleted(prim) and WeeklyOHLC(prim), which bucket a daily lookback series into ISO weeks, oldest first, the first exposing completed weeks alone (the legacy engine’s weekly view, a week complete on its Friday session bar, the holiday-shortened week the accepted approximation) and the second including the week in progress. Resample in periods.go is the general form for any timeframe and location (Higher timeframes from base bars).
Aligned reads and release-stamped series
These are the helpers of Lining up series; each doc comment names its pairing class (as-of, same-clock or release clock). Data helpers: no order, no profile.
| Helper | What it does | Where it is explained |
|---|---|---|
AsOfClose(series, cutoff) (tier2.go) | the newest close whose bar closed at or before cutoff, and true; (0, false) when there is none: the aligned read of an irregular aux series without leaking a future release | The clock and the “as known at” rule |
AllFresh(ctx, ids...) (tier2.go) | true when every named series’ newest bar closed at ctx.Now() (an empty list vacuously, an unseen id not): the all-inputs-aligned gate of a cross-series strategy | Missing bars |
AsOfCloses(aux, prim, n), JoinCloses(a, b, n) and ReleaseClock (NewReleaseClock, Observe, Len, Series) (align.go) | the three pairing patterns: the slow series carried onto each of the last n primary closes; the closes of the last n bar pairs whose close times match; the aux value and the primary’s last close recorded at each release | Three patterns |
AgeAt(s, now), StaleLegs(now, maxAge, ids, legs), StaleSeries(ctx, maxAge, ids...), Cadence(s, loc) and CompareLegs(a, b, loc) (align.go) | how long ago a series’ newest bar closed; the legs that are empty or older than maxAge; a leg’s interval and session end, and whether two legs share them | Missing bars |
Period (PeriodDay to PeriodYear), ShiftRef(ref, p, k), RefValue(s, ref), PeriodsAgo(s, p, k) and PairByRef(a, b, n) (periods.go) | reference-period arithmetic over a release-stamped series, keyed by Ref so that a period that was not published is reported missing rather than skipped over | Release-stamped series |
Timeframe (TimeframeDay to TimeframeYear), HTFBar, Resample(s, tf, loc), HTFCloses(bars), PeriodStarts(s, tf, loc) and RequireCloseStamped(s) (periods.go) | true resampling of base bars into calendar periods in a location, the completed bars apart from the developing one; one flag per bar for the first bar of its period; the refusal of a series stamped at its start | Higher timeframes from base bars |
Keys, CalendarKey (KeyMonth to KeyTOD), CalendarIndex (NewCalendarIndex(cal, opts), At, Bar, ExpirationDate, Zone), CalendarIndexOptions, KeysAt(cal, t), WeekdayClosure, KeySeries(s, idx, key), SessionStarts(s, cal), TradeDateStarts(s, cal, tf) and ResampleSessions(s, cal) (calkeys.go) | the calendar and session keys of a bar on its exchange trade date (the nseries WP0.9 keys month, weekday, dom, doy, tdm, tdr, tdy, with tdh, tdw, the week, session and expiration keys and the time of day), NaN when the calendar cannot say; one flag per bar for the first bar of a trade date, week, month or year; one session bar per trade date | Calendar and session keys |
LastBefore(s, cal, date), PriorSession(s, cal) and SessionWindow(cal, date, boundary) (sessions.go) | the prior session (or week) of a bar: the newest bar of a declared session series or of an aligned view of one whose trade date precedes the bar’s; the same from the kit’s trade-date resample of the grid buffer; the window an intraday grid boundary names on a trade date, whose close marks the session’s last bar | Prior sessions and weeks on base bars |
Positioning series
cftc.go addresses the Commitments of Traders series: CFTCCodeForSymbol(symbol) maps a futures symbol in any form (bare, @-prefixed or lake-canonical) to the CFTC contract-market code of its own contract, each code one contract market rather than a commodity-code sum; BareProduct(symbol) reduces a symbol to its bare product root; COTSymbol(code, group) builds cot:CFTC:<code>:<group>; COTLegSymbols(symbol, category) names a category’s long and short legs; LongShortRatio(long, short) is a category’s long positions over its short ones, false when the short side is not positive or a value is not finite; and TFFSymbols and NonUSFutures enumerate the markets reported in the Traders-in-Financial-Futures breakdown and the non-US contracts with no report. Data helpers, no order, no profile; see Release-stamped series: COT, FRED and RBA.
Bars built from the tape, statistics and observations
Three files hold pure helpers over the engine’s event data, each documented with its chapter: eventstats.go over a bar’s construction statistics (AggressorImbalance, AggressorCoverage, AverageTradeSize, VWAPDisplacement, StatColumn, FlowDelta; Construction statistics); marketstats.go over ctx.MarketStatistics and the definitions (OpenInterestChange, SettlementGap, DaysToExpiry; Statistics and definitions as events); and observations.go over an observation history (ObsPoint, ObsLatestKnown, ObsKnownBefore, ObsRevisionSurprise, ObsGrowth; Observations as events). Data helpers, no order, no profile.
Re-entries inside a base trade
Many systems have a base: entry and exit rules that, left alone, give a position bar by bar. Sources then add a stop that cuts the real position before the base exits, and some of them re-enter while the base trade is still on: Pruitt’s oscillator systems take a later signal after their bracket has cut a trade, Carver’s Starter System keeps a trade through its opening rule’s flip and reverses at the stop, Ruggiero’s modified channel breakout switches its exit after ten bars and re-enters at the channel. nseries expresses the base and a cut position as series (the cut stays flat until the base’s next entry, the register’s V-142), but not a re-entry, which depends on the real fills and needs a loop (V-222). kit.BaseTrade (basetrade.go; GLE-524, row 31 of the register’s V-867) is that loop on the strategy side, with no engine change. It is a pure state machine like the Tracker: once per primary bar the strategy hands it the bar’s TradeState, the bar, and the base’s four flags with its own stop test, and it returns Want, the direction (+1, 0 or -1) the real position should hold after this bar’s decision. It builds no order.
st := ctx.Trade(bar) // once per primary bar
want := s.bt.Decide(st, bar, kit.Signals{LongEntry: le, ShortEntry: se, Stop: hit})
diff := int64(want)*qty - ctx.Position(bar.Symbol).Quantity // the strategy's order
Timing. Want(t) is the position after bar t’s decision, nseries’s convention for a position series. An order decided at bar t’s close is first seen on bar t+1, whether it is a market-on-close order (filled at t’s close under lifetime v1, at the next session’s close under v2, t+1’s on daily bars) or a market order (filled at t+1’s open); a resting stop that fills during bar t is seen on bar t. So the latch tells a cut from a pending entry by what it asked for: an exit it did not want (the real position left while Want was on) is a cut, which is how a stop resting at the venue is recognised without a flag; a flat position while Want is on and nothing has exited is an entry not yet filled. The contract is that every exit of the real position is either one Want asked for or a cut. An entry whose attached stop fills inside its own bar leaves the position flat at both decisions, so the trade state shows no transition; a strategy whose own fill-driven book saw it calls RoundTrip(dir, price) once, after Decide, with the entry’s direction and fill price: inside a base trade it is the wanted entry and its cut (OriginalPrice taken from the price when not yet seen), inside a cut base trade the re-entry and its cut, and anything else is left alone. The demos never call it.
The rules.
- The base is nseries
PositionSigned’s transition on the four flags: flat takes one entry (both on one bar stay flat), a position reverses on the opposite entry whatever its exits say, otherwise its own exit closes it, and its own entry is ignored while in position.Base,BaseEntryBar,BaseEntryCloseandBaseBarsSinceEntry()read it. - The stop (
Signals.Stop) is the strategy’s own test on the real trade, read only while the real position is on as the latch wants it, and not on a bar on which the base enters, reverses or exits: the base’s transition decides that bar. A stop setsJustCutandCut. - The re-entry rule (
ReEntry):ReEntryNone, the zero value, keeps a cut position flat until the base’s next entry or reversal;ReEntrySignalre-enters on the base’s own entry flag while the real position is flat inside the cut base trade (not on the cut bar itself);ReEntryOrderleaves the re-entry to an order the strategy rests whileArmed()(at the base trade’sOriginalPrice, the real’s first fill in it, or at a level of its own, such as the price its first entry order was placed at), and that order’s fill is the re-entry (JustReEntered).MaxReEntriesbounds the re-entries of one base trade (0 is no limit). A re-entered trade can be cut and re-entered again. - Holding through the base (
HoldThroughBase): the real trade ignores the base’s exits and reversals and leaves only by a cut; on the cut bar it joins a base that already points the other way (the opposite trade opens at once) and otherwise waits for the base’s next entry. This is Carver’s Starter System, whose moving average only opens trades. - The diagnostic (
Missed) is the register’s V-222 split of the base from the real position: the base’s own entry flag firing inside a base trade while the real position is wanted flat, or on the bar the base exits after a cut. UnderReEntryNoneit marks every bar on which a source that re-enters would part from the cut recipe. - The switched exit is
SwitchedLevel(barsSinceEntry, after, early, late):earlywhile the real trade’sTradeState.BarsSinceEntry()is belowafter,latefrom then on. That count is 0 on the bar the fill is first observed, which is the fill bar for an intrabar stop and a next-open market order (TradeStation’s count) and one bar later for a market-on-close fill under lifetime v1. Under v2 an MOC fills at the close of the bar it is first observed on, so the count is 0 there.
Identities. With no stop, Base and Want equal PositionSigned on the same flags bar for bar. Under ReEntryNone with close fills, Want equals nseries’s tier-A cut recipe bar for bar. The kit’s spec test pins both on nseries’s own fixture for Pruitt’s Box 2.7 (group s of t6-momentum1b.csv, 600 bars, copied with its digest): 23 base trades, 13 cuts and the 18 bars on which nseries counts a same-direction pivot inside a cut base trade (TestRecipeT6HistogramPivot); under ReEntrySignal those 18 bars are the re-entries and Want equals a TradeStation loop of the system on every bar.
Restart. The base is per-process state, like BarsSinceEntry. A backtest is exact. After a live restart the first Decide adopts an open position as the base trade, so a plain held trade is recovered, but not a cut state or a trade held through the base’s flip.
Order lifetime. BaseTrade rests nothing and reads no working order, so the profile does not reach it. The orders that carry the real position to Want are the strategy’s: market-on-close or market orders under either profile, or controller intents under lifetime v2.
The demos. Three examples under strategies/demo/go/, each built by make build and each with a spec test through the engine (its fills compared exactly with an independent reference), review tests (and mutation review tests for the two whose mutation sweep found gaps the spec tests missed), and a cf21_conform_test.go (the two that support both lifetimes pin their legacy blotter and their v2 parity; cyclechannel its requirement):
| Demo | Source and rules | Orders and lifetime | Departures |
|---|---|---|---|
histopivot | Pruitt, The Ultimate Algorithmic Trading System Toolbox (2016), Box 2.7: the 12, 26 and 9 MACD histogram’s two-bar pivot below zero buys, above zero sells short, decided at the close; the chapter 2 bracket, 3 ATR(10) target and 1 ATR stop from the entry close, tested on the close; ReEntry (default true) takes a later pivot inside a cut base trade, false keeps nseries’s cut recipe | market-on-close entries, reversals and exits, at the decision’s close under lifetime v1 and at the next session’s close under v2, for which it asks for the exchange calendar; supports lifetime v2 | none in the rules; the histogram reads the whole history up to MaxBars (4,096) bars, after which its averages restart at the window’s oldest bar |
startersystem | Carver, Leveraged Trading (2019), chapters 5 and 6: long while the 16-day average is above the 64-day one, short while below; a trailing stop at half the annual instrument risk in price units (the sample deviation of 25 daily returns times 16, or the Risk input), the gap frozen at the fill, against the highest close since the fill (lowest when short), breached by a close strictly beyond; the trade survives the rule’s flip and reverses at the stop when the rule already points the other way; Hybrid closes on the flip instead (Carver’s chapter 9 base with the same stop) | market orders at the next open; supports lifetime v2 (no branch); withholds an order while one on the symbol is working | the gap is taken at the fill, with the volatility of the fill bar’s closes |
cyclechannel | Ruggiero, Cybernetic Trading Strategies (1997), Table 15.8: stop and reverse at the highest high and lowest low of the dominant cycle’s bars; while in a trade, an exit at the half-cycle channel for its first ten bars (SwitchedLevel) and at the full channel after them; after an early exit the entry stop at the channel stays declared, which is the re-entry (ReEntryOrder) | first-touch stops (TouchBuy, TouchSell, GTC) declared through kit.Controller, one unit a leg; requires lifetime v2 | the proprietary cycle is nseries’s HilbertPeriod, rounded and clamped to 6..50 (or FixedCycle); the proprietary trend filter is dropped, so the base is Table 15.4’s breakout; a half cycle is truncated; first-touch stops are backtest-only; an outside bar that fills both entry stops while flat is caught up at the next open |
Printed results outside the marketfeed archive (Ruggiero’s currencies from 1980, Carver’s instruments) are cited, not reproduced; the tests check the rules on fixtures: Carver’s gold example (entry 1,300, risk 11%, gap 71.50, lines 1,228.50 and 1,278.50), Box 2.7’s 18 re-entries, and Ruggiero’s order set against a TradeStation loop on a 400-bar walk.
nseries’s bar-level form. nseries’s PositionSignedRules family (nseries PR 186, from the family advice of GLE-525 and GLE-526, pinned since GLE-524’s WP3) runs a whole rule set of this kind on flags and levels, with no fill: the bar-level signal form of a re-entering latch. BaseTrade is the engine-side form: the base runs on flags, the real position on fills. Where a source’s re-entry reads only bar data, the two describe the same trades, and under close fills without slippage Base equals PositionSigned and Want under ReEntryNone equals the cut recipe. BaseTrade does not depend on it, and no test yet compares Want with PositionSignedRules on the same rules.
Pending stop entries and resting exits
Many sources enter with a stop order that waits for its fill: “buy the next new high” after a signal, “place a buy order above the high price of that day”, TradeStation’s BUY NEXT BAR AT CLOSE+.05*C/100 STOP, or a buy stop “trailed down” to each day’s high until it is hit. Their exits are often resting stops re-priced every bar: ExitLong at Lowest(Low,StopLen) Stop, or a stop “below the lower inner band”. nseries can only approximate these on bars (an entry flag on the bar that reaches the level, a fill priced as o.Maximum(level); V-655, V-736, V-817 and V-852 of the register), because whether and where the order fills depends on the next bars’ prices; on the engine they are ordinary stop orders. kit.PendingEntry (pending.go; GLE-524, row 29 of the register’s V-867) keeps such an entry from its arm to its end, and five demos show the orders, with no engine change.
PendingEntry. A pure state machine like the Tracker and BaseTrade: it builds no order. Once per primary bar, after ctx.Trade, Observe(tradeState) folds in the bar that just ended, then the strategy’s rules may Arm(side, level) the entry for the next bar, and while Resting() the strategy returns its stop at Level:
st := ctx.Trade(bar)
s.pe.Observe(st) // the fill, the withdrawal or the expiry
if signal {
s.pe.Arm(+1, bar.High+tick) // a re-arm re-prices it and restarts its life
}
if s.pe.Resting() && ctx.Position(bar.Symbol).Quantity == 0 {
orders = append(orders, algolang.StopBuy(bar.Symbol, qty, s.pe.Level))
}- Its end (
End, one per bar):EntryFilledwhen the position opens, reverses or grows onto the entry’s side;EntryWithdrawnwhen the position changes otherwise (so an exit while a reversal is pending withdraws it) or the strategy callsCancel;EntryExpiredafterMaxBarsbars unfilled (0 is no limit);EntryReplacedwhen an arm on the other side replaces it. The position is read fromTradeState’s transitions alone (JustEntered,JustExited,JustAdded), so a partial exit that leaves the position on its side ends nothing, unless the strategy reports a fill it saw itself: a position that opens and closes inside one bar (an entry whose attached stop fills on its own bar) is flat at both decisions and shows no transition, so a strategy whose own fill-driven book saw the entry fill callsFill()afterObserveand before its rules, which ends the entryEntryFilled(and turns anEntryExpiredof that bar intoEntryFilled). With nothing pendingFilldoes nothing, and the demos never call it. - Re-pricing. A same-side
Armwhile pending movesLeveland restarts the life: the trailed stop of a source that keeps “trailing it down to the high of each previous day’s bar”. - Through the market.
Through(last)says whether the level is at or through the last close, where a plain stop is refused at submission (When and how orders fill); the demos then rest the first-touch form (TouchBuy,TouchSell), backtest-only. - Restart. The state is per process: after a live restart a pending entry is forgotten (the venue’s Day order has expired by then).
One code path for both lifetimes. A strategy that returns its resting stops again on every primary bar, each stamped by kit.IDStamper, passes each decision’s orders through kit.OneBar (GLE-1362), and makes the same fills and ids under --lifetime v1 and v2 with no branch: under v1 the venue expires an unfilled stop after its bar, and under v2 OneBar sends it GTC and cancels it at the next decision. The lifecycle counts differ only as conform.Expect.OneBar allows, explicit cancellations under v2 where v1 counts TIF_EXPIRED ones. Until GLE-1362 the demos returned Day stops and relied on v2’s one-bar fallback for a Day order the calendar could not place, which a v2 backtest now denies (day_close_unplaced); with a served calendar a Day order returned at a daily bar’s close would live the next session, but the file-csv adapter the demos’ tests run through serves none (Calendar cancellation instants (lifetime v2)). Under lifetime v2 the same stop can instead be one kit.Controller intent re-priced each bar (a cancel at the bar, the successor at the turn): the demos do not need it. A resting exit is a first-touch stop, because an exit level (a 12-bar low, a band) can equal or be through the last close. No exit rests on the bar an entry fills: it is first placed at the close of the bar on which the fill is seen, as TradeStation places exits for an open position.
The demos. Five examples under strategies/demo/go/, each built by make build, each supporting lifetime v2 with no branch, each with spec tests through the engine under both lifetimes (its fills compared exactly with an independent loop of the source’s rules on a seeded walk and, for Four-Bar Fear, eight hand-built fixtures), unit tests of its pinned helpers (fearArms, katsanosMFI, forceLines, momentumSignals, dpo and starBands), and a cf21_conform_test.go (the frozen legacy blotter, v2 parity and the declaration), and review tests from the review panels (order types against the position, other quantities and inputs, a second session, OnInit’s bounds); fourbarfear and forcepullback also have mutation review tests (a run with no tick size, where an entry at the last close must rest as a first-touch stop):
| Demo | Source and rules | Orders | Departures |
|---|---|---|---|
fourbarfear | Downs, Stocks & Commodities V16:8 (1998): after four closes strictly inside the bull fear and bear fear levels (the midpoints of the last 12 highs’ and lows’ ranges), a close above bull fear arms a buy stop one tick over the bar’s high (“buy the next new high”), a close below bear fear a sell stop; out one tick beyond the three-day low (high) ending at the decision bar | PendingEntry (EntryBars 1: the next bar only; 0: until filled), withdrawn by any change of the position and replaced by an opposite arm; first-touch exit stops; an opposite arm while in a position reverses: alone for the position plus Qty when its level is at or beyond the exit’s, otherwise beside the exit, unjoined, so a bar that reaches both exits and enters | the stop’s price, life and the reversal are unstated by Downs |
mfidirection | Katsanos, Stocks & Commodities V29:8 (2011), the MFI direction test: his money flow index (the rising typical prices’ flow over the total, 21 bars) crossing over its 50-bar average above 50 with a 7-bar rise beyond one population deviation (30 bars) buys NEXT BAR AT CLOSE+.05*C/100 STOP; out at the next open on the cross under its 30-bar average below 60 or once barssinceentry > 42; long only | PendingEntry with MaxBars 1; market exits | the level is not rounded to the tick; a level at the close (Pct 0) rests as a first-touch stop; one symbol, a fixed quantity, no commission |
forcepullback | Elder through Sarkett, Stocks & Commodities V13:4 (1995), Rules 1 and 2: the day the two-day EMA of the force index turns negative in an uptrend (the 13-day EMA of the close rising), a buy stop “above the high price of that day”; “a protective stop below the low of the trade day or the previous day, whichever is lower”; out at the next open once the EMA is positive or the uptrend ends; Rule 2 mirrors it | PendingEntry (EntryBars 1; Rearm re-prices it on every negative day); the protective stop a first-touch stop fixed at the fill bar’s close; market exits | the entry’s life and the exit are unstated (the two exits Sarkett names are combined); the protective stop is placed at the fill bar’s close, not intrabar |
momentumfirst | Ruggiero, Cybernetic Trading Strategies (1997), Table 4.13: the 3-10 oscillator equal to its 32-bar high above zero buys at the next open, its low below zero sells, reversing; ExitLong at Lowest(Low,StopLen) Stop and its mirror, StopLen 12 | market entries and reversals; the exit a first-touch stop at the 12-bar extreme ending at the decision bar, re-priced every bar | “buy at open” is the next open; the stop does not work on the entry bar |
dualdpo | Star, Stocks & Commodities V32:8 (2014): the 20-bar detrended price oscillator (or the 9-bar, Trigger fast) crossing zero enters at the next open; the stop one tick beyond the 1-deviation band of the 20-bar Bollinger channels (or the 3-deviation band, InitialStop outer), ratcheting with the inner band; after a close in the upper channel the first close back at or below the upper inner band sells PartialQty (1 of 2) at the next open | market entries, reversals and partial exits; the stop a first-touch stop re-priced every bar | reversals, the stop’s offset and trail, and the partial’s size and timing are readings; her full exit on the middle-channel return is not taken |
Printed results outside the marketfeed archive (Ruggiero’s yen from 1976, Katsanos’s 30 stocks, Downs’s 1990s grid of futures and stocks) are cited, not reproduced; the tests check the rules on fixtures, and archive runs are witnesses (GLE-524’s PR body). nseries’s recipes for the same sources (the register’s WP6.1a, WP6.1b, WP6.5a and WP6.7b pages) remain the bar-level forms: Four-Bar Fear’s pinned reading is EntryBars 1 here and its “pending until filled” variant EntryBars 0; Katsanos’s hold of 44 bars is BarsSinceEntry() > 42 with next-open exits; Elder’s state and event flags are Rearm true and false; Momentum First’s two unrepresentable points (the fill at the stop or a gapped open, and the entry bar) are represented; Star’s book variant on closes stands against the resting stop. triplescreen (Prior sessions and weeks on base bars) takes Penfold’s break entry the same way, a PendingEntry with MaxBars 1, and its frozen v1 blotter is unchanged.
Overlapping per-signal trades
Some sources take every signal as its own trade, even when a new signal fires while an earlier signal’s trade is still open. Palmquist’s declining-volume pullback buys at the next open and sells a fixed number of bars later, and his test lists one trade per signal. With a hold of three bars two of his signals never overlap, so nseries’s Position latch reproduces the list; with a hold of four or more a signal can fall inside an earlier signal’s trade, and the latch, which ignores an entry while it is long, loses that trade (register V-736, extract C260). kit.LotBook (lotbook.go; GLE-524, row 32 of the register’s V-867) holds one lot per signal, each with its own exit, on one symbol, with no engine change.
One order per lot. One account nets positions per symbol, and the report pairs fills into trades first in, first out (The performance report: one trade per entry-lot and exit-fill overlap). So the book builds one Day market order (or market-on-close order) per lot, exits first and oldest first, and the report’s trades are the lots’ trades. Netting the bar’s orders into one loses that exactly when one lot’s exit and another lot’s entry fall on the same bar: a sell of 1 and a buy of 1 at one open net to no order, and the report then pairs the first lot’s entry with the second lot’s exit. A probe with signals on bars 5, 9, 10 and 20, a hold of 4 and opens 100, 101, … gave 105→109, 109→113, 110→114 and 120→124 with one order per lot, and 105→113, 110→114 and 120→124 netted: the same net profit, one trade too few. The position view cannot see such a rotation either (the position stays at 1 and TradeState sets no transition), so the book learns its fills from OnFill, matching each fill to its lot by the order’s client id.
func (s *Strategy) OnFill(_ *algolang.Context, f algolang.Fill) { s.book.OnFill(f) }
// OnBar, primary bars only:
s.book.Observe(bar) // apply the fills, count the bar, decide the exits
if signal {
s.book.Enter(+1, qty, kit.LotExit{Hold: hold}) // one lot per signal
}
return s.book.Orders(bar.Symbol), nil // one order per due exit, then one per new entry
- Exits.
LotExit{Hold, Stop, Target}: afterHoldbars (0 is no limit), on a close strictly beyondStoporTarget(0 or NaN disables either), or when the strategy callsClose(tag)orCloseAll(). With market orders a lot entered on signal bar t is bought at o[t+1] and, withHoldh, sold at o[t+1+h]: nseries’so.Position(sig.Shift(1), nil, h)ando.TradeResult. WithMOCset, under lifetime v1, it is bought at c[t] and sold at c[t+h],c.Position(sig, nil, h). Under v2 an MOC goes out before a later session’s close (Market-on-close orders): on daily bars each lot trades one bar later, at c[t+1] and c[t+1+h]; intraday an MOC is not filled by the next decision, which the book assumes, so use market orders there. - The ledger.
Lots()keeps every lot (its tag, side, quantities, state, the bars on which its entry and exit were applied, and its quantity-weighted prices). While every exit comes in entry order the report’s trades are the ledger’s closed lots one for one. An exit ordered while an older lot stays open (a level or aCloseon a younger lot) is counted inOutOfOrder; the report then pairs it with the oldest lot, so its trade list differs from the ledger while the total is the same, and the ledger is the per-lot record. - One side at a time.
Enterrefuses the other side while any lot is pending, open or exiting: opposite overlapping lots cannot be held apart in one account. - Fills.
OnFillrecords; the nextObserveapplies. An entry still unfilled at the next decision is withdrawn and a late fill for it is refused; an incomplete exit is re-issued for its remainder (_x2,_x3, …). That is theTracker’s assumption that an order is filled by the next decision, which the simulator’s market orders meet, and its market-on-close orders under lifetime v1, or on daily bars under v2. - Restart. The book is per-process state: after a live restart it is empty, and a strategy adopts an inherited position as one lot with
Adopt(qty, price, exit)or flattens it. - Client ids are
<Prefix>_<signal bar close UnixNano>_<k>_eand..._x(_x2,_x3for re-issues); they carry no symbol, so a strategy with several books gives each its ownPrefix. A tag that two bars with one close time would repeat skips to the next free<k>, so each id names one lot for the whole run. - Cost. Every per-bar loop starts at the oldest lot still in play, so a long run’s ledger of finished lots does not slow the bar.
Order lifetime. The book’s Day market orders are consumed on their first eligible bar under either profile, and it reads no working order, so it serves both. Its market-on-close orders (MOC) serve v2 on daily bars only, a bar later than under v1.
The demo. strategies/demo/go/volumepullback, run under both profiles:
| Demo | Source and rules | Orders and lifetime | Departures |
|---|---|---|---|
volumepullback | Palmquist, “Data-Driven Trading”, Stocks & Commodities V29:13 (December 2011): at least three strictly lower highs on at least three strictly lower volumes ending on the setup bar, a strictly higher high on the next bar, its close above MinClose (5) and its 21-bar average volume above MinVolume (200,000), no signal before the 21st bar (nseries’s t6DecliningVolumePullback, its five lines verbatim); one lot per signal bought at the next open and sold Hold (3) bars later at the open | one market order per lot through LotBook; supports lifetime v2 (no branch) | MinVolume is in the feed’s volume unit (shares for an ETF, contracts for a future; the unit of his AIQ scan is uncertain); after a live restart an open position is adopted as one lot |
Its spec tests run it through the engine on a 600-bar fixture (testdata/pullbacks_1d.csv, written by gen_pullbacks.py 39 600) with 90 signals: at Hold 3 its trades are nseries’s latch trade for trade, 89 of 89 closed trades (nseries’s own probe reported 99 of 99 on its random series, C260); at Hold 4, with 70 pairs of signals four bars apart, and at Hold 9, with three lots open at once, the report’s FIFO trades of the run’s fills are the per-signal enumeration, while netting the same fills per bar gives fewer trades for the same total and the latch drops signals. The gate’s edges (the 21st bar, a close or an average volume equal to its minimum) run on constructed bars, and the demo’s review tests check its signal on the 21-bar window in process and its fresh book for each session, and cf21_conform_test.go checks both profiles against the frozen v1 blotter (testdata/cf21/v1_fills.json, 179 fills).
Not covered. Opposite overlapping trades, and same-side trades whose exits come out of entry order, cannot be attributed per signal by one account’s FIFO report; the ledger keeps them, and an opt-in report pairing by the client id’s lot tag is the follow-up if a source needs them in the report. The 8-day pattern’s grid of sixteen stop and target pairs (C305) is an event study rather than a strategy: it belongs to keyed statistics (GLE-529) or a --config run matrix.
Tests
kit_test.go covers StopSuite on both sides, the Tracker’s transitions and its reversal, the weekly resamplers, the sizers, the CFTC codes (each a contract market), Flatten and the stamper; openedat_test.go the Tracker’s adoption after a restart and OpenedAt across an add, a flip and a flat; tier2_test.go LoserCooldown and AsOfClose; tournament_tr5_spec_test.go, kit_reconcile_review_test.go, kit_reconcile_mutation_review_test.go, aa00_rollwindows_tournament_spec_test.go, rom15_rollown_mutation_review_test.go and gle409_combo_test.go the controller; aa00_cs21_exiting_tournament_spec_test.go and cs21r_exiting_review_test.go the exit-once gate; tournament_basetrade_spec_test.go (with nseries’s Box 2.7 fixture, testdata/t6-momentum1b-s.csv), basetrade_mutation_review_test.go, basetrade_review_test.go, tournament_basetrade_roundtrip_spec_test.go and basetrade_roundtrip_review_test.go (its RoundTrip, GLE-555) the base-trade latch; tournament_pending_spec_test.go, pending_review_test.go, tournament_pending_fill_spec_test.go and pending_fill_review_test.go (its Fill, GLE-554) the pending stop entry; tournament_lotbook_spec_test.go (its FIFO claims replayed through engine/report’s recorder), lotbook_mutation_review_test.go and lotbook_review_test.go the lot book; and the tournament_*_spec_test.go files with their review and fixture tests (gle406_review_test.go, gle408_observations_test.go, gle413_cotlegs_test.go among them) the alignment, period, event-statistics, market-statistics, observation and positioning helpers; tournament_calkeys_spec_test.go, calkeys_mutation_review_test.go and calkeys_review_test.go the calendar and session keys, with nseries’s reference keys in testdata/t6-calendar-keys.csv; tournament_sessions_spec_test.go the prior-session helpers and StopEntry; and sessions_nseries_crosscheck_test.go the prior-session helpers against nseries’s prior-period latches. go test ./strategies/kit/ runs in a few seconds and needs no engine; the cross-check’s golden form (sessions_nseries_crosscheck_golden_test.go, with its recorder testdata/xcdump) runs in make test-golden.