Class State<Data>

Per-signal mutable state scoped by state name.

Works like a value bound to the CURRENT pending or scheduled signal: new State({ name: "trade", initialData: { peakPercent: 0 } }).setState(...) inside any strategy lifecycle callback. No context is passed through arguments — every instance method resolves the signal, mode and timestamp itself from backtest.methodContextService / backtest.executionContextService, so the class is unavailable outside async_hooks lifecycle callbacks by design.

initialData provides the default value when no state exists yet — a plain object or a sync/async factory returning one. The factory receives an InitialDispatchContract payload with the resolved signal context (signal row, active/schedule type, currentPrice, mode, logical time), so the initial state can be derived from the actual entry; it yields a fresh object per access, so the default is never shared by reference.

Look-ahead bias protection: a read at a when earlier than the stored when yields initialData, and a write with a smaller when overwrites (a restarted backtest resets live-written state).

Requires an explicit State.enable() call before use — the subscription it creates disposes per-signal instances when the signal is cancelled or closed, preventing stale instances from accumulating.

State.enable();

const state = new State({
name: "trade",
initialData: () => ({ peakPercent: 0, minutesOpen: 0 }),
});

// inside a strategy callback:
await state.setState((prev) => ({
peakPercent: Math.max(prev.peakPercent, currentPercent),
minutesOpen: prev.minutesOpen + 1,
}));
const { peakPercent } = await state.getState();

Type Parameters

  • Data extends object = object

Constructors

  • Type Parameters

    • Data extends object = object

    Parameters

    • params: { initialData: Data | InitialDataFn<Data>; name: string }

    Returns State<Data>

Properties

_getState: <Value extends object = object>(
    dto: {
        backtest: boolean;
        bucketName: string;
        initialValue: object;
        signalId: string;
        when: Date;
    },
) => Promise<Value>

Context-free read of the current state value for a signal. Routes to StateBacktest or StateLive based on dto.backtest.

Type declaration

    • <Value extends object = object>(
          dto: {
              backtest: boolean;
              bucketName: string;
              initialValue: object;
              signalId: string;
              when: Date;
          },
      ): Promise<Value>
    • Type Parameters

      • Value extends object = object

      Parameters

      • dto: {
            backtest: boolean;
            bucketName: string;
            initialValue: object;
            signalId: string;
            when: Date;
        }
        • backtest: boolean

          Flag indicating if the context is backtest or live

        • bucketName: string

          State name

        • initialValue: object

          Default value when no persisted state exists

        • signalId: string

          Signal identifier

        • when: Date

          Logical timestamp at which the read is happening (look-ahead guard)

      Returns Promise<Value>

      Current state value

Error if State is not enabled

_setState: <Value extends object = object>(
    dispatch: Value | Dispatch<Value>,
    dto: {
        backtest: boolean;
        bucketName: string;
        initialValue: object;
        signalId: string;
        when: Date;
    },
) => Promise<Value>

Context-free update of the state value for a signal. Routes to StateBacktest or StateLive based on dto.backtest.

Type declaration

    • <Value extends object = object>(
          dispatch: Value | Dispatch<Value>,
          dto: {
              backtest: boolean;
              bucketName: string;
              initialValue: object;
              signalId: string;
              when: Date;
          },
      ): Promise<Value>
    • Type Parameters

      • Value extends object = object

      Parameters

      • dispatch: Value | Dispatch<Value>

        New value or updater function receiving current value

      • dto: {
            backtest: boolean;
            bucketName: string;
            initialValue: object;
            signalId: string;
            when: Date;
        }
        • backtest: boolean

          Flag indicating if the context is backtest or live

        • bucketName: string

          State name

        • initialValue: object

          Default value when no persisted state exists

        • signalId: string

          Signal identifier

        • when: Date

          Logical timestamp this value belongs to

      Returns Promise<Value>

      Updated state value

Error if State is not enabled

disable: () => void

Disables state storage by unsubscribing from signal lifecycle events. Safe to call multiple times.

enable: () => (...args: any[]) => any & ISingleshotClearable<
    () => (...args: any[]) => any,
>

Enables state storage by subscribing to signal lifecycle events. Clears memoized instances in StateBacktest and StateLive when a signal is cancelled or closed, preventing stale instances from accumulating. Uses singleshot to ensure one-time subscription.

Cleanup function that unsubscribes from all emitters

getState: () => Promise<Data>

Read the current state value for the active pending or scheduled signal. Resolves the signal, mode and timestamp from execution context — no context arguments required.

Type declaration

    • (): Promise<Data>
    • Returns Promise<Data>

      Current state value (initialData when nothing was written yet)

Error if no execution/method context or no pending/scheduled signal exists

setState: (dispatch: Data | Dispatch<Data>) => Promise<Data>

Update the state value for the active pending or scheduled signal. Resolves the signal, mode and timestamp from execution context — no context arguments required.

Type declaration

    • (dispatch: Data | Dispatch<Data>): Promise<Data>
    • Parameters

      • dispatch: Data | Dispatch<Data>

        New value or updater function receiving current value

      Returns Promise<Data>

      Updated state value

Error if no execution/method context or no pending/scheduled signal exists