Data, decisions, and fills

Before writing a strategy, separate three responsibilities:

marketfeed archive -> data adapter -> Algolang engine <-> strategy process
                                          |
                                  simulator and reports

Marketfeed acquires and stores observations; its adapter serves the requested series. Algolang assembles the run, advances its event clock, maintains the account, simulates orders and records results. The strategy consumes what is known at each decision and proposes orders. It does not fetch vendor data itself. Only marketfeed talks to Databento; Algolang’s bundled databento adapter reads recorded files for tests and examples.

What marketfeed supplies

Data productWhat a strategy gains
Historical OHLCV and, where stored, trade printsTime bars, finer execution paths, or activity bars built from the tape
Canonical identities and instrument metadataExchange, tick size, point value, currency and served margin information
Exchange calendars and session barsTrade dates, regular/extended sessions, early closes and settlement metadata
Continuous futures composites and roll schedulesA logical futures series, its held contracts, raw prices and adjustment constants
Equity adjustment streams and corporate actionsSplit/dividend-aware prices and supported position accounting
Release-stamped COT, economic and FX observationsValues available at a publication instant, with their reference periods
Statistics, instrument definitions and contract listingsOpen interest, published settlements and the listed futures curve where available
Live gateway streamsBars, quotes and relevant events for supported live workflows

These are capabilities, not a promise that every symbol and era is populated. Check coverage, calendar completeness and data notes for the exact run. A successful exit can still accompany a short warm-up or less history than you requested: compare the actual first and last bars with the intended study window before interpreting its duration. A five-minute bar can be built from one-minute history; that same history cannot be refined into true thirty-second bars. An intrabar path preserves stored constituents; it cannot recreate an absent tape.

Marketfeed now streams session-anchored intraday grids for dated futures and raw equities. History and subscription use the same grid revision; a changed calendar refuses the subscription instead of silently changing its windows. Bars restart at each session window and its last bar can be short. Continuous futures grids, paths on grid bars and adjusted-equity grids still cannot stream. Check capabilities before promoting a historical multi-series run to a live configuration.

Activity bars and trade-print subscriptions also remain unavailable from marketfeed’s live source. Its equity live feed has different volume coverage from the archive’s venue tape. A volume threshold calibrated on one feed can behave differently on the other even when prices look similar.

Names describe the instrument, not its interval:

ExampleMeaning
eq:ARCX:SPYEquity/ETF, raw price view
eq:ARCX:SPY:adj=splitSplit-adjusted equity price view
fut:XCME:ESContinuous E-mini S&P 500 root
fut:XCME:ES:Z25A particular dated futures contract
fut:XCME:ES:cont:ofs=B1:adj=noneRaw deferred composite, one held rank behind the front
macro:FRED:GDPEconomic series served by publication time
cot:CFTC:13874A:LFLeveraged-funds positioning report for the indicated contract market

Do not substitute acquisition aliases such as ES.c.0. The exchange portion is part of the identity. A data-only index or synthetic spread may be a useful signal without being a tradeable instrument.

Instruments, series and the universe

An instrument identifies a market or reference. A series identifies the observations you receive for it. The same instrument might have a daily series for trend and a five-minute series for entries. Those streams have different timestamps and history depths even though both refer to the same holding. A series can also contain published economic observations rather than tradeable prices.

The run’s universe is its collection of configured instruments. The first configured instrument is the primary; a strategy can use it as its main decision clock. Additional data can be configured outside the strategy or declared by the strategy at startup. Each stream can have a SeriesID, a stable name such as trend or gdp. When absent, the SDK keys its bar buffer by the symbol. Use that identity consistently when requesting history.

Two permissions are separate: receiving a symbol’s observations and trading that symbol. A data-only reference helps decide what to do but does not become a permissible order destination merely because its price is in a buffer. Later chapters show reference-only expansion and explicit tradeable-symbol declarations. These declarations are startup requirements, not HTTP calls made by the strategy on each bar.

What a bar does and does not contain

OHLCV means open, high, low, close and volume. A time bar summarizes a window; an activity bar instead closes after a volume, trade-count or other construction threshold. The close is the last observation in that bar’s construction, not necessarily an exchange’s official settlement price.

Bar factHow to interpret it
Open and close timesThe bar’s observation window and completion instant. Use the delivered timestamps, not a guessed duration.
Open / high / low / closeThe prices the strategy’s selected view exposes. They do not establish the sequence of every intrabar touch.
VolumeQuantity counted by the source and construction; different feeds can cover different trading activity.
Symbol and SeriesIDThe instrument and the particular stream. Gate decisions on the intended stream.
Session and trade date, when servedExchange-calendar context. An overnight session’s trade date can differ from its opening calendar date.
Raw prices and active contract, when suppliedThe venue price and held dated contract underlying an adjusted continuous series.

A one-minute window ending at 10:31 is actionable once its completed bar is delivered. A trade exactly at a construction boundary can belong to the next window. Session bars can have special close stamps and short final windows: use their served facts. Never infer an “official close” by simply adding an interval or comparing a timestamp’s printed hour.

An instant and its local display are different concepts. 10:00-05:00 and 15:00Z identify the same instant. The exchange calendar determines which session that instant belongs to. New York and London change daylight saving on different dates, so a fixed conversion such as “London is always five hours ahead” is wrong. The cross-exchange chapter supplies a fixture that tests this directly.

History, indicators and information available now

The current bar alone cannot produce a 200-day moving average. A strategy declares lookback, the retained history it needs. The engine tries to provide warm-up, observations before the requested trading start, and the SDK stores them without invoking OnBar. Lookback is a buffer requirement; warm-up is the data actually supplied. A short archive can leave the buffer incomplete, so the strategy must still check its length.

In the SDK’s indexed series view, index 0 is the newest bar, index 1 the previous bar. Bulk columns, such as all closes, are ordered oldest first. indicators.Closes(series) supplies that column to nseries. An SMA is the arithmetic mean of the last N closes. A crossover compares the previous relationship of two averages with the current relationship; hence a 20/200-day cross needs at least 201 daily closes, not merely 200.

Indicator availability must be checked explicitly. Some indicator prefixes contain seed or raw values rather than fully formed calculations. Changing the bar interval changes what “N periods” means. A daily and hourly average of the same length answer different questions, and a repeated economic value carried over daily bars does not create new economic releases.

With several series, a buffered value may be old. Freshness asks whether the latest bar closed at this decision; age asks how long ago its source observation became available. Alignment places streams on a common decision grid using an explicit rule, usually the latest information already known. It must not borrow a later bar just because that bar makes a table look complete. For economic data, the reference month, publication instant and revision vintage are separate facts.

Prices, quantities and account state

A tick is the instrument’s minimum price increment. Point value is the money change for a one-point move in one unit. For ES, a 0.25-point tick with USD 50 point value is USD 12.50 per contract. Two contracts multiply that exposure by two. A futures contract’s quoted price is not the cash amount paid to acquire it; margin and exposure are separate from the strategy’s initial account capital.

An adjusted series provides a consistent basis for indicators across events such as contract rolls or equity splits. A raw price is the dated contract’s or share’s venue price at that time. The engine bridges these views for supported logical-symbol orders. Combining an adjusted level with a raw-priced dated-contract order without conversion is a price error, not a different choice of indicator. The continuous-futures chapter shows both the adjustment and order-addressing paths.

Realized P&L comes from closed exposure. Unrealized P&L marks what is still held against the current price. Marked equity includes both and the accounted costs. The SDK exposes actual position, working orders, account state and requested portfolio statistics. These enquiries have different scopes: a member’s position is not automatically the aggregate position of every strategy sharing an account.

Decisions, working orders and the small SDK interface

A market order requests execution when eligible. A limit constrains its acceptable price; a stop activates when its trigger is reached. Attached orders and combos express relationships among orders or legs. An order can be admitted and remain working, partially fill, finish, be refused, or be cancelled. Requesting cancellation is not confirmation that cancellation has completed. Use the order view and notifications to determine what happened.

The ordinary Day time-in-force follows its supported session cancellation boundary. GTC means good till cancelled under the supported venue rules; it is not a guarantee against every expiry, roll or venue event. An explicit one-bar expiry is a separate policy. These distinctions become practical in the resting-stop, bracket and timer strategies.

Every Go strategy implements three methods: Name and Description identify it, while OnBar reads a completed bar and returns an order list plus an error. The main function calls algolang.Run to hand control to the SDK. The ctx argument is the SDK’s Context, the strategy’s view of the run: its clock, series, positions, orders and logging facilities. A nil order list means there is nothing to submit at this decision.

Optional interfaces add behavior. OnInit validates inputs before decisions; Lookback requests history; data declarations request extra series; OnFill observes executions. A tagged exported Go field becomes a configurable input, with defaults and constraints applied by the SDK. Untagged fields are private program state. They persist in that process but do not automatically survive a restart or become correct just because a live position was adopted.

The SDK discovers these interfaces by their exact method signatures. There is no polling loop to write and no callback registration file. The full event chapter distinguishes the three order-producing callbacks from notifications; at first, OnBar is enough. Keep signal calculations deterministic, derive exposure from fills, and retain extra state only when the calculation needs it.

The clock is part of the strategy

OnBar sees a completed bar. An ordinary market order returned from it first participates in the next bar’s path, normally at the next open plus slippage. A signal using today’s close therefore cannot buy at today’s open. The final signal may have no later bar to fill on, and an open position at the end is not automatically a completed trade.

Warm-up supplies earlier bars to indicator buffers without trading them or calling OnBar. Always guard against insufficient history anyway. A crossover requires two complete average values; a 200-period average crossover therefore needs 201 bars. Session days are not calendar days, and a 200-period average becomes a 200-hour average if you change the run to hourly bars.

At equal close times, ordinary reference series are processed before the primary, and release-stamped series after it. A macro release at exactly a primary bar’s close is consequently not available to that primary decision. Timers at that instant run after the bars. Do not assume that every event carrying the same timestamp has already reached your callback.

Each series advances in close-time order. Time bars must close strictly later than the preceding bar of that series; activity bars may share a timestamp. On a real-time feed an exact repeated time bar is dropped with a note; other out-of-order delivery stops the run. This per-series guarantee does not mean different markets always arrive together: a live run waits only briefly for co-closing peers. Keep the freshness checks in the cross-exchange example.

Put costs in from the first experiment

Both commissions and slippage default to zero. Set them deliberately. --commission-per-share charges per share or futures contract on each fill; --commission-per-order adds a flat charge per fill, despite its name. They can both apply. --slippage-ticks moves market-style fills adversely by that many instrument ticks. Limits use their own fill rule; this is not a universal spread model applied to every order.

For a one-contract ES round trip, illustrative assumptions of USD 2.50 per contract per side and one tick per side imply USD 5 commission and USD 25 slippage if the tick is 0.25 and the point value is USD 50. That is USD 30 before any extra fills, including rolls. These are arithmetic examples, not a broker quote. Obtain your own costs and test harsher assumptions too.

Inspect tick size, point value and currency, rather than treating one share and one futures contract as comparable exposure. --margin-model report reports margin requirements but does not block entries; enforce also denies entries that fail its initial-margin check. Neither promises automatic margin-call liquidation. Later chapters add order and portfolio controls.

Hello and the capability declaration

Before writing orders, inspect Hello, the smallest observer. It logs each bar and returns no orders. Its complete source follows. The full event journal later explains every callback and its delivery rules; the next chapter begins trading with a 20/200-day crossover.

algolang.CapabilityLifetimeV2 is not deprecated or removed in this SDK. It remains the token for accepting the engine’s order-lifetime contract. Hello now declares it through RequiredCapabilities, so startup refuses an engine that does not offer it. Some earlier examples still use SupportedCapabilities, which accepts a capability when offered without requiring it. Support and requirement are not the same thing: the migration to one order lifetime is moving the supplied strategies to the required form.

Hello also implements OneBarRule() bool, returning true. This asks the engine to expire eligible unfilled resting orders after the next bar; market orders and several other order classes are exempt. Hello places no orders, but demonstrates the declaration used by the migrated strategies. Per-order OneBar, CancelAt and CancelAfter fields remain available. These expiry controls do not remove the capability handshake. Historical v1/v2 terminology is not a reason to delete a token still used by this SDK. The prose and examples here follow the implementation in this checkout.

Complete source: hello

The numbered reading notes below explain the complete program; the inline comments describe individual steps. Keep all the listed files together. MODULE means the module path printed by go list -m in this checkout.

  1. Name, Description and OnBar are the required strategy interface. This program observes bars and returns an empty order list.

  2. RequiredCapabilities requires the engine’s order-lifetime contract; OneBarRule opts into engine-managed expiry for eligible resting orders. CapabilityLifetimeV2 is still the active SDK token during the migration.

  3. ctx.Logf keeps messages off protocol stdout. main delegates the event loop to algolang.Run and reports a fatal error on stderr.

Build the supplied files directly:

go build -o bin/hello ./strategies/demo/go/hello
bin/hello --algolang-describe

This program requires engine capabilities. The current standalone --algolang-selftest offers none, so it intentionally refuses this program during negotiation. Inspect its inputs with --algolang-describe and use the chapter’s engine run to exercise it; do not remove the capability requirement to make a standalone probe pass.

hello/main.go

// Command hello is the simplest possible Algolang strategy: it logs each
// bar's symbol and close, and never trades.
package main

import (
    "fmt"
    "os"

    algolang "MODULE/sdk/strategy"
)

// buildID is stamped by the Makefile via -ldflags.
var buildID string

type Hello struct{}

func (h *Hello) Name() string        { return "Hello" }
func (h *Hello) Description() string { return "Logs every bar; the smallest possible strategy." }

// RequiredCapabilities declares the one order lifetime (GLE-1906): the
// strategy requires lifetime v2. It places no order, so the one-bar rule
// (OneBarRule) has nothing to end.
func (h *Hello) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule turns the engine's one-bar rule on, as every strategy on the one
// order lifetime does.
func (h *Hello) OneBarRule() bool { return true }

func (h *Hello) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    ctx.Logf("hello: %s closed at %g", bar.Symbol, bar.Close)
    return nil, nil
}

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

Previous: Build, install, and run · Next: A 20/200-day crossover