Skip to main content
Version: latest

Backtest

The backtest subpackage groups components relating to backtesting.

This module provides a data client for backtesting.

class BacktestDataClient

Bases: DataClient

BacktestDataClient(ClientId client_id, MessageBus msgbus, Cache cache, Clock clock, config: NautilusConfig | None = None)

Provides an implementation of DataClient for backtesting.

  • Parameters:
    • client_id (ClientId) – The data client ID.
    • msgbus (MessageBus) – The message bus for the client.
    • cache (Cache) – The cache for the client.
    • clock (Clock) – The clock for the client.
    • config (NautilusConfig , optional) – The configuration for the instance.

degrade(self)

Degrade the component.

While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

dispose(self)

Dispose of the component.

While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

fault(self)

Fault the component.

Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.

While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

classmethod fully_qualified_name(cls)

Return the fully qualified name for the components class.

  • Return type: str

id

The components ID.

  • Returns: ComponentId

is_connected

If the client is connected.

  • Returns: bool

is_degraded

bool

Return whether the current component state is DEGRADED.

  • Return type: bool
  • Type: Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

request(self, DataType data_type, UUID4 correlation_id)

reset(self)

Reset the component.

All stateful fields are reset to their initial value.

While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

subscribe(self, DataType data_type)

subscribed_custom_data(self)

Return the custom data types subscribed to.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

unsubscribe(self, DataType data_type)

venue

The clients venue ID (if applicable).

  • Returns: Venue or None

class BacktestMarketDataClient

Bases: MarketDataClient

BacktestMarketDataClient(ClientId client_id, MessageBus msgbus, Cache cache, Clock clock)

Provides an implementation of MarketDataClient for backtesting.

  • Parameters:
    • client_id (ClientId) – The data client ID.
    • msgbus (MessageBus) – The message bus for the client.
    • cache (Cache) – The cache for the client.
    • clock (Clock) – The clock for the client.

degrade(self)

Degrade the component.

While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

dispose(self)

Dispose of the component.

While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

fault(self)

Fault the component.

Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.

While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

classmethod fully_qualified_name(cls)

Return the fully qualified name for the components class.

  • Return type: str

id

The components ID.

  • Returns: ComponentId

is_connected

If the client is connected.

  • Returns: bool

is_degraded

bool

Return whether the current component state is DEGRADED.

  • Return type: bool
  • Type: Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

request(self, DataType data_type, UUID4 correlation_id)

Request data for the given data type.

  • Parameters:
    • data_type (DataType) – The data type for the subscription.
    • correlation_id (UUID4) – The correlation ID for the response.

request_bars(self, BarType bar_type, int limit, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)

request_instrument(self, InstrumentId instrument_id, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)

request_instruments(self, Venue venue, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)

request_order_book_snapshot(self, InstrumentId instrument_id, int limit, UUID4 correlation_id)

request_quote_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)

request_trade_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)

reset(self)

Reset the component.

All stateful fields are reset to their initial value.

While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

subscribe(self, DataType data_type)

Subscribe to data for the given data type.

  • Parameters: data_type (DataType) – The data type for the subscription.

subscribe_bars(self, BarType bar_type)

subscribe_instrument(self, InstrumentId instrument_id)

subscribe_instrument_close(self, InstrumentId instrument_id)

subscribe_instrument_status(self, InstrumentId instrument_id)

subscribe_instruments(self)

subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)

subscribe_order_book_snapshots(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)

subscribe_quote_ticks(self, InstrumentId instrument_id)

subscribe_trade_ticks(self, InstrumentId instrument_id)

subscribe_venue_status(self, Venue venue)

subscribed_bars(self)

Return the bar types subscribed to.

subscribed_custom_data(self)

Return the custom data types subscribed to.

subscribed_instrument_close(self)

Return the instrument closes subscribed to.

subscribed_instrument_status(self)

Return the status update instruments subscribed to.

subscribed_instruments(self)

Return the instruments subscribed to.

subscribed_order_book_deltas(self)

Return the order book delta instruments subscribed to.

subscribed_order_book_snapshots(self)

Return the order book snapshot instruments subscribed to.

subscribed_quote_ticks(self)

Return the quote tick instruments subscribed to.

subscribed_trade_ticks(self)

Return the trade tick instruments subscribed to.

subscribed_venue_status(self)

Return the status update instruments subscribed to.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

unsubscribe(self, DataType data_type)

Unsubscribe from data for the given data type.

  • Parameters: data_type (DataType) – The data type for the subscription.

unsubscribe_bars(self, BarType bar_type)

unsubscribe_instrument(self, InstrumentId instrument_id)

unsubscribe_instrument_close(self, InstrumentId instrument_id)

unsubscribe_instrument_status(self, InstrumentId instrument_id)

unsubscribe_instruments(self)

unsubscribe_order_book_deltas(self, InstrumentId instrument_id)

unsubscribe_order_book_snapshots(self, InstrumentId instrument_id)

unsubscribe_quote_ticks(self, InstrumentId instrument_id)

unsubscribe_trade_ticks(self, InstrumentId instrument_id)

unsubscribe_venue_status(self, Venue venue)

venue

The clients venue ID (if applicable).

  • Returns: Venue or None

class BacktestEngine

Bases: object

BacktestEngine(config: BacktestEngineConfig | None = None) -> None

Provides a backtest engine to run a portfolio of strategies over historical data.

  • Parameters: config (BacktestEngineConfig , optional) – The configuration for the instance.
  • Raises: TypeError – If config is not of type BacktestEngineConfig.

add_actor(self, Actor actor: Actor)

Add the given actor to the backtest engine.

  • Parameters: actor (Actor) – The actor to add.

add_actors(self, list actors: list[Actor])

Add the given list of actors to the backtest engine.

  • Parameters: actors (list [Actor ]) – The actors to add.

add_data(self, list data, ClientId client_id=None, bool validate=True, bool sort=True)

Add the given custom data to the backtest engine.

  • Parameters:
    • data (list *[*Data ]) – The data to add.
    • client_id (ClientId , optional) – The data client ID to associate with custom data.
    • validate (bool , default True) – If data should be validated (recommended when adding data directly to the engine).
    • sort (bool , default True) – If data should be sorted by ts_init with the rest of the stream after adding (recommended when adding data directly to the engine).
  • Raises:
    • ValueError – If data is empty.
    • ValueError – If data contains objects which are not a type of Data.
    • ValueError – If instrument_id for the data is not found in the cache.
    • ValueError – If data elements do not have an instrument_id and client_id is None.
    • TypeError – If data is a type provided by Rust pyo3 (cannot add directly to engine yet).

WARNING

Assumes all data elements are of the same type. Adding lists of varying data types could result in incorrect backtest logic.

Caution if adding data without sort being True, as this could lead to running backtests on a stream which does not have monotonically increasing timestamps.

add_exec_algorithm(self, ExecAlgorithm exec_algorithm: ExecAlgorithm)

Add the given execution algorithm to the backtest engine.

  • Parameters: exec_algorithm (ExecAlgorithm) – The execution algorithm to add.

add_exec_algorithms(self, list exec_algorithms: list[ExecAlgorithm])

Add the given list of execution algorithms to the backtest engine.

  • Parameters: exec_algorithms (list [ExecAlgorithm ]) – The execution algorithms to add.

add_instrument(self, Instrument instrument)

Add the instrument to the backtest engine.

The instrument must be valid for its associated venue. For instance, derivative instruments which would trade on margin cannot be added to a venue with a CASH account.

add_strategies(self, list strategies: list[Strategy])

Add the given list of strategies to the backtest engine.

  • Parameters: strategies (list [Strategy ]) – The strategies to add.

add_strategy(self, Strategy strategy: Strategy)

Add the given strategy to the backtest engine.

  • Parameters: strategy (Strategy) – The strategy to add.

add_venue(self, Venue venue: Venue, OmsType oms_type: OmsType, AccountType account_type: AccountType, list starting_balances: list[Money], base_currency: Currency | None = None, default_leverage: Decimal | None = None, leverages: dict[InstrumentId, Decimal] | None = None, modules: list[SimulationModule] | None = None, fill_model: FillModel | None = None, fee_model: FeeModel | None = None, latency_model: LatencyModel | None = None, BookType book_type: BookType = BookType.L1_MBP, routing: bool = False, frozen_account: bool = False, bar_execution: bool = True, reject_stop_orders: bool = True, support_gtd_orders: bool = True, support_contingent_orders: bool = True, use_position_ids: bool = True, use_random_ids: bool = False, use_reduce_only: bool = True)

Add a SimulatedExchange with the given parameters to the backtest engine.

  • Parameters:
    • venue (Venue) – The venue ID.
    • oms_type (OmsType {HEDGING, NETTING}) – The order management system type for the exchange. If HEDGING will generate new position IDs.
    • account_type (AccountType) – The account type for the client.
    • starting_balances (list [Money ]) – The starting account balances (specify one for a single asset account).
    • base_currency (Currency , optional) – The account base currency for the client. Use None for multi-currency accounts.
    • default_leverage (Decimal , optional) – The account default leverage (for margin accounts).
    • leverages (dict [InstrumentId , Decimal ] , optional) – The instrument specific leverage configuration (for margin accounts).
    • modules (list [SimulationModule ] , optional) – The simulation modules to load into the exchange.
    • fill_model (FillModel , optional) – The fill model for the exchange.
    • fee_model (FeeModel , optional) – The fee model for the venue.
    • latency_model (LatencyModel , optional) – The latency model for the exchange.
    • book_type (BookType, default BookType.L1_MBP) – The default order book type for fill modelling.
    • routing (bool , default False) – If multi-venue routing should be enabled for the execution client.
    • frozen_account (bool , default False) – If the account for this exchange is frozen (balances will not change).
    • bar_execution (bool , default True) – If bars should be processed by the matching engine(s) (and move the market).
    • reject_stop_orders (bool , default True) – If stop orders are rejected on submission if trigger price is in the market.
    • support_gtd_orders (bool , default True) – If orders with GTD time in force will be supported by the venue.
    • support_contingent_orders (bool , default True) – If contingent orders will be supported/respected by the venue. If False then its expected the strategy will be managing any contingent orders.
    • use_position_ids (bool , default True) – If venue position IDs will be generated on order fills.
    • use_random_ids (bool , default False) – If all venue generated identifiers will be random UUID4’s.
    • use_reduce_only (bool , default True) – If the reduce_only execution instruction on orders will be honored.
  • Raises: ValueError – If venue is already registered with the engine.

backtest_end

datetime | None

Return the last backtest run time range end (if run).

  • Return type: datetime or None
  • Type: BacktestEngine.backtest_end

backtest_start

datetime | None

Return the last backtest run time range start (if run).

  • Return type: datetime or None
  • Type: BacktestEngine.backtest_start

cache

CacheFacade

Return the engines internal read-only cache.

change_fill_model(self, Venue venue, FillModel model)

Change the fill model for the exchange of the given venue.

  • Parameters:
    • venue (Venue) – The venue of the simulated exchange.
    • model (FillModel) – The fill model to change to.

clear_actors(self)

Clear all actors from the engines internal trader.

clear_data(self)

Clear the engines internal data stream.

Does not clear added instruments.

clear_exec_algorithms(self)

Clear all execution algorithms from the engines internal trader.

clear_strategies(self)

Clear all trading strategies from the engines internal trader.

data

list[Data]

Return the engines internal data stream.

  • Return type: list[Data]
  • Type: BacktestEngine.data

dispose(self)

Dispose of the backtest engine by disposing the trader and releasing system resources.

Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.

dump_pickled_data(self)

Return the internal data stream pickled.

  • Return type: bytes

end(self)

Manually end the backtest.

get_result(self)

Return the backtest result from the last run.

instance_id

UUID4

Return the engines instance ID.

This is a unique identifier per initialized engine.

  • Return type: UUID4
  • Type: BacktestEngine.instance_id

iteration

int

Return the backtest engine iteration count.

  • Return type: int
  • Type: BacktestEngine.iteration

kernel

NautilusKernel

Return the internal kernel for the engine.

list_venues(self)

Return the venues contained within the engine.

  • Return type: list[Venue]

load_pickled_data(self, bytes data)

Load the given pickled data directly into the internal data stream.

It is highly advised to only pass data to this method which was obtained through a call to .dump_pickled_data().

WARNING

This low-level direct access method makes the following assumptions: : - The data contains valid Nautilus objects only, which inherit from Data.

  • The data was successfully pickled from a call to pickle.dumps().
  • The data was sorted prior to pickling.
  • All required instruments have been added to the engine.

logger

Logger

Return the internal logger for the engine.

  • Return type: Logger
  • Type: BacktestEngine.logger

machine_id

str

Return the engines machine ID.

  • Return type: str
  • Type: BacktestEngine.machine_id

portfolio

PortfolioFacade

Return the engines internal read-only portfolio.

reset(self)

Reset the backtest engine.

All stateful fields are reset to their initial value.

Note: instruments and data are not dropped/reset, this can be done through a separate call to .clear_data() if desired.

run(self, start: datetime | str | int | None = None, end: datetime | str | int | None = None, run_config_id: str | None = None, streaming: bool = False)

Run a backtest.

At the end of the run the trader and strategies will be stopped, then post-run analysis performed.

If more data than can fit in memory is to be run through the backtest engine, then streaming mode can be utilized. The expected sequence is as follows:

  • Add initial data batch and strategies.
  • Call run(streaming=True).
  • Call clear_data().
  • Add next batch of data stream.
  • Call either run(streaming=False) or end(). When there is no more data to run on.
  • Parameters:
    • start (datetime or str or int , optional) – The start datetime (UTC) for the backtest run. If None engine runs from the start of the data.
    • end (datetime or str or int , optional) – The end datetime (UTC) for the backtest run. If None engine runs to the end of the data.
    • run_config_id (str , optional) – The tokenized BacktestRunConfig ID.
    • streaming (bool , default False) – If running in streaming mode. If False then will end the backtest following the run iterations.
  • Raises:
    • ValueError – If no data has been added to the engine.
    • ValueError – If the start is >= the end datetime.

run_config_id

str

Return the last backtest engine run config ID.

  • Return type: str or None
  • Type: BacktestEngine.run_config_id

run_finished

datetime | None

Return when the last backtest run finished (if run).

  • Return type: datetime or None
  • Type: BacktestEngine.run_finished

run_id

UUID4

Return the last backtest engine run ID (if run).

  • Return type: UUID4 or None
  • Type: BacktestEngine.run_id

run_started

datetime | None

Return when the last backtest run started (if run).

  • Return type: datetime or None
  • Type: BacktestEngine.run_started

trader

Trader

Return the engines internal trader.

  • Return type: Trader
  • Type: BacktestEngine.trader

trader_id

TraderId

Return the engines trader ID.

  • Return type: TraderId
  • Type: BacktestEngine.trader_id

class SimulatedExchange

Bases: object

SimulatedExchange(Venue venue, OmsType oms_type, AccountType account_type, list starting_balances, Currency base_currency: Currency | None, default_leverage: Decimal, dict leverages: dict[InstrumentId, Decimal], list modules, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, TestClock clock, FillModel fill_model, FeeModel fee_model, LatencyModel latency_model=None, BookType book_type=BookType.L1_MBP, bool frozen_account=False, bool bar_execution=True, bool reject_stop_orders=True, bool support_gtd_orders=True, bool support_contingent_orders=True, bool use_position_ids=True, bool use_random_ids=False, bool use_reduce_only=True, bool use_message_queue=True) -> None

Provides a simulated exchange venue.

  • Parameters:
    • venue (Venue) – The venue to simulate.
    • oms_type (OmsType {HEDGING, NETTING}) – The order management system type used by the exchange.
    • account_type (AccountType) – The account type for the client.
    • starting_balances (list [Money ]) – The starting balances for the exchange.
    • base_currency (Currency , optional) – The account base currency for the client. Use None for multi-currency accounts.
    • default_leverage (Decimal) – The account default leverage (for margin accounts).
    • leverages (dict [InstrumentId , Decimal ]) – The instrument specific leverage configuration (for margin accounts).
    • modules (list *[*SimulatedModule ]) – The simulation modules for the exchange.
    • portfolio (PortfolioFacade) – The read-only portfolio for the exchange.
    • msgbus (MessageBus) – The message bus for the exchange.
    • cache (CacheFacade) – The read-only cache for the exchange.
    • clock (TestClock) – The clock for the exchange.
    • fill_model (FillModel) – The fill model for the exchange.
    • fee_model (FeeModel) – The fee model for the exchange.
    • latency_model (LatencyModel , optional) – The latency model for the exchange.
    • book_type (BookType) – The order book type for the exchange.
    • frozen_account (bool , default False) – If the account for this exchange is frozen (balances will not change).
    • bar_execution (bool , default True) – If bars should be processed by the matching engine(s) (and move the market).
    • reject_stop_orders (bool , default True) – If stop orders are rejected on submission if in the market.
    • support_gtd_orders (bool , default True) – If orders with GTD time in force will be supported by the exchange.
    • support_contingent_orders (bool , default True) – If contingent orders will be supported/respected by the exchange. If False then its expected the strategy will be managing any contingent orders.
    • use_position_ids (bool , default True) – If venue position IDs will be generated on order fills.
    • use_random_ids (bool , default False) – If all exchange generated identifiers will be random UUID4’s.
    • use_reduce_only (bool , default True) – If the reduce_only execution instruction on orders will be honored.
    • use_message_queue (bool , default True) – If an internal message queue should be used to process trading commands in sequence after they have initially arrived. Setting this to False would be appropriate for real-time sandbox environments, where we don’t want to introduce additional latency of waiting for the next data event before processing the trading command.
  • Raises:
    • ValueError – If instruments is empty.
    • ValueError – If instruments contains a type other than Instrument.
    • ValueError – If starting_balances is empty.
    • ValueError – If starting_balances contains a type other than Money.
    • ValueError – If base_currency and multiple starting balances.
    • ValueError – If modules contains a type other than SimulationModule.

account_type

The account base currency.

  • Returns: AccountType

add_instrument(self, Instrument instrument)

Add the given instrument to the exchange.

  • Parameters: instrument (Instrument) – The instrument to add.
  • Raises:
    • ValueError – If instrument.id.venue is not equal to the venue ID.
    • InvalidConfiguration – If instrument is invalid for this venue.

adjust_account(self, Money adjustment)

Adjust the account at the exchange with the given adjustment.

  • Parameters: adjustment (Money) – The adjustment for the account.

bar_execution

If bars should be processed by the matching engine(s) (and move the market).

  • Returns: bool

base_currency

The account base currency (None for multi-currency accounts).

  • Returns: Currency or None

best_ask_price(self, InstrumentId instrument_id)

Return the best ask price for the given instrument ID (if found).

  • Parameters: instrument_id (InstrumentId) – The instrument ID for the price.
  • Return type: Price or None

best_bid_price(self, InstrumentId instrument_id)

Return the best bid price for the given instrument ID (if found).

  • Parameters: instrument_id (InstrumentId) – The instrument ID for the price.
  • Return type: Price or None

book_type

The exchange default order book type.

  • Returns: BookType

cache

The cache wired to the exchange.

  • Returns: CacheFacade

default_leverage

The accounts default leverage.

  • Returns: Decimal

exec_client

The execution client wired to the exchange.

  • Returns: BacktestExecClient

fee_model

The fee model for the exchange.

  • Returns: FeeModel

fill_model

The fill model for the exchange.

  • Returns: FillModel

get_account(self)

Return the account for the registered client (if registered).

  • Return type: Account or None

get_book(self, InstrumentId instrument_id)

Return the order book for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The instrument ID for the price.
  • Return type: OrderBook or None

get_books(self)

Return all order books within the exchange.

get_matching_engine(self, InstrumentId instrument_id)

Return the matching engine for the given instrument ID (if found).

  • Parameters: instrument_id (InstrumentId) – The instrument ID for the matching engine.
  • Return type: OrderMatchingEngine or None

get_matching_engines(self)

Return all matching engines for the exchange (for every instrument).

get_open_ask_orders(self, InstrumentId instrument_id=None)

Return the open ask orders at the exchange.

  • Parameters: instrument_id (InstrumentId , optional) – The instrument_id query filter.
  • Return type: list[Order]

get_open_bid_orders(self, InstrumentId instrument_id=None)

Return the open bid orders at the exchange.

  • Parameters: instrument_id (InstrumentId , optional) – The instrument_id query filter.
  • Return type: list[Order]

get_open_orders(self, InstrumentId instrument_id=None)

Return the open orders at the exchange.

  • Parameters: instrument_id (InstrumentId , optional) – The instrument_id query filter.
  • Return type: list[Order]

id

The exchange ID.

  • Returns: Venue

initialize_account(self)

Initialize the account to the starting balances.

instruments

The exchange instruments.

  • Returns: dict[InstrumentId, Instrument]

is_frozen_account

If the account for the exchange is frozen.

  • Returns: bool

latency_model

The latency model for the exchange.

  • Returns: LatencyModel

leverages

The accounts instrument specific leverage configuration.

  • Returns: dict[InstrumentId, Decimal]

modules

The simulation modules registered with the exchange.

  • Returns: list[SimulationModule]

msgbus

The message bus wired to the exchange.

  • Returns: MessageBus

oms_type

The exchange order management system type.

  • Returns: OmsType

process(self, uint64_t ts_now)

Process the exchange to the given time.

All pending commands will be processed along with all simulation modules.

  • Parameters: ts_now (uint64_t) – The current UNIX timestamp (nanoseconds).

process_bar(self, Bar bar)

Process the exchanges market for the given bar.

Market dynamics are simulated by auctioning open orders.

  • Parameters: bar (Bar) – The bar to process.

process_instrument_status(self, InstrumentStatus data)

Process a specific instrument status.

  • Parameters: data (VenueStatus) – The status update to process.

process_order_book_delta(self, OrderBookDelta delta)

Process the exchanges market for the given order book delta.

  • Parameters: data (OrderBookDelta) – The order book delta to process.

process_order_book_deltas(self, OrderBookDeltas deltas)

Process the exchanges market for the given order book deltas.

process_quote_tick(self, QuoteTick tick)

Process the exchanges market for the given quote tick.

Market dynamics are simulated by auctioning open orders.

  • Parameters: tick (QuoteTick) – The tick to process.

process_trade_tick(self, TradeTick tick)

Process the exchanges market for the given trade tick.

Market dynamics are simulated by auctioning open orders.

  • Parameters: tick (TradeTick) – The tick to process.

process_venue_status(self, VenueStatus data)

Process the exchange for the given status.

  • Parameters: data (VenueStatus) – The status update to process.

register_client(self, BacktestExecClient client)

Register the given execution client with the simulated exchange.

reject_stop_orders

If stop orders are rejected on submission if in the market.

  • Returns: bool

reset(self)

Reset the simulated exchange.

All stateful fields are reset to their initial value.

send(self, TradingCommand command)

Send the given trading command into the exchange.

set_fill_model(self, FillModel fill_model)

Set the fill model for all matching engines.

  • Parameters: fill_model (FillModel) – The fill model to set.

set_latency_model(self, LatencyModel latency_model)

Change the latency model for this exchange.

  • Parameters: latency_model (LatencyModel) – The latency model to set.

starting_balances

The account starting balances for each backtest run.

  • Returns: bool

support_contingent_orders

If contingent orders will be supported/respected by the venue.

  • Returns: bool

support_gtd_orders

If orders with GTD time in force will be supported by the venue.

  • Returns: bool

use_message_queue

If an internal message queue is being used to sequentially process incoming trading commands.

  • Returns: bool

use_position_ids

If venue position IDs will be generated on order fills.

  • Returns: bool

use_random_ids

If venue order and position IDs will be randomly generated UUID4s.

  • Returns: bool

use_reduce_only

If the reduce_only option on orders will be honored.

  • Returns: bool

class BacktestExecClient

Bases: ExecutionClient

BacktestExecClient(SimulatedExchange exchange, MessageBus msgbus, Cache cache, TestClock clock, bool routing=False, bool frozen_account=False) -> None

Provides an execution client for the BacktestEngine.

  • Parameters:
    • exchange (SimulatedExchange) – The simulated exchange for the backtest.
    • msgbus (MessageBus) – The message bus for the client.
    • cache (Cache) – The cache for the client.
    • clock (TestClock) – The clock for the client.
    • routing (bool) – If multi-venue routing is enabled for the client.
    • frozen_account (bool) – If the backtest run account is frozen.

account_id

The clients account ID.

  • Returns: AccountId or None

account_type

The clients account type.

  • Returns: AccountType

base_currency

The clients account base currency (None for multi-currency accounts).

  • Returns: Currency or None

batch_cancel_orders(self, BatchCancelOrders command)

cancel_all_orders(self, CancelAllOrders command)

cancel_order(self, CancelOrder command)

degrade(self)

Degrade the component.

While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

dispose(self)

Dispose of the component.

While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

fault(self)

Fault the component.

Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.

While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

classmethod fully_qualified_name(cls)

Return the fully qualified name for the components class.

  • Return type: str

generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None)

Generate an AccountState event and publish on the message bus.

  • Parameters:
    • balances (list [AccountBalance ]) – The account balances.
    • margins (list [MarginBalance ]) – The margin balances.
    • reported (bool) – If the balances are reported directly from the exchange.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account state event occurred.
    • info (dict *[*str , object ]) – The additional implementation specific account information.

generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderAccepted event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.

generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, unicode reason, uint64_t ts_event)

Generate an OrderCancelRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • reason (str) – The order cancel rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.

generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderCanceled event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.

generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderExpired event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.

generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event)

Generate an OrderFilled event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • trade_id (TradeId) – The trade ID.
    • venue_position_id (PositionId, optional with no default so None must be passed explicitly) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise pass None and the execution engine OMS will handle position ID resolution.
    • order_side (OrderSide {BUY, SELL}) – The execution order side.
    • order_type (OrderType) – The execution order type.
    • last_qty (Quantity) – The fill quantity for this execution.
    • last_px (Price) – The fill price for this execution (not average price).
    • quote_currency (Currency) – The currency of the price.
    • commission (Money) – The fill commission.
    • liquidity_side (LiquiditySide {NO_LIQUIDITY_SIDE, MAKER, TAKER}) – The execution liquidity side.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order filled event occurred.

generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, unicode reason, uint64_t ts_event)

Generate an OrderModifyRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • reason (str) – The order update rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.

generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, unicode reason, uint64_t ts_event)

Generate an OrderRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • reason (datetime) – The order rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.

generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event)

Generate an OrderSubmitted event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.

generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderTriggered event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.

generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False)

Generate an OrderUpdated event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • quantity (Quantity) – The orders current quantity.
    • price (Price) – The orders current price.
    • trigger_price (Price, optional with no default so None must be passed explicitly) – The orders current trigger price.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update event occurred.
    • venue_order_id_modified (bool) – If the ID was modified for this event.

get_account(self)

Return the account for the client (if registered).

  • Return type: Account or None

id

The components ID.

  • Returns: ComponentId

is_connected

If the client is connected.

  • Returns: bool

is_degraded

bool

Return whether the current component state is DEGRADED.

  • Return type: bool
  • Type: Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

modify_order(self, ModifyOrder command)

oms_type

The venues order management system type.

  • Returns: OmsType

query_order(self, QueryOrder command)

Initiate a reconciliation for the queried order which will generate an OrderStatusReport.

  • Parameters: command (QueryOrder) – The command to execute.

reset(self)

Reset the component.

All stateful fields are reset to their initial value.

While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

submit_order(self, SubmitOrder command)

submit_order_list(self, SubmitOrderList command)

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

venue

The clients venue ID (if not a routing client).

  • Returns: Venue or None

class FeeModel

Bases: object

Provides an abstract fee model for trades.

get_commission(self, Order order, Quantity fill_qty, Price fill_px, Instrument instrument)

Return the commission for a trade.

  • Parameters:
    • order (Order) – The order to calculate the commission for.
    • fill_qty (Quantity) – The fill quantity of the order.
    • fill_px (Price) – The fill price of the order.
    • instrument (Instrument) – The instrument for the order.
  • Return type: Money

class FillModel

Bases: object

FillModel(double prob_fill_on_limit=1.0, double prob_fill_on_stop=1.0, double prob_slippage=0.0, random_seed: int | None = None)

Provides probabilistic modeling for order fill dynamics including probability of fills and slippage by order type.

  • Parameters:
    • prob_fill_on_limit (double) – The probability of limit order filling if the market rests on its price.
    • prob_fill_on_stop (double) – The probability of stop orders filling if the market rests on its price.
    • prob_slippage (double) – The probability of order fill prices slipping by one tick.
    • random_seed (int , optional) – The random seed (if None then no random seed).
  • Raises:
    • ValueError – If any probability argument is not within range [0, 1].
    • TypeError – If random_seed is not None and not of type int.

is_limit_filled(self)

Return a value indicating whether a LIMIT order filled.

  • Return type: bool

is_slipped(self)

Return a value indicating whether an order fill slipped.

  • Return type: bool

is_stop_filled(self)

Return a value indicating whether a STOP-MARKET order filled.

  • Return type: bool

prob_fill_on_limit

The probability of limit orders filling on the limit price.

  • Returns: bool

prob_fill_on_stop

The probability of stop orders filling on the stop price.

  • Returns: bool

prob_slippage

The probability of aggressive order execution slipping.

  • Returns: bool

class FixedFeeModel

Bases: FeeModel

FixedFeeModel(Money commission, bool charge_commission_once: bool = True)

Provides a fixed fee model for trades.

  • Parameters:
    • commission (Money) – The fixed commission amount for trades.
    • charge_commission_once (bool , default True) – Whether to charge the commission once per order or per fill.
  • Raises: ValueError – If commission is not a positive amount.

get_commission(self, Order order, Quantity fill_qty, Price fill_px, Instrument instrument)

class LatencyModel

Bases: object

LatencyModel(uint64_t base_latency_nanos=NANOSECONDS_IN_MILLISECOND, uint64_t insert_latency_nanos=0, uint64_t update_latency_nanos=0, uint64_t cancel_latency_nanos=0)

Provides a latency model for simulated exchange message I/O.

  • Parameters:
    • base_latency_nanos (int , default 1_000_000_000) – The base latency (nanoseconds) for the model.
    • insert_latency_nanos (int , default 0) – The order insert latency (nanoseconds) for the model.
    • update_latency_nanos (int , default 0) – The order update latency (nanoseconds) for the model.
    • cancel_latency_nanos (int , default 0) – The order cancel latency (nanoseconds) for the model.
  • Raises:
    • ValueError – If base_latency_nanos is negative (< 0).
    • ValueError – If insert_latency_nanos is negative (< 0).
    • ValueError – If update_latency_nanos is negative (< 0).
    • ValueError – If cancel_latency_nanos is negative (< 0).

base_latency_nanos

The default latency to the exchange.

  • Returns: int

cancel_latency_nanos

The latency (nanoseconds) for order cancel messages to reach the exchange.

  • Returns: int

insert_latency_nanos

The latency (nanoseconds) for order insert messages to reach the exchange.

  • Returns: int

update_latency_nanos

The latency (nanoseconds) for order update messages to reach the exchange.

  • Returns: int

class MakerTakerFeeModel

Bases: FeeModel

Provide a fee model for trades based on a maker/taker fee schedule and notional value of the trade.

get_commission(self, Order order, Quantity fill_qty, Price fill_px, Instrument instrument)

class FXRolloverInterestModule

Bases: SimulationModule

FXRolloverInterestModule(config: FXRolloverInterestConfig)

Provides an FX rollover interest simulation module.

active_task_ids(self)

Return the active task identifiers.

add_synthetic(self, SyntheticInstrument synthetic)

Add the created synthetic instrument to the cache.

  • Parameters: synthetic (SyntheticInstrument) – The synthetic instrument to add to the cache.
  • Raises: KeyError – If synthetic is already in the cache.

cache

The read-only cache for the actor.

  • Returns: CacheFacade

cancel_all_tasks(self)

Cancel all queued and active tasks.

cancel_task(self, task_id: TaskId)

Cancel the task with the given task_id (if queued or active).

If the task is not found then a warning is logged.

  • Parameters: task_id (TaskId) – The task identifier.

clock

The actors clock.

  • Returns: Clock

config

The actors configuration.

  • Returns: NautilusConfig

degrade(self)

Degrade the component.

While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

deregister_warning_event(self, type event)

Deregister the given event type from warning log levels.

  • Parameters: event (type) – The event class to deregister.

dispose(self)

Dispose of the component.

While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

exchange

fault(self)

Fault the component.

Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.

While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

classmethod fully_qualified_name(cls)

Return the fully qualified name for the components class.

  • Return type: str

handle_bar(self, Bar bar)

Handle the given bar data.

If state is RUNNING then passes to on_bar.

  • Parameters: bar (Bar) – The bar received.

WARNING

System method (not intended to be called by user code).

handle_bars(self, list bars)

Handle the given historical bar data by handling each bar individually.

  • Parameters: bars (list [Bar ]) – The bars to handle.

WARNING

System method (not intended to be called by user code).

handle_data(self, Data data)

Handle the given data.

If state is RUNNING then passes to on_data.

  • Parameters: data (Data) – The data received.

WARNING

System method (not intended to be called by user code).

handle_event(self, Event event)

Handle the given event.

If state is RUNNING then passes to on_event.

  • Parameters: event (Event) – The event received.

WARNING

System method (not intended to be called by user code).

handle_historical_data(self, data)

Handle the given historical data.

  • Parameters: data (Data) – The historical data received.

WARNING

System method (not intended to be called by user code).

handle_instrument(self, Instrument instrument)

Handle the given instrument.

Passes to on_instrument if state is RUNNING.

  • Parameters: instrument (Instrument) – The instrument received.

WARNING

System method (not intended to be called by user code).

handle_instrument_close(self, InstrumentClose update)

Handle the given instrument close update.

If state is RUNNING then passes to on_instrument_close.

WARNING

System method (not intended to be called by user code).

handle_instrument_status(self, InstrumentStatus data)

Handle the given instrument status update.

If state is RUNNING then passes to on_instrument_status.

WARNING

System method (not intended to be called by user code).

handle_instruments(self, list instruments)

Handle the given instruments data by handling each instrument individually.

  • Parameters: instruments (list [Instrument ]) – The instruments received.

WARNING

System method (not intended to be called by user code).

handle_order_book(self, OrderBook order_book)

Handle the given order book.

Passes to on_order_book if state is RUNNING.

  • Parameters: order_book (OrderBook) – The order book received.

WARNING

System method (not intended to be called by user code).

handle_order_book_deltas(self, deltas)

Handle the given order book deltas.

Passes to on_order_book_deltas if state is RUNNING. The deltas will be nautilus_pyo3.OrderBookDeltas if the pyo3_conversion flag was set for the subscription.

  • Parameters: deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.

WARNING

System method (not intended to be called by user code).

handle_quote_tick(self, QuoteTick tick)

Handle the given quote tick.

If state is RUNNING then passes to on_quote_tick.

  • Parameters: tick (QuoteTick) – The tick received.

WARNING

System method (not intended to be called by user code).

handle_quote_ticks(self, list ticks)

Handle the given historical quote tick data by handling each tick individually.

  • Parameters: ticks (list [QuoteTick ]) – The ticks received.

WARNING

System method (not intended to be called by user code).

handle_trade_tick(self, TradeTick tick)

Handle the given trade tick.

If state is RUNNING then passes to on_trade_tick.

  • Parameters: tick (TradeTick) – The tick received.

WARNING

System method (not intended to be called by user code).

handle_trade_ticks(self, list ticks)

Handle the given historical trade tick data by handling each tick individually.

  • Parameters: ticks (list [TradeTick ]) – The ticks received.

WARNING

System method (not intended to be called by user code).

handle_venue_status(self, VenueStatus data)

Handle the given venue status update.

If state is RUNNING then passes to on_venue_status.

  • Parameters: data (VenueStatus) – The status update received.

WARNING

System method (not intended to be called by user code).

has_active_tasks(self)

Return a value indicating whether there are any active tasks.

  • Return type: bool

has_any_tasks(self)

Return a value indicating whether there are any queued or active tasks.

  • Return type: bool

has_pending_requests(self)

Return whether the actor is pending processing for any requests.

  • Returns: True if any requests are pending, else False.
  • Return type: bool

has_queued_tasks(self)

Return a value indicating whether there are any queued tasks.

  • Return type: bool

id

The components ID.

  • Returns: ComponentId

indicators_initialized(self)

Return a value indicating whether all indicators are initialized.

  • Returns: True if all initialized, else False
  • Return type: bool

is_degraded

bool

Return whether the current component state is DEGRADED.

  • Return type: bool
  • Type: Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_pending_request(self, UUID4 request_id)

Return whether the request for the given identifier is pending processing.

  • Parameters: request_id (UUID4) – The request ID to check.
  • Returns: True if request is pending, else False.
  • Return type: bool

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

load(self, dict state)

Load the actor/strategy state from the give state dictionary.

Calls on_load and passes the state.

  • Parameters: state (dict *[*str , object ]) – The state dictionary.
  • Raises: RuntimeError – If actor/strategy is not registered with a trader.

WARNING

Exceptions raised will be caught, logged, and reraised.

log

The actors logger.

  • Returns: Logger

log_diagnostics(self, Logger logger)

Log diagnostics out to the BacktestEngine logger.

  • Parameters: logger (Logger) – The logger to log to.

msgbus

The message bus for the actor (if registered).

  • Returns: MessageBus or None

on_bar(self, Bar bar)

Actions to be performed when running and receives a bar.

  • Parameters: bar (Bar) – The bar received.

WARNING

System method (not intended to be called by user code).

on_data(self, data)

Actions to be performed when running and receives data.

  • Parameters: data (Data) – The data received.

WARNING

System method (not intended to be called by user code).

on_degrade(self)

Actions to be performed on degrade.

WARNING

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_dispose(self)

Actions to be performed on dispose.

Cleanup/release any resources used here.

WARNING

System method (not intended to be called by user code).

on_event(self, Event event)

Actions to be performed running and receives an event.

  • Parameters: event (Event) – The event received.

WARNING

System method (not intended to be called by user code).

on_fault(self)

Actions to be performed on fault.

Cleanup any resources used by the actor here.

WARNING

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_historical_data(self, data)

Actions to be performed when running and receives historical data.

  • Parameters: data (Data) – The historical data received.

WARNING

System method (not intended to be called by user code).

on_instrument(self, Instrument instrument)

Actions to be performed when running and receives an instrument.

  • Parameters: instrument (Instrument) – The instrument received.

WARNING

System method (not intended to be called by user code).

on_instrument_close(self, InstrumentClose update)

Actions to be performed when running and receives an instrument close update.

WARNING

System method (not intended to be called by user code).

on_instrument_status(self, InstrumentStatus data)

Actions to be performed when running and receives an instrument status update.

  • Parameters: data (InstrumentStatus) – The instrument status update received.

WARNING

System method (not intended to be called by user code).

on_load(self, dict state)

Actions to be performed when the actor state is loaded.

Saved state values will be contained in the give state dictionary.

WARNING

System method (not intended to be called by user code).

on_order_book(self, OrderBook order_book)

Actions to be performed when running and receives an order book.

  • Parameters: order_book (OrderBook) – The order book received.

WARNING

System method (not intended to be called by user code).

on_order_book_deltas(self, deltas)

Actions to be performed when running and receives order book deltas.

  • Parameters: deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.

WARNING

System method (not intended to be called by user code).

on_quote_tick(self, QuoteTick tick)

Actions to be performed when running and receives a quote tick.

  • Parameters: tick (QuoteTick) – The tick received.

WARNING

System method (not intended to be called by user code).

on_reset(self)

Actions to be performed on reset.

WARNING

System method (not intended to be called by user code).

Should be overridden in a user implementation.

on_resume(self)

Actions to be performed on resume.

WARNING

System method (not intended to be called by user code).

on_save(self)

Actions to be performed when the actor state is saved.

Create and return a state dictionary of values to be saved.

  • Returns: The strategy state dictionary.
  • Return type: dict[str, bytes]

WARNING

System method (not intended to be called by user code).

on_start(self)

Actions to be performed on start.

The intent is that this method is called once per trading ‘run’, when initially starting.

It is recommended to subscribe/request for data here.

WARNING

System method (not intended to be called by user code).

Should be overridden in a user implementation.

on_stop(self)

Actions to be performed on stop.

The intent is that this method is called to pause, or when done for day.

WARNING

System method (not intended to be called by user code).

Should be overridden in a user implementation.

on_trade_tick(self, TradeTick tick)

Actions to be performed when running and receives a trade tick.

  • Parameters: tick (TradeTick) – The tick received.

WARNING

System method (not intended to be called by user code).

on_venue_status(self, VenueStatus data)

Actions to be performed when running and receives a venue status update.

  • Parameters: data (VenueStatus) – The venue status update received.

WARNING

System method (not intended to be called by user code).

pending_requests(self)

Return the request IDs which are currently pending processing.

  • Return type: set[UUID4]

portfolio

The read-only portfolio for the actor.

  • Returns: PortfolioFacade

pre_process(self, Data data)

Abstract method pre_process (implement in subclass).

process(self, uint64_t ts_now)

Process the given tick through the module.

  • Parameters: ts_now (uint64_t) – The current UNIX time (nanoseconds) in the simulated exchange.

publish_data(self, DataType data_type, Data data)

Publish the given data to the message bus.

  • Parameters:
    • data_type (DataType) – The data type being published.
    • data (Data) – The data to publish.

publish_signal(self, unicode name, value, uint64_t ts_event=0)

Publish the given value as a signal to the message bus. Optionally setup persistence for this signal.

  • Parameters:
    • name (str) – The name of the signal being published.
    • value (object) – The signal data to publish.
    • ts_event (uint64_t , optional) – UNIX timestamp (nanoseconds) when the signal event occurred. If None then will timestamp current time.

queue_for_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)

Queues the callable func to be executed as fn(*args, **kwargs) sequentially.

  • Parameters:
    • func (Callable) – The function to be executed.
    • args (positional arguments) – The positional arguments for the call to func.
    • kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
  • Raises: TypeError – If func is not of type Callable.

queued_task_ids(self)

Return the queued task identifiers.

register_base(self, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, Clock clock)

Register with a trader.

  • Parameters:
    • portfolio (PortfolioFacade) – The read-only portfolio for the actor.
    • msgbus (MessageBus) – The message bus for the actor.
    • cache (CacheFacade) – The read-only cache for the actor.
    • clock (Clock) – The clock for the actor.

WARNING

System method (not intended to be called by user code).

register_executor(self, loop: asyncio.AbstractEventLoop, executor: Executor)

Register the given Executor for the actor.

  • Parameters:
    • loop (asyncio.AsbtractEventLoop) – The event loop of the application.
    • executor (concurrent.futures.Executor) – The executor to register.
  • Raises: TypeError – If executor is not of type concurrent.futures.Executor

register_indicator_for_bars(self, BarType bar_type, Indicator indicator)

Register the given indicator with the actor/strategy to receive bar data for the given bar type.

  • Parameters:
    • bar_type (BarType) – The bar type for bar updates.
    • indicator (Indicator) – The indicator to register.

register_indicator_for_quote_ticks(self, InstrumentId instrument_id, Indicator indicator)

Register the given indicator with the actor/strategy to receive quote tick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for tick updates.
    • indicator (Indicator) – The indicator to register.

register_indicator_for_trade_ticks(self, InstrumentId instrument_id, Indicator indicator)

Register the given indicator with the actor/strategy to receive trade tick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for tick updates.
    • indicator (indicator) – The indicator to register.

register_venue(self, SimulatedExchange exchange)

Register the given simulated exchange with the module.

register_warning_event(self, type event)

Register the given event type for warning log levels.

  • Parameters: event (type) – The event class to register.

registered_indicators

Return the registered indicators for the strategy.

request_bars(self, BarType bar_type, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request historical Bar data.

If end is None then will request up to the most recent data.

  • Parameters:
    • bar_type (BarType) – The bar type for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_data(self, DataType data_type, ClientId client_id, callback: Callable[[UUID4], None] | None = None)

Request custom data for the given data type from the given data client.

  • Parameters:
    • data_type (DataType) – The data type for the request.
    • client_id (ClientId) – The data client ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises: TypeError – If callback is not None and not of type Callable.

request_instrument(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request Instrument data for the given instrument ID.

If end is None then will request up to the most recent data.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_instruments(self, Venue venue, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request all Instrument data for the given venue.

If end is None then will request up to the most recent data.

  • Parameters:
    • venue (Venue) – The venue for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_order_book_snapshot(self, InstrumentId instrument_id, int limit, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request an order book snapshot.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
    • limit (int , optional) – The limit on the depth of the order book snapshot (default is None).
    • client_id (ClientId , optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If the instrument_id is None.
    • TypeError – If callback is not None and not of type Callable.

request_quote_ticks(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request historical QuoteTick data.

If end is None then will request up to the most recent data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_trade_ticks(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request historical TradeTick data.

If end is None then will request up to the most recent data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

reset(self)

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

run_in_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)

Schedules the callable func to be executed as fn(*args, **kwargs).

  • Parameters:
    • func (Callable) – The function to be executed.
    • args (positional arguments) – The positional arguments for the call to func.
    • kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
  • Returns: The unique task identifier for the execution. This also corresponds to any future objects memory address.
  • Return type: TaskId
  • Raises: TypeError – If func is not of type Callable.

save(self)

Return the actor/strategy state dictionary to be saved.

Calls on_save.

  • Raises: RuntimeError – If actor/strategy is not registered with a trader.

WARNING

Exceptions raised will be caught, logged, and reraised.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

subscribe_bars(self, BarType bar_type, ClientId client_id=None, bool await_partial=False)

Subscribe to streaming Bar data for the given bar type.

  • Parameters:
    • bar_type (BarType) – The bar type to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • await_partial (bool , default False) – If the bar aggregator should await the arrival of a historical partial bar prior to actively aggregating new bars.

subscribe_data(self, DataType data_type, ClientId client_id=None)

Subscribe to data of the given data type.

  • Parameters:
    • data_type (DataType) – The data type to subscribe to.
    • client_id (ClientId , optional) – The data client ID. If supplied then a Subscribe command will be sent to the corresponding data client.

subscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to update Instrument data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the subscription.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to close updates for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to status updates for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instruments(self, Venue venue, ClientId client_id=None)

Subscribe to update Instrument data for the given venue.

  • Parameters:
    • venue (Venue) – The venue for the subscription.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

subscribe_order_book_at_interval(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, int interval_ms=1000, dict kwargs=None, ClientId client_id=None, bool managed=True)

Subscribe to an OrderBook at a specified interval for the given instrument ID.

The DataEngine will only maintain one order book for each instrument. Because of this - the level, depth and kwargs for the stream will be set as per the last subscription request (this will also affect all subscribers).

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
    • book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) – The order book type.
    • depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
    • interval_ms (int) – The order book snapshot interval in milliseconds (must be positive).
    • kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • managed (bool , default True) – If an order book should be managed by the data engine based on the subscribed feed.
  • Raises:
    • ValueError – If depth is negative (< 0).
    • ValueError – If interval_ms is not positive (> 0).

WARNING

Consider subscribing to order book deltas if you need intervals less than 100 milliseconds.

subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, dict kwargs=None, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False)

Subscribe to the order book data stream, being a snapshot then deltas for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
    • book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) – The order book type.
    • depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
    • kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • managed (bool , default True) – If an order book should be managed by the data engine based on the subscribed feed.
    • pyo3_conversion (bool , default False) – If received deltas should be converted to nautilus_pyo3.OrderBookDeltas prior to being passed to the on_order_book_deltas handler.

subscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to streaming QuoteTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to streaming TradeTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_venue_status(self, Venue venue, ClientId client_id=None)

Subscribe to status updates for the given venue.

  • Parameters:
    • venue (Venue) – The venue to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

to_importable_config(self)

Returns an importable configuration for this actor.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

unsubscribe_bars(self, BarType bar_type, ClientId client_id=None)

Unsubscribe from streaming Bar data for the given bar type.

  • Parameters:
    • bar_type (BarType) – The bar type to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_data(self, DataType data_type, ClientId client_id=None)

Unsubscribe from data of the given data type.

  • Parameters:
    • data_type (DataType) – The data type to unsubscribe from.
    • client_id (ClientId , optional) – The data client ID. If supplied then an Unsubscribe command will be sent to the data client.

unsubscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe from update Instrument data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe to status updates of the given venue.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to unsubscribe to status updates for.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

unsubscribe_instruments(self, Venue venue, ClientId client_id=None)

Unsubscribe from update Instrument data for the given venue.

  • Parameters:
    • venue (Venue) – The venue for the subscription.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

unsubscribe_order_book_at_interval(self, InstrumentId instrument_id, int interval_ms=1000, ClientId client_id=None)

Unsubscribe from an OrderBook at a specified interval for the given instrument ID.

The interval must match the previously subscribed interval.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • interval_ms (int) – The order book snapshot interval in milliseconds.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_order_book_deltas(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe the order book deltas stream for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe from streaming QuoteTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe from streaming TradeTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_venue_status(self, Venue venue, ClientId client_id=None)

Unsubscribe to status updates for the given venue.

  • Parameters:
    • venue (Venue) – The venue to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

update_synthetic(self, SyntheticInstrument synthetic)

Update the synthetic instrument in the cache.

  • Parameters: synthetic (SyntheticInstrument) – The synthetic instrument to update in the cache.
  • Raises: KeyError – If synthetic does not already exist in the cache.

class SimulationModule

Bases: Actor

SimulationModule(config: SimulationModuleConfig)

The base class for all simulation modules.

WARNING

This class should not be used directly, but through a concrete subclass.

active_task_ids(self)

Return the active task identifiers.

add_synthetic(self, SyntheticInstrument synthetic)

Add the created synthetic instrument to the cache.

  • Parameters: synthetic (SyntheticInstrument) – The synthetic instrument to add to the cache.
  • Raises: KeyError – If synthetic is already in the cache.

cache

The read-only cache for the actor.

  • Returns: CacheFacade

cancel_all_tasks(self)

Cancel all queued and active tasks.

cancel_task(self, task_id: TaskId)

Cancel the task with the given task_id (if queued or active).

If the task is not found then a warning is logged.

  • Parameters: task_id (TaskId) – The task identifier.

clock

The actors clock.

  • Returns: Clock

config

The actors configuration.

  • Returns: NautilusConfig

degrade(self)

Degrade the component.

While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

deregister_warning_event(self, type event)

Deregister the given event type from warning log levels.

  • Parameters: event (type) – The event class to deregister.

dispose(self)

Dispose of the component.

While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

exchange

fault(self)

Fault the component.

Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.

While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

classmethod fully_qualified_name(cls)

Return the fully qualified name for the components class.

  • Return type: str

handle_bar(self, Bar bar)

Handle the given bar data.

If state is RUNNING then passes to on_bar.

  • Parameters: bar (Bar) – The bar received.

WARNING

System method (not intended to be called by user code).

handle_bars(self, list bars)

Handle the given historical bar data by handling each bar individually.

  • Parameters: bars (list [Bar ]) – The bars to handle.

WARNING

System method (not intended to be called by user code).

handle_data(self, Data data)

Handle the given data.

If state is RUNNING then passes to on_data.

  • Parameters: data (Data) – The data received.

WARNING

System method (not intended to be called by user code).

handle_event(self, Event event)

Handle the given event.

If state is RUNNING then passes to on_event.

  • Parameters: event (Event) – The event received.

WARNING

System method (not intended to be called by user code).

handle_historical_data(self, data)

Handle the given historical data.

  • Parameters: data (Data) – The historical data received.

WARNING

System method (not intended to be called by user code).

handle_instrument(self, Instrument instrument)

Handle the given instrument.

Passes to on_instrument if state is RUNNING.

  • Parameters: instrument (Instrument) – The instrument received.

WARNING

System method (not intended to be called by user code).

handle_instrument_close(self, InstrumentClose update)

Handle the given instrument close update.

If state is RUNNING then passes to on_instrument_close.

WARNING

System method (not intended to be called by user code).

handle_instrument_status(self, InstrumentStatus data)

Handle the given instrument status update.

If state is RUNNING then passes to on_instrument_status.

WARNING

System method (not intended to be called by user code).

handle_instruments(self, list instruments)

Handle the given instruments data by handling each instrument individually.

  • Parameters: instruments (list [Instrument ]) – The instruments received.

WARNING

System method (not intended to be called by user code).

handle_order_book(self, OrderBook order_book)

Handle the given order book.

Passes to on_order_book if state is RUNNING.

  • Parameters: order_book (OrderBook) – The order book received.

WARNING

System method (not intended to be called by user code).

handle_order_book_deltas(self, deltas)

Handle the given order book deltas.

Passes to on_order_book_deltas if state is RUNNING. The deltas will be nautilus_pyo3.OrderBookDeltas if the pyo3_conversion flag was set for the subscription.

  • Parameters: deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.

WARNING

System method (not intended to be called by user code).

handle_quote_tick(self, QuoteTick tick)

Handle the given quote tick.

If state is RUNNING then passes to on_quote_tick.

  • Parameters: tick (QuoteTick) – The tick received.

WARNING

System method (not intended to be called by user code).

handle_quote_ticks(self, list ticks)

Handle the given historical quote tick data by handling each tick individually.

  • Parameters: ticks (list [QuoteTick ]) – The ticks received.

WARNING

System method (not intended to be called by user code).

handle_trade_tick(self, TradeTick tick)

Handle the given trade tick.

If state is RUNNING then passes to on_trade_tick.

  • Parameters: tick (TradeTick) – The tick received.

WARNING

System method (not intended to be called by user code).

handle_trade_ticks(self, list ticks)

Handle the given historical trade tick data by handling each tick individually.

  • Parameters: ticks (list [TradeTick ]) – The ticks received.

WARNING

System method (not intended to be called by user code).

handle_venue_status(self, VenueStatus data)

Handle the given venue status update.

If state is RUNNING then passes to on_venue_status.

  • Parameters: data (VenueStatus) – The status update received.

WARNING

System method (not intended to be called by user code).

has_active_tasks(self)

Return a value indicating whether there are any active tasks.

  • Return type: bool

has_any_tasks(self)

Return a value indicating whether there are any queued or active tasks.

  • Return type: bool

has_pending_requests(self)

Return whether the actor is pending processing for any requests.

  • Returns: True if any requests are pending, else False.
  • Return type: bool

has_queued_tasks(self)

Return a value indicating whether there are any queued tasks.

  • Return type: bool

id

The components ID.

  • Returns: ComponentId

indicators_initialized(self)

Return a value indicating whether all indicators are initialized.

  • Returns: True if all initialized, else False
  • Return type: bool

is_degraded

bool

Return whether the current component state is DEGRADED.

  • Return type: bool
  • Type: Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_pending_request(self, UUID4 request_id)

Return whether the request for the given identifier is pending processing.

  • Parameters: request_id (UUID4) – The request ID to check.
  • Returns: True if request is pending, else False.
  • Return type: bool

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

load(self, dict state)

Load the actor/strategy state from the give state dictionary.

Calls on_load and passes the state.

  • Parameters: state (dict *[*str , object ]) – The state dictionary.
  • Raises: RuntimeError – If actor/strategy is not registered with a trader.

WARNING

Exceptions raised will be caught, logged, and reraised.

log

The actors logger.

  • Returns: Logger

log_diagnostics(self, Logger logger)

Abstract method (implement in subclass).

msgbus

The message bus for the actor (if registered).

  • Returns: MessageBus or None

on_bar(self, Bar bar)

Actions to be performed when running and receives a bar.

  • Parameters: bar (Bar) – The bar received.

WARNING

System method (not intended to be called by user code).

on_data(self, data)

Actions to be performed when running and receives data.

  • Parameters: data (Data) – The data received.

WARNING

System method (not intended to be called by user code).

on_degrade(self)

Actions to be performed on degrade.

WARNING

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_dispose(self)

Actions to be performed on dispose.

Cleanup/release any resources used here.

WARNING

System method (not intended to be called by user code).

on_event(self, Event event)

Actions to be performed running and receives an event.

  • Parameters: event (Event) – The event received.

WARNING

System method (not intended to be called by user code).

on_fault(self)

Actions to be performed on fault.

Cleanup any resources used by the actor here.

WARNING

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_historical_data(self, data)

Actions to be performed when running and receives historical data.

  • Parameters: data (Data) – The historical data received.

WARNING

System method (not intended to be called by user code).

on_instrument(self, Instrument instrument)

Actions to be performed when running and receives an instrument.

  • Parameters: instrument (Instrument) – The instrument received.

WARNING

System method (not intended to be called by user code).

on_instrument_close(self, InstrumentClose update)

Actions to be performed when running and receives an instrument close update.

WARNING

System method (not intended to be called by user code).

on_instrument_status(self, InstrumentStatus data)

Actions to be performed when running and receives an instrument status update.

  • Parameters: data (InstrumentStatus) – The instrument status update received.

WARNING

System method (not intended to be called by user code).

on_load(self, dict state)

Actions to be performed when the actor state is loaded.

Saved state values will be contained in the give state dictionary.

WARNING

System method (not intended to be called by user code).

on_order_book(self, OrderBook order_book)

Actions to be performed when running and receives an order book.

  • Parameters: order_book (OrderBook) – The order book received.

WARNING

System method (not intended to be called by user code).

on_order_book_deltas(self, deltas)

Actions to be performed when running and receives order book deltas.

  • Parameters: deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.

WARNING

System method (not intended to be called by user code).

on_quote_tick(self, QuoteTick tick)

Actions to be performed when running and receives a quote tick.

  • Parameters: tick (QuoteTick) – The tick received.

WARNING

System method (not intended to be called by user code).

on_reset(self)

Actions to be performed on reset.

WARNING

System method (not intended to be called by user code).

Should be overridden in a user implementation.

on_resume(self)

Actions to be performed on resume.

WARNING

System method (not intended to be called by user code).

on_save(self)

Actions to be performed when the actor state is saved.

Create and return a state dictionary of values to be saved.

  • Returns: The strategy state dictionary.
  • Return type: dict[str, bytes]

WARNING

System method (not intended to be called by user code).

on_start(self)

Actions to be performed on start.

The intent is that this method is called once per trading ‘run’, when initially starting.

It is recommended to subscribe/request for data here.

WARNING

System method (not intended to be called by user code).

Should be overridden in a user implementation.

on_stop(self)

Actions to be performed on stop.

The intent is that this method is called to pause, or when done for day.

WARNING

System method (not intended to be called by user code).

Should be overridden in a user implementation.

on_trade_tick(self, TradeTick tick)

Actions to be performed when running and receives a trade tick.

  • Parameters: tick (TradeTick) – The tick received.

WARNING

System method (not intended to be called by user code).

on_venue_status(self, VenueStatus data)

Actions to be performed when running and receives a venue status update.

  • Parameters: data (VenueStatus) – The venue status update received.

WARNING

System method (not intended to be called by user code).

pending_requests(self)

Return the request IDs which are currently pending processing.

  • Return type: set[UUID4]

portfolio

The read-only portfolio for the actor.

  • Returns: PortfolioFacade

pre_process(self, Data data)

Abstract method pre_process (implement in subclass).

process(self, uint64_t ts_now)

Abstract method (implement in subclass).

publish_data(self, DataType data_type, Data data)

Publish the given data to the message bus.

  • Parameters:
    • data_type (DataType) – The data type being published.
    • data (Data) – The data to publish.

publish_signal(self, unicode name, value, uint64_t ts_event=0)

Publish the given value as a signal to the message bus. Optionally setup persistence for this signal.

  • Parameters:
    • name (str) – The name of the signal being published.
    • value (object) – The signal data to publish.
    • ts_event (uint64_t , optional) – UNIX timestamp (nanoseconds) when the signal event occurred. If None then will timestamp current time.

queue_for_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)

Queues the callable func to be executed as fn(*args, **kwargs) sequentially.

  • Parameters:
    • func (Callable) – The function to be executed.
    • args (positional arguments) – The positional arguments for the call to func.
    • kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
  • Raises: TypeError – If func is not of type Callable.

queued_task_ids(self)

Return the queued task identifiers.

register_base(self, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, Clock clock)

Register with a trader.

  • Parameters:
    • portfolio (PortfolioFacade) – The read-only portfolio for the actor.
    • msgbus (MessageBus) – The message bus for the actor.
    • cache (CacheFacade) – The read-only cache for the actor.
    • clock (Clock) – The clock for the actor.

WARNING

System method (not intended to be called by user code).

register_executor(self, loop: asyncio.AbstractEventLoop, executor: Executor)

Register the given Executor for the actor.

  • Parameters:
    • loop (asyncio.AsbtractEventLoop) – The event loop of the application.
    • executor (concurrent.futures.Executor) – The executor to register.
  • Raises: TypeError – If executor is not of type concurrent.futures.Executor

register_indicator_for_bars(self, BarType bar_type, Indicator indicator)

Register the given indicator with the actor/strategy to receive bar data for the given bar type.

  • Parameters:
    • bar_type (BarType) – The bar type for bar updates.
    • indicator (Indicator) – The indicator to register.

register_indicator_for_quote_ticks(self, InstrumentId instrument_id, Indicator indicator)

Register the given indicator with the actor/strategy to receive quote tick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for tick updates.
    • indicator (Indicator) – The indicator to register.

register_indicator_for_trade_ticks(self, InstrumentId instrument_id, Indicator indicator)

Register the given indicator with the actor/strategy to receive trade tick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for tick updates.
    • indicator (indicator) – The indicator to register.

register_venue(self, SimulatedExchange exchange)

Register the given simulated exchange with the module.

register_warning_event(self, type event)

Register the given event type for warning log levels.

  • Parameters: event (type) – The event class to register.

registered_indicators

Return the registered indicators for the strategy.

request_bars(self, BarType bar_type, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request historical Bar data.

If end is None then will request up to the most recent data.

  • Parameters:
    • bar_type (BarType) – The bar type for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_data(self, DataType data_type, ClientId client_id, callback: Callable[[UUID4], None] | None = None)

Request custom data for the given data type from the given data client.

  • Parameters:
    • data_type (DataType) – The data type for the request.
    • client_id (ClientId) – The data client ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises: TypeError – If callback is not None and not of type Callable.

request_instrument(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request Instrument data for the given instrument ID.

If end is None then will request up to the most recent data.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_instruments(self, Venue venue, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request all Instrument data for the given venue.

If end is None then will request up to the most recent data.

  • Parameters:
    • venue (Venue) – The venue for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_order_book_snapshot(self, InstrumentId instrument_id, int limit, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request an order book snapshot.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
    • limit (int , optional) – The limit on the depth of the order book snapshot (default is None).
    • client_id (ClientId , optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If the instrument_id is None.
    • TypeError – If callback is not None and not of type Callable.

request_quote_ticks(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request historical QuoteTick data.

If end is None then will request up to the most recent data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

request_trade_ticks(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None)

Request historical TradeTick data.

If end is None then will request up to the most recent data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
  • Returns: The request_id for the request.
  • Return type: UUID4
  • Raises:
    • ValueError – If start and end are not None and start is >= end.
    • TypeError – If callback is not None and not of type Callable.

reset(self)

Abstract method (implement in subclass).

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

run_in_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)

Schedules the callable func to be executed as fn(*args, **kwargs).

  • Parameters:
    • func (Callable) – The function to be executed.
    • args (positional arguments) – The positional arguments for the call to func.
    • kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
  • Returns: The unique task identifier for the execution. This also corresponds to any future objects memory address.
  • Return type: TaskId
  • Raises: TypeError – If func is not of type Callable.

save(self)

Return the actor/strategy state dictionary to be saved.

Calls on_save.

  • Raises: RuntimeError – If actor/strategy is not registered with a trader.

WARNING

Exceptions raised will be caught, logged, and reraised.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.

WARNING

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

subscribe_bars(self, BarType bar_type, ClientId client_id=None, bool await_partial=False)

Subscribe to streaming Bar data for the given bar type.

  • Parameters:
    • bar_type (BarType) – The bar type to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • await_partial (bool , default False) – If the bar aggregator should await the arrival of a historical partial bar prior to actively aggregating new bars.

subscribe_data(self, DataType data_type, ClientId client_id=None)

Subscribe to data of the given data type.

  • Parameters:
    • data_type (DataType) – The data type to subscribe to.
    • client_id (ClientId , optional) – The data client ID. If supplied then a Subscribe command will be sent to the corresponding data client.

subscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to update Instrument data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the subscription.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to close updates for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to status updates for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instruments(self, Venue venue, ClientId client_id=None)

Subscribe to update Instrument data for the given venue.

  • Parameters:
    • venue (Venue) – The venue for the subscription.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

subscribe_order_book_at_interval(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, int interval_ms=1000, dict kwargs=None, ClientId client_id=None, bool managed=True)

Subscribe to an OrderBook at a specified interval for the given instrument ID.

The DataEngine will only maintain one order book for each instrument. Because of this - the level, depth and kwargs for the stream will be set as per the last subscription request (this will also affect all subscribers).

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
    • book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) – The order book type.
    • depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
    • interval_ms (int) – The order book snapshot interval in milliseconds (must be positive).
    • kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • managed (bool , default True) – If an order book should be managed by the data engine based on the subscribed feed.
  • Raises:
    • ValueError – If depth is negative (< 0).
    • ValueError – If interval_ms is not positive (> 0).

WARNING

Consider subscribing to order book deltas if you need intervals less than 100 milliseconds.

subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, dict kwargs=None, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False)

Subscribe to the order book data stream, being a snapshot then deltas for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
    • book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) – The order book type.
    • depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
    • kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
    • managed (bool , default True) – If an order book should be managed by the data engine based on the subscribed feed.
    • pyo3_conversion (bool , default False) – If received deltas should be converted to nautilus_pyo3.OrderBookDeltas prior to being passed to the on_order_book_deltas handler.

subscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to streaming QuoteTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Subscribe to streaming TradeTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_venue_status(self, Venue venue, ClientId client_id=None)

Subscribe to status updates for the given venue.

  • Parameters:
    • venue (Venue) – The venue to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

to_importable_config(self)

Returns an importable configuration for this actor.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

unsubscribe_bars(self, BarType bar_type, ClientId client_id=None)

Unsubscribe from streaming Bar data for the given bar type.

  • Parameters:
    • bar_type (BarType) – The bar type to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_data(self, DataType data_type, ClientId client_id=None)

Unsubscribe from data of the given data type.

  • Parameters:
    • data_type (DataType) – The data type to unsubscribe from.
    • client_id (ClientId , optional) – The data client ID. If supplied then an Unsubscribe command will be sent to the data client.

unsubscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe from update Instrument data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe to status updates of the given venue.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument to unsubscribe to status updates for.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

unsubscribe_instruments(self, Venue venue, ClientId client_id=None)

Unsubscribe from update Instrument data for the given venue.

  • Parameters:
    • venue (Venue) – The venue for the subscription.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

unsubscribe_order_book_at_interval(self, InstrumentId instrument_id, int interval_ms=1000, ClientId client_id=None)

Unsubscribe from an OrderBook at a specified interval for the given instrument ID.

The interval must match the previously subscribed interval.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • interval_ms (int) – The order book snapshot interval in milliseconds.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_order_book_deltas(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe the order book deltas stream for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe from streaming QuoteTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None)

Unsubscribe from streaming TradeTick data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_venue_status(self, Venue venue, ClientId client_id=None)

Unsubscribe to status updates for the given venue.

  • Parameters:
    • venue (Venue) – The venue to unsubscribe from.
    • client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.

update_synthetic(self, SyntheticInstrument synthetic)

Update the synthetic instrument in the cache.

  • Parameters: synthetic (SyntheticInstrument) – The synthetic instrument to update in the cache.
  • Raises: KeyError – If synthetic does not already exist in the cache.

class BacktestNode

Bases: object

Provides a node for orchestrating groups of backtest runs.

  • Parameters: configs (list [BacktestRunConfig ]) – The backtest run configurations.
  • Raises:
    • ValueError – If configs is None or empty.
    • ValueError – If configs contains a type other than BacktestRunConfig.

property configs : list[BacktestRunConfig]

Return the loaded backtest run configs for the node.

get_log_guard()

Return the global logging systems log guard.

May return None if no internal engines are initialized yet.

  • Return type: nautilus_pyo3.LogGuard | LogGuard | None

get_engine(run_config_id: str)

Return the backtest engine associated with the given run config ID (if found).

  • Parameters: run_config_id (str) – The run configuration ID for the created engine.
  • Return type: BacktestEngine or None

get_engines()

Return all backtest engines created by the node.

run()

Run the backtest node which will synchronously execute the list of loaded backtest run configs.

Any exceptions raised from a backtest will be printed to stdout and the next backtest run will commence (if any).

  • Returns: The results of the backtest runs.
  • Return type: list[BacktestResult]

classmethod load_catalog(config: BacktestDataConfig)

classmethod load_data_config(config: BacktestDataConfig)

dispose()

class BacktestResult

Bases: object

Represents the results of a single complete backtest run.

trader_id : str

machine_id : str

run_config_id : str | None

instance_id : str

run_id : str

run_started : int | None

run_finished : int | None

backtest_start : int | None

backtest_end : int | None

elapsed_time : float

iterations : int

total_events : int

total_orders : int

total_positions : int

stats_pnls : dict[str, dict[str, float]]

stats_returns : dict[str, float]

ensure_plotting(func)

Decorate a function that require a plotting library.

Ensures library is installed and providers a better error about how to install if not found.