Strategy SDK API

Strategy SDK API

Generated from the exported SDK declarations and Go documentation. Examples use import algolang as documentation shorthand; substitute your installation’s package import when compiling Go.

AccountBalance

type AccountBalance struct {
	Currency string
	Total    float64
	Locked   float64
	Free     float64
}

AccountState

AccountState mirrors the wire AccountState (Sections 7.5, 8.5).

type AccountState struct {
	BaseCurrency string
	Reported     bool // venue-reported vs system-calculated
	Balances     []AccountBalance
	// NetLiquidation is the account's value in BaseCurrency: every balance
	// converted at the rate in force and open positions marked (GLE-391),
	// when HasNetLiquidation. A computed value may be zero or negative; a
	// cash account state, or a venue that reports none, leaves both unset.
	NetLiquidation    float64
	HasNetLiquidation bool
	// InitialMargin and MaintenanceMargin are what the open positions
	// require, in BaseCurrency, when HasMargin (GLE-411): buying power is
	// NetLiquidation less InitialMargin, and NetLiquidation below
	// MaintenanceMargin is a margin call. Margins lists each position's
	// requirement in its own currency.
	InitialMargin     float64
	MaintenanceMargin float64
	HasMargin         bool
	Margins           []MarginBalance
	Timestamp         time.Time
}

AdoptHandler

AdoptHandler is the optional handler for live-mode startup reconciliation (Section 11.3). The SDK probes for it via a type assertion, exactly like FillHandler/CancelHandler. OnAdoptedState runs once, after OnInit and before any bars, in live mode under the match_ledger policy. By the time it is called the SDK has already seeded ctx.Position()/ctx.WorkingOrders() from the adopted state, so the strategy can inspect or react to what it inherited: cancel inherited orders, log, reconstruct non-derivable state (counters, cooldowns), or refuse to continue by returning a non-nil error. A strategy with no AdoptHandler still has its position + working-order state seeded automatically.

type AdoptHandler interface {
	OnAdoptedState(ctx *Context, state AdoptedState) error
}

AdoptedOrder

AdoptedOrder is one inherited working order. ClientID is the original strategy-supplied label, recovered from the ledger (match_ledger); ParentClientID is populated for a bracket child.

type AdoptedOrder struct {
	Symbol         string
	Side           Side
	Quantity       int64
	Type           OrderType
	Price          float64
	StopPrice      float64
	TIF            TimeInForce
	ClientID       string
	ParentClientID string

	// The complete supported order frame (GLE-200 I2). TrailAmount, OCOGroup
	// and AttachedOrders complete the Order fields (an attached child of an
	// unfilled parent carries Status OrderStatusInactive); Attempt and OrderRef
	// identify the attempt; Status, FilledQuantity and RemainingQuantity are
	// its recovered state (OrderStatusPendingCancel and
	// OrderStatusSubmissionUnknown included); SubmittedAt is the original
	// submission instant (zero when the wire carries none); OwnerID the owning
	// deployment. All zero on a v1 frame.
	TrailAmount       float64        `json:",omitempty"`
	OCOGroup          string         `json:",omitempty"`
	AttachedOrders    []AdoptedOrder `json:",omitempty"`
	Attempt           uint32         `json:",omitempty"`
	OrderRef          string         `json:",omitempty"`
	Status            OrderStatus    `json:",omitempty"`
	FilledQuantity    int64          `json:",omitempty"`
	RemainingQuantity int64          `json:",omitempty"`
	SubmittedAt       time.Time      `json:",omitzero"`
	OwnerID           string         `json:",omitempty"`
}

AdoptedPosition

AdoptedPosition is one inherited open position. Quantity is signed (negative is short). On a non-adjusted (raw) run AvgPrice is the venue-real average cost.

type AdoptedPosition struct {
	Symbol   string
	Quantity int64
	AvgPrice float64
	OpenedAt time.Time // best available
}

AdoptedState

AdoptedState is the live-mode startup-reconciliation snapshot (Section 11.3): the positions and working orders the strategy is starting with, recovered from the engine’s order ledger + the broker. The engine delivers it once, after OnInit and before any bars, in live mode under the match_ledger policy (empty contents if nothing was open); a backtest never sends it. The SDK seeds ctx.Position()/ctx.WorkingOrders() from it before OnAdoptedState (and before the first bar), so a strategy with no AdoptHandler still resumes with correct state.

type AdoptedState struct {
	Positions     []AdoptedPosition
	WorkingOrders []AdoptedOrder
	// OwnerID is the deployment identity the engine recovered this state under
	// (GLE-200 I2); every working order's OwnerID equals it. Empty on a v1
	// snapshot.
	OwnerID string `json:",omitempty"`
}

Aggressor

Aggressor is the side that initiated a trade.

type Aggressor int8

AlignedSeries

AlignedSeries declares an aligned series (GLE-353): a view that carries the latest value of the Source series, as known at each bar of the Grid series, onto that bar. The view is read like any series, with ctx.Series(SeriesID), and lines up index for index with the grid from the newest end. A strategy returns these from AlignedSeries() (SeriesAligner).

  • SeriesID is the view’s id. It must be unique among the run’s series ids and the other views.
  • Source is the canonical id (SeriesID, else Symbol) of a configured or declared series: the values the view carries.
  • Grid is the canonical id of the clock series; "" is the primary.

A sample is the newest source bar visible at the grid bar’s close: one that closed before it, or at the same instant unless the source is a release (cot:, macro:, fx:RBA:) and the grid is not. Its prices, volume, Ref and adjustment fields are the source bar’s; OpenTime and CloseTime are the grid bar’s; SourceOpenTime, SourceCloseTime and Updates say which source bar it carries. The view buffers as many samples as its grid buffers bars.

type AlignedSeries struct {
	SeriesID string
	Source   string
	Grid     string
}

Annotation

Annotation is a note on a bar.

type Annotation struct {
	Text     string
	Position AnnotationPosition
	// Price is the price an AnnotationAt marks; the other positions ignore it.
	Price float64
	Shape AnnotationShape
	// Color is "#RRGGBB", or "" to let the viewer choose.
	Color string
}

AnnotationPosition

AnnotationPosition is where an annotation sits on its bar.

type AnnotationPosition int

AnnotationShape

AnnotationShape is an annotation’s marker.

type AnnotationShape int

AttachMOC

AttachMOC returns entry with a market-on-close order attached that closes it (GLE-1375): the opposite side, the entry’s symbol and quantity, Day, its ClientID the entry’s with “_moc” appended when the entry has one (blank, an automatic label, when it has none). The entry’s AttachedOrders are copied, not shared. Under order lifetime v2 in a backtest the MOC goes out only if the entry fills, at the send time before the RTH close of the session the entry fills in, and is cancelled with an unfilled entry; it shares the entry’s other children’s OCO group, so a protective stop’s fill cancels it and its fill cancels the stop. Lifetime v1 and live runs refuse an attached MOC.

func AttachMOC(entry Order) Order

Bar

Bar is the canonical bar event (Section 7.4). CloseTime is the canonical bar timestamp and decision point.

type Bar struct {
	Symbol    string
	SeriesID  string    // which series this bar belongs to (Section 7.12)
	OpenTime  time.Time // start of the period the bar represents
	CloseTime time.Time // end of the period / decision point (canonical bar time)
	Open      float64
	High      float64
	Low       float64
	Close     float64
	Volume    float64

	// Raw (unadjusted) OHLC: the venue-real prices before corporate-action /
	// continuous-futures adjustment (Section 8.9, 8.10). Meaningful only when
	// isAdjusted is true; on a non-adjusted bar these mirror the adjusted
	// Open/High/Low/Close (see SetRaw / RawPrice). Continuous futures set these
	// via SetRaw alongside the additive CumulativeAdjustment (Section 9.2).
	RawOpen  float64
	RawHigh  float64
	RawLow   float64
	RawClose float64

	// CumulativeAdjustment is the additive (Panama) offset — the futures method.
	CumulativeAdjustment float64
	// CumulativePriceRatio is the multiplicative factor — the equity method
	// (1.0 = no adjustment).
	CumulativePriceRatio float64

	// ActiveContract is the underlying dated contract live for this bar on a
	// continuous-futures run (Section 8.9), e.g. "ESM26". The strategy computes on
	// the back-adjusted continuous series (Symbol) but can address orders to this
	// actual tradeable contract — priced in RAW terms (see RawClose). Empty on a
	// plain (non-continuous) bar.
	ActiveContract string

	// Path is the intra-bar path: for a bar produced by coarsening finer bars,
	// the finer constituent bars it was aggregated from, ascending by OpenTime.
	// Non-nil only when the data request opted in (BarSpec.include_path) and
	// coarsening occurred. One level deep — constituents carry no nested path.
	Path []Bar

	// Session carries the trading-day attributes of a session-keyed daily or
	// weekly bar (the run's series requested a session container): the
	// exchange trade date the bar is keyed by, which era served it, and the
	// settlement facts. Nil on every epoch bar, so a plain run is
	// byte-identical to before. Mirrors the wire BarSession (Section 8.4).
	Session *BarSession

	// Ref is the reference period an irregular series' value describes (a COT
	// report's as-of date, a FRED/RBA observation date) as that date's UTC
	// midnight (GLE-261; wire field Bar.ref_date). Key periods by Ref, not by
	// OpenTime: on such a bar OpenTime is the previous release, and a period
	// that was never published has no bar. Zero on every price bar.
	Ref time.Time

	// Seam facts on a composite (:cont) bar whose bucket straddles a roll cut
	// (GLE-314 P0; wire fields Bar.seam_prior_contract / seam_partial).
	// SeamPriorContract names the OUTGOING dated contract (e.g. "M26") whose
	// span the bucket started in when the feed's straddle policy built the
	// bar across a cut; SeamPartial is true when the bar covers only part of
	// its bucket window (a straddle=split fragment). Empty/false on every
	// other bar. Mirrored from the data wire like ActiveContract; pb only
	// (the abar CSV line does not carry them).
	SeamPriorContract string
	SeamPartial       bool

	// Aligned-series provenance (GLE-353). On a sample of an aligned series
	// (see AlignedSeries) OpenTime and CloseTime are the GRID bar's, so the
	// view lines up index for index with its grid, while these say which
	// source bar the sample carries: its own OpenTime and CloseTime (the
	// instant its value became known), and how many source bars became
	// visible since the view's previous sample (0: the value is carried
	// forward; 2 or more: a catch-up whose intermediate values the view does
	// not show; 1 on the view's first sample). All zero on every bar that is
	// not a sample.
	SourceOpenTime  time.Time
	SourceCloseTime time.Time
	Updates         int

	// Stats holds the construction statistics of a bar built from the trade
	// stream (GLE-386; wire fields Bar.tick_count .. close_threshold): every
	// event bar marketfeed serves, and every bar the Databento adapter builds
	// from trades. Nil when the bar carries none (a time bar from stored
	// OHLCV, a CSV-wire bar), so "no statistics" never reads as zeros. pb
	// strategy wire only.
	Stats *BarStats
	// contains filtered or unexported fields
}

Bar.AdjustedPrice

AdjustedPrice returns the strategy-visible (adjusted) OHLC component selected by f. This is the default view and is always populated.

func (b Bar) AdjustedPrice(f PriceField) float64

Bar.IsAdjusted

IsAdjusted reports whether this bar carries a meaningful raw view (a continuous-futures or corporate-action adjustment is in effect).

func (b Bar) IsAdjusted() bool

Bar.RawPrice

RawPrice returns the venue-real (unadjusted) OHLC component selected by f when this bar carries a meaningful raw view; otherwise it returns the adjusted price (raw == adjusted on a non-adjusted bar). Always safe to call.

func (b Bar) RawPrice(f PriceField) float64

Bar.SetRaw

SetRaw stamps the raw OHLC and cumulative adjustment fields onto the bar and marks it adjusted. It is the entry point for the pbconv/wire layers to set the unexported isAdjusted flag; the plain decode path never calls it, leaving isAdjusted false. The bar is marked adjusted unconditionally, even when raw equals adjusted (e.g. a 1:1 rename or a cumulative ratio of 1.0), per the is_adjusted-keyed defaulting rule.

func (b *Bar) SetRaw(open, high, low, close, cumAdj, cumRatio float64)

BarKind

BarKind selects which bar-construction algorithm produces the bars when Schema.Kind == Bars (Section 8.4). Values equal algolangpb.BarKind_* so BarKind -> algolangpb.BarKind is a faithful int cast (same value discipline as SchemaKind / CorporateActionType).

type BarKind int

BarSession

BarSession is the trading-day attribute block of a session-keyed bar. A trading day is NOT a calendar day (CME opens 17:00 CT the prior evening); its identity is TradeDate, a date with no clock. SessionKind is the era that served the bar (“eth” or “rth”, or the custom:HHMM-HHMM window a custom request named), never the request’s “session” alias. Settle is meaningful only when HasSettle (0 is a price, not absence).

type BarSession struct {
	TradeDate         string // YYYY-MM-DD exchange trade date
	SessionKind       string // "eth" | "rth" | "custom:HHMM-HHMM"
	Settle            float64
	HasSettle         bool
	EarlyClose        bool
	CloseIsSettlement bool
}

BarStats

BarStats is the construction-statistics block of a bar built from trades (GLE-386). A bar has one only when it was built from at least one trade (TickCount > 0), so inside the block a zero is a real zero: BuyVolume 0 means no aggressor-buy volume traded, not that the figure is unknown.

type BarStats struct {
	// TickCount is the number of trades folded into the bar (always > 0).
	TickCount int64
	// VWAP is the bar's volume-weighted average price (Notional / Volume as
	// built), in the same price frame as the bar's Open/High/Low/Close: on an
	// adjusted bar it is adjusted with them while Notional stays raw, so there
	// VWAP != Notional / Volume.
	VWAP float64
	// Notional is the sum of price x size over the bar's trades, in raw
	// venue prices and NOT multiplied by the point value.
	Notional float64
	// BuyVolume and SellVolume are the sizes of trades whose aggressor was
	// explicitly the buyer ('B') or the seller ('A'). Trades without an
	// aggressor count in neither, so BuyVolume + SellVolume <= Volume.
	BuyVolume  float64
	SellVolume float64
	// CloseThreshold is the threshold the bar closed against for an
	// imbalance or runs bar in expectation mode, in the kind's unit (trades,
	// size, or price x size). 0 when there is none: a static threshold, any
	// other kind, or a partial bar flushed at the end of the data.
	CloseThreshold float64
}

BarStats.AggressorVolume

AggressorVolume returns BuyVolume + SellVolume: the bar’s volume whose aggressor side is known. Trades without an aggressor count in neither, so on a well-formed bar it is at most the bar’s Volume.

func (s BarStats) AggressorVolume() float64

BarStats.HasCloseThreshold

HasCloseThreshold reports whether the bar closed against a realised expectation-mode threshold: CloseThreshold is finite and > 0. A static threshold, any kind other than imbalance and runs bars, and a partial bar flushed at the end of the data all carry 0 and report false. A negative, NaN or infinite value also reports false.

func (s BarStats) HasCloseThreshold() bool

Boundary

Boundary is a set of calendar boundary kinds, one bit per kind. Six bits are defined; the other ten are free for later kinds.

type Boundary uint16

BoundaryAll

BoundaryAll is every boundary kind (63).

const BoundaryAll = BoundaryRTHOpen | BoundaryRTHClose | BoundaryETHOpen | BoundaryETHClose | BoundaryDayCancelClose | BoundarySpanEnd

Bracket

Bracket wraps an entry order with a take-profit limit and a stop-loss stop. The TP and SL inherit the entry’s symbol and are sized to the entry’s quantity on the opposite side. Client IDs are auto-generated if not pre-set.

func Bracket(entry Order, takeProfit, stopLoss float64) Order

BuyLeg

BuyLeg and SellLeg are combo legs (GLE-409) that buy, or sell, ratio contracts of symbol per combo unit when the combo is bought.

func BuyLeg(symbol string, ratio int64) ComboLeg

Calendar

Calendar is the lookup view of one root’s exchange-calendar facts, built by NewCalendar. The zero Calendar is the empty calendar: every lookup on it reports “not found” and Complete reports CalendarReasonNoCalendar.

A Calendar built by NewCalendar is immutable: it owns a private deep copy of the facts, no method writes to it, and nothing is filled in lazily. It is safe to copy and safe for concurrent use.

type Calendar struct {
	// contains filtered or unexported fields
}

Calendar.Complete

Complete reports whether the facts of the instant window [from, to) are complete enough for precise-time use. It returns nil when they are, else a *CalendarIncompleteError naming the first failure. acceptUnverified admits a root whose session eras are not recorded.

func (c Calendar) Complete(from, to time.Time, acceptUnverified bool) error

Calendar.Day

Day returns a deep copy of the record of the trade date date, or the zero TradingDay and false when the calendar has no record for it.

func (c Calendar) Day(date string) (TradingDay, bool)

Calendar.DayCancelClose

DayCancelClose places the DAY-cancel close of the session a Day order submitted at at belongs to: the earliest DAY-cancel close STRICTLY after at (an order submitted at a close is the next session’s), an early close applied, a closed day skipped. It is the rule the simulator applies under order lifetime v2, where a resting Day order the calendar cannot place is denied (day_close_unplaced) rather than given the one-bar rule, so a strategy can ask before it submits and choose its own course when there is no answer.

It refuses rather than guesses, with an error that wraps ErrDayCloseUnplaced: a zero at; no DAY-cancel close served after at (NextBoundary); facts not complete for precise-time use over the window from at to the close inclusive (the error then also wraps Complete’s *CalendarIncompleteError); or a close the record of its own trade date does not confirm. acceptUnverified is the run’s calendar-accept-unverified policy for the root, which the SDK is not told: pass false unless the run was started with the root in that list.

func (c Calendar) DayCancelClose(at time.Time, acceptUnverified bool) (DayClose, error)

Calendar.Facts

Facts returns a deep copy of the facts the calendar was built from, with every instant in UTC and every empty container nil.

func (c Calendar) Facts() ExchangeCalendar

Calendar.NextBoundary

NextBoundary returns the earliest boundary of a requested kind strictly after t, and the set of requested kinds found at exactly that instant. Only the defined bits of kinds count.

It refuses rather than guesses: a day whose facts cannot place a requested kind ends the search with no answer, because it might hold an earlier boundary than any later day. It answers from the served days and ignores the coverage bounds and ErasRecorded; a caller that needs a precise instant checks Complete over the window first.

func (c Calendar) NextBoundary(t time.Time, kinds Boundary) (time.Time, Boundary, bool)

Calendar.Revision

Revision returns the content digest of the calendar’s inputs.

func (c Calendar) Revision() string

Calendar.Root

Root returns the root the calendar serves, for example “fut:XCME:ES”.

func (c Calendar) Root() string

Calendar.Span

Span returns the half-open span [start, end) the trade date date owns, or two zero times and false when the calendar has no record for it.

func (c Calendar) Span(date string) (start, end time.Time, ok bool)

Calendar.TradeDate

TradeDate returns the trade date whose span contains t (compared as instants), or "" and false when no served day’s span does: t before the first span, at or after the last span’s end, or inside a gap.

func (c Calendar) TradeDate(t time.Time) (string, bool)

Calendar.Zone

Zone returns the IANA name of the venue’s clock, for example “America/Chicago”; load it with time.LoadLocation to render local wall clocks.

func (c Calendar) Zone() string

CalendarIncompleteError

CalendarIncompleteError is Complete’s answer for a window whose facts are not complete.

type CalendarIncompleteError struct {
	Root      string // the calendar's root; "" only for CalendarReasonNoCalendar
	TradeDate string // the first incomplete trade date; "" for a reason that names no date
	Reason    string // one of the CalendarReason constants
	Detail    string // the reason's text (section 3.7)
}

CalendarIncompleteError.Error

Error reports the reason’s text, naming the calendar’s root when it has one.

func (e *CalendarIncompleteError) Error() string

CalendarKindETH, CalendarKindRTH

The symbol’s own trading day (ExchangeCalendar.TradingDayKind), from the wire vocabulary.

const (
	CalendarKindETH = wire.CalendarKindETH
	CalendarKindRTH = wire.CalendarKindRTH
)

CalendarObserver

CalendarObserver is the optional hook for the exchange-calendar push. The SDK probes for it with a type assertion. Implementing it sets InitAck.needs_calendar. OnCalendar runs once per pushed root, after the SDK has stored the calendar (so ctx.Calendar answers inside the hook) and before the first warm-up bar. A non-nil error refuses the run.

type CalendarObserver interface {
	OnCalendar(ctx *Context, cal Calendar) error
}

CalendarReasonNoCalendar, CalendarReasonEmptyWindow, CalendarReasonErasUnrecorded, CalendarReasonNotServed, CalendarReasonOutsideCoverage, CalendarReasonDateUnknown, CalendarReasonEarlyCloseUnknown, CalendarReasonRTHPlaceholder, CalendarReasonRTHUnknown

The reasons Complete reports, in CalendarIncompleteError.Reason.

const (
	CalendarReasonNoCalendar        = "no-calendar"
	CalendarReasonEmptyWindow       = "empty-window"
	CalendarReasonErasUnrecorded    = "eras-unrecorded"
	CalendarReasonNotServed         = "not-served"
	CalendarReasonOutsideCoverage   = "outside-coverage"
	CalendarReasonDateUnknown       = "date-unknown"
	CalendarReasonEarlyCloseUnknown = "early-close-unknown"
	CalendarReasonRTHPlaceholder    = "rth-placeholder"
	CalendarReasonRTHUnknown        = "rth-unknown"
)

CalendarRequirer

CalendarRequirer is the opt-in declaration that a strategy reads the exchange calendar without the hook. NeedsCalendar is called once, after OnInit, and true sets InitAck.needs_calendar.

type CalendarRequirer interface {
	NeedsCalendar() bool
}

CalendarRoot

CalendarRoot returns the root whose calendar serves a symbol: the first three ‘:’-separated fields of the text before the first ‘@’, when there are at least three and none of them is empty; otherwise “”. One calendar serves a root, so the bare root, each dated contract and the :cont composite share it. A synthetic spread (spr:, ratio:) is served on its first plain leg’s clock, so its root is that leg’s (GLE-1425).

func CalendarRoot(symbol string) string

CancelAtRequestID

CancelAtRequestID is the request id of the cancellation the engine requests at an order’s CancelAt (GLE-1362): the CancelResponse that answers it and, when it succeeds, the OrderCancel (CancelReasonExplicit) carry it, so a strategy can tell its scheduled cancellations from its own ctx.Cancel requests. clientID and attempt are the order’s.

func CancelAtRequestID(clientID string, attempt uint32) string

CancelHandler

type CancelHandler interface {
	OnCancel(ctx *Context, cancel OrderCancel)
}

CancelOutcome

CancelOutcome is the classified outcome of one cancel request under order lifetime v2 (GLE-200 I2). Values equal algolangpb.CancelOutcome_CANCEL_OUTCOME_*.

type CancelOutcome int

CancelOutcome.String

String renders o in lower snake case (“confirmed”); a value outside the enumeration renders as cancel_outcome_.

func (o CancelOutcome) String() string

CancelReason

type CancelReason int

CancelResponse

CancelResponse is the SDK-native mirror of the wire CancelResponse (GLE-200 I2): the classified answer to one cancel request. RequestID echoes the request; Status and RemainingQuantity are the attempt’s state as evidence; Timestamp is zero when the wire carries none.

type CancelResponse struct {
	ClientID          string
	Attempt           uint32
	RequestID         string
	Outcome           CancelOutcome
	Reason            string
	Status            OrderStatus
	RemainingQuantity int64
	Timestamp         time.Time
	OrderRef          string
}

CancelResponseHandler

CancelResponseHandler observes classified cancel responses (lifetime-v2 only). The SDK hands each CancelResponse to OnCancelResponse as it arrives. On a run that negotiated lifetime-v2 (stdio-pb-v1 or stdio-csv-v2) the working view moves on the response first, whether or not the strategy has the handler (a confirmed cancel retires the attempt). On a v1 run the SDK changes no Context state for it, and a strategy without the handler ignores the event.

type CancelResponseHandler interface {
	OnCancelResponse(ctx *Context, c CancelResponse)
}

CapabilityComboOrders

CapabilityComboOrders is the combo-order capability token (GLE-409): a strategy that places combo orders requires it beside CapabilityLifetimeV2. The engine offers it on a lifetime-v2 backtest on the pb wire with no continuous series, and denies a combo from a strategy that did not accept it.

const CapabilityComboOrders = wire.CapabilityComboOrders

CapabilityLifetimeV2

CapabilityLifetimeV2 is the order-lifetime v2 capability token (GLE-200 I2). Under it an order rests until it fills, is cancelled or a documented venue event ends it, the strategy cancels explicitly, and the engine reports each attempt’s status transitions (OrderUpdate) and the classified outcome of each cancel request (CancelResponse).

const CapabilityLifetimeV2 = wire.CapabilityLifetimeV2

CapabilityOrderConviction

CapabilityOrderConviction is the order-conviction capability token (GLE-532): a strategy that sets Order.Conviction declares it, normally in SupportedCapabilities. The engine offers it on a lifetime-v2 run on the pb or csv2 wire. An order carrying a conviction on a run that did not accept the token is refused by the SDK, so the value is never silently dropped; Context.OrderConviction reports whether it was accepted.

const CapabilityOrderConviction = wire.CapabilityOrderConviction

CapabilityRequirer

CapabilityRequirer is the opt-in declaration of the capabilities a strategy needs the engine to put in effect.

The SDK calls RequiredCapabilities once, after the input values are applied and before OnInit, and matches the tokens against the engine’s offer (InitConfig.Capabilities). A token this build does not define fails initialisation (Error code init_failed); a token the engine did not offer refuses the run (Error code capability_unsupported) and OnInit is not called; otherwise the tokens are accepted in the InitAck. A strategy that does not implement the interface, or returns no tokens, requires nothing and its InitAck is unchanged. For its part the engine refuses a strategy that leaves lifetime-v2 unaccepted when the run offers it, so a strategy that implements the v2 order lifetime declares it here.

type CapabilityRequirer interface {
	RequiredCapabilities() []string
}

CapabilityRollRebase

CapabilityRollRebase is the roll-rebase capability token (GLE-1458). The engine offers it on a run with –roll-rebase on; the SDK accepts it by itself on stdio-pb-v1, because the SDK restates the strategy’s own prices at each rebase (Context.applyRebase). A strategy neither requires nor supports it.

const CapabilityRollRebase = wire.CapabilityRollRebase

CapabilitySupporter

CapabilitySupporter is the opt-in declaration of the capabilities a strategy accepts when the engine offers them and runs without when it does not (GLE-200 I16): a strategy that implements both order lifetimes and follows the run’s profile declares lifetime v2 here, so it runs v2 under –lifetime v2 and the legacy profile, byte-identical, otherwise.

The SDK calls SupportedCapabilities once, where it calls RequiredCapabilities, and walks the tokens after the required ones: a token this build does not define fails initialisation (Error code init_failed), as for RequiredCapabilities; a token the engine offered is accepted (duplicates collapsed, a token already required counted once); a token the engine did not offer is left out, and the run proceeds. A strategy that supports nothing and requires nothing accepts nothing. The strategy reads the outcome with Context.LifetimeV2 (or InitConfig .Capabilities in OnInit).

type CapabilitySupporter interface {
	SupportedCapabilities() []string
}

ComboLeg

ComboLeg is one leg of a combo order (GLE-409), as an IBKR combo (BAG) leg: a contract, the action it takes when the combo is bought, and the contracts it trades per combo unit. Selling the combo reverses every leg’s action. The combo’s net price per unit is the sum over its legs of ratio × leg price, added for a leg bought and subtracted for a leg sold: buying a calendar spread whose legs are “buy the next, sell the front” pays next − front.

type ComboLeg struct {
	Symbol string
	Side   Side  // the leg's action when the combo is bought
	Ratio  int64 // contracts per combo unit, positive
}

ComboLimit

ComboLimit is a limit combo order (GLE-409) at net, the price per combo unit (ComboLeg): a Buy fills at a net at or below it, a Sell at or above.

func ComboLimit(side Side, qty int64, net float64, legs ...ComboLeg) Order

ComboMarket

ComboMarket is a market combo order (GLE-409): side Buy executes every leg’s action, Sell the reverse, qty combo units, all legs or none.

func ComboMarket(side Side, qty int64, legs ...ComboLeg) Order

ComboSymbol

ComboSymbol is the symbol a combo order of legs carries (GLE-409): “combo:” and each leg as B or S, its ratio, “@” and its symbol, joined by “|”, in the given order; “combo:B1@fut:XCME:ES:M26|S1@fut:XCME:ES:H26” is the calendar spread that buys the June contract and sells the March one.

func ComboSymbol(legs []ComboLeg) string

Context

Context is the strategy’s window onto the engine (Section 7.5). It is an opaque struct with unexported fields; the SDK maintains it from the order/fill/cancel stream.

type Context struct {
	// contains filtered or unexported fields
}

Context.Account

Account returns the engine-maintained account snapshot.

func (c *Context) Account() AccountState

Context.ActiveContract

ActiveContract returns the dated contract a continuous series is currently served from (the latest bar’s Bar.ActiveContract) and true, or "" and false when symbol is not a continuous series or none of its bars has arrived yet. Symbol is the logical symbol, for example “fut:XCME:ES”; each continuous series of a run has its own (GLE-420). An order addressed to the contract counts against the logical symbol in Flat and Exposure.

func (c *Context) ActiveContract(symbol string) (string, bool)

Context.Annotate

Annotate marks the bar being decided with a, on that bar’s series. A bar may carry several annotations; they are kept in the order made. A call outside a bar decision, or an AnnotationAt whose Price is not a number, is ignored with a warning, given once a run, as Plot’s are.

func (c *Context) Annotate(a Annotation)

Context.ArmSessionTimer

ArmSessionTimer arms the timer id at the first instant of the form b+offset strictly after Now, where b is a boundary of one of kinds (a set of Boundary bits) on the exchange calendar of symbol, and anchors the timer on symbol, as given (not its root): the engine admits an anchored timer only when that calendar is complete from the decision to the instant, under the run’s own policy, and refuses it otherwise (calendar_incomplete). It returns the instant, in UTC, so a strategy can log or keep it. A negative offset arms ahead of the boundary (“five minutes before the RTH close”), a positive one after it.

The helper needs a decision instant. In OnInit and OnCalendar (and any hook before the first bar) Now is the zero time, the search starts before the first span the calendar serves, no boundary is found and the call fails; ArmTimer works there. A large positive offset that puts the search before the first span fails the same way.

It fails with the zero time and nothing queued when the run cannot carry timers (ErrTimersUnavailable), when no calendar was pushed for the root of symbol (implement CalendarObserver or CalendarRequirer), and when the calendar places no boundary of kinds after Now less offset. It does not call Calendar.Complete.

func (c *Context) ArmSessionTimer(id, symbol string, kinds Boundary, offset time.Duration) (time.Time, error)

Context.ArmTimer

ArmTimer arms the one-shot timer id for the instant at (order lifetime v2 only). At the instant the engine decides there, delivering a TimerFired to OnTimer (TimerHandler). Arming an id that is armed replaces it when the engine admits the new arm; a refused arm changes nothing.

The call queues the command: it goes out with the reply to the next decision (a Bar, a LifecycleTurn or a TimerFired), after the reply’s cancel requests and before its OrderResponse, in issue order with the other timer commands. Issued in OnInit, or in any hook outside a decision, it waits for the next decision’s reply; the warm-up and late-bar replies carry none.

The SDK refuses only what it alone can know: on a nil Context or a run that did not negotiate lifetime-v2 it returns ErrTimersUnavailable (itself) and queues nothing. Every other check (an empty id, a zero instant, an instant not after the decision, one after the run’s end, the armed limit) is the engine’s, made when the command reaches it; its refusal comes back as a TimerRefused (TimerRefusalHandler). The id and the instant are queued as given.

func (c *Context) ArmTimer(id string, at time.Time) error

Context.BarCount

BarCount returns the number of PRIMARY bars dispatched to OnBar for symbol so far this run (Tier-1 T1.7): the processed-bars frame, warmup excluded, that a legacy “minimum bars before decisions” gate counts in. It counts every OnBar dispatch of a bar for symbol (aux-series bars are not counted). The current bar is included (it is counted before OnBar runs).

func (c *Context) BarCount(symbol string) int

Context.Calendar

Calendar returns the calendar the engine pushed whose root is CalendarRoot(symbol), and true; or the zero Calendar and false when no calendar was pushed for that root (or at all), or the symbol has no root.

func (c *Context) Calendar(symbol string) (Calendar, bool)

Context.Cancel

Cancel requests cancellation of one of the strategy’s working orders by its ClientID (F4b). It QUEUES the request: the SDK emits an OrderCancelRequest envelope for it after OnBar returns (before the OrderResponse), and the engine answers asynchronously — a successful cancel arrives as an OrderCancel event with CancelReasonExplicit (removing the order from WorkingOrders()); an unknown/already-terminal ID is rejected engine-side with a CancelReject (logged, not fatal). ctx.WorkingOrders() still shows the order until the cancel event arrives, exactly as a live venue behaves. Cancel-then-resubmit in the same OnBar is supported: the engine processes cancels BEFORE that bar’s new orders. An empty clientID can never match an order and is dropped here with a log line rather than sent as a doomed request. Supported on stdio-pb-v1 and on stdio-csv-v2, where the request is a cancel line ahead of the batch’s order lines; the stdio-csv-v1 runner fails loudly on a queued cancel.

Under lifetime v2 (GLE-200 I3) the request addresses one attempt of the label (the newest one not already pending cancellation) and carries a request id; the view marks that attempt pending cancellation at once, and it stays in WorkingOrders(), counted by Flat and Exposure, until the engine’s answer retires it (OrderCancel, a confirmed CancelResponse) or refuses it (CancelReject, a refused CancelResponse). The request is sent even when no attempt of the label is live; the engine answers it. Cancel is valid in every live status, Submitting included: a strategy need not wait for a Working acknowledgement before cancelling.

func (c *Context) Cancel(clientID string)

Context.CancelTimer

CancelTimer disarms the timer id (order lifetime v2 only). Like ArmTimer it queues the command, which goes out with the reply to the next decision in issue order with the other timer commands; the engine answers a disarm with nothing, and disarming an id that is not armed changes nothing. On a nil Context or a run that did not negotiate lifetime-v2 it returns ErrTimersUnavailable (itself) and queues nothing. The id is queued as given: CancelTimer("") is a disarm of “”.

func (c *Context) CancelTimer(id string) error

Context.CurrentAdjustment

CurrentAdjustment returns the cumulative ADDITIVE adjustment (the futures/Panama method: adjusted = raw + offset) in effect for symbol as of the most recent bar, or 0 if none has been seen (Section 8.9). For a non-adjusted symbol — and for an equity (multiplicative) symbol — it is 0; the identity here is 0 (add 0 == no adjustment). For the multiplicative (equity/Ratio) cumulative factor use CurrentAdjustmentRatio.

func (c *Context) CurrentAdjustment(symbol string) float64

Context.CurrentAdjustmentRatio

CurrentAdjustmentRatio returns the cumulative MULTIPLICATIVE price ratio (the equity/Ratio method: adjusted = raw * ratio) in effect for symbol as of the most recent bar (Section 8.9). The identity here is 1.0 (multiply by 1 == no adjustment), so this never returns 0: an unseen symbol, a non-adjusted bar, and a post-split anchor bar (whose Bar.CumulativePriceRatio stays 0 because equity AdjustBar returns the anchor bar unchanged) all map to 1.0. A futures (Panama) bar likewise carries ratio 0 and so reports 1.0 here — correct, as futures have no multiplicative ratio (use CurrentAdjustment for those).

func (c *Context) CurrentAdjustmentRatio(symbol string) float64

Context.Curve

Curve returns the contracts of the futures root (e.g. “fut:XCME:ES”) listed at ctx.Now(), front first: ascending by Expiration, then Symbol (GLE-410). It is data.SelectListing, the rule every adapter’s listing applies, over the latest record delivered for each contract of a declared CONTRACT_LISTING series of root. A contract appears once it is activated, has a first bar and is known, all by now, and leaves at its expiration; a contract listed after now is never in it, because its record has not been delivered. The slice is a copy the caller owns. It is nil when root has no contract listed now, when nothing of root has been delivered, or before the first delivery or bar gives the context a time.

func (c *Context) Curve(root string) []MarketListing

Context.DataAge

DataAge returns how old the newest bar of the series seriesID is at Now: Now less that bar’s CloseTime, and true. The series is keyed as Series is, by its bars’ SeriesID, else their Symbol. It returns 0, false when the Context holds no series of that id or the series holds no bar (and on a nil Context). The age is not clamped: it is 0 at a bar of the series, the series’ staleness at a timer’s decision (no bar travels with a TimerFired), and negative when Now lies before the newest close.

func (c *Context) DataAge(seriesID string) (time.Duration, bool)

Context.DayCancelClose

DayCancelClose places, on the exchange calendar of symbol, the DAY-cancel close a Day order submitted now would end at: Calendar.DayCancelClose at Now. It fails with an error that wraps ErrDayCloseUnplaced when no calendar was pushed for the root of symbol (implement CalendarObserver or CalendarRequirer to ask for one), or when the calendar cannot place the close. Now is the zero time outside a decision, so it fails in OnInit and OnCalendar.

func (c *Context) DayCancelClose(symbol string, acceptUnverified bool) (DayClose, error)

Context.Definition

Definition returns the definition in force for a contract in a series: the one delivered last. The boolean is false when none has been delivered.

func (c *Context) Definition(seriesID, symbol string) (MarketDefinition, bool)

Context.Definitions

Definitions returns the definitions in force in a series, one per contract, sorted by Symbol. The slice is a copy the caller owns. It is nil when the series is unknown or no definition has been delivered.

func (c *Context) Definitions(seriesID string) []MarketDefinition

Context.Exposure

Exposure returns both the position and the working orders for a symbol (under lifetime v2, every unresolved attempt on it, in submission order).

func (c *Context) Exposure(symbol string) Exposure

Context.Flat

Flat reports whether the strategy has no position AND no working orders in the symbol (Section 7.5). Restart-correct by construction. Under lifetime v2 every unresolved commitment counts: a submission awaiting its acknowledgement, a pending cancellation, a held order, an inactive child.

func (c *Context) Flat(symbol string) bool

Context.HeldFront

HeldFront returns the front contract while the logical symbol’s active contract is held behind it (GLE-412): on a deferred schedule (B1, B2) the contract nearer expiry that the series does not hold, e.g. “ZQH26” while it holds “ZQJ26”. It comes from the latest roll notice, so it is known from the first roll the run sees, and only to a strategy that implements RollObserver (the engine sends roll notices only to one). false before the first roll, on a front holding, and on a run from an engine or feed that does not disclose the front.

func (c *Context) HeldFront(symbol string) (string, bool)

Context.Instrument

Instrument returns the resolved instrument metadata for symbol (Sections 7.13.5, 7.13.6). Maintained by the SDK from the InstrumentsResolved push; a local query, not a round-trip — the metadata analogue of Position. A symbol absent from the retained map (and every non-declaring run, whose map is nil) yields the symbol-only zero value InstrumentInfo{Symbol: symbol}, mirroring Position’s zero-fallback shape.

func (c *Context) Instrument(symbol string) InstrumentInfo

Context.IsPrimary

IsPrimary reports whether bar belongs to the primary instrument rather than a declared aux series (Tier-1 T1.4): true when the bar carries no distinct SeriesID, or its SeriesID/Symbol is the primary. The mechanical replacement for a hand-written if bar.SeriesID == "vix" { return } aux-skip prolog.

func (c *Context) IsPrimary(bar Bar) bool

Context.LatestStatistic

LatestStatistic returns the latest statistic of a contract and kind in a series: the delivered, non-deleted one with the greatest date key (its TsRef when set, else its visibility instant), and among equal keys the one delivered last. The boolean is false when there is none.

func (c *Context) LatestStatistic(seriesID, symbol string, kind StatKind) (MarketStatistic, bool)

Context.LifetimeV2

LifetimeV2 reports whether the run negotiated order lifetime v2 (GLE-200; the lifetime-v2 capability, offered under –lifetime v2 and accepted by a CapabilityRequirer or CapabilitySupporter): the attempt-indexed working view is in force, every submission is answered with an OrderUpdate and every cancel request with a CancelResponse, and lifecycle turns are granted. False on a run under the legacy profile and on a nil Context.

func (c *Context) LifetimeV2() bool

Context.Log

Log emits a diagnostic log line over the wire (Log envelope).

func (c *Context) Log(msg string)

Context.Logf

func (c *Context) Logf(format string, args ...any)

Context.MarketObservations

MarketObservations returns the Lookback buffer of a declared OBSERVATIONS series, oldest first: the most recent observations delivered, withdrawals included, as many as the declaration asked for (at least 1). The slice is a copy the caller may keep or modify. It returns nil when the series is unknown or nothing has been delivered yet. For every revision ever delivered, use Observations.

func (c *Context) MarketObservations(seriesID string) []MarketObservation

Context.MarketStatistics

MarketStatistics returns the statistics buffered for a declared STATISTICS series, oldest (first delivered) first. The slice is a copy the caller owns. It is nil when the series is unknown or nothing has been delivered yet.

func (c *Context) MarketStatistics(seriesID string) []MarketStatistic

Context.MarketTrades

MarketTrades returns the buffered trades of the declared TRADES series seriesID, oldest first, as a new slice the caller owns: mutating it never changes the buffer. It returns nil when the series holds no trade or is unknown.

The buffer keeps the newest Lookback trades of the series (at least one). A trade reaches it when it becomes visible: before the first bar whose close is strictly after the trade’s TsRecv, so a trade received exactly at a bar’s close is first seen by the next bar.

func (c *Context) MarketTrades(seriesID string) []MarketTrade

Context.Now

Now returns the bar timestamp currently being processed (Section 11.1): simulation time in backtest, the most recent bar’s timestamp in live.

func (c *Context) Now() time.Time

Context.Observations

Observations returns an immutable view of everything delivered so far for a declared OBSERVATIONS series, and true. It returns the empty view and false when nothing has been delivered for seriesID. Unlike MarketObservations it is not bounded by Lookback, because asking what was known when needs the whole vintage history.

The view is a snapshot: observations delivered later do not appear in it, so a view kept from one handler call stays valid and unchanged. It cannot be used to change the context’s records.

func (c *Context) Observations(seriesID string) (ObservationHistory, bool)

Context.OrderConviction

OrderConviction reports whether the run accepted the order-conviction capability (GLE-532; CapabilityOrderConviction, offered on a lifetime-v2 run on the pb or csv2 wire and accepted by a CapabilityRequirer or CapabilitySupporter), so an order may carry a Conviction. A strategy that supports the capability and finds it unaccepted leaves Conviction nil.

func (c *Context) OrderConviction() bool

Context.Plot

Plot records value as the point of the plot name on the bar being decided: the bar OnBar was called with, on that bar’s series. A plot is named by its series and name, so a strategy that plots “fast” on two series’ bars has two plots. The style of a plot’s first call is its style for the run (the zero value is a line over the prices); a later call’s style is ignored. Called twice for one name in a bar, the last value is kept. NaN or ±Inf is no point at this bar: a gap.

A call outside a bar decision (in OnInit, a warm-up or late bar, a lifecycle turn, a timer or another handler), or with an empty name, is ignored with a warning, given once a run. Plots travel on the stdio-pb-v1 wire only; on the CSV wires every call is ignored, silently, so that a strategy that plots writes those wires exactly as before.

func (c *Context) Plot(name string, value float64, style ...PlotStyle)

Context.Portfolio

Portfolio returns the portfolio view for this decision; the zero view if the strategy has none.

func (c *Context) Portfolio() PortfolioView

Context.Position

Position returns the strategy’s position in symbol. Maintained by the SDK from the fill stream; a local query, not a round-trip.

func (c *Context) Position(symbol string) Position

Context.PrimarySymbol

PrimarySymbol returns the run’s primary instrument — Instruments[0] from Init (Tier-1 T1.4) — or "" if none was configured (a direct-context unit test).

func (c *Context) PrimarySymbol() string

Context.RunID

RunID returns the engine-assigned run identifier.

func (c *Context) RunID() string

Context.Series

Series returns the lookback series for seriesID. For single-series strategies the series identifier defaults to the symbol (Section 7.12).

func (c *Context) Series(seriesID string) Series

Context.Trade

Trade advances the position-lifecycle state machine for bar.Symbol with the current bar and returns the resulting TradeState snapshot (Tier-1 T1.1). It is the SDK-owned replacement for kit.Tracker.Update(ctx.Position(sym), bar): call it exactly once per PRIMARY bar (after skipping declared aux-series bars), and read the transitions (JustEntered/JustExited/JustAdded), the entry snapshot, bars-held, and the trailing extremes off the returned value. Because fills for the prior bar are applied before OnBar, ctx.Position(sym) here already carries this bar’s opening state, exactly as the top-of-OnBar tracker call observed.

func (c *Context) Trade(bar Bar) TradeState

Context.TradeState

TradeState returns the LAST snapshot for symbol WITHOUT advancing it — the read-only peek for OnFill or a cross-symbol glance. A symbol never advanced through Trade yields the zero TradeState{Symbol: symbol}.

func (c *Context) TradeState(symbol string) TradeState

Context.WorkingOrders

WorkingOrders returns the strategy’s currently-active orders, neither filled nor cancelled. Under lifetime v2 (GLE-200 I3) it is the attempt-indexed view: every unresolved attempt, attached children included, in submission order; on a v1 run the v1 map, in map order.

func (c *Context) WorkingOrders() []WorkingOrder

CorporateActionNotice

CorporateActionNotice is the SDK-native mirror of the wire CorporateActionNotice (Section 8.10): the engine -> strategy informational message a strategy is NOTIFIED of via the optional CorporateActionObserver, delivered once per phase (the phase is carried on the notice). In E8a it is purely a notification — receiving it performs NO Context mutation and no position auto-mirror (E8b).

type CorporateActionNotice struct {
	Symbol        string
	Type          CorporateActionType
	Phase         CorporateActionPhase
	EffectiveDate time.Time
	PriceRatio    float64
	QuantityRatio float64
	// QuantityNum/QuantityDen are the EXACT rational of QuantityRatio the engine
	// resolved ONCE (10.0->10/1, 1.5->3/2, 0.1->1/10) and stamped on the notice
	// (Section 8.10, Option A). The SDK auto-mirror applies oldQty*QuantityNum/
	// QuantityDen via the SAME shared whole-unit primitive the engine sim uses
	// (internal/wholeunit.SplitQty), so it does NO rationalization and cannot drift.
	// A non-quantity event (rename, cash dividend) carries 0/0 and the quantity
	// mirror is a no-op.
	QuantityNum int64
	QuantityDen int64
	NewSymbol   string
	CashAmount  float64
}

CorporateActionObserver

CorporateActionObserver is the optional handler for equity corporate actions (Section 8.10). The SDK probes for it via a type assertion, exactly like FillHandler/CancelHandler. A single method is dispatched once per phase (ANNOUNCED, then EFFECTIVE); the phase is carried on the notice. In E8a this is purely informational — no Context state is mutated before the call.

type CorporateActionObserver interface {
	OnCorporateAction(ctx *Context, notice CorporateActionNotice)
}

CorporateActionPhase

CorporateActionPhase is the lifecycle phase of a CorporateActionNotice (Section 8.10). Values equal algolangpb.ActionPhase_* so CorporateActionPhase(pb.GetPhase()) is a faithful conversion (the SDK cannot import the proto package — pbconv imports this one).

type CorporateActionPhase int

CorporateActionType

CorporateActionType enumerates the equity capital events (Section 8.10). Values equal algolangpb.CorporateActionType_CA_* (0..10) so CorporateActionType(pb.GetType()) is a faithful conversion (same value discipline as CancelReason).

type CorporateActionType int

DataRequirement

DataRequirement is one declared series: a stable, strategy-chosen SeriesID that addresses the series everywhere else (ctx.Series(SeriesID)), the underlying Symbol, the data Schema, and the per-series history depth to pre-buffer (Section 7.13.3). A strategy returns a slice of these from DataRequirements().

type DataRequirement struct {
	SeriesID string
	Symbol   string
	Schema   DataSchemaSpec
	Lookback int
}

DataRequirer

DataRequirer is the opt-in declaration of the market data a strategy needs beyond the run’s configured universe (Sections 7.2, 7.13). The SDK probes for it via a type assertion, exactly like FillHandler/RollObserver. A strategy that returns one or more DataRequirements has each declared series fetched and pre-buffered into ctx.Series(id) before its first OnBar, at that series’ own Lookback depth. Like RollObserver, implementing DataRequirer influences an InitAck capability (it sets InitAck.needs_instruments, gating the post-Init InstrumentsResolved delivery, Section 7.13.5) in addition to carrying the declaration itself in InitAck.data_requirements. A strategy that implements only OnBar declares nothing and receives exactly the config-driven data it does today (Section 7.13.11); declaration is purely additive.

type DataRequirer interface {
	DataRequirements() []DataRequirement
}

DataSchemaSpec

DataSchemaSpec describes the schema of a declared series (Section 7.13.3). For Kind == Bars, BarKind and the construction fields describe the series’ own bar construction (GLE-390); BarKindUnspecified with every construction field zero takes the run’s. For the sampled-quote schema Interval is the sampling interval.

type DataSchemaSpec struct {
	Kind         SchemaKind
	BarKind      BarKind // when Kind == Bars
	Interval     string  // bar interval, or sampling interval for sampled quotes
	Threshold    float64 // volume/tick/dollar/range/imbalance bars
	Consolidated bool    // cross-venue consolidated variant

	// Session names the trading-day container or intraday grid the series is
	// served from ("eth", "rth", "session", "utc-day", "custom:HHMM-HHMM");
	// "" takes the run's session (GLE-390).
	Session string
	// ReversalMult is BARS_RENKO's reversal multiple (0 = 2.0).
	ReversalMult float64
	// ThresholdMode and the expectation parameters configure the IMBALANCE and
	// RUNS families (Section 8.4.12).
	ThresholdMode    ThresholdMode
	EwmaSpanBars     float64
	EwmaSpanSignal   float64
	InitExpectedSize float64
	InitSignedRate   float64 // 0 = 0.5
	// CloseOnBoundary is the BARS_TIME live-mode boundary close.
	CloseOnBoundary bool
	// LeadIn warms an event-bar constructor before the run (GLE-397).
	LeadIn time.Duration
	// IncludePath and PathInterval request the intra-bar path of a time-bar
	// series; unset takes the run's path request.
	IncludePath  bool
	PathInterval string
}

DataSchemaSpec.Construction

Construction is the bar construction a declared bar schema asks for: its bar kind, threshold mode and every construction parameter, copied. A schema that names no bar kind and sets no construction parameter maps to the zero Construction, which takes the run’s construction. Interval, Session, Kind and Consolidated are not part of a construction.

func (s DataSchemaSpec) Construction() barspec.Construction

DayCancelAssumed, DayCancelUnknown

TradingDay.DayCancelBasis. A DayCancel window is set only under DayCancelAssumed (the Globex trade-date session rule). DayCancelUnknown labels equities and venues without tables.

const (
	DayCancelAssumed = wire.DayCancelAssumed
	DayCancelUnknown = wire.DayCancelUnknown
)

DayClose

DayClose is the DAY-cancel close a Day order ends at (GLE-1362): At, in UTC; the trade date whose session closes there; and that day’s DayCancelBasis (DayCancelAssumed in a backtest).

type DayClose struct {
	At        time.Time
	TradeDate string
	Basis     string
}

DefinitionHandler

DefinitionHandler is the optional observer of declared INSTRUMENT_DEFINITION series (GLE-406). OnDefinition runs once per definition, in replay order, before the bar that follows its TsEvent; ctx.Now() is its TsEvent during the call. Observe-only.

type DefinitionHandler interface {
	OnDefinition(ctx *Context, d MarketDefinition)
}

DenyDayCloseUnplaced, DenyMOCCloseUnplaced, DenyCancelAtNotFuture, DenyCancelAtUnsupported

Order lifetime v2’s deterministic cancellation (GLE-1362). A backtest under lifetime v2 never falls back to the one-bar rule: a Day order that can rest (every Day order but a market, market-on-open or market-on-close order) ends at the DAY-cancel close the exchange calendar places for it (Calendar.DayCancelClose), and one the calendar cannot place is refused with a Reason that begins with DenyDayCloseUnplaced. Withdrawing an order at any other time is the strategy’s: it cancels the order itself (ctx.Cancel, from a bar or a timer) or names the instant on the order (Order.CancelAt) and the engine requests the cancellation then.

These refusals reach the strategy as OrderUpdate events with Status OrderStatusDenied and a Reason that begins with the token and “: " (the rest of the text is for people, not for parsing). A backtest’s denials are the simulator’s, so an OrderCancel{Rejected} follows each; a live run’s DenyCancelAtUnsupported is the engine’s, before the venue, and none follows.

const (
	// DenyDayCloseUnplaced: a Day order that can rest, under order lifetime
	// v2 in a backtest, whose DAY-cancel close the exchange calendar cannot
	// place (no calendar for its root, facts not complete for precise-time
	// use, or no submission instant). A bracket child that cannot be placed
	// when its parent fills is cancelled Rejected at its activation instead.
	DenyDayCloseUnplaced = "day_close_unplaced"
	// DenyMOCCloseUnplaced: a market-on-close order, under order lifetime v2
	// in a backtest, whose send time before an RTH close the exchange
	// calendar cannot place (no calendar for its root, facts not complete for
	// precise-time use, or no decision instant). An attached MOC that cannot
	// be placed when its parent fills is cancelled Rejected at its activation
	// instead (GLE-1375).
	DenyMOCCloseUnplaced = "moc_close_unplaced"
	// DenyCancelAtNotFuture: Order.CancelAt is not after the decision the
	// order was submitted at.
	DenyCancelAtNotFuture = "cancel_at_not_future"
	// DenyCancelAtUnsupported: Order.CancelAt where the engine cannot
	// schedule it: a run on lifetime v1, a live venue, an attached child or
	// a combo order.
	DenyCancelAtUnsupported = "cancel_at_unsupported"
)

DirectorVaRLimit, DirectorDeployedPercent, DirectorDeployedValue, DirectorDirectionalLimit, DirectorOpenPositions, DirectorGroupPositions, DirectorMarginLimit, DirectorPeakDrawdown, DirectorPeriodDrawdown, DirectorNotTopN, DirectorReducing, DirectorDrawdownLadder, DirectorOrderSize, DirectorEntryRate, DirectorLiquidity, DirectorVolatility, DirectorRestricted, DirectorStaleData, DirectorInputMissing, DirectorInputStale, DirectorWarmingUp, DirectorConfigInvalid, DirectorInvalidConviction, DirectorInvalidOrder, DirectorBelowMinimum, DirectorCloseConflict, DirectorLogUnavailable, DirectorAccepted, DirectorTrimmed, DirectorStateChanged

The trade director (GLE-532) refuses an order, or the opening part of one, that breaks one of the run’s configured rules. A refusal reaches the strategy as an OrderUpdate with Status OrderStatusDenied and a Reason that begins with one of the tokens below and “: " (the rest of the text is for people, not for parsing); the attempt did not reach the venue and no OrderCancel{Rejected} follows. A trim reaches it as the normal acceptance update with the accepted Quantity and a Reason beginning DirectorTrimmed. The tokens are the reason codes of docs/trade-director-spec.md §9.

const (
	// One per rule kind.
	DirectorVaRLimit         = "director_var_limit"
	DirectorDeployedPercent  = "director_deployed_percent"
	DirectorDeployedValue    = "director_deployed_value"
	DirectorDirectionalLimit = "director_directional_limit"
	DirectorOpenPositions    = "director_open_positions"
	DirectorGroupPositions   = "director_group_positions"
	DirectorMarginLimit      = "director_margin_limit"
	DirectorPeakDrawdown     = "director_peak_drawdown"
	DirectorPeriodDrawdown   = "director_period_drawdown"
	DirectorNotTopN          = "director_not_top_n"
	DirectorReducing         = "director_reducing"
	DirectorDrawdownLadder   = "director_drawdown_ladder"
	DirectorOrderSize        = "director_order_size"
	DirectorEntryRate        = "director_entry_rate"
	DirectorLiquidity        = "director_liquidity"
	DirectorVolatility       = "director_volatility"
	DirectorRestricted       = "director_restricted"
	DirectorStaleData        = "director_stale_data"
	// The director's own conditions.
	DirectorInputMissing      = "director_input_missing"
	DirectorInputStale        = "director_input_stale"
	DirectorWarmingUp         = "director_warming_up"
	DirectorConfigInvalid     = "director_config_invalid"
	DirectorInvalidConviction = "director_invalid_conviction"
	DirectorInvalidOrder      = "director_invalid_order"
	DirectorBelowMinimum      = "director_below_minimum"
	DirectorCloseConflict     = "director_close_conflict"
	DirectorLogUnavailable    = "director_log_unavailable"
	// Audit codes: an unchanged acceptance, a trim and a state transition.
	DirectorAccepted     = "director_accepted"
	DirectorTrimmed      = "director_trimmed"
	DirectorStateChanged = "director_state_changed"
)

EquityPoint

EquityPoint is one point of an equity curve.

type EquityPoint struct {
	At           time.Time
	MarkedEquity float64
	ClosedEquity float64
}

ErrDayCloseUnplaced

ErrDayCloseUnplaced is the sentinel every DayCancelClose error wraps: the calendar cannot place the DAY-cancel close a Day order would end at.

var ErrDayCloseUnplaced = errors.New("the exchange calendar cannot place the DAY-cancel close")

ErrInvalidCalendar

ErrInvalidCalendar is the sentinel every NewCalendar error wraps.

var ErrInvalidCalendar = errors.New("invalid calendar")

ErrTimersUnavailable

ErrTimersUnavailable is the error ArmTimer, ArmSessionTimer and CancelTimer return on a run that did not negotiate lifetime-v2 (and on a nil Context): nothing is queued. The SDK refuses at the call, rather than send a command that would end the run with a protocol error at the engine, so a strategy that arms a deadline should check the error.

var ErrTimersUnavailable = errors.New("algolang: timers need order lifetime v2 (GLE-200 I12): require CapabilityLifetimeV2 and run under an engine that offers lifetime-v2 on stdio-pb-v1")

ExchangeCalendar

ExchangeCalendar is the exchange-calendar facts of one root (GLE-200 I11): a header (identity, revision and provenance) and Days, the trade dates the engine pushed with it, in ascending order. The engine pushes one calendar per root to a strategy that sets InitAck.NeedsCalendar.

One calendar serves a root: the bare root, each dated contract and the :cont composite share it. Root names the owner (e.g. “fut:XCME:ES”) and ExchangeTimezone its IANA clock.

Revision is the content digest of the calendar inputs, 64 lowercase hex characters. Equal revisions mean equal TradingDay records for every date. Law names the rules the revision digests.

CoverageFrom and CoverageTo bound the trade dates the calendar answers. CoverageFrom is "” for an unbounded first era and table start, and CoverageTo is "” when there is no table.

GridRevisions maps an intraday-grid boundary to its grid revision. DayCancelRule names the assumed rule behind every DayCancel.

type ExchangeCalendar struct {
	// Root is the owner of the calendar, for example "fut:XCME:ES".
	Root string
	// ExchangeTimezone is the IANA name of the venue's exchange-local clock, for
	// example "America/Chicago".
	ExchangeTimezone string
	// Revision is the content digest of the calendar inputs: 64 lowercase hex
	// characters.
	Revision string
	// Law names the rules this revision digests, for example "mf-cal-v2".
	Law string
	// TradingDayKind is CalendarKindETH or CalendarKindRTH: the symbol's own
	// trading day.
	TradingDayKind string
	// RTHSemantics records how the regular hours are defined, for example
	// "globex-day-portion".
	RTHSemantics string
	// ErasRecorded is false when the root's session setting was back-applied to
	// all history, unverified.
	ErasRecorded bool
	// Eras are the session eras of the root's timeline, for provenance.
	Eras []SessionEraInfo
	// HolidayTable identifies the table the calendar was built from; nil when
	// the venue has none.
	HolidayTable *HolidayTableInfo
	// CoverageFrom is the first trade date the calendar answers; empty for an
	// unbounded first era and table start.
	CoverageFrom string
	// CoverageTo is the last trade date the calendar answers; empty when there
	// is no table.
	CoverageTo string
	// GridRevisions maps an intraday-grid boundary to the grid revision, which
	// ties grid requests to this calendar.
	GridRevisions map[string]string
	// DayCancelRule names the assumed rule behind every DayCancel, for example
	// "globex-trade-date-session", or "none".
	DayCancelRule string
	// Days holds the days the wire carries beside the header, ascending by
	// TradeDate.
	Days []TradingDay
}

Exposure

Exposure pairs position and working orders for a symbol (Section 7.5).

type Exposure struct {
	Position      Position
	WorkingOrders []WorkingOrder
}

Fill

type Fill struct {
	ClientID       string
	Symbol         string
	Side           Side
	Quantity       int64
	Price          float64
	Timestamp      time.Time
	Commission     float64
	ParentClientID string // empty for unattached orders

	// RawPriceVal / AdjustedPriceVal are overrides for the venue-real and
	// adjusted fill prices (Section 8.9, 8.10). A value of 0 means "same as
	// Price": a fill's adjusted price IS its strategy-visible Price, so only a
	// differing raw price carries information. Read them through RawPrice /
	// AdjustedPrice, which apply that fallback so the raw==adjusted guarantee
	// holds however the Fill was constructed. For a continuous-futures fill the
	// per-segment additive offset is recovered as Price - RawPrice() (Section 9.2).
	RawPriceVal      float64
	AdjustedPriceVal float64

	// Order lifetime v2 (GLE-200 I2). Attempt echoes Order.Attempt; ExecID is
	// the venue's execution identifier (the de-duplication key of a partial
	// execution); OrderRef is the engine's durable canonical reference for the
	// attempt; RemainingQuantity is the attempt's quantity still working after
	// this execution (0 on a full fill). All zero on a v1 fill.
	Attempt           uint32 `json:",omitempty"`
	ExecID            string `json:",omitempty"`
	OrderRef          string `json:",omitempty"`
	RemainingQuantity int64  `json:",omitempty"`
	// ComboLeg is the 1-based index, in the combo's Legs, of the leg this
	// fill executes (GLE-409); 0 on a fill of any other order. ClientID and
	// Attempt are the combo's, Symbol and Side the leg's.
	ComboLeg int `json:",omitempty"`
	// Name echoes the filled order's Name (GLE-666); empty when it has none,
	// and on a fill of no order: a roll leg, an expiry settlement, a
	// corporate action's leg.
	Name string `json:",omitempty"`
	// Origin says who made the order the fill executes when it is not the
	// strategy's (GLE-1491): at an AlgoDesk desk, a fill the desk made on the
	// strategy's book, whose ClientID is empty. FillOriginOrder on every
	// other fill.
	Origin FillOrigin `json:",omitempty"`
}

Fill.AdjustedPrice

AdjustedPrice returns the strategy-visible (adjusted) fill price, falling back to Price when no override is set.

func (f Fill) AdjustedPrice() float64

Fill.RawPrice

RawPrice returns the venue-real fill price, falling back to Price when no raw override is set (a non-adjusted fill, where raw == adjusted == Price).

func (f Fill) RawPrice() float64

FillHandler

type FillHandler interface {
	OnFill(ctx *Context, fill Fill)
}

FillOrigin

FillOrigin says who made the order a fill executes (Fill.Origin, GLE-1491); it mirrors the wire’s FillOrigin.

type FillOrigin int

FillOrigin.String

String is the origin’s name: “order”, “operator”, “flatten”, “liquidation” or “assigned”; “origin(N)” for any other value.

func (o FillOrigin) String() string

Flatten

Flatten builds the market order that closes a position of signed size qty (Tier-1 T1.5): a long (qty > 0) yields a MarketSell of qty, a short (qty < 0) a MarketBuy of -qty. A zero qty has nothing to close and yields the zero Order (Symbol set), which the caller should not emit — mirroring kit.Flatten, whose contract is the same. Pass ctx.Position(sym).Quantity.

func Flatten(symbol string, qty int64) Order

GuardHeld, GuardDuplicateLiveLabel, GuardCancelRace, GuardCancelRefused, GuardCancelUnknown, GuardHoldTimeout, GuardShutdown, GuardCorporateAction, GuardContractExpired, GuardRolled

The engine admission race guard (GLE-200 I6, order lifetime v2) holds a new order while a cancellation it could race is unresolved, and refuses an order it cannot admit safely. Its decisions reach the strategy as OrderUpdate events: Status OrderStatusHeld with a Reason that begins with GuardHeld and “: “; on a refusal, Status OrderStatusDenied with a Reason that begins with one of the other tokens below and “: " (the rest of the text is for people, not for parsing). A refused attempt did not reach the venue, and no OrderCancel{Rejected} follows the denial (a venue denial is followed by one). An order a trade director trimmed (GLE-532) is held with a Reason that begins with DirectorTrimmed and carries the GuardHeld explanation after “; “.

const (
	// GuardHeld: held behind the pending cancellation of an attempt on the
	// same symbol and side, or of the label's previous attempt; released
	// (OrderStatusWorking) once every such attempt has ended without
	// executing.
	GuardHeld = "held"
	// GuardDuplicateLiveLabel: the label's previous attempt is still live,
	// or held, with no cancellation requested.
	GuardDuplicateLiveLabel = "duplicate_live_label"
	// GuardCancelRace: an attempt the order was held behind executed (in
	// whole or in part) while its cancellation was pending.
	GuardCancelRace = "cancel_race"
	// GuardCancelRefused: the venue refused the cancellation the order
	// depended on and the attempt is still working.
	GuardCancelRefused = "cancel_refused"
	// GuardCancelUnknown: the outcome of the cancellation the order depended
	// on is unknown.
	GuardCancelUnknown = "cancel_unknown"
	// GuardHoldTimeout: the order was held for the run's hold timeout.
	GuardHoldTimeout = "hold_timeout"
	// GuardShutdown: the run ended while the order was held.
	GuardShutdown = "hold_shutdown"
	// GuardCorporateAction: a corporate action on the order's instrument
	// cancelled its working orders while the order was held (GLE-200 I14);
	// it is refused rather than released at its pre-action levels.
	GuardCorporateAction = "hold_corporate_action"
	// GuardContractExpired: the order's dated futures contract expired while
	// the order was held (GLE-200 I14 unit 2a); it is refused rather than
	// released onto a contract that no longer trades.
	GuardContractExpired = "hold_contract_expired"
	// GuardRolled: the order names a dated futures contract that a continuous
	// series rolled out of while the order was held (GLE-491); it is refused
	// rather than released onto a contract the series has left, as the roll
	// cancels the working orders pinned to that contract.
	GuardRolled = "hold_rolled"
)

HelloLine

HelloLine is the handshake line the SDK writes to stdout on startup (Section 7.8), without the trailing newline.

func HelloLine() string

HolidayTableInfo

HolidayTableInfo identifies the holiday and early-close table a calendar was built from. Stem names it (e.g. “cme_equity”), Version is its content digest, and RangeFrom and RangeTo bound the YYYY-MM-DD dates it knows.

type HolidayTableInfo struct {
	Stem      string
	Version   string
	RangeFrom string
	RangeTo   string
}

InitAck

InitAck is the strategy’s reply to Init (Section 6.4).

type InitAck struct {
	LookbackBars  int
	Instruments   []string // empty = all from Init
	NeedsFills    bool
	NeedsSessions bool
	NeedsRolls    bool
	// NeedsInstruments mirrors NeedsRolls: the SDK sets it iff the strategy
	// implements the universe-resolved handler, and it gates the engine's
	// InstrumentsResolved push (Section 7.13.5) so OnBar-only strategies never
	// receive it. False (the zero value) for an OnBar-only strategy.
	NeedsInstruments bool
	// NeedsMarketEvents is set when the strategy declares a TRADES series or
	// implements MarketTradeHandler (GLE-389); it gates the engine's
	// MarketEvents delivery.
	NeedsMarketEvents bool
	Name              string
	Description       string
	Inputs            []InputDef
	// DataRequirements / TradeableSymbols carry the strategy's data and venue
	// declarations (Section 7.13.3); empty for an OnBar-only strategy.
	DataRequirements []DataRequirement
	TradeableSymbols []string
	// AlignedSeries carries the strategy's aligned-series declarations
	// (GLE-353); empty for a strategy that declares none.
	AlignedSeries []AlignedSeries
	// Capabilities the strategy accepts (GLE-200 I2; wire
	// InitAck.capabilities), each one the engine offered in
	// InitConfig.Capabilities. Nil for a strategy that requires none, so its
	// InitAck is byte-identical.
	Capabilities []string `json:",omitempty"`
	// NeedsCalendar mirrors NeedsRolls for exchange-calendar facts (GLE-200
	// I11; wire InitAck.needs_calendar): the SDK sets it when the strategy
	// consumes the calendar (I11 unit A3), gating the engine's
	// ExchangeCalendarBatch push. False for every other strategy, so its
	// InitAck is byte-identical.
	NeedsCalendar bool `json:",omitempty"`
	// NeedsPortfolio is set when the strategy implements PortfolioWatcher
	// (GLE-1372; wire InitAck.needs_portfolio), gating the engine's
	// PortfolioView push; Portfolio is what it asked the view to carry.
	// False and zero for every other strategy, so its InitAck is
	// byte-identical.
	NeedsPortfolio bool           `json:",omitempty"`
	Portfolio      PortfolioNeeds `json:",omitzero"`
}

InitConfig

type InitConfig struct {
	RunID       string
	StartTime   time.Time
	EndTime     time.Time
	Instruments []InstrumentInfo

	// Capabilities the engine puts in effect for this run (GLE-200 I2; wire
	// Init.capabilities): CapabilityLifetimeV2 and, since GLE-409,
	// CapabilityComboOrders. Nil on every run that selects none, and from
	// every engine that predates the field.
	Capabilities []string `json:",omitempty"`
}

Initializer

type Initializer interface {
	OnInit(ctx *Context, cfg InitConfig) error
}

InputDef

InputDef mirrors the wire InputDef for InitAck reporting (Section 6.4).

type InputDef struct {
	Name          string
	Type          string // int | float | bool | string | duration
	DefaultValue  string
	Description   string
	AllowedValues []string
	MinValue      string
	MaxValue      string
	Step          string
}

InstrumentInfo

type InstrumentInfo struct {
	Symbol      string
	ExchangeMIC string
	AssetClass  string
	TickSize    float64
	PointValue  float64
	Currency    string
	// Expiration is the dated futures contract's expiration instant (UTC);
	// zero for a root, an equity, or an adapter that does not supply it
	// (wire InstrumentInfo.expiration, Section 8.9 calendar backstop).
	Expiration time.Time
	// ExchangeTimezone is the IANA name of the venue's exchange-local clock
	// (GLE-200 I11; wire InstrumentInfo.exchange_timezone), e.g.
	// "America/Chicago"; empty from an adapter that predates the field or
	// does not know it. Omitted from JSON when empty so every artefact that
	// embeds an InstrumentInfo stays byte-identical.
	ExchangeTimezone string `json:",omitempty"`
	// Margin is the margin per contract with its provenance (GLE-400; wire
	// InstrumentInfo.margin); nil when the adapter serves none. Omitted from
	// JSON when nil, so artefacts from adapters without margins stay
	// byte-identical.
	Margin *MarginRequirement `json:",omitempty"`
	// TickSizeSource says where TickSize came from (GLE-400): the adapter's
	// registry or the exchange definitions in force at the answer's instant;
	// "" when undisclosed.
	TickSizeSource TickSizeSource `json:",omitempty"`
	// Description is the instrument's name for people (GLE-1358; wire
	// InstrumentInfo.description), e.g. "E-Mini S&P 500"; empty from an
	// adapter that predates the field or has none. Omitted from JSON when
	// empty so every artefact that embeds an InstrumentInfo stays
	// byte-identical.
	Description string `json:",omitempty"`
}

LifecycleTurn

LifecycleTurn is one lifecycle decision turn (lifetime-v2 only, GLE-200 I4): the engine has delivered the outcomes of the strategy’s commands at the instant At (the OrderUpdate and CancelResponse events the working view already reflects) and grants the strategy a decision on them before the clock advances. Turn is 1-based within the instant, Budget the number of turns the run grants per instant. No bar travels with a turn: the series, the bar counts and the signal state are unchanged; ctx.Now() is At.

type LifecycleTurn struct {
	At     time.Time
	Turn   uint32
	Budget uint32
}

LimitBuy

func LimitBuy(symbol string, qty int64, price float64) Order

LimitSell

func LimitSell(symbol string, qty int64, price float64) Order

ListingHandler

ListingHandler is implemented by a strategy that wants each contract listing as it is delivered (GLE-410). OnListing runs once the record is in the context and ctx.Now() has moved to the instant it was delivered, so ctx.Curve inside the handler already reflects it.

type ListingHandler interface {
	// OnListing is called for every delivered record of every declared CONTRACT_LISTING series, in
	// delivery order: a contract's first record at its KnownAt, and a restated one (its LastBar
	// grows each day it trades) at the daily listing that restated it.
	OnListing(ctx *Context, l MarketListing)
}

Lookbacker

type Lookbacker interface {
	Lookback() int
}

MarginBalance

MarginBalance is one open position’s margin requirement, in Currency (GLE-411): Initial and Maintenance for its whole quantity.

type MarginBalance struct {
	Symbol      string
	Currency    string
	Initial     float64
	Maintenance float64
}

MarginRequirement

MarginRequirement is one instrument’s margin per contract, with its provenance.

type MarginRequirement struct {
	// Initial is the initial margin per contract, in Currency.
	Initial float64
	// Maintenance is the maintenance margin per contract, in Currency.
	Maintenance float64
	// Currency is the ISO 4217 code both margins are in, e.g. "USD".
	Currency string
	// Source says where the requirement came from.
	Source MarginSource
	// CapturedAt is when the value was captured or curated, in UTC; zero =
	// undated (a seed).
	CapturedAt time.Time
	// AccountDependent reports that the value may depend on the capturing
	// account's positions.
	AccountDependent bool
	// Contract is the dated contract code the capture was taken on, e.g.
	// "Z26"; "" for a root-level seed.
	Contract string
}

MarginSource

MarginSource says where a margin requirement came from; "” = a source the wire left unspecified or this SDK does not know.

type MarginSource string

MarketBuy

func MarketBuy(symbol string, qty int64) Order

MarketDefinition

MarketDefinition is one point-in-time instrument definition of a declared INSTRUMENT_DEFINITION series (GLE-406): what the venue said a contract was at TsEvent, delivered at TsEvent. Venues resend definitions daily; the latest one delivered for a contract is the one in force.

type MarketDefinition struct {
	SeriesID   string // the declared series' id
	Symbol     string // the dated contract, e.g. "fut:XCME:ES:M26"
	RawSymbol  string // the venue's symbol, e.g. "ESM6"
	Activation time.Time
	Expiration time.Time // the last trading instant; zero when undefined
	TickSize   float64
	// ContractSize is the contract's size in its unit of measure (the
	// definition's unit_of_measure_qty, the point value: 50 for ES).
	ContractSize float64
	Currency     string
	Exchange     string // the listing venue's MIC
	// MaturityYear/Month/Day are the calendar maturity the venue symbol
	// encodes; Month and Day are 0 when the venue gives no such granularity.
	MaturityYear, MaturityMonth, MaturityDay int
	TsEvent                                  time.Time // when the definition was current
}

MarketListing

MarketListing is one contract of a declared CONTRACT_LISTING series (GLE-410): a contract of the series’ futures root, as a listing request at the instant it was delivered would return it. Its first delivery is at KnownAt; it is delivered again when a later daily listing restates it, which happens every day the contract trades, since LastBar grows. The latest one delivered for a contract is the one Context.Curve reads.

type MarketListing struct {
	SeriesID string // the declared series' id
	Symbol   string // the dated contract, e.g. "fut:XCME:ES:M26"
	Contract string // the contract code, e.g. "M26"
	// The contract is listed from Activation up to but excluding Expiration.
	Activation time.Time
	Expiration time.Time
	// MaturityYear/Month/Day are the calendar maturity; Month and Day are 0
	// when the venue gives no such granularity.
	MaturityYear, MaturityMonth, MaturityDay int
	FirstBar                                 time.Time // the start of the contract's first stored bar
	LastBar                                  time.Time // the end of its newest stored bar, never after the delivery instant
	TickSize                                 float64
	KnownAt                                  time.Time // when the listing became known: no earlier than Activation and FirstBar
	TsRecv                                   time.Time // when this record was delivered: KnownAt, or the daily listing that restated it
}

MarketObservation

MarketObservation is one observation of a declared OBSERVATIONS series (GLE-408): one published value of one reference period of a release-stamped series, the first release or a later revision, delivered at AvailableAt, the instant it became public. A period’s revisions arrive as their own records, in order; the newest one delivered is the period’s value as known now.

type MarketObservation struct {
	SeriesID    string    // the declared series' id
	Symbol      string    // the series, e.g. "macro:FRED:GDP"
	Ref         time.Time // the reference period, UTC midnight
	AvailableAt time.Time // the instant the value became public
	Value       float64   // the value; 0 when Withdrawn
	Withdrawn   bool      // the source withdrew the period's value in this vintage
	Revision    uint32    // 0 = the period's first release; +1 per later vintage
	Vintage     time.Time // the vintage date, UTC midnight
}

MarketOnCloseBuy

MarketOnCloseBuy / MarketOnCloseSell build a market-on-close order. Price/StopPrice MUST stay zero (the simulator rejects a level on an MOC as misuse). Under order lifetime v2 in a backtest (GLE-1375) it waits until a send time shortly before the RTH close of the first session whose send-time window opens after the decision — on daily bars, the next session’s — then fills as a market order at the first price at or after it; it needs the exchange calendar (CalendarRequirer), may be an attached order (it goes out only if its parent fills), and is cancellable until its send time. Under lifetime v1 (F4a), submitted from OnBar(bar N) it settles at bar N’s close, the price the strategy just observed, and never rests; live, IBKR receives a DAY MOC ticket that rests until the closing auction. TIF stays Day either way and does not end the order before its send time.

func MarketOnCloseBuy(symbol string, qty int64) Order

MarketOnCloseSell

func MarketOnCloseSell(symbol string, qty int64) Order

MarketSell

func MarketSell(symbol string, qty int64) Order

MarketStatistic

MarketStatistic is one venue statistic of a declared STATISTICS series (GLE-406): a settlement price, an open interest, a cleared volume. It is delivered at its publication: VisibleAt, the first non-zero of TsRecv, TsEvent and TsRef. A statistic is revised — a preliminary and a final settlement, an open interest restated the next morning — and each revision arrives as its own record; the latest one delivered is the one known now.

type MarketStatistic struct {
	SeriesID string   // the declared series' id
	Symbol   string   // the dated contract, e.g. "fut:XCME:ES:M26"
	Kind     StatKind // StatSettlementPrice, StatOpenInterest, StatClearedVolume, ...
	// Price is set for price kinds (HasPrice), Quantity for count kinds
	// (HasQuantity); a value that does not apply is absent, never zero.
	Price       float64
	HasPrice    bool
	Quantity    int64
	HasQuantity bool
	// TsRef is the trading date the statistic applies to; zero when the venue
	// did not date it (CME statistics before 2015 are undated).
	TsRef   time.Time
	TsEvent time.Time // the venue's sending instant
	TsRecv  time.Time // when it was published
	Deleted bool      // the venue withdrew this value
}

MarketStatistic.VisibleAt

VisibleAt is the instant the statistic becomes known: its TsRecv, else its TsEvent, else its TsRef.

func (s MarketStatistic) VisibleAt() time.Time

MarketTrade

MarketTrade is one trade of a declared TRADES series (GLE-389), delivered to MarketTradeHandler.OnMarketTrade and kept in ctx.MarketTrades(seriesID). A trade becomes visible at TsRecv: it is delivered before the first bar whose close is strictly after TsRecv, never at or before it.

type MarketTrade struct {
	SeriesID  string    // the declared series' id (its Symbol when the declaration gave none)
	Symbol    string    // the instrument the trade printed on, e.g. "fut:XCME:ES:Z25"
	Price     float64   // raw venue price
	Size      int64     // contracts or shares
	Aggressor Aggressor // the side that took liquidity, when the venue says
	TsEvent   time.Time // the matching engine's instant
	TsRecv    time.Time // when the data provider received it: the instant it became visible
	// BadTsRecv marks a trade whose TsRecv the provider flags as unreliable
	// (CME Globex before 2017-05-21 22:00 UTC, where TsRecv equals TsEvent).
	BadTsRecv bool
}

MarketTradeHandler

MarketTradeHandler is the optional observer of declared TRADES series (GLE-389). OnMarketTrade runs once per trade, in replay order, before the bar that follows it; ctx.Now() is the trade’s TsRecv during the call. It is observe-only: it returns no orders (decisions stay at bar closes, where the strategy can read ctx.MarketTrades). Implementing it, or declaring a TRADES series, sets InitAck.needs_market_events.

type MarketTradeHandler interface {
	OnMarketTrade(ctx *Context, t MarketTrade)
}

Member

Member is one strategy of the portfolio. In an engine backtest the view has one member, the reader, whose ID is the run’s (ctx.RunID()).

type Member struct {
	ID       string
	Strategy string // the strategy's name
	Label    string // display label
	Symbols  []string
	State    MemberState
	// Visibility is what the reader sees of this member.
	Visibility Visibility
	// Reader is set on the member that is the strategy reading the view.
	Reader bool
}

MemberOrder

MemberOrder is one member’s working order. Orders sent at a decision appear in the next view, not in the view that decision read.

type MemberOrder struct {
	Member      string
	Symbol      string
	Contract    string
	ClientID    string
	Attempt     uint32 // 0 on a lifetime-v1 run
	Side        Side
	Remaining   int64
	Type        OrderType
	LimitPrice  float64
	StopPrice   float64
	TIF         TimeInForce
	Reducing    bool // it reduces the member's position; else it opens
	State       MemberOrderState
	SubmittedAt time.Time
}

MemberOrderState

MemberOrderState is where a working order is in its life, as the view reports it. The zero value is unknown.

type MemberOrderState int

MemberState

MemberState is where a member of the portfolio is in its session. The zero value is unknown.

type MemberState int

MultiSymbol

type MultiSymbol interface {
	// IsMultiSymbol declares that this strategy must see bars from every
	// portfolio symbol within a single instance (Section 8.7).
	IsMultiSymbol() bool
}

NewCalendar

NewCalendar checks the facts the lookups depend on and returns the view, or the zero Calendar and an error that wraps ErrInvalidCalendar. The view holds a deep copy of facts: every instant in UTC (a zero time stays zero), every empty slice or map nil, and no memory the caller can reach.

func NewCalendar(facts ExchangeCalendar) (Calendar, error)

NewObservationHistory

NewObservationHistory builds a view over a copy of obs, which is taken to be in delivery order; it is neither sorted nor checked. A strategy’s own tests use it to hand a handler or a kit helper a vintage history without running the engine, and so do the kit’s. Changing obs afterwards does not change the view.

func NewObservationHistory(obs []MarketObservation) ObservationHistory

ObservationHandler

ObservationHandler is implemented by a strategy that wants each observation as it is delivered. OnObservation runs once the observation is in the context’s buffer and history and ctx.Now() has moved to the instant the observation became public, so a query made inside the handler already includes the observation it is handed.

type ObservationHandler interface {
	// OnObservation is called for every delivered observation of every declared OBSERVATIONS
	// series, withdrawals included, in delivery order.
	OnObservation(ctx *Context, o MarketObservation)
}

ObservationHistory

ObservationHistory is an immutable view of the observations of one declared series delivered up to some point, in delivery order (non-decreasing AvailableAt; within a period, revision order).

Every query that takes an instant is answered only from the observations published by then, so a strategy asking what a period was known to be at t never sees a revision made after t, which is the look-ahead that revised data invites. Periods are compared with time.Time.Equal. Every slice a method returns is new and belongs to the caller. The zero value is an empty history.

type ObservationHistory struct {
	// contains filtered or unexported fields
}

ObservationHistory.All

All returns every observation in delivery order. The slice is a copy.

func (h ObservationHistory) All() []MarketObservation

ObservationHistory.AsKnownAt

AsKnownAt returns, for each period, its last delivered observation published at or before t, ascending by Ref. The bound is inclusive: an observation published at t is known at t. A withdrawal is returned like any other observation, because a period whose latest word is a withdrawal has no known value, and dropping the withdrawal would let the revision before it resurface. A period with no observation published by t is omitted.

func (h ObservationHistory) AsKnownAt(t time.Time) []MarketObservation

ObservationHistory.Latest

Latest returns the last delivered observation of period ref, which may be a withdrawal. It is the period’s state at the end of the view, not at an earlier instant; for that, use ValueAt or AsKnownAt. It returns the zero observation and false when the period has none.

func (h ObservationHistory) Latest(ref time.Time) (MarketObservation, bool)

ObservationHistory.Len

Len returns the number of observations in the view, withdrawals included.

func (h ObservationHistory) Len() int

ObservationHistory.Refs

Refs returns the distinct periods of the view in ascending order. Of several equal Ref values the one from the earliest delivered observation is returned.

func (h ObservationHistory) Refs() []time.Time

ObservationHistory.Revisions

Revisions returns the observations of period ref in delivery order, withdrawals included, with no bound on availability. It returns nil when the period has none.

func (h ObservationHistory) Revisions(ref time.Time) []MarketObservation

ObservationHistory.ValueAt

ValueAt returns the value of period ref as known at t: the Value of its last delivered observation published at or before t. It returns 0 and false when there is no such observation or when it is a withdrawal.

func (h ObservationHistory) ValueAt(ref, t time.Time) (float64, bool)

Order

type Order struct {
	Symbol         string
	Side           Side
	Quantity       int64
	Type           OrderType
	Price          float64
	StopPrice      float64
	TrailAmount    float64 // for StopTrailing
	TIF            TimeInForce
	ClientID       string
	AttachedOrders []Order // activated on this order's fill; mutual OCO
	// OCOGroup, when non-empty, joins this order into a STANDALONE mutual
	// one-cancels-other group with every other working order of the same
	// symbol carrying the same tag — no parent required. The first member to
	// fill cancels the siblings. The sibling analogue of AttachedOrders, for
	// per-bar re-placed exit pairs (protective stop + profit-taking limit).
	OCOGroup string
	// Attempt is the attempt number of this physical submission under ClientID
	// (GLE-200 I2): 1-based and increasing per label within one strategy
	// instance. ClientID is the logical intent key; (ClientID, Attempt)
	// identifies one attempt, and every event about the attempt echoes both.
	// 0 (unset) on a v1 submission; the SDK stamps it only under lifetime v2
	// (I3).
	Attempt uint32 `json:",omitempty"`
	// Legs makes the order a combo (GLE-409): an IBKR-style combo of dated
	// contracts filled all legs or none. Symbol is then ComboSymbol(Legs),
	// Quantity the number of combo units, and a Limit's Price the net price
	// per unit (see ComboLeg), which may be zero or negative. Empty on every
	// other order.
	Legs []ComboLeg `json:",omitempty"`
	// Conviction is the strategy's optional, signed conviction in the order
	// (GLE-532), for the engine's trade director to rank by: finite, in
	// [-1, 1], non-negative on a buy and non-positive on a sell (zero is
	// valid on either side). nil means none, which is distinct from an
	// explicit zero. It travels as the pb Order.signal and as the csv2 order
	// line's eleventh field, and only on a run that accepted
	// CapabilityOrderConviction; the SDK refuses it otherwise. An order
	// without one encodes exactly as before the field existed.
	Conviction *float64 `json:",omitempty"`
	// Name is the order's display name (GLE-666), TradeStation's "LE" or
	// "Trail stop", set with Named: a label for reports and charts, echoed
	// on the order's fills (Fill.Name). ClientID stays the logical intent
	// key. Empty names none, and the report then names the trade by the
	// order's effect: Buy, Sell, Sell Short or Buy to Cover. It travels as
	// the pb Order.name and the csv2 order line's twelfth field, and not on
	// stdio-csv-v1, which drops it.
	Name string `json:",omitempty"`
	// CancelAt is the instant at which the engine requests this order's
	// cancellation on the strategy's behalf, unless the order has ended by
	// then (order lifetime v2, GLE-1362). The engine answers with a
	// CancelResponse whose RequestID is CancelAtRequestID(ClientID, Attempt)
	// and, when the cancellation succeeds, an OrderCancel (CancelReasonExplicit)
	// carrying the same id; a fill before the instant wins, and a pending,
	// refused or unknown answer leaves the order working, as for ctx.Cancel.
	// The zero time schedules nothing. It must be after the decision the order
	// is submitted at (DenyCancelAtNotFuture otherwise) and is refused
	// (DenyCancelAtUnsupported) on a lifetime-v1 run, a live venue, an
	// attached order and a combo. It travels as the pb Order.cancel_at and the
	// csv2 order line's thirteenth field, and not on stdio-csv-v1.
	CancelAt time.Time `json:",omitzero"`
}

Order.Named

Named returns a copy of o with its display name set (GLE-666), for reports and charts: MarketBuy(“ES”, 1).Named(“LE”). Its fills echo the name, and its trades carry it. Children keep their own names.

func (o Order) Named(name string) Order

OrderCancel

type OrderCancel struct {
	ClientID    string
	Timestamp   time.Time
	Reason      CancelReason
	TriggeredBy string // sibling's ClientID for OCO; empty otherwise

	// Order lifetime v2 (GLE-200 I2). Attempt and OrderRef identify the
	// attempt; RequestID echoes the cancel request this cancel answers when
	// Reason is CancelReasonExplicit; RemainingQuantity is the quantity that was
	// still working when the order was cancelled. All zero on a v1 cancel.
	Attempt           uint32 `json:",omitempty"`
	OrderRef          string `json:",omitempty"`
	RequestID         string `json:",omitempty"`
	RemainingQuantity int64  `json:",omitempty"`
}

OrderStatus

OrderStatus is one attempt’s lifecycle status under order lifetime v2 (GLE-200 I2). Values equal algolangpb.OrderStatus_ORDER_STATUS_* so an int cast converts faithfully (the same value discipline as CancelReason). The first seven are live states; Filled, Cancelled, Rejected, Denied and Expired are terminal (see Terminal).

type OrderStatus int

OrderStatus.String

String renders s in lower snake case (“pending_cancel”); a value outside the enumeration renders as order_status_.

func (s OrderStatus) String() string

OrderStatus.Terminal

Terminal reports whether s ends its attempt: Filled, Cancelled, Rejected, Denied and Expired. The live states, Unspecified and any value outside the enumeration report false.

func (s OrderStatus) Terminal() bool

OrderType

type OrderType int

OrderUpdate

OrderUpdate is the SDK-native mirror of the wire OrderUpdate (GLE-200 I2): one attempt’s status transition, delivered only on a run that negotiated lifetime-v2. Quantity, FilledQuantity and RemainingQuantity are the attempt’s original, cumulative filled and still-working quantities; Reason and BrokerCode carry the venue’s or the engine’s text for a terminal or held transition; Timestamp is zero when the wire carries none. ReplacesAttempt (GLE-200 I15) is set when the engine itself re-placed the order (a continuous roll re-places a working order on the incoming contract): the update names the new attempt, its OrderRef and the attempt it replaces, which ends without an OrderCancel of its own; 0 on every other update.

type OrderUpdate struct {
	ClientID          string
	Attempt           uint32
	OrderRef          string
	Symbol            string
	Status            OrderStatus
	Quantity          int64
	FilledQuantity    int64
	RemainingQuantity int64
	Timestamp         time.Time
	Reason            string
	BrokerCode        string
	ParentClientID    string
	OwnerID           string
	ReplacesAttempt   uint32 `json:",omitempty"`
}

OrderUpdateHandler

OrderUpdateHandler observes attempt status transitions (lifetime-v2 only). The SDK hands each OrderUpdate to OnOrderUpdate as it arrives. On a run that negotiated lifetime-v2 (stdio-pb-v1 or stdio-csv-v2) the working view moves on the update first, whether or not the strategy has the handler, so the handler reads the view as the event left it; positions move on Fill events alone. On a v1 run the SDK changes no Context state for it, and a strategy without the handler ignores the event.

type OrderUpdateHandler interface {
	OnOrderUpdate(ctx *Context, u OrderUpdate)
}

OwnedPosition

OwnedPosition is one member’s holding in one logical symbol. Amounts are in the portfolio’s base currency; OpenPnL and RealizedPnL are gross of commission, as the report’s trades are.

The prices follow the run (GLE-1504). Without –roll-rebase a continuous series’ row is in the served frame, the end-adjusted prices the strategy’s bars have. With –roll-rebase it is in the held contract’s own prices, as the strategy’s bars are then: Mark is the series’ latest close as the strategy sees it, AveragePrice is the entry moved by the rolls since entry, equal to ctx.Position(symbol).AvgPrice, and Notional is at that mark. OpenPnL and RealizedPnL are money and stay as the report states them in either case.

type OwnedPosition struct {
	Member   string
	Symbol   string // logical symbol (a continuous series' root)
	Contract string // the physical contract held; Symbol when there is none
	Quantity int64  // signed: negative is short
	// AveragePrice is the open lots' quantity-weighted entry price; on a
	// --roll-rebase run, a held continuous series' is the strategy's own
	// average, the entry moved by each roll's rebase.
	AveragePrice float64
	Mark         float64
	MarkTime     time.Time
	PointValue   float64
	Currency     string // the symbol's quote currency
	OpenPnL      float64
	RealizedPnL  float64 // the symbol's closed trades
	Notional     float64 // signed: Quantity x Mark x PointValue, in base currency
}

Performance

Performance is a member’s performance ratios, or the portfolio’s, on the net equity curve so far. A ratio that cannot be computed yet (fewer than 20 daily returns for Sharpe and Sortino, under a day for the annual return) has its Has flag false.

type Performance struct {
	Member          string
	AnnualReturn    float64 // CAGR from the first bar to the view
	HasAnnualReturn bool
	Sharpe          float64
	HasSharpe       bool
	SharpeDays      int // daily returns behind Sharpe
	Sortino         float64
	HasSortino      bool
	Calmar          float64
	HasCalmar       bool
	// TimeInMarket is the fraction of bars with a position open, and its
	// long and short parts.
	TimeInMarket      float64
	TimeInMarketLong  float64
	TimeInMarketShort float64
	HasTimeInMarket   bool
}

PlotKind

PlotKind is how a plot is drawn.

type PlotKind int

PlotPoint

PlotPoint is one plotted value of a bar, as the SDK sends it: the plot named Name on the bar’s series has Value at the bar. Style is set on the first point of each plot, nil afterwards.

type PlotPoint struct {
	Name  string
	Value float64
	Style *PlotStyle
}

PlotStyle

PlotStyle is how a plot is drawn. The zero value is a line over its series’ prices, in a colour the viewer chooses.

type PlotStyle struct {
	Kind PlotKind
	// Pane is "" to draw over the series' prices, or the name of a sub-pane
	// below them, shared by every plot that names it.
	Pane string
	// Color is "#RRGGBB", or "" to let the viewer choose.
	Color string
}

PolicyWorkingOrders, PolicySymbolWorkingOrders, PolicyQuantity, PolicyExposure, PolicyRateBudget

The engine admission policy (GLE-200 I6 unit 2, order lifetime v2) refuses a new order that would exceed one of the run’s configured limits: the working orders per instance and per symbol, the quantity of one order, the position a symbol could reach, and the submissions per window of event time. Every limit counts the orders the race guard holds, and the policy decides at both of the guard’s admission points: a new order (admitted or held) and the release of a held one. A refusal reaches the strategy as an OrderUpdate with Status OrderStatusDenied and a Reason that begins with one of the tokens below and “: " (the rest of the text is for people, not for parsing). As with the race guard’s denials, the attempt did not reach the venue and no OrderCancel{Rejected} follows.

const (
	// PolicyWorkingOrders: the instance's working orders (held, pending a
	// cancellation, of unknown outcome and attached children included) would
	// exceed the run's max-working-orders.
	PolicyWorkingOrders = "cap_working_orders"
	// PolicySymbolWorkingOrders: the working orders on the order's symbol
	// would exceed the run's max-symbol-working-orders.
	PolicySymbolWorkingOrders = "cap_symbol_working_orders"
	// PolicyQuantity: the order's quantity, or an attached order's, exceeds
	// the run's max-order-quantity.
	PolicyQuantity = "cap_quantity"
	// PolicyExposure: with the order, the position the symbol could reach
	// (every working and held order counted, each at its remaining quantity)
	// would pass the run's max-position, either way.
	PolicyExposure = "cap_exposure"
	// PolicyRateBudget: the run's budget of max-submissions new orders per
	// submission-window of event time is used up.
	PolicyRateBudget = "rate_budget"
)

PortfolioCurve

PortfolioCurve chooses the equity curves a view carries.

type PortfolioCurve int

PortfolioDetail

PortfolioDetail chooses the rows a view carries for peers.

type PortfolioDetail int

PortfolioNeeds

PortfolioNeeds is what a PortfolioWatcher asks the view to carry. The zero value asks for every member’s rows and no curve.

type PortfolioNeeds struct {
	Detail PortfolioDetail
	Curve  PortfolioCurve
}

PortfolioView

PortfolioView is the portfolio as of the decision being made (GLE-1372; docs/portfolio-view-spec.md §7.4): positions, working orders and totals per symbol, and each member’s and the portfolio’s figures. It holds nothing later than AsOf, and no decision made at AsOf. ctx.Portfolio returns it; read it in the decision, since the next view replaces it.

The zero value is the view of a strategy that has none (it did not ask, its visibility is none, it runs live, or no view has arrived yet): Valid reports false and every query returns its zero value.

type PortfolioView struct {
	// contains filtered or unexported fields
}

PortfolioView.AsOf

AsOf is the instant the view describes.

func (p PortfolioView) AsOf() time.Time

PortfolioView.BaseCurrency

BaseCurrency is the currency of the view’s amounts.

func (p PortfolioView) BaseCurrency() string

PortfolioView.Equity

Equity is member’s equity curve to date, oldest first; "” is the portfolio’s. It is empty unless the strategy asked for that curve (PortfolioNeeds.Curve). The SDK keeps the history, so the engine sends each point once; the slice is the SDK’s own, so do not modify it.

func (p PortfolioView) Equity(member string) []EquityPoint

PortfolioView.ID

ID is the portfolio’s id: the run-config file’s name in an engine backtest, empty for a bare command line.

func (p PortfolioView) ID() string

PortfolioView.Members

Members lists the portfolio’s members.

func (p PortfolioView) Members() []Member

PortfolioView.Orders

Orders lists member’s working orders; "” lists every visible member’s.

func (p PortfolioView) Orders(member string) []MemberOrder

PortfolioView.Performance

Performance is member’s performance ratios; "” is the portfolio’s.

func (p PortfolioView) Performance(member string) Performance

PortfolioView.Position

Position is member’s holding in symbol; zero if flat or not visible.

func (p PortfolioView) Position(member, symbol string) OwnedPosition

PortfolioView.Positions

Positions lists every visible open position.

func (p PortfolioView) Positions() []OwnedPosition

PortfolioView.Reader

Reader is the reading strategy’s member id (ctx.RunID() in an engine backtest).

func (p PortfolioView) Reader() string

PortfolioView.Stats

Stats is member’s statistics column for side; "” is the portfolio’s.

func (p PortfolioView) Stats(member string, side TradeSide) TradeStats

PortfolioView.Summary

Summary is member’s account figures; "” is the portfolio’s.

func (p PortfolioView) Summary(member string) Summary

PortfolioView.Total

Total is the portfolio’s position in symbol over every member; zero when no member holds it or works an order in it.

func (p PortfolioView) Total(symbol string) SymbolTotal

PortfolioView.Valid

Valid reports whether the view holds a portfolio.

func (p PortfolioView) Valid() bool

PortfolioView.Visibility

Visibility is what the portfolio file grants the reader.

func (p PortfolioView) Visibility() Visibility

PortfolioWatcher

PortfolioWatcher is implemented by a strategy that reads the portfolio view (GLE-1372; docs/portfolio-view-spec.md §7.4). The SDK sets InitAck.needs_portfolio for it, and the engine then pushes a PortfolioView before each of its decisions. PortfolioNeeds is called once, after OnInit.

type PortfolioWatcher interface {
	PortfolioNeeds() PortfolioNeeds
}

Position

type Position struct {
	Symbol   string
	Quantity int64
	// OpenedAt is the wall-clock time the CURRENT open position was established:
	// the timestamp of the fill that moved the position from flat (or flipped it
	// through zero). Zero when flat. Preserved across same-side adds and partial
	// reduces. Restart-correct: seeded from AdoptedPosition.OpenedAt on live
	// adoption (F1). The SDK maintains it in applyFill from the same fill stream
	// the sim's positionState.OpenedAt is maintained from, so the two agree.
	OpenedAt time.Time
	// AvgPrice is the strategy-facing (adjusted-frame) average cost: the DEFAULT
	// view, kept equal to AvgPriceAdjusted on every update. It is a named field
	// (not a method) so all existing readers compile and read unchanged. On a
	// non-adjusted run AvgPrice == AvgPriceRaw == AvgPriceAdjusted.
	AvgPrice float64
	// AvgPriceRaw is the venue-real (on-the-day) average cost, blended from each
	// fill's RawPrice(); AvgPriceAdjusted is the adjusted-frame average cost,
	// blended from each fill's AdjustedPrice(). On a non-adjusted run
	// RawPrice()==AdjustedPrice()==Price, so all three are byte-identical to the
	// single-column AvgPrice the SDK maintained before E7. The split-time rewrite
	// (Quantity*ratio, AvgPriceRaw*priceRatio, AvgPriceAdjusted UNCHANGED —
	// continuous) is E8 via the CorporateActionNotice, NOT here.
	AvgPriceRaw      float64
	AvgPriceAdjusted float64
	// Realized is the cumulative realized PnL for this symbol in account currency
	// (Tier-1 T1.2), maintained by the SDK in applyFill with the SAME average-cost
	// arithmetic the engine simulator uses (engine/sim applyToPosition): PnL is
	// booked on the closed quantity against the venue-real (raw) average cost,
	// scaled by ctx.Instrument(symbol).PointValue (1 when unresolved). On a
	// non-adjusted run it equals the sim's per-symbol RealizedPnL fill-for-fill, so
	// a strategy reads exact realized PnL without re-deriving an OnFill ledger. It
	// is CUMULATIVE across the run (not reset when the position goes flat); a loser
	// test compares its value at entry against its value at exit.
	Realized float64
}

PriceField

PriceField selects one OHLC component for the AdjustedPrice/RawPrice accessors (Section 8.9 / 9.2).

type PriceField int

PriceNotFinite

The engine refuses at the wire, before the trade director, the simulator or a live venue sees it, an order whose price, stop price or trail amount, or an attached order’s, is not a finite number: NaN, +Inf or -Inf (GLE-1090). The Go SDK never sends one, but a strategy on the protobuf wire, or on the stdio-csv-v1 wire, that is written without it can. The refusal is made on every order lifetime, with or without a trade director, in a backtest and in live mode, and its reason is the token below, “: " and the first offending field: “price_not_finite: price=NaN”, “price_not_finite: stop_price=+Inf”, “price_not_finite: attached=0 trail_amount=-Inf”. Under lifetime v2 it reaches the strategy as an OrderUpdate with Status OrderStatusDenied and that Reason, and no OrderCancel{Rejected} follows; under lifetime v1 the strategy hears an OrderCancel{Rejected} for the order before its next bar. Zero and negative levels are not refused here.

const (
	// PriceNotFinite: the order's price, stop price or trail amount, or an
	// attached order's, is NaN or an infinity.
	PriceNotFinite = "price_not_finite"
)

RTHStateOpen, RTHStateClosed, RTHStateNoneDeclared, RTHStatePlaceholder, RTHStateUnknown

TradingDay.RTHState. Only RTHStateOpen carries an RTH window. The others are explicit states that travel instead of a guessed window.

const (
	RTHStateOpen         = wire.RTHStateOpen
	RTHStateClosed       = wire.RTHStateClosed
	RTHStateNoneDeclared = wire.RTHStateNoneDeclared
	RTHStatePlaceholder  = wire.RTHStatePlaceholder
	RTHStateUnknown      = wire.RTHStateUnknown
)

Rebase

Rebase is one roll of a continuous series on a run with –roll-rebase on (GLE-1458). The strategy calculates on prices adjusted only by the rolls that have happened: at each roll the engine re-adjusts the series’ history onto the incoming contract’s basis and sends it, and every price the strategy holds moves onto that basis.

A level x moves to Level(x): x * Ratio under the ratio method, x + Gap under panama. A distance (a trailing amount, an ATR) moves to Distance(d): it scales by Ratio and is unmoved by Gap. Exactly one of the two applies: under panama Gap is the raw seam gap (incoming - outgoing at the cut) and Ratio is 1; under ratio Gap is 0 and Ratio is the seam ratio (incoming / outgoing). An unadjusted series is never rebased.

Bars is the series’ history on the incoming basis, oldest first: the series’ last bars, up to its declared lookback. They replace the series’ buffer (ctx.Series) before OnRebase runs.

type Rebase struct {
	Symbol   string    // the logical continuous symbol, e.g. "fut:XCME:ES"
	SeriesID string    // the series' id when it is not its symbol; "" otherwise
	From, To string    // the outgoing and incoming contracts
	At       time.Time // the roll's cut
	Gap      float64   // additive move of a level (panama); 0 otherwise
	Ratio    float64   // multiplicative move of a level (ratio); 1 otherwise
	Bars     []Bar     // the series' history on the incoming basis, oldest first
}

Rebase.Distance

Distance moves the price distance d onto the incoming basis: d * Ratio under the ratio method; unchanged otherwise, since an additive move leaves a distance alone.

func (r Rebase) Distance(d float64) float64

Rebase.Level

Level moves the price level x onto the incoming basis: x * Ratio under the ratio method, x + Gap otherwise. The engine restates its own book with this method, so the strategy’s view and the engine’s agree to the bit.

func (r Rebase) Level(x float64) float64

Rebase.RestateOrder

RestateOrder returns o moved onto the incoming basis, as the engine restates a working order at a roll: the levels its type prices (Price for a limit, stop-limit or limit-on-close order; StopPrice for a stop, stop-limit or first-touch stop) move by Level, its trailing amount by Distance, and its attached orders likewise. Every other field is unchanged, so a market order keeps its zero price. The result is a new Order; o is not modified.

func (r Rebase) RestateOrder(o Order) Order

RebaseObserver

RebaseObserver is the optional hook for a roll rebase (GLE-1458): on a run with –roll-rebase on, at each roll of a continuous series the engine sends the series’ history re-adjusted onto the incoming contract’s basis. Before OnRebase runs, the SDK has already moved everything it keeps onto that basis: the series’ buffer holds r.Bars, and the position’s average cost, the working orders’ levels and the trade anchors are restated (see Rebase). OnRebase is for what the strategy keeps itself: an indicator’s running state, a level it computed, a stop it tracks. Move a level with r.Level and a distance with r.Distance, or recompute from ctx.Series. It places no orders: the strategy acts on the new basis at its next decision. It runs straight after OnRoll, when the strategy also implements RollObserver. Every strategy on such a run is rebased, whether or not it implements the hook.

type RebaseObserver interface {
	OnRebase(ctx *Context, r Rebase)
}

ReplyDeclined

IBKR’s order reply messages (GLE-200 I6 unit 3b): IBKR answers an order submission that draws one of its precautions or warnings (an order size or value limit, a price too far from the market, no market data, …) with a question the client must confirm or decline before the order is transmitted. The engine’s IBKR venue confirms only the message ids on the deployment’s allow-list (the run’s venue-reply-allow) and declines every other one, and a declined order is not transmitted. The decline reaches the strategy as the venue’s denial of the order: on lifetime v2, an OrderUpdate with Status OrderStatusDenied and a Reason that begins with ReplyDeclined and “: “, followed by the declined message ids and IBKR’s text (for people, not for parsing), then the OrderCancel{Rejected} that follows every venue denial; on v1, the OrderCancel{Rejected} alone, the text going to the operator’s denial line.

const (
	// ReplyDeclined: the venue declined an IBKR order reply message whose
	// message id is not on the deployment's allow-list, so the order was not
	// transmitted.
	ReplyDeclined = "reply_declined"
)

RollObserver

RollObserver is the opt-in continuous-futures roll hook (Section 8.9). A strategy that implements it receives OnRoll immediately after the engine updates the active-contract mapping; informational only, it cannot influence the roll. Implementing it sets InitAck.needs_rolls, gating RollNotice delivery.

rawGap is the SAME-BAR seam price difference removed at the roll (incoming_roll_price - outgoing_roll_price at the same instant) – the true price difference under every method. priceRatio is the multiplicative seam factor the ratio method removed (incoming/outgoing); it is 0 (unset) under the panama/unadjusted methods.

type RollObserver interface {
	OnRoll(symbol, from, to string, atDate time.Time, rawGap, priceRatio float64)
}

Run

Run hands the process over to the SDK (Section 7.9): input reflection, the –algolang-* flags, the stdout handshake, then the protocol loop until the engine sends Shutdown. It is the last call in a strategy’s main; a non-nil error means the process should exit non-zero.

When the first stdin line is not an “ALGO/” handshake line, the SDK falls back to raw stdio-csv-v1 replay mode (spec Section 12.1/B.3): stdin lines are processed as engine CSV lines and EOF is a clean shutdown. Replay-mode stdout still begins with the hello line, so pipe consumers can sed 1d it away.

func Run(s Strategy) error

SDKVersion

SDKVersion identifies this SDK build in the handshake hello line (Section 7.8).

func SDKVersion() string

SchemaFromConstruction

SchemaFromConstruction is the inverse of DataSchemaSpec.Construction for a bar series: the Bars schema carrying c’s bar kind, threshold mode and every construction parameter, with the given interval and session, not consolidated.

func SchemaFromConstruction(c barspec.Construction, interval, session string) DataSchemaSpec

SchemaKind

SchemaKind selects the data schema of a declared series (Section 7.13.3). Its values equal algolangpb.DataSchema_* so SchemaKind -> algolangpb.DataSchema is a faithful int cast in toPBDataRequirements (the SDK cannot import the proto package on its public surface — same value discipline as Side/OrderType and CorporateActionType). The two engine-internal schemas algolangpb.DataSchema CORPORATE_ACTIONS(=12) and ADJUSTMENT_FACTORS(=13) are deliberately NOT given named constants here: they are the engine’s corporate-action / price-adjustment schemas and are NOT declarable via a DataRequirement in this scope.

type SchemaKind int

SellLeg

func SellLeg(symbol string, ratio int64) ComboLeg

Series

Series is the lookback history view (Section 7.6). Bulk slice views are read-only views into the SDK’s internal ring buffer; their lifetime is the current OnBar call (the contract mirrors bufio.Scanner.Bytes()).

type Series interface {
	Len() int

	// Fresh is true when this series' latest bar closed at the current
	// decision point: its CloseTime equals ctx.Now() (Section 7.12).
	Fresh() bool

	// Indexed access; 0 is current, 1 is previous, etc.
	Bar(i int) Bar
	Open(i int) float64
	High(i int) float64
	Low(i int) float64
	Close(i int) float64
	Volume(i int) float64

	// Bulk views. The returned slices are valid only until the
	// next OnBar callback. Copy if you need to keep them.
	Opens() []float64
	Highs() []float64
	Lows() []float64
	Closes() []float64
	Volumes() []float64
}

SeriesAligner

SeriesAligner is the opt-in declaration of aligned series (GLE-353): views that carry one series’ latest value onto every bar of another series’ clock, so a 1d primary, a weekly COT report and a quarterly FRED series line up bar for bar. The SDK probes for it via a type assertion and builds every sample itself; the engine validates each declaration and fetches the source’s history far enough back to fill the view’s warm-up. See AlignedSeries.

type SeriesAligner interface {
	AlignedSeries() []AlignedSeries
}

SessionEraInfo

SessionEraInfo is one session era of the root’s timeline, kept for provenance (the windows are already computed under it). From is "” for an unbounded first era and To is "” for the era in force. Days, RTH, ETH, Cut, Continuous and Source are the era’s declaration as the data adapter records it.

type SessionEraInfo struct {
	From       string
	To         string
	Days       string
	RTH        string
	ETH        string
	Cut        string
	Continuous bool
	Source     string
}

SessionHandler

type SessionHandler interface {
	OnSessionStart(ctx *Context, s SessionInfo)
	OnSessionEnd(ctx *Context, s SessionInfo)
}

SessionInfo

type SessionInfo struct {
	SessionID string
	Time      time.Time
}

Shutdowner

type Shutdowner interface {
	OnShutdown(ctx *Context)
}

Side

type Side int

StatKind

StatKind is a venue statistic’s kind. Values equal algolangpb.StatType, so a kind the SDK does not name still arrives as its number.

type StatKind int16

StatisticHandler

StatisticHandler is the optional observer of declared STATISTICS series (GLE-406). OnStatistic runs once per statistic, in replay order, before the bar that follows its publication; ctx.Now() is its VisibleAt during the call. Observe-only, like OnMarketTrade.

type StatisticHandler interface {
	OnStatistic(ctx *Context, s MarketStatistic)
}

StopBuy

func StopBuy(symbol string, qty int64, stop float64) Order

StopLimitBuy

func StopLimitBuy(symbol string, qty int64, stop, limit float64) Order

StopLimitSell

func StopLimitSell(symbol string, qty int64, stop, limit float64) Order

StopSell

func StopSell(symbol string, qty int64, stop float64) Order

Strategy

Strategy is the required interface (Section 7.1).

type Strategy interface {
	// Name is a short display name. Appears in run manifests, optimiser
	// reports, strategy registries, and any UI listing the strategy.
	Name() string

	// Description is a brief human-readable description of what the
	// strategy does and when it's appropriate.
	Description() string

	// OnBar processes a single bar and returns any orders to submit. See
	// Section 6.8 for the bar/fill/cancel sequencing guarantees.
	OnBar(ctx *Context, bar Bar) ([]Order, error)
}

Summary

Summary is a member’s account figures, or the portfolio’s, as of the view. Equity, net profit and drawdowns are net of commission (the report’s equity curve); OpenPnL and RealizedPnL are gross (its trades).

type Summary struct {
	Member         string
	Capital        float64
	MarkedEquity   float64
	ClosedEquity   float64
	NetProfit      float64 // MarkedEquity - Capital
	ReturnToDate   float64 // NetProfit / Capital; 0 without capital
	OpenPnL        float64
	RealizedPnL    float64
	Commission     float64 // every fill's, so far
	PeakEquity     float64
	Drawdown       float64 // PeakEquity - MarkedEquity
	DrawdownPct    float64 // Drawdown / PeakEquity
	MaxDrawdown    float64
	MaxDrawdownPct float64
	GrossExposure  float64 // base currency, at the marks
	NetExposure    float64
	Margin         float64 // initial margin in use; 0 when none is modelled
	OpenPositions  int
	FirstBar       time.Time
	// HasStatistics is false when the run keeps no statistics (a backtest
	// with --report off): the equity and drawdown figures are then zero.
	HasStatistics bool
}

SupportedProtocols

SupportedProtocols returns the strategy-wire protocols this SDK speaks, in preference order. The engine makes the final choice (Section 8.3); it offers stdio-csv-v2 only on a run that puts order lifetime v2 in effect (GLE-200 I10), and an engine that predates it ignores the token.

func SupportedProtocols() []string

SymbolTotal

SymbolTotal is the portfolio’s position in one logical symbol over every member. Short is positive: the quantity held short. IfAllFilled is Net plus the working buys less the working sells.

type SymbolTotal struct {
	Symbol                    string
	Net, Gross, Long, Short   int64
	MembersLong, MembersShort int
	NetNotional               float64 // base currency
	GrossNotional             float64
	WorkingBuy, WorkingSell   int64
	IfAllFilled               int64
}

ThresholdMode

ThresholdMode selects how an IMBALANCE or RUNS bar closes (Section 8.4.12). Values equal algolangpb.ThresholdMode_*.

type ThresholdMode int

TickSizeSource

TickSizeSource says where an InstrumentInfo’s tick size came from; "” = undisclosed (an adapter that predates the field).

type TickSizeSource string

TimeInForce

type TimeInForce int

TimerFired

TimerFired is one scheduled decision: the timer ID, armed for the instant At, fires at the decision instant FiredAt. A zero time stands for an instant the wire did not carry.

During OnTimer, ctx.Now() is FiredAt (not At). No bar travels with a timer: the series and the bar counts do not move and the account is not pushed again, a series is Fresh only when its newest bar closed at FiredAt, and ctx.DataAge reports each series’ staleness.

type TimerFired struct {
	ID      string
	At      time.Time
	FiredAt time.Time
}

TimerHandler

TimerHandler decides at the timers the strategy arms (lifetime-v2 only). The SDK calls OnTimer for each TimerFired and answers it exactly as it answers a Bar: the cancel requests queued with ctx.Cancel go out first, then the timer commands queued with ArmTimer, ArmSessionTimer and CancelTimer in issue order, then an OrderResponse carrying the returned orders, each labelled (a blank ClientID becomes an automatic one) and tracked at FiredAt, with its attempt stamped under lifetime v2. A strategy without the handler answers every timer with an empty response (its queued commands still go out). An error ends the run, as an OnBar error does.

type TimerHandler interface {
	OnTimer(ctx *Context, t TimerFired) ([]Order, error)
}

TimerRefusalHandler

TimerRefusalHandler observes the engine’s refusals of the strategy’s timers (lifetime-v2 only); no reply. The SDK calls OnTimerRefused for each TimerRefused the engine sends, whether it refused the arm or could not honour the timer at its instant, and changes no Context state for it: a refusal is not a decision, so Now stays the last decision’s. Commands the handler queues go out with the reply to the next decision. A strategy without the handler goes on as if nothing came.

type TimerRefusalHandler interface {
	OnTimerRefused(ctx *Context, r TimerRefused)
}

TimerRefusalInvalid, TimerRefusalNotFuture, TimerRefusalAfterEnd, TimerRefusalCalendarIncomplete, TimerRefusalLimit, TimerRefusalCoarse

The codes of a TimerRefused, in TimerRefused.Code: the engine’s refusal codes. The engine checks an arm in a fixed order and refuses it with the first rule that fails: timer_invalid (an empty id or an unset instant), timer_not_future (an instant not after the decision), timer_after_end (an instant after the run’s end), calendar_incomplete (an anchored timer whose calendar is not complete up to the instant) and timer_limit (a new id when 4096 timers are already armed). timer_coarse is not an arm’s refusal: the engine reports it at the timer’s instant, when the bars are too coarse for it to decide there. The Reason of a refusal starts with its code.

const (
	TimerRefusalInvalid            = "timer_invalid"
	TimerRefusalNotFuture          = "timer_not_future"
	TimerRefusalAfterEnd           = "timer_after_end"
	TimerRefusalCalendarIncomplete = "calendar_incomplete"
	TimerRefusalLimit              = "timer_limit"
	TimerRefusalCoarse             = "timer_coarse"
)

TimerRefused

TimerRefused is the engine’s refusal of one timer: ID and At as the strategy armed it (At zero when the arm had none), a stable Code (one of the TimerRefusal constants), the engine’s Reason text (it starts with Code) and the Timestamp of the refusal (zero when the wire carried none).

Timestamp is the instant of the decision that armed the timer or, for TimerRefusalCoarse, the timer’s own instant. A refusal is an observation, not a decision: it moves no clock.

type TimerRefused struct {
	ID        string
	At        time.Time
	Code      string
	Reason    string
	Timestamp time.Time
}

TouchBuy

TouchBuy / TouchSell build a first-touch stop (Tier-1 T1.6, OrderType StopTouch): a stop that may rest on the WRONG side of the last price and fills at the first touch at-or-through its level (buys at max(open, stop), sells at min(open, stop)) — the backtest-parity form of the legacy AtOrHigher/AtOrLower breakout. Unlike StopBuy/StopSell it is never rejected for resting through the market, so a strategy that has already computed “the market is past my level” need not transform to a market order. Backtest-only: rejected on the IBKR live map.

func TouchBuy(symbol string, qty int64, stop float64) Order

TouchSell

func TouchSell(symbol string, qty int64, stop float64) Order

TradeDateLayout

TradeDateLayout is the time.Parse layout of every calendar date string (TradeDate, CoverageFrom, CoverageTo, EraFrom): YYYY-MM-DD.

const TradeDateLayout = wire.TradeDateLayout

TradeSide

TradeSide picks a statistics column: every trade, the long trades or the short trades (the report’s All, Long and Short).

type TradeSide int

TradeState

TradeState is the position-lifecycle snapshot the SDK maintains per symbol (Tier-1 T1.1): the entry snapshot, bars-held count, trailing extremes, and this-bar transitions the legacy engine used to hand a strategy — graduated out of strategies/kit.Tracker into the SDK, which owns the fill/bar stream authoritatively. Obtain it with ctx.Trade(bar) once per PRIMARY bar (the drop-in for the old tr.Update(ctx.Position(sym), bar)), or read the last snapshot without advancing with ctx.TradeState(symbol).

It is a value snapshot: reading it never mutates engine state. The restart caveat that applied to kit.Tracker applies here unchanged — BarIdx / BarsSinceEntry are per-PROCESS bar counters (exact in backtest; after a live restart mid-position they recount from the first post-restart bar), while EntryTime is seeded from the SDK’s restart-recovered Position.OpenedAt (F1) so TimeInTrade stays exact across a restart.

type TradeState struct {
	Symbol   string
	Quantity int64 // signed position at this bar (the old Update return value)

	BarIdx   int // count of primary bars advanced through Trade (1-based)
	EntryBar int // BarIdx at which the current position opened

	// Entry snapshot, captured on the flat->position transition (one bar after
	// the signal, when the fill is first observable — the accepted convention).
	EntryPrice float64
	EntryHigh  float64
	EntryLow   float64
	// EntryTime is p.OpenedAt at entry (F1): the TRUE original entry time,
	// restart-correct. Zero when flat.
	EntryTime time.Time

	// Peak / Trough are the highest high / lowest low since entry — the anchors
	// for trailing-stop levels.
	Peak, Trough float64

	// JustEntered / JustExited / JustAdded report this bar's transition. JustAdded
	// is a same-side size INCREASE (pyramid add): the hold clock and entry price
	// re-anchor to the add while Peak/Trough keep running. JustAdopted reports the
	// live-restart case (first advance already saw an OPEN position whose OpenedAt
	// predates the bar); never set in a pure backtest.
	JustEntered, JustExited, JustAdded, JustAdopted bool

	// LastLossBar is the BarIdx on which the most recent LOSING position was
	// observed closed (close beyond the held average in the losing direction),
	// 0 if none — the loser-cooldown anchor. This uses the close-vs-average
	// APPROXIMATION kit.Tracker used; for the EXACT realized-PnL loser test use
	// kit.LoserCooldown built on ctx.Position(sym).Realized (T1.2 / T2.3).
	LastLossBar int
}

TradeState.BarsSinceEntry

BarsSinceEntry returns the number of primary bars this PROCESS has observed the current position open (0 on the observation bar itself).

func (t TradeState) BarsSinceEntry() int

TradeState.InCooldown

InCooldown reports whether a WaitBarsAfterLoser-style entry cooldown is active under the close-vs-average loser approximation: waitBars > 0, a loss has occurred, and fewer than waitBars primary bars have elapsed since it.

func (t TradeState) InCooldown(waitBars int) bool

TradeState.TimeInTrade

TimeInTrade returns the exact wall-clock elapsed since the current position’s TRUE entry (now - EntryTime, EntryTime == Position.OpenedAt), zero when flat. Restart-correct (F1).

func (t TradeState) TimeInTrade(now time.Time) time.Duration

TradeStats

TradeStats is one statistics column: the report’s All, Long or Short column over the trades so far, on gross trade P&L. A ratio that cannot be computed yet (no losing trade, say) has its Has flag false.

type TradeStats struct {
	Trades                int // closed
	OpenTrades            int
	Winners, Losers       int
	Even                  int
	PercentProfitable     float64 // Winners / Trades
	GrossProfit           float64
	GrossLoss             float64 // <= 0
	ProfitFactor          float64
	HasProfitFactor       bool
	NetProfit             float64 // the closed trades' gross P&L
	AverageTrade          float64
	AverageWinner         float64
	AverageLoser          float64
	Payoff                float64 // AverageWinner / -AverageLoser
	HasPayoff             bool
	LargestWinner         float64
	LargestLoser          float64
	MaxConsecutiveWinners int
	MaxConsecutiveLosers  int
	AverageBars           float64
	Commission            float64 // the column's trades', open ones included
	Slippage              float64
	OpenPnL               float64
}

TradeableDeclarer

TradeableDeclarer is the opt-in, additive admission of symbols to the venue universe (Sections 7.2, 7.13.2). The SDK probes for it via a type assertion. The returned symbols are added to the set the engine permits orders on, on top of the run’s configured symbols; “see a symbol’s data” (DataRequirer) and “trade a symbol” (TradeableDeclarer) are orthogonal. Like DataRequirer, implementing it sets InitAck.needs_instruments (Section 7.13.5). Carried in InitAck.tradeable_symbols. Optional and additive: an OnBar-only strategy declares nothing and behaves exactly as a config-driven run.

type TradeableDeclarer interface {
	TradeableSymbols() []string
}

TradingDay

TradingDay is the calendar record of one trade date (GLE-200 I11).

TradeDate (YYYY-MM-DD) is the identity. [SpanStart, SpanEnd) is the half-open set of instants the date owns. Under an overnight session a weekend owns no span and has no record; its instants belong to Monday.

The record rule has three special cases:

  • A holiday that owns a span is Closed with no windows.
  • A closed weekday of a per-weekday era is Closed, with WeekdayState “closed-weekday”.
  • A date the holiday table does not know has ClosedKnown false, RTHState “unknown” and no windows.

ETH holds the legs in ascending order with the early close applied. RTH is set iff RTHState is “open”. EarlyCloseAt is set iff EarlyClose and EarlyCloseKnown; an early close whose time is unknown must refuse precise use. DayCancel is the session at whose close a DAY order is cancelled, and is set only with DayCancelBasis “assumed”. EraFrom is the era in force ("" for an unbounded first era).

A zero time is an instant the wire did not carry.

type TradingDay struct {
	// TradeDate is the date's identity, YYYY-MM-DD (TradeDateLayout).
	TradeDate string
	// SpanStart is the first instant this date owns; the span is the half-open
	// interval [SpanStart, SpanEnd).
	SpanStart time.Time
	// SpanEnd is the first instant after the span.
	SpanEnd time.Time
	// Closed is a full-day closure, or a closed weekday of a per-weekday era.
	Closed bool
	// ClosedKnown reports that the holiday table knows this date; false outside
	// the table's range or when the venue has no table.
	ClosedKnown bool
	// EarlyClose reports an early close on this date.
	EarlyClose bool
	// EarlyCloseKnown reports that the early close's time is known; an early
	// close with this false must refuse precise use.
	EarlyCloseKnown bool
	// EarlyCloseAt is the early-close instant; set iff EarlyClose and
	// EarlyCloseKnown.
	EarlyCloseAt time.Time
	// ETH holds the date's extended-hours legs, ascending, early close applied;
	// empty when the date is closed or declares none.
	ETH []TradingWindow
	// RTH is the regular-hours window; non-nil iff RTHState is RTHStateOpen.
	RTH *TradingWindow
	// RTHState is one of the RTHState constants.
	RTHState string
	// DayCancel is the session at whose close a DAY order is cancelled; set
	// only with DayCancelBasis DayCancelAssumed.
	DayCancel *TradingWindow
	// DayCancelBasis is DayCancelAssumed or DayCancelUnknown.
	DayCancelBasis string
	// EraFrom is the first date of the session era in force; empty for an
	// unbounded first era.
	EraFrom string
	// WeekdayState is WeekdayTrading or WeekdayClosedWeekday.
	WeekdayState string
}

TradingWindow

TradingWindow is a window of trading (GLE-200 I11). Close is the close instant, and the closing second belongs to the window, as the intraday grid places it: treat a window as the closed interval [Open, Close]. Early marks a Close that is the holiday table’s early close. A zero Open or Close is an instant the wire did not carry.

type TradingWindow struct {
	// Open is the instant the window opens.
	Open time.Time
	// Close is the close instant; the closing second belongs to the window.
	Close time.Time
	// Early reports that Close is the holiday table's early close.
	Early bool
}

TrailingStopBuy

func TrailingStopBuy(symbol string, qty int64, trail float64) Order

TrailingStopSell

func TrailingStopSell(symbol string, qty int64, trail float64) Order

TransportQueued, TransportOverload, TransportShutdown

The engine’s transport scheduler (GLE-200 I6 unit 3, order lifetime v2) paces a live run’s requests to the venue: it sends at most a configured number of submissions and cancel requests within any window of the run’s operational clock, every queued cancel request ahead of every queued submission, and it queues what the window does not cover, or what the venue refused for pacing, until the window allows. Its decisions reach the strategy as OrderUpdate events: Status OrderStatusHeld with a Reason that begins with TransportQueued and “: " while a submission waits (released as OrderStatusWorking, Denied or SubmissionUnknown when it is sent); on a refusal, Status OrderStatusDenied with a Reason that begins with one of the other tokens below and “: " (the rest of the text is for people, not for parsing). A refused submission did not reach the venue, and no OrderCancel{Rejected} follows the denial. A cancel request for a submission that is still queued withdraws it without reaching the venue (a confirmed CancelResponse); a queued cancel request is answered when it is sent, or, when the run ends first, with CancelOutcomeUnknown and a Reason that begins with TransportShutdown and “: " (every cancel request gets one response).

const (
	// TransportQueued: the submission is queued for the venue, behind the
	// transport window or after the venue refused it for pacing.
	TransportQueued = "transport_queued"
	// TransportOverload: the transport queue already held the run's maximum
	// number of submissions.
	TransportOverload = "transport_overload"
	// TransportShutdown: the run ended while the submission (Denied) or the
	// cancel request (a CancelResponse with CancelOutcomeUnknown) was queued.
	TransportShutdown = "transport_shutdown"
)

TurnHandler

TurnHandler decides on lifecycle turns (lifetime-v2 only). The SDK calls OnLifecycleTurn for each LifecycleTurn envelope and answers it exactly as it answers a Bar: the cancel requests queued with ctx.Cancel (by the handler, or by an observer before the turn) go out first, then an OrderResponse carrying the returned orders, each stamped with its label’s next attempt and tracked in the working view. A strategy without the handler answers every turn with an empty response (its queued cancel requests still go out). An error ends the run, as an OnBar error does.

type TurnHandler interface {
	OnLifecycleTurn(ctx *Context, t LifecycleTurn) ([]Order, error)
}

UniverseHandler

UniverseHandler is the optional hook for the resolved-universe push (Sections 7.13.4, 7.13.5, Phase 6). The SDK probes for it via a type assertion, exactly like AdoptHandler/RollObserver. Implementing it sets InitAck.needs_instruments (the needs_rolls/RollNotice capability idiom), gating the engine’s post-Init InstrumentsResolved delivery. OnUniverseResolved runs once, after the SDK has seeded the instrument map (so ctx.Instrument(sym) is correct) and before any warmup bar — for abort/validation. Returning a non-nil error refuses the run, mirroring OnAdoptedState. A strategy with no UniverseHandler still has ctx.Instrument() seeded automatically (sizing needs no hook). NeedsInstruments is ALSO set by DataRequirer/TradeableDeclarer, so a declaring strategy receives the push and a populated ctx.Instrument() even without implementing this hook.

type UniverseHandler interface {
	OnUniverseResolved(ctx *Context) error
}

Visibility

Visibility is what the portfolio file lets a member see (spec §7.3). The zero value is unknown.

type Visibility int

WeekdayTrading, WeekdayClosedWeekday

TradingDay.WeekdayState. WeekdayClosedWeekday marks a closed weekday of a per-weekday era, always with Closed set.

const (
	WeekdayTrading       = wire.WeekdayTrading
	WeekdayClosedWeekday = wire.WeekdayClosedWeekday
)

WorkingOrder

WorkingOrder is an order the strategy submitted that is neither filled nor cancelled (Section 7.5).

type WorkingOrder struct {
	Order       Order
	SubmittedAt time.Time

	// Order lifetime v2 (GLE-200 I3): one attempt's state in the
	// attempt-indexed working view a run that negotiated lifetime-v2 keeps
	// (Order.Attempt identifies the attempt). Status is the attempt's
	// lifecycle status, always a live one in the view; FilledQuantity and
	// RemainingQuantity its cumulative filled and still-working quantities;
	// ParentClientID the parent's label on an attached child; OrderRef the
	// engine's durable reference once an event carried it; CancelRequestID
	// the request id of the strategy's cancel request while it is pending
	// ("" when none is). All zero on a v1 run, whose view is unchanged.
	// ReplacesAttempt (GLE-200 I15) is the attempt this attempt replaced
	// when the engine re-placed the order (a continuous roll; the entry's
	// latest replacement), 0 for an attempt the strategy submitted.
	Status            OrderStatus `json:",omitempty"`
	FilledQuantity    int64       `json:",omitempty"`
	RemainingQuantity int64       `json:",omitempty"`
	ParentClientID    string      `json:",omitempty"`
	OrderRef          string      `json:",omitempty"`
	CancelRequestID   string      `json:",omitempty"`
	ReplacesAttempt   uint32      `json:",omitempty"`
}