An event journal: every strategy callback

An event journal: every strategy callback

The earlier strategies used events as they needed them. Now collect the full contract in one place. eventlog is a complete, non-trading journal that implements all 23 callback methods in the current Go SDK. Its sequence counter records delivery order, and each log includes the context clock and event payload. It is useful when a signal appears to have seen information too early, an order remains working, or a roll changes a stored price.

go build -o bin/eventlog ./strategies/demo/go/eventlog
mkdir -p results/learning
bin/algo run \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/eventlog --symbols fut:XCME:ES:H26 --bar-interval 1d \
  --date-from 2026-03-09 --date-to 2026-03-13 \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --plate full --color never --chart lines \
  --results-dir results/learning/events \
  > results/learning/events.txt 2> results/learning/events.log

This run needs archive bars and a served exchange calendar. The calendar observer requests the calendar even though this journal places no orders. The basic dated-contract run exercises startup, bars and shutdown. It does not manufacture fills, timers, corporate actions or adopted positions just to exercise their handlers. The bracket, timer and roll chapters provide those execution examples.

To observe additional data, supply one or more journal inputs: Trades, Statistics and Definitions name instruments with the corresponding archive coverage; Observations names a release-stamped series such as macro:FRED:GDP; Listings names a futures root such as fut:XCME:ES. For example, add --inputs Observations=macro:FRED:GDP,Listings=fut:XCME:ES and choose dates containing publications. Keep the primary a dated contract for this all-hooks journal with declared market events: the continuous-run path rejects that combination. Use a continuous primary with no extra event inputs to inspect rolls and rebases instead. The declarations are made once at startup. Merely implementing an observer does not acquire its data.

How delivery and responses work

algolang.Run owns the input loop and calls these methods serially. The required interface contains Name, Description and OnBar; all other hooks are optional interfaces discovered by their exact Go signatures. Implementing only one of the two SessionHandler methods does not implement that interface. The complete source below includes compile-time assertions so such mistakes cannot silently disable a handler.

There are three order-producing decisions: OnBar, OnLifecycleTurn and OnTimer. Each returns ([]Order, error). An error ends the run. For a normal protobuf decision reply the SDK sends queued cancel requests first, queued timer commands next, then the returned orders. Orders receive client IDs if omitted and attempts under the negotiated lifetime. A notification such as OnFill returns no order list: record state there and act at a decision. Calling ctx.Cancel or a timer method queues a command; it does not synchronously contact the venue from inside that observer.

The SDK generally applies its state update before notifying the strategy. For example, the position already includes a fill in OnFill. There are important exceptions and distinct clocks below. Do not assume that ctx.Now() equals every notification’s timestamp: fills, cancels, session notices, timer refusals and corporate-action notices do not themselves advance it. Read the event’s own time when recording when it occurred.

The reference describes the full protobuf strategy protocol (stdio-pb-v1, the normal choice). --data-protocol pb chooses the adapter wire, a separate connection. The CSV2 strategy protocol has bars, fills, cancels, order updates, cancel responses, lifecycle turns, roll/rebase, corporate-action and session notices, but not the full market-event, calendar, adoption or timer exchange described here. Legacy CSV is narrower again. A schema enum or handler method is not proof that a particular adapter, wire, archive or live venue can produce the event.

Startup and orderly shutdown

OnInit — initialize or refuse

Initializer.OnInit(ctx, cfg InitConfig) error runs after tagged input values are applied and capabilities negotiated, before history and decisions. Use it to validate relationships between inputs and construct private state. cfg contains run configuration and the initially configured instruments. The expanded universe and exchange calendar arrive later; do not require them here. ctx.Now() is initially zero. Returning an error refuses startup. After initialization, the SDK reads history and data declarations and sends its acknowledgement.

OnUniverseResolved — validate the expanded instruments

UniverseHandler.OnUniverseResolved(ctx) error runs after the resolved instrument map is stored and before warm-up. Query ctx.Instrument(symbol) for tick size, point value and other served metadata; return an error if it cannot support the strategy. Implementing this hook requests the push. Data and tradeable-symbol declarations also request it, and their metadata is available without a handler. The callback is a startup validation point, not a facility for adding subscriptions during a running strategy.

OnCalendar — validate exchange-calendar facts

CalendarObserver.OnCalendar(ctx, cal Calendar) error runs once per pushed root, after that calendar is stored, following universe resolution and before warm-up. cal.Root, cal.Zone, cal.Revision, cal.Day, cal.Complete and the boundary queries expose its facts. Return an error to reject insufficient coverage. Implementing the hook requests delivery; NeedsCalendar() bool can request it without a hook. A session-relative timer needs a real decision clock: arm it later rather than calling ArmSessionTimer here.

OnAdoptedState — reconcile an inherited live position

AdoptHandler.OnAdoptedState(ctx, state AdoptedState) error runs in the live startup-adoption path, after initialization and before bars. The SDK has already seeded positions and working orders from state, even if this hook is absent. Reconstruct strategy-owned counters, lots or cooldowns where possible, validate what was inherited, or return an error to refuse it. Adoption must be explicitly authorized in the run settings; a handler does not enable it. An empty snapshot is possible. Existing venue exposure is not evidence that the strategy’s private state has been recovered.

OnShutdown — finish an orderly run

Shutdowner.OnShutdown(ctx) runs on the engine’s explicit shutdown message. Log summaries and close resources here. It is not an opportunity to return liquidation orders and it is not guaranteed after a crash, protocol failure or a stream closing without Shutdown. In particular, do not rely on it to protect an open live position. The last stored account or portfolio view is what it was last supplied, not a promise of a fresh final valuation.

Decision callbacks

OnBar — decide on a delivered close

Strategy.OnBar(ctx, bar Bar) ([]Order, error) runs for each ordinary decision bar, including additional series that participate in delivery. The SDK first sets Now to bar.CloseTime, appends the bar, updates aligned views and freshness, and increments the processed count for its symbol. The callback therefore sees its current bar at series index zero. Use SeriesID, ctx.IsPrimary and explicit gating to decide which clock can trade.

Warm-up bars fill buffers without calling OnBar. A bar marked late is buffered without a decision too. A reference with the same close time may arrive before or after the primary callback; instantaneous comparisons must wait for both observations or deliberately use an as-of rule. Fills already delivered for earlier orders have changed position. A returned order is a new intent; it has not yet filled.

OnLifecycleTurn — respond to order outcomes at this instant

TurnHandler.OnLifecycleTurn(ctx, turn LifecycleTurn) ([]Order, error) grants another decision after the preceding commands’ lifecycle outcomes, before the engine advances time. turn.At, turn.Turn and turn.Budget identify the instant, one-based turn and allowed turn budget. Now is At; no new bar arrives and bar counts do not advance. Order and cancel notifications have already updated the working-order view.

Use this to reconcile a desired working order after a confirmed cancellation or refusal. Do not recompute an event indicator as if another price bar arrived, or assume unlimited turns. Without the hook the SDK sends an empty order response, while still flushing queued commands. This exchange requires the lifetime capability; it is distinct from a new fill or market-data event.

OnTimer — decide at an armed deadline

TimerHandler.OnTimer(ctx, timer TimerFired) ([]Order, error) runs when an accepted one-shot timer fires. The payload has ID, requested At and decision instant FiredAt; Now becomes FiredAt. Series and bar counts do not move, and no extra account snapshot is promised. Check DataAge and the relevant prices before constructing an order. Re-arm explicitly for repetition. The timer chapter shows session-relative arming. The random-exit chapter distinguishes historical coarse-bar refusal from streaming clock wake-ups; the current FiredAt field is not a measurement of wall-clock dispatch lateness.

Order and timer notifications

OnFill — observe an execution

FillHandler.OnFill(ctx, fill Fill) observes an actual fill, possibly only part of an order. The payload identifies instrument, side, quantity, price, commission, timestamp, client ID and attempt where carried. The SDK has applied it to position and its working-order view before this method. Maintain any private fill ledger or per-entry lot state here. A status update alone must not be counted as another fill, and two fill records need not mean two completed trades.

OnOrderUpdate — observe one order attempt’s status

OrderUpdateHandler.OnOrderUpdate(ctx, update OrderUpdate) reports the attempt’s transitions: its client ID, attempt, status, quantities, reason, venue reference and replacement relationship where supplied. The working view moves first; positions move only on fills. Thus a filled-status update can precede the fill that changes quantity. Read actual position when sizing the next order. Key state by attempt as well as label when retries or rolls can reuse a client ID.

OnCancelResponse — inspect a cancel request’s outcome

CancelResponseHandler.OnCancelResponse(ctx, response CancelResponse) is the classified answer to a specific cancellation request. RequestID ties it to the request, and Outcome, Status, remaining quantity and reason describe the evidence. The SDK applies the response first; a confirmed cancellation retires the attempt. A pending or rejected cancellation is not permission to assume the order has gone. Use a lifecycle turn to make any dependent order decision after the response.

OnCancel — observe cancellation of the order

CancelHandler.OnCancel(ctx, cancel OrderCancel) reports an order cancellation and its reason, for example an explicit cancel, OCO outcome or expiry. The SDK removes the cancelled order before the hook. This is different from the answer to a cancel request: a confirmed OnCancelResponse can already have retired the attempt, so the subsequent cancellation must not be counted as another position change. Cancellation itself does not change the filled position.

OnTimerRefused — observe an unavailable deadline

TimerRefusalHandler.OnTimerRefused(ctx, refusal TimerRefused) reports ID, At, Code, Reason and the refusal Timestamp. The codes are timer_invalid, timer_not_future, timer_after_end, calendar_incomplete, timer_limit and timer_coarse. The first five can reject an arm; timer_coarse reports that historical replay cannot resolve the promised decision inside a coarse bar; real-time streaming does not apply that check. A refusal does not advance Now or produce a decision. Record the failure and apply a deliberate fallback at a later decision; silently losing a planned exit is not a fallback.

Published market and reference data

These observers receive declared event series on the protobuf strategy wire. The SDK stores each record before calling its handler. They observe information becoming available; they do not return orders. The supplied replay delivers events before the following bar according to their visibility time, rather than making a reference period available retrospectively.

OnMarketTrade — observe a market print

MarketTradeHandler.OnMarketTrade(ctx, trade MarketTrade) receives each print in a declared Trades series. Price, size, aggressor, TsEvent, TsRecv and the unreliable-receive-time flag describe it. Now moves to nonzero TsRecv, and ctx.MarketTrades(seriesID) includes the print. In replay it precedes the first bar whose close is strictly after TsRecv. A market print is not your strategy’s fill; the two have different handlers and accounting.

OnStatistic — observe a published venue statistic

StatisticHandler.OnStatistic(ctx, statistic MarketStatistic) receives settlement, open-interest, cleared-volume and other supported statistic records from a declared Statistics series. VisibleAt is the first nonzero of receive, event and reference time; it advances Now. Preliminary and final values or later restatements are separate records, not a rewrite of what an earlier decision knew. Query the stored statistics to select the relevant kind, contract and trading date.

OnDefinition — observe instrument metadata in force

DefinitionHandler.OnDefinition(ctx, definition MarketDefinition) receives a declared InstrumentDefinition record, with metadata such as expiration. The definition is stored first and Now moves to nonzero TsEvent. Definitions can change; use the definition delivered by the decision rather than importing today’s contract metadata into all historical decisions.

OnObservation — observe a release, revision or withdrawal

ObservationHandler.OnObservation(ctx, observation MarketObservation) receives every record from declared Observations series, including withdrawals. The fields distinguish Ref (reference period), AvailableAt (publication), Vintage, Revision, Value and Withdrawn. The buffer and history are updated before the hook, and Now moves to publication time. A withdrawn zero is not an observed economic zero. The GDP example shows queries that retain this distinction and avoid revision lookahead.

OnListing — observe the contract curve changing

ListingHandler.OnListing(ctx, listing MarketListing) receives records from a declared ContractListing series. A contract’s first record arrives at KnownAt; later daily listings can restate it as its observed LastBar grows. TsRecv records the delivery instant, which becomes Now. ctx.Curve already includes the record inside the hook. Activation, expiration, maturity, first/last bar and tick size describe what was known then; the eventually complete curve would introduce hindsight.

Sessions, corporate actions and continuous futures

OnSessionStart — observe a host session marker

SessionHandler.OnSessionStart(ctx, session SessionInfo) receives the host’s SessionID and Time when it sends a session-start marker. The SDK calls it without changing the context clock or series. This is a supported wire hook, not a promise that the normal engine sends a marker for every exchange open: the current run loops do not generate those daily callbacks. For an order just after the main open, use served bar session facts or a calendar timer.

OnSessionEnd — observe a host session-end marker

SessionHandler.OnSessionEnd(ctx, session SessionInfo) is the matching notification and has the same delivery limitation. Both session methods are required to implement SessionHandler. It is not an order-producing callback and must not be used as the only way to flatten before the exchange close. The session-close strategies earlier use explicit decision mechanisms.

OnCorporateAction — observe announcement and effectiveness

CorporateActionObserver.OnCorporateAction(ctx, notice CorporateActionNotice) receives announced and effective phases of served equity actions. Inspect the type and phase, old/new symbols, quantity and price transformations and action times. At the effective phase, supported split rescaling, merger re-keying or symbol renaming is mirrored into SDK position and working-order state before the hook. Announcement alone does not apply it. Restate any additional state owned by the strategy consistently; a stale comment that calls all corporate-action notices purely informational predates these effective-phase updates.

OnRoll — observe the active contract changing

RollObserver.OnRoll(symbol, from, to string, atDate time.Time, rawGap, priceRatio float64) is the one callback here without a context argument. Implementing it requests roll notices. It follows the active-contract-map change and cannot veto the roll. rawGap is incoming minus outgoing price at the same seam instant; priceRatio is incoming/outgoing for ratio adjustment, and is zero when unset under other methods. Do not confuse a contract change with a signal to send a second manual roll order.

OnRebase — restate strategy-owned price state

RebaseObserver.OnRebase(ctx, rebase Rebase) follows a roll rebase when enabled, directly after OnRoll if both hooks exist. The SDK has already replaced the series history and restated its position average cost, working levels and trade anchors. Move private levels with rebase.Level, distances with rebase.Distance, or rebuild running indicators from the replaced history. It returns no orders. Omitting the hook does not turn off SDK rebasing; it leaves your private price state your responsibility.

Messages that have no strategy callback

The event vocabulary is wider than the callback list. These distinctions prevent implementing a plausible-looking method that the SDK never calls:

Message or declarationHow the strategy uses it
Account-state pushSDK stores it; query ctx.Account() at a decision. There is no OnAccount hook.
Portfolio-view pushRequest it with PortfolioNeeds, then query ctx.Portfolio() and the requested curve/statistics. There is no OnPortfolio hook.
Warm-up batch or late barBuffered without OnBar; no separate warm-up/late-bar callback.
Legacy cancel rejectionSDK adjusts the applicable pending-cancel state and logs it; no OnCancelReject. The classified cancellation API is OnCancelResponse.
Engine error, EOF or protocol failurealgolang.Run returns an error; handle it in main. No OnError, OnDisconnect or guaranteed shutdown callback.
Engine logEngine diagnostic, not an OnLog callback to the strategy.
Quotes, order books, imbalance and trading-status schemasTheir schema identifiers do not supply OnQuote, OnBook, OnImbalance or OnStatus strategy hooks in this SDK. Check actual data-path support before designing around them.
Inputs, capabilities, lookback, data, alignment, tradeable symbols, calendar needs, portfolio needs and one-bar policyStartup declarations queried by the SDK, not asynchronous callbacks.

Account enquiries can therefore change between decisions without a bespoke handler, while a function named OnAccount would simply be an unused Go method. The manual’s build checks the callback inventory against the SDK interfaces so this reference cannot silently omit a newly added hook.

Complete source: eventlog

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

  1. The compile-time interface assertions cover all 23 callback methods in the current SDK. They make a renamed or mistyped hook a build failure instead of a silently ignored method.

  2. DataRequirements enables optional event families only when their symbol inputs are supplied. PortfolioNeeds requests account-wide enquiries, and the calendar observer requests calendar delivery.

  3. Every hook logs its payload and returns without trading. The counter is delivery order; the logged context clock is not a substitute for each payload’s own timestamp.

  4. The three decision hooks return empty order lists. To build a trading strategy, observe and update state in notification hooks, then construct orders at an actual decision.

Build the supplied files directly:

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

eventlog/main.go

// Command eventlog records every strategy callback supported by this SDK.
// It is an event journal, not a trading strategy: all decisions return no orders.
package main

import (
    "encoding/json"
    "fmt"
    "os"
    "time"

    algolang "MODULE/sdk/strategy"
)

var buildID string

type EventLog struct {
    Trades       string `algolang:"desc=Optional symbol whose trade prints to observe"`
    Statistics   string `algolang:"desc=Optional symbol whose venue statistics to observe"`
    Definitions  string `algolang:"desc=Optional symbol whose instrument definitions to observe"`
    Observations string `algolang:"desc=Optional release-stamped series to observe"`
    Listings     string `algolang:"desc=Optional futures root whose contract listings to observe"`

    sequence int
    ctx      *algolang.Context // OnRoll has no context argument.
}

// These assertions check exact signatures, including the two-method session interface.
var (
    _ algolang.Strategy                = (*EventLog)(nil)
    _ algolang.Initializer             = (*EventLog)(nil)
    _ algolang.UniverseHandler         = (*EventLog)(nil)
    _ algolang.CalendarObserver        = (*EventLog)(nil)
    _ algolang.AdoptHandler            = (*EventLog)(nil)
    _ algolang.FillHandler             = (*EventLog)(nil)
    _ algolang.CancelHandler           = (*EventLog)(nil)
    _ algolang.OrderUpdateHandler      = (*EventLog)(nil)
    _ algolang.CancelResponseHandler   = (*EventLog)(nil)
    _ algolang.TurnHandler             = (*EventLog)(nil)
    _ algolang.TimerHandler            = (*EventLog)(nil)
    _ algolang.TimerRefusalHandler     = (*EventLog)(nil)
    _ algolang.SessionHandler          = (*EventLog)(nil)
    _ algolang.MarketTradeHandler      = (*EventLog)(nil)
    _ algolang.StatisticHandler        = (*EventLog)(nil)
    _ algolang.DefinitionHandler       = (*EventLog)(nil)
    _ algolang.ObservationHandler      = (*EventLog)(nil)
    _ algolang.ListingHandler          = (*EventLog)(nil)
    _ algolang.CorporateActionObserver = (*EventLog)(nil)
    _ algolang.RollObserver            = (*EventLog)(nil)
    _ algolang.RebaseObserver          = (*EventLog)(nil)
    _ algolang.Shutdowner              = (*EventLog)(nil)
)

func (s *EventLog) Name() string { return "Event journal" }
func (s *EventLog) Description() string {
    return "Logs strategy events in delivery order without placing orders."
}
func (s *EventLog) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule lets the engine end eligible resting orders after the next bar.
func (s *EventLog) OneBarRule() bool { return true }
func (s *EventLog) Lookback() int    { return 2 }
func (s *EventLog) PortfolioNeeds() algolang.PortfolioNeeds {
    return algolang.PortfolioNeeds{Curve: algolang.CurvePortfolio}
}

// Implementing observers alone does not subscribe to their data. Declare each
// requested family explicitly; omit empty inputs so the basic run needs only bars.
func (s *EventLog) DataRequirements() []algolang.DataRequirement {
    var out []algolang.DataRequirement
    for _, item := range []struct {
        id, symbol string
        kind       algolang.SchemaKind
        lookback   int
    }{
        {"prints", s.Trades, algolang.Trades, 100},
        {"stats", s.Statistics, algolang.Statistics, 100},
        {"definitions", s.Definitions, algolang.InstrumentDefinition, 1},
        {"observations", s.Observations, algolang.Observations, 100},
        // Listings retain the latest record per contract and require zero lookback.
        {"listings", s.Listings, algolang.ContractListing, 0},
    } {
        if item.symbol != "" {
            out = append(out, algolang.DataRequirement{
                SeriesID: item.id, Symbol: item.symbol, Lookback: item.lookback,
                Schema: algolang.DataSchemaSpec{Kind: item.kind},
            })
        }
    }
    return out
}

func (s *EventLog) record(ctx *algolang.Context, event string, payload any) {
    s.sequence++
    // JSON expands nested session/metadata pointers into values, making the
    // journal readable and repeatable rather than printing process addresses.
    encoded, err := json.Marshal(payload)
    if err != nil {
        ctx.Logf("event=%d hook=%s payload encoding failed: %v", s.sequence, event, err)
        return
    }
    ctx.Logf("event=%d hook=%s context_now=%s payload=%s", s.sequence,
        event, ctx.Now().Format(time.RFC3339Nano), encoded)
}

func (s *EventLog) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
    s.ctx = ctx
    s.record(ctx, "OnInit", cfg.RunID)
    return nil
}
func (s *EventLog) OnUniverseResolved(ctx *algolang.Context) error {
    s.record(ctx, "OnUniverseResolved", ctx.Instrument(ctx.PrimarySymbol()))
    return nil
}
func (s *EventLog) OnCalendar(ctx *algolang.Context, cal algolang.Calendar) error {
    s.record(ctx, "OnCalendar", cal.Root()+" "+cal.Zone()+" "+cal.Revision())
    return nil
}
func (s *EventLog) OnAdoptedState(ctx *algolang.Context, state algolang.AdoptedState) error {
    s.record(ctx, "OnAdoptedState", state)
    return nil
}

// Only these three callbacks are order-producing decisions. This observer keeps
// them empty; in a trading strategy, return orders after checking actual state.
func (s *EventLog) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    s.record(ctx, "OnBar", bar)
    return nil, nil
}
func (s *EventLog) OnLifecycleTurn(ctx *algolang.Context, turn algolang.LifecycleTurn) ([]algolang.Order, error) {
    s.record(ctx, "OnLifecycleTurn", turn)
    return nil, nil
}
func (s *EventLog) OnTimer(ctx *algolang.Context, timer algolang.TimerFired) ([]algolang.Order, error) {
    s.record(ctx, "OnTimer", timer)
    return nil, nil
}

// Notifications observe the state left by an event. Returning from them does not
// submit orders. Queued commands wait for the SDK's next applicable reply.
func (s *EventLog) OnFill(ctx *algolang.Context, fill algolang.Fill) {
    s.record(ctx, "OnFill", fill)
}
func (s *EventLog) OnCancel(ctx *algolang.Context, cancel algolang.OrderCancel) {
    s.record(ctx, "OnCancel", cancel)
}
func (s *EventLog) OnOrderUpdate(ctx *algolang.Context, update algolang.OrderUpdate) {
    s.record(ctx, "OnOrderUpdate", update)
}
func (s *EventLog) OnCancelResponse(ctx *algolang.Context, response algolang.CancelResponse) {
    s.record(ctx, "OnCancelResponse", response)
}
func (s *EventLog) OnTimerRefused(ctx *algolang.Context, refusal algolang.TimerRefused) {
    s.record(ctx, "OnTimerRefused", refusal)
}
func (s *EventLog) OnSessionStart(ctx *algolang.Context, session algolang.SessionInfo) {
    s.record(ctx, "OnSessionStart", session)
}
func (s *EventLog) OnSessionEnd(ctx *algolang.Context, session algolang.SessionInfo) {
    s.record(ctx, "OnSessionEnd", session)
}
func (s *EventLog) OnMarketTrade(ctx *algolang.Context, trade algolang.MarketTrade) {
    s.record(ctx, "OnMarketTrade", trade)
}
func (s *EventLog) OnStatistic(ctx *algolang.Context, statistic algolang.MarketStatistic) {
    s.record(ctx, "OnStatistic", statistic)
}
func (s *EventLog) OnDefinition(ctx *algolang.Context, definition algolang.MarketDefinition) {
    s.record(ctx, "OnDefinition", definition)
}
func (s *EventLog) OnObservation(ctx *algolang.Context, observation algolang.MarketObservation) {
    s.record(ctx, "OnObservation", observation)
}
func (s *EventLog) OnListing(ctx *algolang.Context, listing algolang.MarketListing) {
    s.record(ctx, "OnListing", listing)
}
func (s *EventLog) OnCorporateAction(ctx *algolang.Context, notice algolang.CorporateActionNotice) {
    s.record(ctx, "OnCorporateAction", notice)
}
func (s *EventLog) OnRoll(symbol, from, to string, atDate time.Time, rawGap, priceRatio float64) {
    s.record(s.ctx, "OnRoll", fmt.Sprintf("%s %s -> %s date=%s gap=%g ratio=%g",
        symbol, from, to, atDate.Format(time.RFC3339Nano), rawGap, priceRatio))
}
func (s *EventLog) OnRebase(ctx *algolang.Context, rebase algolang.Rebase) {
    // No private price state needs restating in this observer. Avoid logging the
    // entire replacement history, which can be large.
    s.record(ctx, "OnRebase", fmt.Sprintf("replacement bars=%d", len(rebase.Bars)))
}
func (s *EventLog) OnShutdown(ctx *algolang.Context) {
    s.record(ctx, "OnShutdown", fmt.Sprintf("previous callbacks=%d", s.sequence))
}

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

Previous: A range-break filter on an event clock · Next: A portfolio of crossover strategies