Backtest

The backtest subpackage groups components relating to backtesting.

Loaders

class CSVTickDataLoader

Bases: object

Provides a means of loading tick data pandas DataFrames from CSV files.

static load ( file_path ) pandas.core.frame.DataFrame

Return the tick pandas.DataFrame loaded from the given csv file.

Parameters

file_path ( str , path object or file-like object ) – The path to the CSV file.

Returns

pd.DataFrame

class CSVBarDataLoader

Bases: object

Provides a means of loading bar data pandas DataFrames from CSV files.

static load ( file_path ) pandas.core.frame.DataFrame

Return the bar pandas.DataFrame loaded from the given csv file.

Parameters

file_path ( str , path object or file-like object ) – The path to the CSV file.

Returns

pd.DataFrame

class TardisTradeDataLoader

Bases: object

Provides a means of loading trade data pandas DataFrames from Tardis CSV files.

static load ( file_path ) pandas.core.frame.DataFrame

Return the trade pandas.DataFrame loaded from the given csv file.

Parameters

file_path ( str , path object or file-like object ) – The path to the CSV file.

Returns

pd.DataFrame

class TardisQuoteDataLoader

Bases: object

Provides a means of loading quote data pandas DataFrames from Tardis CSV files.

static load ( file_path ) pandas.core.frame.DataFrame

Return the quote pandas.DataFrame loaded from the given csv file.

Parameters

file_path ( str , path object or file-like object ) – The path to the CSV file.

Returns

pd.DataFrame

class ParquetTickDataLoader

Bases: object

Provides a means of loading tick data pandas DataFrames from Parquet files.

static load ( file_path ) pandas.core.frame.DataFrame

Return the tick pandas.DataFrame loaded from the given parquet file.

Parameters

file_path ( str , path object or file-like object ) – The path to the Parquet file.

Returns

pd.DataFrame

class ParquetBarDataLoader

Bases: object

Provides a means of loading bar data pandas DataFrames from parquet files.

static load ( file_path ) pandas.core.frame.DataFrame

Return the bar pandas.DataFrame loaded from the given parquet file.

Parameters

file_path ( str , path object or file-like object ) – The path to the parquet file.

Returns

pd.DataFrame

Providers

class TestInstrumentProvider

Bases: object

Provides instrument template methods for backtesting.

static adabtc_binance ( ) nautilus_trader.model.instruments.currency_pair.CurrencyPair

Return the Binance ADA/BTC instrument for backtesting.

Returns

CurrencyPair

static btcusdt_binance ( ) nautilus_trader.model.instruments.currency_pair.CurrencyPair

Return the Binance BTCUSDT instrument for backtesting.

Returns

CurrencyPair

static ethusdt_binance ( ) nautilus_trader.model.instruments.currency_pair.CurrencyPair

Return the Binance ETHUSDT instrument for backtesting.

Returns

CurrencyPair

static ethusdt_perp_binance ( ) nautilus_trader.model.instruments.crypto_perpetual.CryptoPerpetual

Return the Binance ETHUSDT-PERP instrument for backtesting.

Returns

CryptoPerpetual

static btcusdt_future_binance ( expiry : Optional [ datetime.date ] = None ) nautilus_trader.model.instruments.crypto_future.CryptoFuture

Return the Binance BTCUSDT instrument for backtesting.

Parameters

expiry ( date , optional ) – The expiry date for the contract.

Returns

CryptoFuture

static ethusd_ftx ( ) nautilus_trader.model.instruments.currency_pair.CurrencyPair

Return the FTX ETH/USD instrument for backtesting.

Returns

CurrencyPair

static xbtusd_bitmex ( ) nautilus_trader.model.instruments.crypto_perpetual.CryptoPerpetual

Return the BitMEX XBT/USD perpetual contract for backtesting.

Returns

CryptoPerpetual

static ethusd_bitmex ( ) nautilus_trader.model.instruments.crypto_perpetual.CryptoPerpetual

Return the BitMEX ETH/USD perpetual swap contract for backtesting.

Returns

CryptoPerpetual

static default_fx_ccy ( symbol : str , venue : Optional [ nautilus_trader.model.identifiers.Venue ] = None ) nautilus_trader.model.instruments.currency_pair.CurrencyPair

Return a default FX currency pair instrument from the given symbol and venue.

Parameters
  • symbol ( str ) – The currency pair symbol.

  • venue ( Venue ) – The currency pair venue.

Returns

CurrencyPair

Raises

ValueError – If symbol length is not in range [6, 7].

class TestDataProvider ( branch = 'develop' )

Bases: object

Provides an API to load data from either the ‘test/’ directory or GitHub repo.

Parameters

branch ( str ) – The NautilusTrader GitHub branch for the path.

Wranglers

class BarDataWrangler ( BarType bar_type , Instrument instrument )

Bases: object

Provides a means of building lists of Nautilus Bar objects.

Parameters
  • bar_type ( BarType ) – The bar type for the wrangler.

  • instrument ( Instrument ) – The instrument for the wrangler.

process ( self , data: pd.DataFrame , double default_volume: float = 1000000.0 , ts_init_delta: int = 0 )

Process the given bar dataset into Nautilus Bar objects.

Expects columns [‘open’, ‘high’, ‘low’, ‘close’, ‘volume’] with ‘timestamp’ index. Note: The ‘volume’ column is optional, will then use the default_volume .

Parameters
  • data ( pd.DataFrame ) – The data to process.

  • default_volume ( float ) – The default volume for each bar (if not provided).

  • ts_init_delta ( int ) – The difference in nanoseconds between the data timestamps and the ts_init value. Can be used to represent/simulate latency between the data source and the Nautilus system.

Returns

list[Bar]

Raises

ValueError – If data is empty.

class QuoteTickDataWrangler ( Instrument instrument )

Bases: object

Provides a means of building lists of Nautilus QuoteTick objects.

Parameters

instrument ( Instrument ) – The instrument for the data wrangler.

process ( self , data: pd.DataFrame , double default_volume: float = 1000000.0 , ts_init_delta: int = 0 )

Process the give tick dataset into Nautilus QuoteTick objects.

Expects columns [‘bid’, ‘ask’] with ‘timestamp’ index. Note: The ‘bid_size’ and ‘ask_size’ columns are optional, will then use the default_volume .

Parameters
  • data ( pd.DataFrame ) – The tick data to process.

  • default_volume ( float ) – The default volume for each tick (if not provided).

  • ts_init_delta ( int ) – The difference in nanoseconds between the data timestamps and the ts_init value. Can be used to represent/simulate latency between the data source and the Nautilus system. Cannot be negative.

Returns

list[QuoteTick]

process_bar_data ( self , bid_data: pd.DataFrame , ask_data: pd.DataFrame , double default_volume: float = 1000000.0 , ts_init_delta: int = 0 , random_seed: Optional[int] = None , bool is_raw: bool = False )

Process the given bar datasets into Nautilus QuoteTick objects.

Expects columns [‘open’, ‘high’, ‘low’, ‘close’, ‘volume’] with ‘timestamp’ index. Note: The ‘volume’ column is optional, will then use the default_volume .

Parameters
  • bid_data ( pd.DataFrame ) – The bid bar data.

  • ask_data ( pd.DataFrame ) – The ask bar data.

  • default_volume ( float ) – The volume per tick if not available from the data.

  • ts_init_delta ( int ) – The difference in nanoseconds between the data timestamps and the ts_init value. Can be used to represent/simulate latency between the data source and the Nautilus system.

  • random_seed ( int , optional ) – The random seed for shuffling order of high and low ticks from bar data. If random_seed is None then won’t shuffle.

  • is_raw ( bool , default False ) – If the data is scaled to the Nautilus fixed precision.

class TradeTickDataWrangler ( Instrument instrument )

Bases: object

Provides a means of building lists of Nautilus TradeTick objects.

Parameters

instrument ( Instrument ) – The instrument for the data wrangler.

process ( self , data: pd.DataFrame , ts_init_delta: int = 0 , bool is_raw=False )

Process the given trade tick dataset into Nautilus TradeTick objects.

Parameters
  • data ( pd.DataFrame ) – The data to process.

  • ts_init_delta ( int ) – The difference in nanoseconds between the data timestamps and the ts_init value. Can be used to represent/simulate latency between the data source and the Nautilus system.

  • is_raw ( bool , default False ) – If the data is scaled to the Nautilus fixed precision.

Raises

ValueError – If data is empty.

Data Client

This module provides a data client for backtesting.

class BacktestDataClient ( ClientId client_id , MessageBus msgbus , Cache cache , Clock clock , Logger logger , dict config=None )

Bases: nautilus_trader.data.client.DataClient

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.

  • logger ( Logger ) – The logger for the client.

  • config ( dict [ str , object ] , optional ) – The configuration for the instance.

degrade ( self ) void

Degrade the component.

While executing on_degrade() , any exception will be logged and reraised. 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 ) void

Dispose of the component.

While executing on_dispose() , any exception will be logged and reraised. 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 ) void

Fault the component.

This method is idempotent and irreversible. No other methods should be called after faulting.

While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str

Return the fully qualified name for the components class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

id

The components ID.

Returns

ComponentId

is_connected

If the client is connected.

Returns

bool

is_degraded

Return whether the current component state is DEGRADED .

Returns

bool

is_disposed

Return whether the current component state is DISPOSED .

Returns

bool

is_faulted

Return whether the current component state is FAULTED .

Returns

bool

is_initialized

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

Returns

bool

is_running

Return whether the current component state is RUNNING .

Returns

bool

is_stopped

Return whether the current component state is STOPPED .

Returns

bool

request ( self , DataType data_type , UUID4 correlation_id ) void
reset ( self ) void

Reset the component.

All stateful fields are reset to their initial value.

While executing on_reset() , any exception will be logged and reraised. 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 ) void

Resume the component.

While executing on_resume() , any exception will be logged and reraised. 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 ) void

Start the component.

While executing on_start() , any exception will be logged and reraised. 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

Return the components current state.

Returns

ComponentState

stop ( self ) void

Stop the component.

While executing on_stop() , any exception will be logged and reraised. 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 ) void
subscribed_generic_data ( self ) list

Return the generic data types subscribed to.

Returns

list[DataType]

trader_id

The trader ID associated with the component.

Returns

TraderId

type

The components type.

Returns

type

unsubscribe ( self , DataType data_type ) void
venue

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

Returns

Venue or None

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

Bases: nautilus_trader.data.client.MarketDataClient

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.

  • logger ( Logger ) – The logger for the client.

degrade ( self ) void

Degrade the component.

While executing on_degrade() , any exception will be logged and reraised. 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 ) void

Dispose of the component.

While executing on_dispose() , any exception will be logged and reraised. 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 ) void

Fault the component.

This method is idempotent and irreversible. No other methods should be called after faulting.

While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str

Return the fully qualified name for the components class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

id

The components ID.

Returns

ComponentId

is_connected

If the client is connected.

Returns

bool

is_degraded

Return whether the current component state is DEGRADED .

Returns

bool

is_disposed

Return whether the current component state is DISPOSED .

Returns

bool

is_faulted

Return whether the current component state is FAULTED .

Returns

bool

is_initialized

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

Returns

bool

is_running

Return whether the current component state is RUNNING .

Returns

bool

is_stopped

Return whether the current component state is STOPPED .

Returns

bool

request ( self , DataType data_type , UUID4 correlation_id ) void

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 from_datetime: Optional[datetime] = None , datetime to_datetime: Optional[datetime] = None ) void
request_instrument ( self , InstrumentId instrument_id , UUID4 correlation_id ) void
request_quote_ticks ( self , InstrumentId instrument_id , int limit , UUID4 correlation_id , datetime from_datetime: Optional[datetime] = None , datetime to_datetime: Optional[datetime] = None ) void
request_trade_ticks ( self , InstrumentId instrument_id , int limit , UUID4 correlation_id , datetime from_datetime: Optional[datetime] = None , datetime to_datetime: Optional[datetime] = None ) void
reset ( self ) void

Reset the component.

All stateful fields are reset to their initial value.

While executing on_reset() , any exception will be logged and reraised. 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 ) void

Resume the component.

While executing on_resume() , any exception will be logged and reraised. 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 ) void

Start the component.

While executing on_start() , any exception will be logged and reraised. 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

Return the components current state.

Returns

ComponentState

stop ( self ) void

Stop the component.

While executing on_stop() , any exception will be logged and reraised. 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 ) void

Subscribe to data for the given data type.

Parameters

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

subscribe_bars ( self , BarType bar_type ) void
subscribe_instrument ( self , InstrumentId instrument_id ) void
subscribe_instrument_close_prices ( self , InstrumentId instrument_id ) void
subscribe_instrument_status_updates ( self , InstrumentId instrument_id ) void
subscribe_instruments ( self ) void
subscribe_order_book_deltas ( self , InstrumentId instrument_id , BookType book_type , int depth=0 , dict kwargs=None ) void
subscribe_order_book_snapshots ( self , InstrumentId instrument_id , BookType book_type , int depth=0 , dict kwargs=None ) void
subscribe_quote_ticks ( self , InstrumentId instrument_id ) void
subscribe_ticker ( self , InstrumentId instrument_id ) void
subscribe_trade_ticks ( self , InstrumentId instrument_id ) void
subscribed_bars ( self ) list

Return the bar types subscribed to.

Returns

list[BarType]

subscribed_generic_data ( self ) list

Return the generic data types subscribed to.

Returns

list[DataType]

subscribed_instrument_close_prices ( self ) list

Return the close price instruments subscribed to.

Returns

list[InstrumentId]

subscribed_instrument_status_updates ( self ) list

Return the status update instruments subscribed to.

Returns

list[InstrumentId]

subscribed_instruments ( self ) list

Return the instruments subscribed to.

Returns

list[InstrumentId]

subscribed_order_book_deltas ( self ) list

Return the order book delta instruments subscribed to.

Returns

list[InstrumentId]

subscribed_order_book_snapshots ( self ) list

Return the order book snapshot instruments subscribed to.

Returns

list[InstrumentId]

subscribed_quote_ticks ( self ) list

Return the quote tick instruments subscribed to.

Returns

list[InstrumentId]

subscribed_tickers ( self ) list

Return the ticker instruments subscribed to.

Returns

list[InstrumentId]

subscribed_trade_ticks ( self ) list

Return the trade tick instruments subscribed to.

Returns

list[InstrumentId]

trader_id

The trader ID associated with the component.

Returns

TraderId

type

The components type.

Returns

type

unsubscribe ( self , DataType data_type ) void

Unsubscribe from data for the given data type.

Parameters

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

unsubscribe_bars ( self , BarType bar_type ) void
unsubscribe_instrument ( self , InstrumentId instrument_id ) void
unsubscribe_instrument_close_prices ( self , InstrumentId instrument_id ) void
unsubscribe_instrument_status_updates ( self , InstrumentId instrument_id ) void
unsubscribe_instruments ( self ) void
unsubscribe_order_book_deltas ( self , InstrumentId instrument_id ) void
unsubscribe_order_book_snapshots ( self , InstrumentId instrument_id ) void
unsubscribe_quote_ticks ( self , InstrumentId instrument_id ) void
unsubscribe_ticker ( self , InstrumentId instrument_id ) void
unsubscribe_trade_ticks ( self , InstrumentId instrument_id ) void
venue

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

Returns

Venue or None

Engine

class BacktestEngine ( config : Optional [ BacktestEngineConfig ] = None )

Bases: object

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 ) None

Add the given actor to the backtest engine.

Parameters

actor ( Actor ) – The actor to add.

add_actors ( self , actors : List [ Actor ] ) None

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 ) None

Add the given data to the backtest engine.

Parameters
  • data ( list [ Data ] ) – The data to add.

  • client_id ( ClientId , optional ) – The data client ID to associate with generic data.

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 .

Warning

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

add_instrument ( self , Instrument instrument ) None

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.

Parameters

instrument ( Instrument ) – The instrument to add.

Raises
  • InvalidConfiguration – If the venue for the instrument has not been added to the engine.

  • InvalidConfiguration – If instrument is not valid for its associated venue.

add_strategies ( self , strategies : List [ Strategy ] ) None

Add the given list of strategies to the backtest engine.

Parameters

strategies ( List [ Strategy ] ) – The strategies to add.

add_strategy ( self , Strategy strategy: Strategy ) None

Add the given strategy to the backtest engine.

Parameters

strategy ( Strategy ) – The strategy to add.

add_venue ( self , Venue venue , OMSType oms_type , AccountType account_type , Currency base_currency , list starting_balances , default_leverage=None , dict leverages=None , list modules=None , FillModel fill_model=None , LatencyModel latency_model=None , BookType book_type=BookType.L1_TBBO , bool routing: bool = False , bool frozen_account=False , bool reject_stop_orders: bool = True ) None

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.

  • base_currency ( Currency , optional ) – The account base currency for the client. Use None for multi-currency accounts.

  • starting_balances ( list [ Money ] ) – The starting account balances (specify one for a single asset account).

  • default_leverage ( Decimal , optional ) – The account default leverage (for margin accounts).

  • leverages ( Dict [ InstrumentId , Decimal ] ) – 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.

  • latency_model ( LatencyModel , optional ) – The latency model for the exchange.

  • book_type (BookType, default BookType.L1_TBBO ) – 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).

  • reject_stop_orders ( bool , default True ) – If stop orders are rejected on submission if trigger price is in the market.

Raises

ValueError – If venue is already registered with the engine.

backtest_end

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

Returns

datetime or None

backtest_start

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

Returns

datetime or None

cache

Return the engines internal read-only cache.

Returns

CacheFacade

change_fill_model ( self , Venue venue , FillModel model ) None

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_data ( self )

Clear the engines internal data stream.

Does not clear added instruments.

data

Return the engines internal data stream.

Returns

list[Data]

dispose ( self ) None

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

This method is idempotent and irreversible. No other methods should be called after disposal.

dump_pickled_data ( self ) bytes

Return the internal data stream pickled.

Returns

bytes

end_streaming ( self )

End the backtest streaming run.

The following sequence of events will occur:
  • The trader will be stopped which in turn stops the strategies.

  • The exchanges will process all pending messages.

  • Post-run analysis is performed.

get_result ( self )

Return the backtest result from the last run.

Returns

BacktestResult

instance_id

Return the engines instance ID.

This is a unique identifier per initialized engine.

Returns

UUID4

iteration

Return the backtest engine iteration count.

Returns

int

kernel

Return the internal kernel for the engine.

Returns

NautilusKernel

list_actors ( self ) list

Return the actors for the backtest.

Returns

List[Actors]

list_strategies ( self ) list

Return the strategies for the backtest.

Returns

List[Strategy]

list_venues ( self )

Return the venues contained within the engine.

Returns

list[Venue]

load_pickled_data ( self , bytes data ) None

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.

machine_id

Return the engines machine ID.

Returns

str

portfolio

Return the engines internal read-only portfolio.

Returns

PortfolioFacade

reset ( self ) None

Reset the backtest engine.

All stateful fields are reset to their initial value.

run ( self , start : Optional [ Union [ datetime , str , int ] ] = None , end : Optional [ Union [ datetime , str , int ] ] = None , run_config_id : Optional [ str ] = None ) None

Run a backtest.

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

Parameters
  • start ( Union [ datetime , str , int ] , optional ) – The start datetime (UTC) for the backtest run. If None engine runs from the start of the data.

  • end ( Union [ datetime , str , 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.

Raises
  • ValueError – If no data has been added to the engine.

  • ValueError – If the start is >= the end datetime.

run_config_id

Return the last backtest engine run config ID.

Returns

str or None

run_finished

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

Returns

datetime or None

run_id

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

Returns

UUID4 or None

run_started

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

Returns

datetime or None

run_streaming ( self , start : Optional [ Union [ datetime , str , int ] ] = None , end : Optional [ Union [ datetime , str , int ] ] = None , run_config_id : Optional [ str ] = None )

Run a backtest in streaming mode.

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() . - Call clear_data() . - Add next batch of data stream. - Call run_streaming() . - Call end_streaming() when there is no more data to run on.

Parameters
  • start ( Union [ datetime , str , int ] , optional ) – The start datetime (UTC) for the current batch of data. If None engine runs from the start of the data.

  • end ( Union [ datetime , str , int ] , optional ) – The end datetime (UTC) for the current batch of data. If None engine runs to the end of the data.

  • run_config_id ( str , optional ) – The tokenized backtest run configuration ID.

Raises
  • ValueError – If no data has been added to the engine.

  • ValueError – If the start is >= the end datetime.

trader

Return the engines internal trader.

Returns

Trader

trader_id

Return the engines trader ID.

Returns

TraderId

Exchange

class SimulatedExchange ( Venue venue, OMSType oms_type, AccountType account_type, Currency base_currency: Optional[Currency], list starting_balances, default_leverage: Decimal, leverages: Dict[InstrumentId, Decimal], list instruments, list modules, MessageBus msgbus, CacheFacade cache, TestClock clock, Logger logger, FillModel fill_model, LatencyModel latency_model=None, BookType book_type=BookType.L1_TBBO, bool frozen_account=False, bool reject_stop_orders=True )

Bases: object

Provides a simulated financial market exchange.

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.

  • base_currency ( Currency , optional ) – The account base currency for the client. Use None for multi-currency accounts.

  • starting_balances ( list [ Money ] ) – The starting balances for the exchange.

  • default_leverage ( Decimal ) – The account default leverage (for margin accounts).

  • leverages ( Dict [ InstrumentId , Decimal ] ) – The instrument specific leverage configuration (for margin accounts).

  • msgbus ( MessageBus ) – The message bus for the exchange.

  • cache ( CacheFacade ) – The read-only cache for the exchange.

  • fill_model ( FillModel ) – The fill model for the exchange.

  • latency_model ( LatencyModel , optional ) – The latency model for the exchange.

  • clock ( TestClock ) – The clock for the exchange.

  • logger ( Logger ) – The logger 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).

  • reject_stop_orders ( bool , default True ) – If stop orders are rejected on submission if in the market.

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 ) void

Add the given instrument to the venue.

Parameters

instrument ( Instrument ) – The instrument to add.

Raises
  • ValueError – If instrument.id.venue is not equal to the venue ID.

  • KeyError – If instrument is already contained within the venue. This is to enforce correct internal identifier indexing.

  • InvalidConfiguration – If instrument is invalid for this venue.

adjust_account ( self , Money adjustment ) void

Adjust the account at the exchange with the given adjustment.

Parameters

adjustment ( Money ) – The adjustment for the account.

base_currency

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

Returns

Currency or None

best_ask_price ( self , InstrumentId instrument_id ) Price

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

Parameters

instrument_id ( InstrumentId ) – The instrument ID for the price.

Returns

Price or None

best_bid_price ( self , InstrumentId instrument_id ) Price

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

Parameters

instrument_id ( InstrumentId ) – The instrument ID for the price.

Returns

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

fill_model

The fill model for the exchange.

Returns

FillModel

get_account ( self ) Account

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

Returns

Account or None

get_book ( self , InstrumentId instrument_id ) OrderBook

Return the order book for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The instrument ID for the price.

Returns

OrderBook or None

get_books ( self ) dict

Return all order books within the exchange.

Returns

dict[InstrumentId, OrderBook]

get_matching_engines ( self ) dict
get_open_ask_orders ( self , InstrumentId instrument_id=None ) list

Return the open ask orders at the exchange.

Parameters

instrument_id ( InstrumentId , optional ) – The instrument_id query filter.

Returns

list[Order]

get_open_bid_orders ( self , InstrumentId instrument_id=None ) list

Return the open bid orders at the exchange.

Parameters

instrument_id ( InstrumentId , optional ) – The instrument_id query filter.

Returns

list[Order]

get_open_orders ( self , InstrumentId instrument_id=None ) list

Return the open orders at the exchange.

Parameters

instrument_id ( InstrumentId , optional ) – The instrument_id query filter.

Returns

list[Order]

id

The exchange ID.

Returns

Venue

initialize_account ( self ) void

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 now_ns ) void

Process the exchange to the gives time.

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

Parameters

now_ns ( uint64_t ) – The UNIX timestamp (nanoseconds) now.

process_bar ( self , Bar bar ) void

Process the exchanges market for the given bar.

Market dynamics are simulated by auctioning open orders.

Parameters

bar ( Bar ) – The bar to process.

process_order_book ( self , OrderBookData data ) void

Process the exchanges market for the given order book data.

Parameters

data ( OrderBookData ) – The order book data to process.

process_quote_tick ( self , QuoteTick tick ) void

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 ) void

Process the exchanges market for the given trade tick.

Market dynamics are simulated by auctioning open orders.

Parameters

tick ( TradeTick ) – The tick to process.

register_client ( self , BacktestExecClient client ) void

Register the given execution client with the simulated exchange.

Parameters

client ( BacktestExecClient ) – The client to register

reject_stop_orders

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

Returns

bool

reset ( self ) void

Reset the simulated exchange.

All stateful fields are reset to their initial value.

send ( self , TradingCommand command ) void

Send the given trading command into the exchange.

Parameters

command ( TradingCommand ) – The command to send.

set_fill_model ( self , FillModel fill_model ) void

Set the fill model for all matching engines.

Parameters

fill_model ( FillModel ) – The fill model to set.

set_latency_model ( self , LatencyModel latency_model ) void

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

Execution

class BacktestExecClient ( SimulatedExchange exchange , MessageBus msgbus , Cache cache , TestClock clock , Logger logger , bool routing=False , bool frozen_account=False )

Bases: nautilus_trader.execution.client.ExecutionClient

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.

  • logger ( Logger ) – The logger 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

cancel_all_orders ( self , CancelAllOrders command ) void
cancel_order ( self , CancelOrder command ) void
degrade ( self ) void

Degrade the component.

While executing on_degrade() , any exception will be logged and reraised. 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 ) void

Dispose of the component.

While executing on_dispose() , any exception will be logged and reraised. 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 ) void

Fault the component.

This method is idempotent and irreversible. No other methods should be called after faulting.

While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str

Return the fully qualified name for the components class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

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

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 ) – The 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 ) void

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 ) – The 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 ) void

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 ) – The 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 ) void

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 ) – The 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 ) void

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 ) – The 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: Optional[PositionId], 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 ) void

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 { NONE , MAKER , TAKER }) – The execution liquidity side.

  • ts_event ( uint64_t ) – The 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 ) void

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 ) – The UNIX timestamp (nanoseconds) when the order update rejection event occurred.

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

Generate an OrderPendingCancel 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 ) – The UNIX timestamp (nanoseconds) when the order pending cancel event occurred.

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

Generate an OrderPendingUpdate 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 ) – The UNIX timestamp (nanoseconds) when the order pending update event occurred.

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

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 ) – The 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 ) void

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 ) – The 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 ) void

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 ) – The 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 ) void

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 ) – The 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 ) Account

Return the account for the client (if registered).

Returns

Account or None

id

The components ID.

Returns

ComponentId

is_connected

If the client is connected.

Returns

bool

is_degraded

Return whether the current component state is DEGRADED .

Returns

bool

is_disposed

Return whether the current component state is DISPOSED .

Returns

bool

is_faulted

Return whether the current component state is FAULTED .

Returns

bool

is_initialized

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

Returns

bool

is_running

Return whether the current component state is RUNNING .

Returns

bool

is_stopped

Return whether the current component state is STOPPED .

Returns

bool

modify_order ( self , ModifyOrder command ) void
oms_type

The venues order management system type.

Returns

OMSType

reset ( self ) void

Reset the component.

All stateful fields are reset to their initial value.

While executing on_reset() , any exception will be logged and reraised. 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 ) void

Resume the component.

While executing on_resume() , any exception will be logged and reraised. 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 ) void

Start the component.

While executing on_start() , any exception will be logged and reraised. 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

Return the components current state.

Returns

ComponentState

stop ( self ) void

Stop the component.

While executing on_stop() , any exception will be logged and reraised. 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 ) void
submit_order_list ( self , SubmitOrderList command ) void
sync_order_status ( self , QueryOrder command ) void

Request a reconciliation for the queried order which will generate an OrderStatusReport

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

Models

class FillModel ( double prob_fill_on_limit=1.0 , double prob_fill_on_stop=1.0 , double prob_slippage=0.0 , random_seed: Optional[int] = None )

Bases: object

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 ) bool

Return a value indicating whether a LIMIT order filled.

Returns

bool

is_slipped ( self ) bool

Return a value indicating whether an order fill slipped.

Returns

bool

is_stop_filled ( self ) bool

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

Returns

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 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 )

Bases: object

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

Modules

class FXRolloverInterestModule ( rate_data : pd.DataFrame )

Bases: nautilus_trader.backtest.modules.SimulationModule

Provides an FX rollover interest simulation module.

Parameters

rate_data ( pd.DataFrame ) – The interest rate data for the internal rollover interest calculator.

log_diagnostics ( self , LoggerAdapter log ) void

Log diagnostics out to the BacktestEngine logger.

Parameters

log ( LoggerAdapter ) – The logger to log to.

process ( self , uint64_t now_ns ) void

Process the given tick through the module.

Parameters

now_ns ( uint64_t ) – The current time in the simulated exchange.

register_exchange ( self , SimulatedExchange exchange ) void

Register the given simulated exchange with the module.

Parameters

exchange ( SimulatedExchange ) – The exchange to register.

reset ( self ) void
class SimulationModule

Bases: object

The abstract base class for all simulation modules.

Warning

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

log_diagnostics ( self , LoggerAdapter log ) void

Abstract method (implement in subclass).

process ( self , uint64_t now_ns ) void

Abstract method (implement in subclass).

register_exchange ( self , SimulatedExchange exchange ) void

Register the given simulated exchange with the module.

Parameters

exchange ( SimulatedExchange ) – The exchange to register.

reset ( self ) void

Abstract method (implement in subclass).

Backtest Node

class BacktestNode ( configs : List [ nautilus_trader.config.backtest.BacktestRunConfig ] )

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 [ nautilus_trader.config.backtest.BacktestRunConfig ]

Return the loaded backtest run configs for the node.

Returns

list[BacktestRunConfig]

get_engine ( run_config_id : str ) Optional [ nautilus_trader.backtest.engine.BacktestEngine ]

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.

Returns

BacktestEngine or None

get_engines ( ) List [ nautilus_trader.backtest.engine.BacktestEngine ]

Return all backtest engines created by the node.

Returns

list[BacktestEngine]

run ( ) List [ nautilus_trader.backtest.results.BacktestResult ]

Execute a group of backtest run configs synchronously.

Returns

list[BacktestResult] – The results of the backtest runs.

Results

class BacktestResult ( trader_id : str , machine_id : str , run_config_id : Optional [ str ] , instance_id : str , run_id : str , run_started : Optional [ int ] , run_finished : Optional [ int ] , backtest_start : Optional [ int ] , backtest_end : Optional [ int ] , 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 ] )

Bases: object

Represents the results of a single complete backtest run.

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.