Skip to main content

nautilus_backtest/
node.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides a [`BacktestNode`] that orchestrates catalog-driven backtests.
17
18use std::iter::Peekable;
19
20use ahash::{AHashMap, AHashSet};
21use nautilus_core::UnixNanos;
22use nautilus_model::{
23    data::{
24        Bar, Data, FundingRateUpdate, HasTsInit, IndexPriceUpdate, InstrumentClose,
25        InstrumentStatus, MarkPriceUpdate, OptionGreeks, OrderBookDelta, OrderBookDepth10,
26        QuoteTick, TradeTick,
27    },
28    enums::{BookType, OtoTriggerMode},
29    identifiers::{InstrumentId, Venue},
30    instruments::Instrument,
31    types::Money,
32};
33use nautilus_persistence::backend::{catalog::ParquetDataCatalog, session::QueryResult};
34
35use crate::{
36    config::{BacktestDataConfig, BacktestRunConfig, NautilusDataType, SimulatedVenueConfig},
37    engine::BacktestEngine,
38    result::BacktestResult,
39};
40
41/// Orchestrates catalog-driven backtests from run configurations.
42///
43/// `BacktestNode` connects the [`ParquetDataCatalog`] with [`BacktestEngine`] to load
44/// historical data and run backtests. Supports both oneshot and streaming modes.
45#[derive(Debug)]
46#[cfg_attr(
47    feature = "python",
48    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.backtest", unsendable)
49)]
50#[cfg_attr(
51    feature = "python",
52    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
53)]
54pub struct BacktestNode {
55    configs: Vec<BacktestRunConfig>,
56    engines: AHashMap<String, BacktestEngine>,
57}
58
59impl BacktestNode {
60    /// Creates a new [`BacktestNode`] instance.
61    ///
62    /// Validates that configs are non-empty and internally consistent:
63    /// - All data config instrument venues must have a matching venue config.
64    /// - L2/L3 book types require order book data in the data configs.
65    /// - Data config time ranges must be valid (start <= end).
66    ///
67    /// # Errors
68    ///
69    /// Returns an error if `configs` is empty or validation fails.
70    pub fn new(configs: Vec<BacktestRunConfig>) -> anyhow::Result<Self> {
71        anyhow::ensure!(!configs.is_empty(), "At least one run config is required");
72        validate_configs(&configs)?;
73        Ok(Self {
74            configs,
75            engines: AHashMap::new(),
76        })
77    }
78
79    /// Returns the run configurations.
80    #[must_use]
81    pub fn configs(&self) -> &[BacktestRunConfig] {
82        &self.configs
83    }
84
85    /// Builds backtest engines from the run configurations.
86    ///
87    /// For each config, creates a [`BacktestEngine`], adds venues, and loads
88    /// instruments from the catalog.
89    ///
90    /// # Errors
91    ///
92    /// Returns an error if engine creation, venue setup, or instrument loading fails.
93    pub fn build(&mut self) -> anyhow::Result<()> {
94        for config in &self.configs {
95            if self.engines.contains_key(config.id()) {
96                continue;
97            }
98
99            let engine_config = config.engine().clone();
100            let mut engine = BacktestEngine::new(engine_config)?;
101
102            for venue_config in config.venues() {
103                let starting_balances: Vec<Money> = venue_config
104                    .starting_balances()
105                    .iter()
106                    .map(|s| s.parse::<Money>())
107                    .collect::<Result<Vec<_>, _>>()
108                    .map_err(|e| anyhow::anyhow!("Invalid starting balance: {e}"))?;
109
110                let default_leverage = venue_config.default_leverage();
111                let leverages = venue_config.leverages().cloned().unwrap_or_default();
112                let margin_model = venue_config.margin_model().cloned();
113                let modules = venue_config
114                    .modules()
115                    .iter()
116                    .cloned()
117                    .map(Into::into)
118                    .collect();
119                let fill_model = venue_config.fill_model().cloned().unwrap_or_default();
120                let fee_model = venue_config.fee_model().cloned().unwrap_or_default();
121                let latency_model = venue_config.latency_model().cloned().map(Into::into);
122                let sim_config = SimulatedVenueConfig::builder()
123                    .venue(Venue::from(venue_config.name().as_str()))
124                    .oms_type(venue_config.oms_type())
125                    .account_type(venue_config.account_type())
126                    .book_type(venue_config.book_type())
127                    .starting_balances(starting_balances)
128                    .maybe_base_currency(venue_config.base_currency())
129                    .default_leverage(default_leverage)
130                    .leverages(leverages)
131                    .maybe_margin_model(margin_model)
132                    .modules(modules)
133                    .fill_model(fill_model)
134                    .fee_model(fee_model)
135                    .maybe_latency_model(latency_model)
136                    .routing(venue_config.routing())
137                    .reject_stop_orders(venue_config.reject_stop_orders())
138                    .support_gtd_orders(venue_config.support_gtd_orders())
139                    .support_contingent_orders(venue_config.support_contingent_orders())
140                    .use_position_ids(venue_config.use_position_ids())
141                    .use_random_ids(venue_config.use_random_ids())
142                    .use_reduce_only(venue_config.use_reduce_only())
143                    .use_market_order_acks(venue_config.use_market_order_acks())
144                    .bar_execution(venue_config.bar_execution())
145                    .bar_adaptive_high_low_ordering(venue_config.bar_adaptive_high_low_ordering())
146                    .trade_execution(venue_config.trade_execution())
147                    .liquidity_consumption(venue_config.liquidity_consumption())
148                    .allow_cash_borrowing(venue_config.allow_cash_borrowing())
149                    .frozen_account(venue_config.frozen_account())
150                    .queue_position(venue_config.queue_position())
151                    .oto_full_trigger(venue_config.oto_trigger_mode() == OtoTriggerMode::Full)
152                    .price_protection_points(venue_config.price_protection_points())
153                    .liquidation_enabled(venue_config.liquidation_enabled())
154                    .liquidation_trigger_ratio(venue_config.liquidation_trigger_ratio())
155                    .liquidation_cancel_open_orders(venue_config.liquidation_cancel_open_orders())
156                    .build()?;
157                engine.add_venue(sim_config)?;
158            }
159
160            for data_config in config.data() {
161                let catalog = create_catalog(data_config)?;
162                let instr_ids: Vec<InstrumentId> = data_config.get_instrument_ids()?;
163                let filter: Option<Vec<String>> = if instr_ids.is_empty() {
164                    None
165                } else {
166                    Some(instr_ids.iter().map(ToString::to_string).collect())
167                };
168
169                let instruments = catalog.query_instruments(filter.as_deref())?;
170
171                if !instr_ids.is_empty() && instruments.is_empty() {
172                    let ids: Vec<String> = instr_ids.iter().map(ToString::to_string).collect();
173                    anyhow::bail!(
174                        "No instruments found in catalog for requested IDs: [{}]",
175                        ids.join(", ")
176                    );
177                }
178
179                for instrument in instruments {
180                    engine.add_instrument(&instrument)?;
181                }
182            }
183
184            for venue_config in config.venues() {
185                let Some(settlement_prices) = venue_config.settlement_prices() else {
186                    continue;
187                };
188                let venue = Venue::from(venue_config.name().as_str());
189
190                for (instrument_id, raw_price) in settlement_prices {
191                    let price = {
192                        let cache = engine.kernel().cache.borrow();
193                        let instrument = cache.try_instrument(instrument_id)?;
194                        instrument.make_price(*raw_price)
195                    };
196                    engine.set_settlement_price(venue, *instrument_id, price)?;
197                }
198            }
199
200            self.engines.insert(config.id().to_string(), engine);
201        }
202
203        Ok(())
204    }
205
206    /// Returns a mutable reference to the engine for the given run config ID.
207    #[must_use]
208    pub fn get_engine_mut(&mut self, id: &str) -> Option<&mut BacktestEngine> {
209        self.engines.get_mut(id)
210    }
211
212    /// Returns a reference to the engine for the given run config ID.
213    #[must_use]
214    pub fn get_engine(&self, id: &str) -> Option<&BacktestEngine> {
215        self.engines.get(id)
216    }
217
218    /// Returns all created backtest engines.
219    #[must_use]
220    pub fn get_engines(&self) -> Vec<&BacktestEngine> {
221        self.engines.values().collect()
222    }
223
224    /// Runs all configured backtests and returns results.
225    ///
226    /// Automatically calls [`build()`](Self::build) if engines have not been created yet.
227    /// For each run config, loads data from the catalog and runs the engine.
228    /// Supports both oneshot (`chunk_size = None`) and streaming modes.
229    ///
230    /// # Errors
231    ///
232    /// Returns an error if building, data loading, or engine execution fails.
233    pub fn run(&mut self) -> anyhow::Result<Vec<BacktestResult>> {
234        // Auto-build if not already done
235        if self.engines.is_empty() {
236            self.build()?;
237        }
238
239        let mut results = Vec::new();
240
241        for config in &self.configs {
242            let engine = self.engines.get_mut(config.id()).ok_or_else(|| {
243                anyhow::anyhow!(
244                    "Engine not found for config '{}'. Call build() first.",
245                    config.id()
246                )
247            })?;
248
249            match config.chunk_size() {
250                None => run_oneshot(engine, config)?,
251                Some(chunk_size) => run_streaming(engine, config, chunk_size)?,
252            }
253
254            results.push(engine.get_result());
255
256            if config.dispose_on_completion() {
257                engine.dispose();
258            } else {
259                engine.clear_data();
260            }
261        }
262
263        Ok(results)
264    }
265
266    /// Creates a [`ParquetDataCatalog`] from a data config.
267    ///
268    /// # Errors
269    ///
270    /// Returns an error if the catalog cannot be created from the URI.
271    pub fn load_catalog(config: &BacktestDataConfig) -> anyhow::Result<ParquetDataCatalog> {
272        create_catalog(config)
273    }
274
275    /// Loads data from the catalog for a specific data config.
276    ///
277    /// # Errors
278    ///
279    /// Returns an error if catalog creation or data querying fails.
280    pub fn load_data_config(
281        config: &BacktestDataConfig,
282        start: Option<UnixNanos>,
283        end: Option<UnixNanos>,
284    ) -> anyhow::Result<Vec<Data>> {
285        load_data(config, start, end)
286    }
287
288    /// Disposes all engines and releases resources.
289    pub fn dispose(&mut self) {
290        for engine in self.engines.values_mut() {
291            engine.dispose();
292        }
293        self.engines.clear();
294    }
295}
296
297fn validate_configs(configs: &[BacktestRunConfig]) -> anyhow::Result<()> {
298    // Kernel initialization sets a thread-local MessageBus that can only be
299    // initialized once per thread, so multiple engines cannot coexist
300    anyhow::ensure!(
301        configs.len() <= 1,
302        "Only one run config per BacktestNode is supported \
303         (kernel MessageBus is a thread-local singleton)"
304    );
305
306    let mut seen_ids = AHashSet::new();
307
308    for config in configs {
309        anyhow::ensure!(
310            seen_ids.insert(config.id()),
311            "Duplicate run config ID '{}'",
312            config.id()
313        );
314
315        let venue_names: Vec<String> = config
316            .venues()
317            .iter()
318            .map(|v| v.name().to_string())
319            .collect();
320
321        for data_config in config.data() {
322            if let (Some(start), Some(end)) = (data_config.start_time(), data_config.end_time()) {
323                anyhow::ensure!(
324                    start <= end,
325                    "Data config start_time ({start}) must be <= end_time ({end})"
326                );
327            }
328
329            for instrument_id in data_config.get_instrument_ids()? {
330                let venue = instrument_id.venue.to_string();
331                anyhow::ensure!(
332                    venue_names.contains(&venue),
333                    "No venue config found for venue '{venue}' (required by instrument {instrument_id})"
334                );
335            }
336        }
337
338        for venue_config in config.venues() {
339            let needs_book_data = matches!(
340                venue_config.book_type(),
341                BookType::L2_MBP | BookType::L3_MBO
342            );
343
344            if needs_book_data {
345                let venue_name = venue_config.name().to_string();
346                let has_book_data = config.data().iter().any(|dc| {
347                    let is_book_type = matches!(
348                        dc.data_type(),
349                        NautilusDataType::OrderBookDelta | NautilusDataType::OrderBookDepth10
350                    );
351
352                    if !is_book_type {
353                        return false;
354                    }
355
356                    // Unfiltered config (no instrument filter) covers all venues
357                    let ids = dc.get_instrument_ids().unwrap_or_default();
358                    ids.is_empty() || ids.iter().any(|id| id.venue.to_string() == venue_name)
359                });
360                anyhow::ensure!(
361                    has_book_data,
362                    "Venue '{venue_name}' has book_type {:?} but no order book data configured",
363                    venue_config.book_type()
364                );
365            }
366        }
367    }
368    Ok(())
369}
370
371fn run_oneshot(engine: &mut BacktestEngine, config: &BacktestRunConfig) -> anyhow::Result<()> {
372    for data_config in config.data() {
373        let data = load_data(data_config, config.start(), config.end())?;
374        if data.is_empty() {
375            log::warn!("No data found for config: {:?}", data_config.data_type());
376            continue;
377        }
378        engine.add_data(data, data_config.client_id(), false, false)?;
379    }
380
381    engine.sort_data();
382    engine.run(
383        config.start(),
384        config.end(),
385        Some(config.id().to_string()),
386        false,
387    )
388}
389
390fn run_streaming(
391    engine: &mut BacktestEngine,
392    config: &BacktestRunConfig,
393    chunk_size: usize,
394) -> anyhow::Result<()> {
395    let data_configs = config.data();
396
397    if data_configs.len() == 1 {
398        // Single config: stream directly from catalog iterator without
399        // materializing the full dataset, bounded by chunk_size
400        let data_config = &data_configs[0];
401        let mut catalog = create_catalog(data_config)?;
402        let result = dispatch_query(&mut catalog, data_config, config.start(), config.end())?;
403        stream_chunks(engine, config, result.peekable(), chunk_size)?;
404    } else {
405        // Multiple configs require loading all data to merge-sort across types
406        let all_data = load_and_merge_data(config)?;
407        stream_chunks(engine, config, all_data.into_iter().peekable(), chunk_size)?;
408    }
409
410    Ok(())
411}
412
413// Feeds data from an iterator to the engine in timestamp-aligned chunks.
414// Each chunk contains up to `chunk_size` events, extended to include all
415// events sharing the boundary timestamp so timers flush correctly.
416fn stream_chunks<I: Iterator<Item = Data>>(
417    engine: &mut BacktestEngine,
418    config: &BacktestRunConfig,
419    mut iter: Peekable<I>,
420    chunk_size: usize,
421) -> anyhow::Result<()> {
422    if iter.peek().is_none() {
423        engine.end();
424        return Ok(());
425    }
426
427    let mut next_start = config.start();
428
429    loop {
430        let chunk = take_aligned_chunk(&mut iter, chunk_size);
431        if chunk.is_empty() {
432            break;
433        }
434
435        let is_last = iter.peek().is_none();
436        let end = if is_last {
437            config.end()
438        } else {
439            chunk.last().map(HasTsInit::ts_init)
440        };
441
442        engine.add_data(chunk, None, false, true)?;
443        engine.run(next_start, end, Some(config.id().to_string()), true)?;
444        engine.clear_data();
445
446        // A shutdown request during the chunk already triggered end() inside
447        // engine.run(); stop loading further chunks so later data is not processed
448        if engine.kernel().is_shutdown_requested() {
449            return Ok(());
450        }
451
452        // Carry forward the end timestamp so the next chunk's run_impl
453        // sets clocks contiguously and processes gap timers correctly
454        next_start = end;
455    }
456
457    engine.end();
458    Ok(())
459}
460
461// Takes up to `chunk_size` items, then extends to include all remaining
462// items sharing the boundary timestamp to avoid splitting same-ts events.
463fn take_aligned_chunk<I: Iterator<Item = Data>>(
464    iter: &mut Peekable<I>,
465    chunk_size: usize,
466) -> Vec<Data> {
467    let mut chunk = Vec::with_capacity(chunk_size);
468
469    for _ in 0..chunk_size {
470        match iter.next() {
471            Some(item) => chunk.push(item),
472            None => return chunk,
473        }
474    }
475
476    if let Some(boundary_ts) = chunk.last().map(HasTsInit::ts_init) {
477        while iter.peek().is_some_and(|d| d.ts_init() == boundary_ts) {
478            chunk.push(iter.next().unwrap());
479        }
480    }
481
482    chunk
483}
484
485fn load_and_merge_data(config: &BacktestRunConfig) -> anyhow::Result<Vec<Data>> {
486    let mut all_data = Vec::new();
487
488    for data_config in config.data() {
489        let data = load_data(data_config, config.start(), config.end())?;
490        if data.is_empty() {
491            log::warn!("No data found for config: {:?}", data_config.data_type());
492            continue;
493        }
494        all_data.extend(data);
495    }
496    all_data.sort_by_key(HasTsInit::ts_init);
497    Ok(all_data)
498}
499
500fn create_catalog(config: &BacktestDataConfig) -> anyhow::Result<ParquetDataCatalog> {
501    let uri = match config.catalog_fs_protocol() {
502        Some(protocol) => format!("{protocol}://{}", config.catalog_path()),
503        None => config.catalog_path().to_string(),
504    };
505    let storage_options = config
506        .catalog_fs_rust_storage_options()
507        .cloned()
508        .or_else(|| config.catalog_fs_storage_options().cloned());
509    ParquetDataCatalog::from_uri(&uri, storage_options, None, None, None)
510}
511
512fn load_data(
513    config: &BacktestDataConfig,
514    run_start: Option<UnixNanos>,
515    run_end: Option<UnixNanos>,
516) -> anyhow::Result<Vec<Data>> {
517    let mut catalog = create_catalog(config)?;
518    let result = dispatch_query(&mut catalog, config, run_start, run_end)?;
519    Ok(result.collect())
520}
521
522fn dispatch_query(
523    catalog: &mut ParquetDataCatalog,
524    config: &BacktestDataConfig,
525    run_start: Option<UnixNanos>,
526    run_end: Option<UnixNanos>,
527) -> anyhow::Result<QueryResult> {
528    catalog.reset_session();
529
530    let identifiers = config.query_identifiers();
531    let start = max_opt(config.start_time(), run_start);
532    let end = min_opt(config.end_time(), run_end);
533    let filter = config.filter_expr();
534    let optimize = config.optimize_file_loading();
535
536    match config.data_type() {
537        NautilusDataType::QuoteTick => {
538            catalog.query::<QuoteTick>(identifiers, start, end, filter, None, optimize)
539        }
540        NautilusDataType::TradeTick => {
541            catalog.query::<TradeTick>(identifiers, start, end, filter, None, optimize)
542        }
543        NautilusDataType::Bar => {
544            catalog.query::<Bar>(identifiers, start, end, filter, None, optimize)
545        }
546        NautilusDataType::OrderBookDelta => {
547            catalog.query::<OrderBookDelta>(identifiers, start, end, filter, None, optimize)
548        }
549        NautilusDataType::OrderBookDepth10 => {
550            catalog.query::<OrderBookDepth10>(identifiers, start, end, filter, None, optimize)
551        }
552        NautilusDataType::MarkPriceUpdate => {
553            catalog.query::<MarkPriceUpdate>(identifiers, start, end, filter, None, optimize)
554        }
555        NautilusDataType::IndexPriceUpdate => {
556            catalog.query::<IndexPriceUpdate>(identifiers, start, end, filter, None, optimize)
557        }
558        NautilusDataType::FundingRateUpdate => {
559            catalog.query::<FundingRateUpdate>(identifiers, start, end, filter, None, optimize)
560        }
561        NautilusDataType::InstrumentStatus => {
562            catalog.query::<InstrumentStatus>(identifiers, start, end, filter, None, optimize)
563        }
564        NautilusDataType::OptionGreeks => {
565            catalog.query::<OptionGreeks>(identifiers, start, end, filter, None, optimize)
566        }
567        NautilusDataType::InstrumentClose => {
568            catalog.query::<InstrumentClose>(identifiers, start, end, filter, None, optimize)
569        }
570    }
571}
572
573fn max_opt(a: Option<UnixNanos>, b: Option<UnixNanos>) -> Option<UnixNanos> {
574    match (a, b) {
575        (Some(a), Some(b)) => Some(a.max(b)),
576        (Some(a), None) => Some(a),
577        (None, Some(b)) => Some(b),
578        (None, None) => None,
579    }
580}
581
582fn min_opt(a: Option<UnixNanos>, b: Option<UnixNanos>) -> Option<UnixNanos> {
583    match (a, b) {
584        (Some(a), Some(b)) => Some(a.min(b)),
585        (Some(a), None) => Some(a),
586        (None, Some(b)) => Some(b),
587        (None, None) => None,
588    }
589}