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.
- Seamless 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 add_venue(
&mut self,
venue: Venue,
oms_type: OmsType,
account_type: AccountType,
book_type: BookType,
starting_balances: Vec<Money>,
base_currency: Option<Currency>,
default_leverage: Option<Decimal>,
leverages: AHashMap<InstrumentId, Decimal>,
modules: Vec<Box<dyn SimulationModule>>,
fill_model: FillModelAny,
fee_model: FeeModelAny,
latency_model: Option<Box<dyn LatencyModel>>,
routing: Option<bool>,
reject_stop_orders: Option<bool>,
support_gtd_orders: Option<bool>,
support_contingent_orders: Option<bool>,
use_position_ids: Option<bool>,
use_random_ids: Option<bool>,
use_reduce_only: Option<bool>,
use_message_queue: Option<bool>,
use_market_order_acks: Option<bool>,
bar_execution: Option<bool>,
bar_adaptive_high_low_ordering: Option<bool>,
trade_execution: Option<bool>,
liquidity_consumption: Option<bool>,
allow_cash_borrowing: Option<bool>,
frozen_account: Option<bool>,
price_protection_points: Option<u32>,
) -> Result<()>
pub fn add_venue( &mut self, venue: Venue, oms_type: OmsType, account_type: AccountType, book_type: BookType, starting_balances: Vec<Money>, base_currency: Option<Currency>, default_leverage: Option<Decimal>, leverages: AHashMap<InstrumentId, Decimal>, modules: Vec<Box<dyn SimulationModule>>, fill_model: FillModelAny, fee_model: FeeModelAny, latency_model: Option<Box<dyn LatencyModel>>, routing: Option<bool>, reject_stop_orders: Option<bool>, support_gtd_orders: Option<bool>, support_contingent_orders: Option<bool>, use_position_ids: Option<bool>, use_random_ids: Option<bool>, use_reduce_only: Option<bool>, use_message_queue: Option<bool>, use_market_order_acks: Option<bool>, bar_execution: Option<bool>, bar_adaptive_high_low_ordering: Option<bool>, trade_execution: Option<bool>, liquidity_consumption: Option<bool>, allow_cash_borrowing: Option<bool>, frozen_account: Option<bool>, price_protection_points: Option<u32>, ) -> Result<()>
§Errors
Returns an error if initializing the simulated exchange for the venue fails.
pub fn change_fill_model(&mut self, venue: Venue, fill_model: FillModelAny)
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.
§Panics
Panics if adding the instrument to the simulated exchange fails.
pub fn add_data( &mut self, data: Vec<Data>, _client_id: Option<ClientId>, validate: bool, sort: bool, )
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 running.
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 running.
Sourcepub fn add_exec_algorithm<T>(&mut self, exec_algorithm: T) -> Result<()>where
T: DataActor + Component + Debug + 'static,
pub fn add_exec_algorithm<T>(&mut self, exec_algorithm: T) -> Result<()>where
T: DataActor + 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 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, allowing additional data to be loaded:
- Add initial data and strategies
- Call
run(streaming=true) - Call
clear_data() - Add next batch of data
- Repeat steps 2-4, then call
run(streaming=false)orend()for the final batch
§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_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.
pub fn add_data_client_if_not_exists(&mut self, client_id: ClientId)
pub fn add_market_data_client_if_not_exists(&mut self, venue: Venue)
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