pub struct BacktestEngine { /* private fields */ }Expand description
Core backtesting engine for running event-driven strategy backtests on historical data.
The BacktestEngine provides a high-fidelity simulation environment that processes
historical market data chronologically through an event-driven architecture. It maintains
simulated exchanges with realistic order matching and execution, allowing strategies
to be tested exactly as they would run in live trading:
- Event-driven data replay with configurable latency models.
- Multi-venue and multi-asset support.
- Realistic order matching and execution simulation.
- Strategy and portfolio performance analysis.
- Transition from backtesting to live trading.
Implementations§
Source§impl BacktestEngine
impl BacktestEngine
Sourcepub fn new(config: BacktestEngineConfig) -> Result<Self>
pub fn new(config: BacktestEngineConfig) -> Result<Self>
Create a new BacktestEngine instance.
§Errors
Returns an error if the core NautilusKernel fails to initialize.
Sourcepub fn kernel_mut(&mut self) -> &mut NautilusKernel
pub fn kernel_mut(&mut self) -> &mut NautilusKernel
Returns a mutable reference to the underlying kernel.
Sourcepub fn machine_id(&self) -> &str
pub fn machine_id(&self) -> &str
Returns the machine ID for this engine.
Sourcepub fn instance_id(&self) -> UUID4
pub fn instance_id(&self) -> UUID4
Returns the unique instance ID for this engine.
Sourcepub fn run_config_id(&self) -> Option<&str>
pub fn run_config_id(&self) -> Option<&str>
Returns the last run config ID, if any.
Sourcepub const fn run_started(&self) -> Option<UnixNanos>
pub const fn run_started(&self) -> Option<UnixNanos>
Returns when the last run started, if any.
Sourcepub const fn run_finished(&self) -> Option<UnixNanos>
pub const fn run_finished(&self) -> Option<UnixNanos>
Returns when the last run finished, if any.
Sourcepub const fn backtest_start(&self) -> Option<UnixNanos>
pub const fn backtest_start(&self) -> Option<UnixNanos>
Returns the last backtest range start, if any.
Sourcepub const fn backtest_end(&self) -> Option<UnixNanos>
pub const fn backtest_end(&self) -> Option<UnixNanos>
Returns the last backtest range end, if any.
Sourcepub fn list_venues(&self) -> Vec<Venue>
pub fn list_venues(&self) -> Vec<Venue>
Returns the list of registered venue identifiers.
Sourcepub fn add_venue(&mut self, config: SimulatedVenueConfig) -> Result<()>
pub fn add_venue(&mut self, config: SimulatedVenueConfig) -> Result<()>
§Errors
Returns an error if initializing the simulated exchange for the venue fails.
Sourcepub fn set_settlement_price(
&mut self,
venue: Venue,
instrument_id: InstrumentId,
price: Price,
) -> Result<()>
pub fn set_settlement_price( &mut self, venue: Venue, instrument_id: InstrumentId, price: Price, ) -> Result<()>
Sets the settlement price for the specified venue instrument.
§Errors
Returns an error if the venue has not been added to the engine.
Sourcepub fn change_fill_model(&mut self, venue: Venue, fill_model: FillModelAny)
pub fn change_fill_model(&mut self, venue: Venue, fill_model: FillModelAny)
Changes the fill model for the specified venue.
Sourcepub fn add_instrument(&mut self, instrument: &InstrumentAny) -> Result<()>
pub fn add_instrument(&mut self, instrument: &InstrumentAny) -> Result<()>
Adds an instrument to the backtest engine for the specified venue.
§Errors
Returns an error if:
- The instrument’s associated venue has not been added via
add_venue. - Attempting to add a
CurrencyPairinstrument for a single-currency CASH account.
Sourcepub fn add_data(
&mut self,
data: Vec<Data>,
_client_id: Option<ClientId>,
validate: bool,
sort: bool,
) -> Result<()>
pub fn add_data( &mut self, data: Vec<Data>, _client_id: Option<ClientId>, validate: bool, sort: bool, ) -> Result<()>
Adds market data to the engine for replay during the backtest run.
§Errors
Returns an error if:
datais empty.validateistrueand the instrument for the first element has not been added to the cache viaadd_instrument.validateistrueand the first element is a [Data::Bar] whoseaggregation_sourceis not [AggregationSource::External].
Sourcepub fn add_strategy<T>(&mut self, strategy: T) -> Result<()>where
T: Strategy + Component + Debug + 'static,
pub fn add_strategy<T>(&mut self, strategy: T) -> Result<()>where
T: Strategy + Component + Debug + 'static,
Adds a strategy to the backtest engine.
§Errors
Returns an error if the strategy is already registered or the trader is in an invalid state for strategy registration.
Sourcepub fn add_strategies<T>(&mut self, strategies: Vec<T>) -> Result<()>where
T: Strategy + Component + Debug + 'static,
pub fn add_strategies<T>(&mut self, strategies: Vec<T>) -> Result<()>where
T: Strategy + Component + Debug + 'static,
Adds the given strategies to the backtest engine. Stops at the first error.
§Errors
Returns an error if any strategy fails to register; preceding strategies remain registered.
Sourcepub fn add_actor<T>(&mut self, actor: T) -> Result<()>where
T: DataActor + Component + Debug + 'static,
pub fn add_actor<T>(&mut self, actor: T) -> Result<()>where
T: DataActor + Component + Debug + 'static,
Adds an actor to the backtest engine.
§Errors
Returns an error if the actor is already registered or the trader is in an invalid state for actor registration.
Sourcepub fn add_actors<T>(&mut self, actors: Vec<T>) -> Result<()>where
T: DataActor + Component + Debug + 'static,
pub fn add_actors<T>(&mut self, actors: Vec<T>) -> Result<()>where
T: DataActor + Component + Debug + 'static,
Adds the given actors to the backtest engine. Stops at the first error.
§Errors
Returns an error if any actor fails to register; preceding actors remain registered.
Sourcepub fn add_exec_algorithm<T>(&mut self, exec_algorithm: T) -> Result<()>where
T: ExecutionAlgorithm + Component + Debug + 'static,
pub fn add_exec_algorithm<T>(&mut self, exec_algorithm: T) -> Result<()>where
T: ExecutionAlgorithm + Component + Debug + 'static,
Adds an execution algorithm to the backtest engine.
§Errors
Returns an error if the algorithm is already registered or the trader is running.
Sourcepub fn add_exec_algorithms<T>(&mut self, exec_algorithms: Vec<T>) -> Result<()>where
T: ExecutionAlgorithm + Component + Debug + 'static,
pub fn add_exec_algorithms<T>(&mut self, exec_algorithms: Vec<T>) -> Result<()>where
T: ExecutionAlgorithm + Component + Debug + 'static,
Adds the given execution algorithms to the backtest engine. Stops at the first error.
§Errors
Returns an error if any execution algorithm fails to register; preceding algorithms remain registered.
Sourcepub fn run(
&mut self,
start: Option<UnixNanos>,
end: Option<UnixNanos>,
run_config_id: Option<String>,
streaming: bool,
) -> Result<()>
pub fn run( &mut self, start: Option<UnixNanos>, end: Option<UnixNanos>, run_config_id: Option<String>, streaming: bool, ) -> Result<()>
Run a backtest.
Processes all data chronologically. When streaming is false (default),
finalizes the run via end. When streaming is true, the
run pauses without finalizing so additional data batches can be loaded.
Timer advancement stops at data exhaustion to avoid producing synthetic
events (e.g. zero-volume bars) past the current batch.
Streaming workflow:
- Add initial data and strategies
- Loop: call
run(streaming=true),clear_data(),add_data(next_batch) - After all batches: call
end()to finalize
§Errors
Returns an error if the backtest encounters an unrecoverable state.
Sourcepub fn reset(&mut self)
pub fn reset(&mut self)
Reset the backtest engine.
All stateful fields are reset to their initial value. Data and instruments persist across resets to enable repeated runs with different strategies.
Sourcepub fn sort_data(&mut self)
pub fn sort_data(&mut self)
Sort the engine’s internal data stream by timestamp.
Useful when data has been added with sort=false for batch performance,
then sorted once before running.
Sourcepub fn clear_data(&mut self)
pub fn clear_data(&mut self)
Clear the engine’s internal data stream. Does not clear instruments.
Sourcepub fn clear_actors(&mut self) -> Result<()>
pub fn clear_actors(&mut self) -> Result<()>
Clear all actors from the engine’s internal trader.
§Errors
Returns an error if any actor fails to dispose.
Sourcepub fn clear_strategies(&mut self) -> Result<()>
pub fn clear_strategies(&mut self) -> Result<()>
Clear all trading strategies from the engine’s internal trader.
§Errors
Returns an error if any strategy fails to dispose.
Sourcepub fn clear_exec_algorithms(&mut self) -> Result<()>
pub fn clear_exec_algorithms(&mut self) -> Result<()>
Clear all execution algorithms from the engine’s internal trader.
§Errors
Returns an error if any execution algorithm fails to dispose.
Sourcepub fn get_result(&self) -> BacktestResult
pub fn get_result(&self) -> BacktestResult
Return the backtest result from the last run.
Sourcepub fn add_data_client_if_not_exists(&mut self, client_id: ClientId)
pub fn add_data_client_if_not_exists(&mut self, client_id: ClientId)
Registers a data client for the given client_id if one does not already exist.
Sourcepub fn add_market_data_client_if_not_exists(&mut self, venue: Venue)
pub fn add_market_data_client_if_not_exists(&mut self, venue: Venue)
Registers a market data client for the given venue if one does not already exist.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for BacktestEngine
impl !RefUnwindSafe for BacktestEngine
impl !Send for BacktestEngine
impl !Sync for BacktestEngine
impl Unpin for BacktestEngine
impl UnsafeUnpin for BacktestEngine
impl !UnwindSafe for BacktestEngine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more