A volume-bar trend with flow confirmation

A volume-bar trend with flow confirmation

volumetrend makes decisions after a fixed amount of activity rather than after a fixed duration. It trades on volume bars, filters with one-minute price trend and confirms with tick-imbalance bars. This exercises three constructions on one symbol:

bin/algo run \
  --adapter bin/databento-adapter \
  --adapter-inputs Path=testdata/xnas-sample/xnas-itch-20220610.trades.csv \
  --data-protocol pb --strategy bin/volumetrend --symbols MSFT \
  --bar-kind volume --threshold 1000 \
  --commission-per-share 0.005 --slippage-ticks 1 --cache off \
  --results-dir results/learning/volume

The primary closes after 1,000 shares; trend uses time bars and flow tick-imbalance bars, each with its own history. Equal-volume bars need not have equal durations or liquidity conditions.

Indicator warm-up and constructor lead-in differ

Lookback requests completed bars for a strategy’s indicator. LeadIn requests earlier trade prints to warm the adapter’s bar constructor before the study window. Stateful imbalance and expectation-based constructions may need both. Missing tape before the sample produces a lead-in note; the engine cannot fabricate earlier constructor state.

The demo makes decisions only on primary volume bars, while references update in event-time order. It targets 100 shares when the minute trend is up and flow confirms, and exits when the trend turns down. Inspect the request line to confirm that all three constructions were actually fetched. A default inherited from the run can otherwise change a declaration’s meaning.

A multi-series run may use bar-path simulation even though its source file contains ticks; tick replay has a single-series restriction. Read the reported simulation resolution and degradation notes. Activity bars change sampling, not execution realism.

For prints between bars, study tapereader; for published open interest, study oiconfirm. Both teach event availability: a statistic must not be attached retroactively to bars before its publication. Source to study: strategies/demo/go/volumetrend/main.go.

Complete source: volumetrend

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 primary volume bars and extra time/tick series have different construction rules. Their lengths count observations on their own clocks.

  2. OnBar requires the relevant buffers before combining trend and flow. A thousand-volume bar is not a fixed elapsed-time interval.

  3. The final orders reconcile the desired primary position. The same archive prints must support each requested bar construction for the run to be meaningful.

Build the supplied files directly:

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

volumetrend/main.go

// Command volumetrend demonstrates per-series bar construction (GLE-390): one
// run mixing three bar kinds. It trades the run's own series, 1,000-share
// volume bars (the run's --bar-kind volume --threshold 1000), and declares two
// more series of the same symbol, each with its own construction:
//
//   - "trend": one-minute time bars, a trend filter (the last close above the
//     simple moving average of the last TrendN closes);
//   - "flow": tick-imbalance bars (a bar closes when the signed trade count
//     since its open reaches Imbalance), built from a five-minute constructor
//     lead-in, an order-flow confirmation (the last imbalance bar closed up).
//
// On each volume bar it wants a long of Qty shares when the trend is up and
// the flow confirms, and flat when the trend turns down; it reads its position
// from the engine and sends one market order for the difference. The declared
// series only update the context: decisions happen on the volume bars.
//
// Run it with `make run-volumetrend` (the bundled MSFT trade sample through the
// Databento adapter; the lead-in needs the pb data wire). Declarations with
// their own construction travel on the pb strategy wire only.
package main

import (
    "fmt"
    "os"
    "time"

    algolang "MODULE/sdk/strategy"
)

// VolumeTrend is the example strategy.
type VolumeTrend struct {
    Trend  string `algolang:"default=1m,desc=Interval of the declared time-bar trend series"`
    TrendN int    `algolang:"default=5,min=2,max=200,desc=Moving-average period on the trend series"`
    // Imbalance is the flow series' static tick-imbalance threshold.
    Imbalance float64 `algolang:"default=15,min=1,desc=Tick-imbalance threshold of the declared flow series"`
    Qty       int     `algolang:"default=100,min=1,max=100000,desc=Shares per entry"`

    symbol string
}

// Name returns the strategy's display name.
func (v *VolumeTrend) Name() string { return "Volume Trend" }

// Description returns a one-line description.
func (v *VolumeTrend) Description() string {
    return "Volume-bar entries gated by a declared time-bar trend filter and a declared tick-imbalance flow confirmation."
}

// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. Its orders are market orders alone, so the
// one-bar rule (OneBarRule) ends none of them.
func (v *VolumeTrend) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does; it exempts market orders.
func (v *VolumeTrend) OneBarRule() bool { return true }

// OnInit records the run's symbol.
func (v *VolumeTrend) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
    if len(cfg.Instruments) == 0 {
        return fmt.Errorf("volumetrend: the run names no instrument")
    }
    v.symbol = cfg.Instruments[0].Symbol
    return nil
}

// Lookback is the depth of the run's own (volume-bar) series.
func (v *VolumeTrend) Lookback() int { return 2 }

// DataRequirements declares the trend and flow series, each with its own
// bar construction.
func (v *VolumeTrend) DataRequirements() []algolang.DataRequirement {
    return []algolang.DataRequirement{
        {SeriesID: "trend", Symbol: v.symbol, Lookback: v.TrendN + 1,
            Schema: algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: v.Trend}},
        {SeriesID: "flow", Symbol: v.symbol, Lookback: 2,
            Schema: algolang.DataSchemaSpec{Kind: algolang.Bars, BarKind: algolang.BarsImbalanceTick,
                Threshold: v.Imbalance, LeadIn: 5 * time.Minute}},
    }
}

// trendUp reports whether the trend series' last close is above the mean of
// its last n closes; ok is false until n closes exist.
func trendUp(ser algolang.Series, n int) (up bool, close, mean float64, ok bool) {
    if ser == nil || ser.Len() < n {
        return false, 0, 0, false
    }
    sum := 0.0
    for i := 0; i < n; i++ {
        sum += ser.Close(i)
    }
    mean = sum / float64(n)
    close = ser.Close(0)
    return close > mean, close, mean, true
}

// OnBar decides on the run's volume bars; the declared series only update
// the context.
func (v *VolumeTrend) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if bar.SeriesID == "trend" || bar.SeriesID == "flow" || bar.Symbol != v.symbol {
        return nil, nil
    }
    up, tclose, tmean, tok := trendUp(ctx.Series("trend"), v.TrendN)
    flow := ctx.Series("flow")
    confirm := flow != nil && flow.Len() > 0 && flow.Close(0) > flow.Open(0)
    pos := ctx.Position(bar.Symbol).Quantity
    want := decide(pos, int64(v.Qty), up && tok, confirm)
    ctx.Logf("volumetrend: %s close=%.2f trend=%.2f/%.2f up=%t flow_up=%t pos=%d target=%d",
        bar.CloseTime.Format(time.RFC3339), bar.Close, tclose, tmean, up && tok, confirm, pos, want)
    if want == pos {
        return nil, nil
    }
    o := algolang.MarketBuy(bar.Symbol, want-pos).Named("LE")
    if want < pos {
        o = algolang.MarketSell(bar.Symbol, pos-want).Named("LX")
    }
    o.ClientID = fmt.Sprintf("volumetrend_%d", bar.CloseTime.UnixNano())
    return []algolang.Order{o}, nil
}

// decide is the position wanted: qty when flat with the trend up and the flow
// confirming, flat when long with the trend no longer up, else unchanged.
func decide(pos, qty int64, up, confirm bool) int64 {
    switch {
    case pos == 0 && up && confirm:
        return qty
    case pos > 0 && !up:
        return 0
    }
    return pos
}

func main() {
    if err := algolang.Run(&VolumeTrend{}); err != nil {
        fmt.Fprintln(os.Stderr, "volumetrend:", err)
        os.Exit(1)
    }
}

Complete source: tapereader

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. DataRequirements declares the trade-print series. OnMarketTrade observes prints; it does not return orders.

  2. window measures the interval from the previous decision through, but excluding, the current close using receive times. Its results are limited by the retained print buffer.

  3. target converts trade count and aggressor imbalance into desired exposure. Orders remain in OnBar, which subtracts the filled position from that target.

Build the supplied files directly:

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

tapereader/main.go

// Command tapereader is a demo strategy that reads the trade tape between bar
// closes and, when trading is intense, trades the bar's close in the direction
// of the tape.
//
// It declares one TRADES series, "tape", on the run's first instrument (MSFT in
// the example run). Before each bar the engine delivers every trade that became
// visible since its previous delivery. A trade becomes visible at its ts_recv,
// the instant the data provider received it, and is delivered before the first
// bar whose close is strictly after that instant: a bar [open, close) does not
// contain its close, so a trade stamped exactly at a bar's close is read at the
// next bar. Each bar therefore reads the window [previous close, this close).
//
// The SDK keeps only the newest Lookback trades of the series, so the window
// counts only the trades still in that buffer: when more than Lookback trades
// print between two closes, the oldest of them are gone before the bar reads
// the tape.
//
// When the window holds at least MinTrades trades and the net aggressor share
// of its volume, (buy-sell)/(buy+sell), is at least Imbalance, the strategy
// targets a long position of Qty; at most minus Imbalance, a short one;
// otherwise it keeps its position. It reaches the target with one market order
// at the bar's close and takes its position from the engine.
//
// Run it on the bundled MSFT trade sample with 1-minute bars:
//
//  make run-tapereader
package main

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

    algolang "MODULE/sdk/strategy"
)

// trSeriesID is the id of the one TRADES series the strategy declares.
const trSeriesID = "tape"

// TapeReader reads the tape of its instrument between bar closes and trades a
// bar's close in the direction of the tape when trading is intense: enough
// trades since the previous close, and a net aggressor share of their volume
// beyond the threshold.
type TapeReader struct {
    Lookback  int     `algolang:"default=2000,min=1,max=1000000,desc=Trades kept per declared series"`
    MinTrades int     `algolang:"default=20,min=1,max=100000,desc=Trades since the previous close needed to act"`
    Imbalance float64 `algolang:"default=0.3,min=0,max=1,desc=Net aggressor share of the window volume needed to enter"`
    Qty       int     `algolang:"default=100,min=1,max=1000000,desc=Position size"`

    // Bookkeeping: the instrument recorded by OnInit, the previous OnBar's
    // close (zero before the first bar) and the number of trades observed.
    symbol    string
    prevClose time.Time
    seen      int64
}

var _ algolang.Strategy = (*TapeReader)(nil)
var _ algolang.Initializer = (*TapeReader)(nil)
var _ algolang.DataRequirer = (*TapeReader)(nil)
var _ algolang.MarketTradeHandler = (*TapeReader)(nil)

// Name returns the strategy's display name.
func (s *TapeReader) Name() string { return "Tape Reader" }

// Description returns a one-sentence summary of the strategy.
func (s *TapeReader) Description() string {
    return "Reads the trade tape between bar closes and trades each close in the direction of the aggressor imbalance when the tape is busy."
}

// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. Its orders are market orders alone, so the
// one-bar rule (OneBarRule) ends none of them.
func (s *TapeReader) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does; it exempts market orders.
func (s *TapeReader) OneBarRule() bool { return true }

// OnInit records the run's first instrument as the one to read and trade. It
// fails when the run has no instrument. It does not use ctx.
func (s *TapeReader) OnInit(_ *algolang.Context, cfg algolang.InitConfig) error {
    if len(cfg.Instruments) == 0 {
        return errors.New("tapereader: the run has no instrument")
    }
    s.symbol = cfg.Instruments[0].Symbol
    s.prevClose = time.Time{}
    s.seen = 0
    return nil
}

// DataRequirements declares the tape: one TRADES series, id "tape", on the
// instrument OnInit recorded, keeping the newest Lookback trades.
func (s *TapeReader) DataRequirements() []algolang.DataRequirement {
    return []algolang.DataRequirement{{
        SeriesID: trSeriesID,
        Symbol:   s.symbol,
        Schema:   algolang.DataSchemaSpec{Kind: algolang.Trades},
        Lookback: s.Lookback,
    }}
}

// OnMarketTrade counts the trades observed and logs the first one. It is
// bookkeeping only: orders come from OnBar.
func (s *TapeReader) OnMarketTrade(ctx *algolang.Context, t algolang.MarketTrade) {
    s.seen++
    if s.seen == 1 && ctx != nil {
        ctx.Logf("tapereader: first trade %s %s price=%g size=%d recv=%s",
            t.SeriesID, t.Symbol, t.Price, t.Size, t.TsRecv.Format(time.RFC3339Nano))
    }
}

// OnBar reads the trades of the window [previous close, this close) from the
// tape buffer, works out the wanted position from their count and aggressor
// imbalance, and sends one market order for the difference from the
// engine-reported position when the two differ.
func (s *TapeReader) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if bar.Symbol != s.symbol {
        return nil, nil
    }
    n, buy, sell := window(ctx.MarketTrades(trSeriesID), s.prevClose, bar.CloseTime)
    s.prevClose = bar.CloseTime
    cur := ctx.Position(bar.Symbol).Quantity
    want := target(cur, int64(s.Qty), n, s.MinTrades, buy, sell, s.Imbalance)
    ctx.Logf("tapereader: %s trades=%d buy=%d sell=%d pos=%d target=%d",
        bar.CloseTime.Format(time.RFC3339), n, buy, sell, cur, want)
    if want == cur {
        return nil, nil
    }
    var order algolang.Order
    if want > cur {
        order = algolang.MarketBuy(bar.Symbol, want-cur).Named("LE")
    } else {
        order = algolang.MarketSell(bar.Symbol, cur-want).Named("SE")
    }
    order.ClientID = fmt.Sprintf("tapereader_%d", bar.CloseTime.UnixNano())
    return []algolang.Order{order}, nil
}

// window summarises the trades with prev <= TsRecv < close: their number, the
// buyer-initiated size and the seller-initiated size (a trade without an
// aggressor counts in n only). The lower bound is inclusive because a trade at
// exactly the previous close was delivered after that bar, so this window must
// count it. trades is oldest first, so the scan runs from the newest trade
// back and stops at the first one before prev: a deep buffer costs only the
// window it holds.
func window(trades []algolang.MarketTrade, prev, close time.Time) (n int, buy, sell int64) {
    for i := len(trades) - 1; i >= 0; i-- {
        t := trades[i]
        if t.TsRecv.Before(prev) {
            break
        }
        if !t.TsRecv.Before(close) {
            continue
        }
        n++
        switch t.Aggressor {
        case algolang.AggressorBuy:
            buy += t.Size
        case algolang.AggressorSell:
            sell += t.Size
        }
    }
    return n, buy, sell
}

// target is the position wanted: when n >= minTrades and buy+sell > 0, the
// imbalance (buy-sell)/(buy+sell) at or above threshold wants +qty and at or
// below -threshold wants -qty; anything else keeps cur.
func target(cur, qty int64, n, minTrades int, buy, sell int64, threshold float64) int64 {
    if n < minTrades || buy+sell <= 0 {
        return cur
    }
    imb := float64(buy-sell) / float64(buy+sell)
    switch {
    case imb >= threshold:
        return qty
    case imb <= -threshold:
        return -qty
    default:
        return cur
    }
}

func main() {
    if err := algolang.Run(&TapeReader{}); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

Complete source: oiconfirm

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 two declarations request published venue statistics and instrument definitions for the traded contract.

  2. OnBar reads open-interest changes, settlement gaps and the definition known then. A statistic’s reference date does not make it available before publication.

  3. The guards distinguish unavailable confirmation from a zero value and account for contract expiration. This avoids carrying a signal through an unknown or expired instrument definition.

Build the supplied files directly:

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

oiconfirm/main.go

// Command oiconfirm is a runnable example of the statistics and definition
// market events: a breakout confirmed by rising open interest, with a
// settlement-anchored exit and a flatten before the contract expires.
//
// Besides its daily bars the strategy declares two market-event series: "stats",
// the venue statistics of the contract (settlement price and open interest),
// and "defs", its instrument definition (expiration). The engine delivers them
// between bars under one visibility law. A statistic becomes visible when it was
// published: its receipt time, else its event time, else its reference time. A
// definition becomes visible at its event time. An event reaches the strategy
// before the first bar whose close is strictly after that instant, so a
// decision never uses a figure the market did not yet have.
//
// Venues revise statistics: a preliminary settlement is followed by a final
// one, and open interest is restated the next morning. The kit helpers read
// revisions latest-first: the record delivered last for a trading date wins,
// and the latest trading date wins over the earlier ones. A definition in force
// is the one delivered last.
//
// Run it with make run-oiconfirm, which replays the daily bars of a dated ES
// contract from the marketfeed archive.
package main

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

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

// OIConfirm goes long on a breakout of the recent high when open interest rose
// into it. It exits when the close falls StopPoints below the latest
// settlement, and flattens ExitDays before the contract expires.
type OIConfirm struct {
    Breakout   int     `algolang:"default=20,min=2,max=250,desc=Bars in the breakout channel"`
    StopPoints float64 `algolang:"default=60,min=0,desc=Exit when the close is this far below the latest settlement"`
    ExitDays   float64 `algolang:"default=5,min=0,desc=Flatten this many days before the contract expires"`
    Qty        int     `algolang:"default=1,min=1,max=1000,desc=Contracts per entry"`

    // symbol is the contract being traded, recorded by OnInit.
    symbol string
}

// Name returns the display name of the strategy.
func (s *OIConfirm) Name() string { return "OI Confirm" }

// Description returns a one-sentence summary of the strategy.
func (s *OIConfirm) Description() string {
    return "Buys a channel breakout confirmed by rising open interest, exits below the latest settlement, and flattens before the contract expires."
}

// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. Its orders are market orders alone, so the
// one-bar rule (OneBarRule) ends none of them.
func (s *OIConfirm) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does; it exempts market orders.
func (s *OIConfirm) OneBarRule() bool { return true }

// OnInit records the traded contract, the first configured instrument. It does
// not touch ctx.
func (s *OIConfirm) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
    if len(cfg.Instruments) == 0 {
        return errors.New("oiconfirm: no instrument configured")
    }
    s.symbol = cfg.Instruments[0].Symbol
    return nil
}

// Lookback is the number of bars the strategy needs: the breakout channel and
// the current bar.
func (s *OIConfirm) Lookback() int { return s.Breakout + 1 }

// DataRequirements declares the two market-event series that go with the bars:
// the venue statistics of the contract ("stats", the last 400 buffered) and its
// instrument definition ("defs", the one in force).
func (s *OIConfirm) DataRequirements() []algolang.DataRequirement {
    return []algolang.DataRequirement{
        {SeriesID: "stats", Symbol: s.symbol, Schema: algolang.DataSchemaSpec{Kind: algolang.Statistics}, Lookback: 400},
        {SeriesID: "defs", Symbol: s.symbol, Schema: algolang.DataSchemaSpec{Kind: algolang.InstrumentDefinition}, Lookback: 1},
    }
}

// OnBar works out the wanted position for the bar from the breakout, the
// open-interest change, the gap to the latest settlement and the days left to
// expiry. It returns one market order when that differs from the current
// position.
func (s *OIConfirm) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if bar.Symbol != s.symbol {
        return nil, nil
    }

    ser := ctx.Series(bar.Symbol)
    breakout := false
    if s.Breakout >= 1 && ser.Len() > s.Breakout {
        channel := ser.High(1)
        for i := 2; i <= s.Breakout; i++ {
            if h := ser.High(i); h > channel {
                channel = h
            }
        }
        breakout = bar.Close > channel
    }

    stats := ctx.MarketStatistics("stats")
    oiChange, oiOK := kit.OpenInterestChange(stats, s.symbol)
    gap, gapOK := kit.SettlementGap(stats, s.symbol, bar.Close)

    var daysLeft float64
    var daysOK bool
    if def, ok := ctx.Definition("defs", s.symbol); ok {
        daysLeft, daysOK = kit.DaysToExpiry(def, bar.CloseTime)
    }

    pos := ctx.Position(bar.Symbol).Quantity
    want := decide(pos, int64(s.Qty), breakout, oiChange, oiOK, gap, gapOK, s.StopPoints, daysLeft, daysOK, s.ExitDays)

    ctx.Logf("oiconfirm: %s close=%.2f breakout=%t oi_change=%d oi_ok=%t settle_gap=%.2f gap_ok=%t days_left=%.1f pos=%d target=%d",
        bar.CloseTime.Format(time.RFC3339), bar.Close, breakout, oiChange, oiOK, gap, gapOK, daysLeft, pos, want)

    if want == pos {
        return nil, nil
    }
    var order algolang.Order
    if want > pos {
        order = algolang.MarketBuy(bar.Symbol, want-pos).Named("LE")
    } else {
        order = algolang.MarketSell(bar.Symbol, pos-want).Named("LX Stop")
        if daysOK && daysLeft <= s.ExitDays {
            order.Name = "Expiry exit"
        }
    }
    order.ClientID = fmt.Sprintf("oiconfirm_%d", bar.CloseTime.UnixNano())
    return []algolang.Order{order}, nil
}

// decide is the pure decision: the position wanted given the current position
// pos, whether the breakout fired, the open-interest change (oiOK false means
// unknown), the settlement gap (gapOK false means unknown) and the days left
// (daysOK false means unknown). The contract is expiring when the days left are
// known and no more than exitDays. A long position is closed when the contract
// is expiring or the gap is known and at or below minus stopPoints, and is
// otherwise kept. A flat position enters qty when the breakout fired with
// rising open interest and the contract is not expiring, and otherwise stays
// flat. A short position, which this strategy never takes, is closed.
func decide(pos, qty int64, breakout bool, oiChange int64, oiOK bool, gap float64, gapOK bool,
    stopPoints float64, daysLeft float64, daysOK bool, exitDays float64) int64 {
    expiring := daysOK && daysLeft <= exitDays
    switch {
    case pos > 0:
        if expiring || (gapOK && gap <= -stopPoints) {
            return 0
        }
        return pos
    case pos == 0:
        if breakout && oiOK && oiChange > 0 && !expiring {
            return qty
        }
        return 0
    default:
        return 0
    }
}

func main() {
    if err := algolang.Run(&OIConfirm{}); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

Previous: Momentum ranking: daily and intraday ETF baskets · Next: A range-break filter on an event clock