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
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 int8AlignedSeries
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
}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) float64Bar.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() boolBar.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) float64Bar.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 intBarSession
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() float64BarStats.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() boolBoundary
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 uint16BoundaryAll
BoundaryAll is every boundary kind (63).
const BoundaryAll = BoundaryRTHOpen | BoundaryRTHClose | BoundaryETHOpen | BoundaryETHClose | BoundaryDayCancelClose | BoundarySpanEndBracket
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) OrderCalendar
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) errorCalendar.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.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() ExchangeCalendarCalendar.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() stringCalendar.Root
Root returns the root the calendar serves, for example “fut:XCME:ES”.
func (c Calendar) Root() stringCalendar.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() stringCalendarIncompleteError
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() stringCalendarKindETH, 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.
func CalendarRoot(symbol string) stringCancelHandler
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 intCancelOutcome.String
String renders o in lower snake case (“confirmed”); a value outside the
enumeration renders as cancel_outcome_
func (o CancelOutcome) String() stringCancelReason
type CancelReason intCancelResponse
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)
}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.CapabilityLifetimeV2CapabilityRequirer
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
}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() AccountStateContext.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.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) intContext.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.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) float64Context.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) float64Context.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) []MarketDefinitionContext.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) ExposureContext.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) boolContext.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) InstrumentInfoContext.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) boolContext.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.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.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) []MarketStatisticContext.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) []MarketTradeContext.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.TimeContext.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) PositionContext.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() stringContext.RunID
RunID returns the engine-assigned run identifier.
func (c *Context) RunID() stringContext.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) SeriesContext.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) TradeStateContext.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) TradeStateContext.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() []WorkingOrderCorporateActionNotice
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 intCorporateActionType
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 intDataRequirement
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.ConstructionDayCancelAssumed, 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
)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)
}ErrInvalidCalendar
ErrInvalidCalendar is the sentinel every NewCalendar error wraps.
var ErrInvalidCalendar = errors.New("invalid calendar")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-v1".
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"`
}Fill.AdjustedPrice
AdjustedPrice returns the strategy-visible (adjusted) fill price, falling back to Price when no override is set.
func (f Fill) AdjustedPrice() float64Fill.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() float64FillHandler
type FillHandler interface {
OnFill(ctx *Context, fill Fill)
}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) OrderGuardHeld, GuardDuplicateLiveLabel, GuardCancelRace, GuardCancelRefused, GuardCancelUnknown, GuardHoldTimeout, GuardShutdown
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).
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"
)HelloLine
HelloLine is the handshake line the SDK writes to stdout on startup (Section 7.8), without the trailing newline.
func HelloLine() stringHolidayTableInfo
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"`
}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): today only CapabilityLifetimeV2. 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"`
}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) OrderLimitSell
func LimitSell(symbol string, qty int64, price float64) OrderLookbacker
type Lookbacker interface {
Lookback() int
}MarketBuy
func MarketBuy(symbol string, qty int64) OrderMarketDefinition
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
}MarketOnCloseBuy
MarketOnCloseBuy / MarketOnCloseSell build a market-on-close order (F4a): submitted from OnBar(bar N) it settles at bar N’s close — the price the strategy just observed — never at a future bar. Price/StopPrice MUST stay zero (the simulator rejects a level on an MOC as misuse). TIF is irrelevant in the simulator and the emulator (the MOC settles the bar it is submitted into and never rests); live, IBKR receives a DAY MOC ticket that rests until the closing auction.
func MarketOnCloseBuy(symbol string, qty int64) OrderMarketOnCloseSell
func MarketOnCloseSell(symbol string, qty int64) OrderMarketSell
func MarketSell(symbol string, qty int64) OrderMarketStatistic
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.TimeMarketTrade
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)
}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)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"`
}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 intOrderStatus.String
String renders s in lower snake case (“pending_cancel”); a value outside
the enumeration renders as order_status_
func (s OrderStatus) String() stringOrderStatus.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() boolOrderType
type OrderType intOrderUpdate
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.
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
}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)
}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"
)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 intRTHStateOpen, 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
)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) errorSDKVersion
SDKVersion identifies this SDK build in the handshake hello line (Section 7.8).
func SDKVersion() stringSchemaFromConstruction
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) DataSchemaSpecSchemaKind
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 intSeries
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 intStatKind
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 int16StatisticHandler
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) OrderStopLimitBuy
func StopLimitBuy(symbol string, qty int64, stop, limit float64) OrderStopLimitSell
func StopLimitSell(symbol string, qty int64, stop, limit float64) OrderStopSell
func StopSell(symbol string, qty int64, stop float64) OrderStrategy
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)
}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() []stringThresholdMode
ThresholdMode selects how an IMBALANCE or RUNS bar closes (Section 8.4.12). Values equal algolangpb.ThresholdMode_*.
type ThresholdMode intTimeInForce
type TimeInForce intTouchBuy
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) OrderTouchSell
func TouchSell(symbol string, qty int64, stop float64) OrderTradeDateLayout
TradeDateLayout is the time.Parse layout of every calendar date string (TradeDate, CoverageFrom, CoverageTo, EraFrom): YYYY-MM-DD.
const TradeDateLayout = wire.TradeDateLayoutTradeState
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() intTradeState.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) boolTradeState.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.DurationTradeableDeclarer
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) OrderTrailingStopSell
func TrailingStopSell(symbol string, qty int64, trail float64) OrderTransportQueued, 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
}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.
Status OrderStatus `json:",omitempty"`
FilledQuantity int64 `json:",omitempty"`
RemainingQuantity int64 `json:",omitempty"`
ParentClientID string `json:",omitempty"`
OrderRef string `json:",omitempty"`
CancelRequestID string `json:",omitempty"`
}