1use std::time::Duration;
19
20use ahash::AHashMap;
21use nautilus_common::{
22 cache::CacheConfig,
23 config::{ConfigError, ConfigErrorCollector, ConfigResult},
24 enums::Environment,
25 logging::logger::LoggerConfig,
26 msgbus::MessageBusConfig,
27};
28use nautilus_core::{UUID4, UnixNanos};
29use nautilus_data::engine::config::DataEngineConfig;
30use nautilus_execution::{
31 engine::config::ExecutionEngineConfig,
32 matching_engine::config::OrderPriorityResetPolicy,
33 models::{
34 fee::{FeeModelAny, FeeModelHandle},
35 fill::{FillModelAny, FillModelHandle},
36 latency::{LatencyModelAny, LatencyModelHandle},
37 },
38};
39use nautilus_model::{
40 accounts::margin_model::{MarginModelAny, MarginModelHandle},
41 data::{BarSpecification, BarType, NautilusDataType},
42 enums::{AccountType, BookType, OmsType, OtoTriggerMode},
43 identifiers::{ClientId, InstrumentId, TraderId, Venue},
44 types::{Currency, Money},
45};
46#[cfg(feature = "streaming")]
47use nautilus_persistence::config::DataCatalogConfig;
48use nautilus_portfolio::config::PortfolioConfig;
49use nautilus_risk::engine::config::RiskEngineConfig;
50use nautilus_system::config::NautilusKernelConfig;
51#[cfg(feature = "streaming")]
52use nautilus_system::config::StreamingConfig;
53use nautilus_trading::ImportableControllerConfig;
54use rust_decimal::Decimal;
55use ustr::Ustr;
56
57use crate::modules::{SimulationModuleAny, SimulationModuleHandle};
58
59pub(crate) const MAX_BACKTEST_CHUNK_SIZE: usize = 1_000_000;
60
61#[cfg_attr(
63 feature = "python",
64 pyo3::pyclass(module = "nautilus_trader.backtest", from_py_object, unsendable)
65)]
66#[cfg_attr(
67 feature = "python",
68 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
69)]
70#[expect(
71 clippy::struct_excessive_bools,
72 reason = "config fields mirror the existing Rust and Python backtest engine surfaces"
73)]
74#[derive(Debug, Clone, bon::Builder)]
75pub struct BacktestEngineConfig {
76 #[builder(default = Environment::Backtest)]
78 pub environment: Environment,
79 #[builder(default)]
81 pub trader_id: TraderId,
82 #[builder(default)]
84 pub load_state: bool,
85 #[builder(default)]
87 pub save_state: bool,
88 #[builder(default)]
92 pub shutdown_on_error: bool,
93 #[builder(default)]
95 pub logging: LoggerConfig,
96 pub instance_id: Option<UUID4>,
98 #[builder(default = Duration::from_mins(1))]
100 pub timeout_connection: Duration,
101 #[builder(default = Duration::from_secs(30))]
103 pub timeout_reconciliation: Duration,
104 #[builder(default = Duration::from_secs(10))]
106 pub timeout_portfolio: Duration,
107 #[builder(default = Duration::from_secs(10))]
109 pub timeout_disconnection: Duration,
110 #[builder(default = Duration::from_secs(10))]
112 pub delay_post_stop: Duration,
113 #[builder(default = Duration::from_secs(5))]
115 pub timeout_shutdown: Duration,
116 pub cache: Option<CacheConfig>,
122 pub msgbus: Option<MessageBusConfig>,
124 pub data_engine: Option<DataEngineConfig>,
126 pub risk_engine: Option<RiskEngineConfig>,
128 pub exec_engine: Option<ExecutionEngineConfig>,
130 pub portfolio: Option<PortfolioConfig>,
132 pub controller: Option<ImportableControllerConfig>,
134 #[cfg(feature = "streaming")]
136 pub streaming: Option<StreamingConfig>,
137 #[cfg(feature = "streaming")]
139 #[builder(default)]
140 pub catalogs: Vec<DataCatalogConfig>,
141 #[builder(default)]
143 pub bypass_logging: bool,
144 #[builder(default = true)]
146 pub run_analysis: bool,
147}
148
149impl NautilusKernelConfig for BacktestEngineConfig {
150 fn environment(&self) -> Environment {
151 self.environment
152 }
153
154 fn trader_id(&self) -> TraderId {
155 self.trader_id
156 }
157
158 fn load_state(&self) -> bool {
159 self.load_state
160 }
161
162 fn save_state(&self) -> bool {
163 self.save_state
164 }
165
166 fn shutdown_on_error(&self) -> bool {
167 self.shutdown_on_error
168 }
169
170 fn logging(&self) -> LoggerConfig {
171 self.logging.clone()
172 }
173
174 fn instance_id(&self) -> Option<UUID4> {
175 self.instance_id
176 }
177
178 fn timeout_connection(&self) -> Duration {
179 self.timeout_connection
180 }
181
182 fn timeout_reconciliation(&self) -> Duration {
183 self.timeout_reconciliation
184 }
185
186 fn timeout_portfolio(&self) -> Duration {
187 self.timeout_portfolio
188 }
189
190 fn timeout_disconnection(&self) -> Duration {
191 self.timeout_disconnection
192 }
193
194 fn delay_post_stop(&self) -> Duration {
195 self.delay_post_stop
196 }
197
198 fn timeout_shutdown(&self) -> Duration {
199 self.timeout_shutdown
200 }
201
202 fn cache(&self) -> Option<CacheConfig> {
203 self.cache.clone()
204 }
205
206 fn msgbus(&self) -> Option<MessageBusConfig> {
207 self.msgbus.clone()
208 }
209
210 fn data_engine(&self) -> Option<DataEngineConfig> {
211 self.data_engine.clone()
212 }
213
214 fn risk_engine(&self) -> Option<RiskEngineConfig> {
215 self.risk_engine.clone()
216 }
217
218 fn exec_engine(&self) -> Option<ExecutionEngineConfig> {
219 self.exec_engine.clone()
220 }
221
222 fn portfolio(&self) -> Option<PortfolioConfig> {
223 self.portfolio
224 }
225
226 #[cfg(feature = "streaming")]
227 fn streaming(&self) -> Option<StreamingConfig> {
228 self.streaming.clone()
229 }
230
231 #[cfg(feature = "streaming")]
232 fn catalogs(&self) -> Vec<DataCatalogConfig> {
233 self.catalogs.clone()
234 }
235}
236
237impl Default for BacktestEngineConfig {
238 fn default() -> Self {
239 Self::builder().build()
240 }
241}
242
243#[allow(missing_debug_implementations)]
261#[expect(
262 clippy::struct_excessive_bools,
263 reason = "venue config fields mirror the existing imperative backtest API"
264)]
265#[derive(bon::Builder)]
266#[builder(finish_fn(name = build_inner, vis = ""))]
267pub struct SimulatedVenueConfig {
268 pub venue: Venue,
270 pub oms_type: OmsType,
272 pub account_type: AccountType,
274 pub book_type: BookType,
276 pub starting_balances: Vec<Money>,
278 pub base_currency: Option<Currency>,
280 pub default_leverage: Option<Decimal>,
282 #[builder(default)]
284 pub leverages: AHashMap<InstrumentId, Decimal>,
285 #[builder(default)]
287 pub fill_model: FillModelHandle,
288 pub fee_model: FeeModelHandle,
294 pub margin_model: Option<MarginModelHandle>,
296 pub latency_model: Option<LatencyModelHandle>,
298 #[builder(default)]
300 pub modules: Vec<SimulationModuleHandle>,
301 #[builder(default = false)]
303 pub routing: bool,
304 #[builder(default = true)]
306 pub reject_stop_orders: bool,
307 #[builder(default = true)]
309 pub support_gtd_orders: bool,
310 #[builder(default = true)]
312 pub support_contingent_orders: bool,
313 #[builder(default = true)]
315 pub use_position_ids: bool,
316 #[builder(default = false)]
318 pub use_random_ids: bool,
319 #[builder(default = true)]
321 pub use_reduce_only: bool,
322 #[builder(default = true)]
324 pub use_message_queue: bool,
325 #[builder(default = false)]
327 pub use_market_order_acks: bool,
328 #[builder(default = true)]
330 pub bar_execution: bool,
331 #[builder(default = false)]
333 pub bar_adaptive_high_low_ordering: bool,
334 #[builder(default = true)]
336 pub trade_execution: bool,
337 #[builder(default = false)]
339 pub liquidity_consumption: bool,
340 #[builder(default = false)]
342 pub allow_cash_borrowing: bool,
343 #[builder(default = false)]
345 pub frozen_account: bool,
346 #[builder(default = false)]
348 pub queue_position: bool,
349 #[builder(default = false)]
351 pub oto_full_trigger: bool,
352 #[builder(default = true)]
354 pub defer_option_settlement: bool,
355 #[builder(default = 0)]
357 pub price_protection_points: u32,
358 #[builder(default = false)]
360 pub liquidation_enabled: bool,
361 #[builder(default = 1.0)]
363 pub liquidation_trigger_ratio: f64,
364 #[builder(default = true)]
366 pub liquidation_cancel_open_orders: bool,
367 #[builder(default)]
369 pub order_priority_reset_policy: OrderPriorityResetPolicy,
370}
371
372impl<S: simulated_venue_config_builder::IsComplete> SimulatedVenueConfigBuilder<S> {
373 pub fn build(self) -> ConfigResult<SimulatedVenueConfig> {
379 let config = self.build_inner();
380 config.validate()?;
381 Ok(config)
382 }
383}
384
385impl SimulatedVenueConfig {
386 pub fn validate(&self) -> ConfigResult<()> {
393 let mut errors = ConfigErrorCollector::new();
394
395 if self.starting_balances.is_empty() {
396 errors.push(ConfigError::empty_field("starting_balances"));
397 }
398
399 if let Some(default_leverage) = self.default_leverage {
400 errors.check(
401 default_leverage > Decimal::ZERO,
402 ConfigError::range(
403 "default_leverage",
404 format!("must be positive, was {default_leverage}"),
405 ),
406 );
407 }
408
409 for (instrument_id, leverage) in &self.leverages {
410 errors.check(
411 *leverage > Decimal::ZERO,
412 ConfigError::range(
413 "leverages",
414 format!("leverage for {instrument_id} must be positive, was {leverage}"),
415 ),
416 );
417 }
418
419 errors.check(
420 self.liquidation_trigger_ratio.is_finite() && self.liquidation_trigger_ratio > 0.0,
421 ConfigError::range(
422 "liquidation_trigger_ratio",
423 format!(
424 "must be a positive finite value, was {}",
425 self.liquidation_trigger_ratio
426 ),
427 ),
428 );
429
430 errors.into_result()
431 }
432}
433
434#[cfg_attr(
436 feature = "python",
437 pyo3::pyclass(module = "nautilus_trader.backtest", from_py_object, unsendable)
438)]
439#[cfg_attr(
440 feature = "python",
441 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
442)]
443#[expect(
444 clippy::struct_excessive_bools,
445 reason = "venue config fields mirror the existing Rust and Python backtest surfaces"
446)]
447#[derive(Debug, Clone, bon::Builder)]
448#[builder(finish_fn(name = build_inner, vis = ""))]
449pub struct BacktestVenueConfig {
450 #[builder(into)]
452 name: Ustr,
453 oms_type: OmsType,
455 account_type: AccountType,
457 book_type: BookType,
459 #[builder(default)]
461 starting_balances: Vec<String>,
462 #[builder(default)]
464 routing: bool,
465 #[builder(default)]
467 frozen_account: bool,
468 #[builder(default = true)]
470 reject_stop_orders: bool,
471 #[builder(default = true)]
473 support_gtd_orders: bool,
474 #[builder(default = true)]
477 support_contingent_orders: bool,
478 #[builder(default = true)]
480 use_position_ids: bool,
481 #[builder(default)]
484 use_random_ids: bool,
485 #[builder(default = true)]
488 use_reduce_only: bool,
489 #[builder(default = true)]
491 bar_execution: bool,
492 #[builder(default)]
499 bar_adaptive_high_low_ordering: bool,
500 #[builder(default = true)]
502 trade_execution: bool,
503 #[builder(default)]
505 use_market_order_acks: bool,
506 #[builder(default)]
508 liquidity_consumption: bool,
509 #[builder(default)]
511 allow_cash_borrowing: bool,
512 #[builder(default)]
514 queue_position: bool,
515 #[builder(default)]
517 oto_trigger_mode: OtoTriggerMode,
518 base_currency: Option<Currency>,
520 default_leverage: Option<Decimal>,
522 leverages: Option<AHashMap<InstrumentId, Decimal>>,
524 fill_model: Option<FillModelAny>,
526 fee_model: Option<FeeModelAny>,
531 margin_model: Option<MarginModelAny>,
533 latency_model: Option<LatencyModelAny>,
535 #[builder(default)]
537 modules: Vec<SimulationModuleAny>,
538 #[builder(default)]
541 price_protection_points: u32,
542 #[builder(default)]
544 liquidation_enabled: bool,
545 #[builder(default = 1.0)]
548 liquidation_trigger_ratio: f64,
549 #[builder(default = true)]
551 liquidation_cancel_open_orders: bool,
552 #[builder(default)]
553 order_priority_reset_policy: OrderPriorityResetPolicy,
554}
555
556impl<S: backtest_venue_config_builder::IsComplete> BacktestVenueConfigBuilder<S> {
557 pub fn build(self) -> ConfigResult<BacktestVenueConfig> {
563 let config = self.build_inner();
564 config.validate()?;
565 Ok(config)
566 }
567
568 #[cfg(feature = "python")]
569 pub(crate) fn build_simulated(
570 self,
571 starting_balances: Vec<Money>,
572 models: BehavioralModels,
573 modules: Vec<SimulationModuleHandle>,
574 use_message_queue: bool,
575 ) -> ConfigResult<SimulatedVenueConfig> {
576 let mut config = self.build_inner();
579 let leverages = config.leverages.take().unwrap_or_default();
580 build_simulated_venue(
581 &config,
582 starting_balances,
583 leverages,
584 models,
585 modules,
586 use_message_queue,
587 )
588 }
589}
590
591impl BacktestVenueConfig {
592 pub fn validate(&self) -> ConfigResult<()> {
599 let mut errors = ConfigErrorCollector::new();
600
601 if self.name.is_empty() {
602 errors.push(ConfigError::empty_field("name"));
603 } else if let Err(e) = Venue::new_checked(self.name.as_str()) {
604 errors.push(ConfigError::invalid_value(
605 "name",
606 format!("must be a valid venue identifier ({e})"),
607 ));
608 }
609
610 if let Some(default_leverage) = self.default_leverage {
611 errors.check(
612 default_leverage > Decimal::ZERO,
613 ConfigError::range(
614 "default_leverage",
615 format!("must be positive, was {default_leverage}"),
616 ),
617 );
618 }
619
620 if let Some(leverages) = &self.leverages {
621 for (instrument_id, leverage) in leverages {
622 errors.check(
623 *leverage > Decimal::ZERO,
624 ConfigError::range(
625 "leverages",
626 format!("leverage for {instrument_id} must be positive, was {leverage}"),
627 ),
628 );
629 }
630 }
631 errors.check(
632 self.liquidation_trigger_ratio.is_finite() && self.liquidation_trigger_ratio > 0.0,
633 ConfigError::range(
634 "liquidation_trigger_ratio",
635 format!(
636 "must be a positive finite value, was {}",
637 self.liquidation_trigger_ratio
638 ),
639 ),
640 );
641
642 for balance in &self.starting_balances {
643 if let Err(reason) = balance.parse::<Money>() {
644 errors.push(ConfigError::invalid_format(
645 "starting_balances",
646 format!("a valid money string, was '{balance}' ({reason})"),
647 ));
648 }
649 }
650
651 errors.into_result()
652 }
653
654 #[must_use]
655 pub fn name(&self) -> Ustr {
656 self.name
657 }
658
659 #[must_use]
660 pub fn oms_type(&self) -> OmsType {
661 self.oms_type
662 }
663
664 #[must_use]
665 pub fn account_type(&self) -> AccountType {
666 self.account_type
667 }
668
669 #[must_use]
670 pub fn book_type(&self) -> BookType {
671 self.book_type
672 }
673
674 #[must_use]
675 pub fn starting_balances(&self) -> &[String] {
676 &self.starting_balances
677 }
678
679 #[must_use]
680 pub fn routing(&self) -> bool {
681 self.routing
682 }
683
684 #[must_use]
685 pub fn frozen_account(&self) -> bool {
686 self.frozen_account
687 }
688
689 #[must_use]
690 pub fn reject_stop_orders(&self) -> bool {
691 self.reject_stop_orders
692 }
693
694 #[must_use]
695 pub fn support_gtd_orders(&self) -> bool {
696 self.support_gtd_orders
697 }
698
699 #[must_use]
700 pub fn support_contingent_orders(&self) -> bool {
701 self.support_contingent_orders
702 }
703
704 #[must_use]
705 pub fn use_position_ids(&self) -> bool {
706 self.use_position_ids
707 }
708
709 #[must_use]
710 pub fn use_random_ids(&self) -> bool {
711 self.use_random_ids
712 }
713
714 #[must_use]
715 pub fn use_reduce_only(&self) -> bool {
716 self.use_reduce_only
717 }
718
719 #[must_use]
720 pub fn bar_execution(&self) -> bool {
721 self.bar_execution
722 }
723
724 #[must_use]
725 pub fn bar_adaptive_high_low_ordering(&self) -> bool {
726 self.bar_adaptive_high_low_ordering
727 }
728
729 #[must_use]
730 pub fn trade_execution(&self) -> bool {
731 self.trade_execution
732 }
733
734 #[must_use]
735 pub fn use_market_order_acks(&self) -> bool {
736 self.use_market_order_acks
737 }
738
739 #[must_use]
740 pub fn liquidity_consumption(&self) -> bool {
741 self.liquidity_consumption
742 }
743
744 #[must_use]
745 pub fn allow_cash_borrowing(&self) -> bool {
746 self.allow_cash_borrowing
747 }
748
749 #[must_use]
750 pub fn order_priority_reset_policy(&self) -> OrderPriorityResetPolicy {
751 self.order_priority_reset_policy
752 }
753
754 #[must_use]
755 pub fn queue_position(&self) -> bool {
756 self.queue_position
757 }
758
759 #[must_use]
760 pub fn oto_trigger_mode(&self) -> OtoTriggerMode {
761 self.oto_trigger_mode
762 }
763
764 #[must_use]
765 pub fn base_currency(&self) -> Option<Currency> {
766 self.base_currency
767 }
768
769 #[must_use]
770 pub fn default_leverage(&self) -> Option<Decimal> {
771 self.default_leverage
772 }
773
774 #[must_use]
775 pub fn leverages(&self) -> Option<&AHashMap<InstrumentId, Decimal>> {
776 self.leverages.as_ref()
777 }
778
779 #[must_use]
780 pub fn fill_model(&self) -> Option<&FillModelAny> {
781 self.fill_model.as_ref()
782 }
783
784 #[must_use]
785 pub fn fee_model(&self) -> Option<&FeeModelAny> {
786 self.fee_model.as_ref()
787 }
788
789 #[must_use]
790 pub fn margin_model(&self) -> Option<&MarginModelAny> {
791 self.margin_model.as_ref()
792 }
793
794 #[must_use]
795 pub fn latency_model(&self) -> Option<&LatencyModelAny> {
796 self.latency_model.as_ref()
797 }
798
799 #[must_use]
800 pub fn modules(&self) -> &[SimulationModuleAny] {
801 &self.modules
802 }
803
804 #[must_use]
805 pub fn price_protection_points(&self) -> u32 {
806 self.price_protection_points
807 }
808
809 #[must_use]
810 pub fn liquidation_enabled(&self) -> bool {
811 self.liquidation_enabled
812 }
813
814 #[must_use]
815 pub fn liquidation_trigger_ratio(&self) -> f64 {
816 self.liquidation_trigger_ratio
817 }
818
819 #[must_use]
820 pub fn liquidation_cancel_open_orders(&self) -> bool {
821 self.liquidation_cancel_open_orders
822 }
823
824 #[cfg(feature = "streaming")]
825 pub(crate) fn to_simulated(&self) -> anyhow::Result<SimulatedVenueConfig> {
826 let starting_balances: Vec<Money> = self
827 .starting_balances()
828 .iter()
829 .map(|s| s.parse::<Money>())
830 .collect::<Result<Vec<_>, _>>()
831 .map_err(|e| anyhow::anyhow!("Invalid starting balance: {e}"))?;
832
833 let leverages = self.leverages().cloned().unwrap_or_default();
834 let fill_model = self.fill_model().cloned().unwrap_or_default().into();
835
836 let fee_model = self
837 .fee_model()
838 .cloned()
839 .ok_or_else(|| {
840 anyhow::anyhow!(
841 "BacktestVenueConfig for '{}' requires an explicit fee_model, including an explicit zero-fee model",
842 self.name()
843 )
844 })?
845 .into();
846
847 let margin_model = self.margin_model().cloned().map(Into::into);
848
849 let latency_model = self.latency_model().cloned().map(Into::into);
850
851 let modules = self.modules().iter().cloned().map(Into::into).collect();
852
853 let models = BehavioralModels {
854 fill: fill_model,
855 fee: fee_model,
856 margin: margin_model,
857 latency: latency_model,
858 };
859
860 Ok(build_simulated_venue(
861 self,
862 starting_balances,
863 leverages,
864 models,
865 modules,
866 true,
867 )?)
868 }
869}
870
871#[cfg(feature = "streaming")]
872fn build_simulated_venue(
873 config: &BacktestVenueConfig,
874 starting_balances: Vec<Money>,
875 leverages: AHashMap<InstrumentId, Decimal>,
876 models: BehavioralModels,
877 modules: Vec<SimulationModuleHandle>,
878 use_message_queue: bool,
879) -> ConfigResult<SimulatedVenueConfig> {
880 SimulatedVenueConfig::builder()
881 .venue(Venue::from(config.name().as_str()))
882 .oms_type(config.oms_type())
883 .account_type(config.account_type())
884 .book_type(config.book_type())
885 .starting_balances(starting_balances)
886 .maybe_base_currency(config.base_currency())
887 .maybe_default_leverage(config.default_leverage())
888 .leverages(leverages)
889 .fill_model(models.fill)
890 .fee_model(models.fee)
891 .maybe_margin_model(models.margin)
892 .maybe_latency_model(models.latency)
893 .modules(modules)
894 .routing(config.routing())
895 .reject_stop_orders(config.reject_stop_orders())
896 .support_gtd_orders(config.support_gtd_orders())
897 .support_contingent_orders(config.support_contingent_orders())
898 .use_position_ids(config.use_position_ids())
899 .use_random_ids(config.use_random_ids())
900 .use_reduce_only(config.use_reduce_only())
901 .use_message_queue(use_message_queue)
902 .use_market_order_acks(config.use_market_order_acks())
903 .bar_execution(config.bar_execution())
904 .bar_adaptive_high_low_ordering(config.bar_adaptive_high_low_ordering())
905 .trade_execution(config.trade_execution())
906 .liquidity_consumption(config.liquidity_consumption())
907 .allow_cash_borrowing(config.allow_cash_borrowing())
908 .frozen_account(config.frozen_account())
909 .queue_position(config.queue_position())
910 .order_priority_reset_policy(config.order_priority_reset_policy())
911 .oto_full_trigger(config.oto_trigger_mode() == OtoTriggerMode::Full)
912 .price_protection_points(config.price_protection_points())
913 .liquidation_enabled(config.liquidation_enabled())
914 .liquidation_trigger_ratio(config.liquidation_trigger_ratio())
915 .liquidation_cancel_open_orders(config.liquidation_cancel_open_orders())
916 .build()
917}
918
919#[cfg(feature = "streaming")]
920#[derive(Debug)]
921pub(crate) struct BehavioralModels {
922 pub(crate) fill: FillModelHandle,
923 pub(crate) fee: FeeModelHandle,
924 pub(crate) margin: Option<MarginModelHandle>,
925 pub(crate) latency: Option<LatencyModelHandle>,
926}
927
928#[derive(Debug, Clone, bon::Builder)]
930#[builder(finish_fn(name = build_inner, vis = ""))]
931#[cfg_attr(
932 feature = "python",
933 pyo3::pyclass(module = "nautilus_trader.backtest", from_py_object, unsendable)
934)]
935#[cfg_attr(
936 feature = "python",
937 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
938)]
939pub struct BacktestDataConfig {
940 data_type: NautilusDataType,
942 #[cfg(feature = "streaming")]
944 catalog: DataCatalogConfig,
945 instrument_id: Option<InstrumentId>,
947 instrument_ids: Option<Vec<InstrumentId>>,
949 start_time: Option<UnixNanos>,
951 end_time: Option<UnixNanos>,
953 filter_expr: Option<String>,
955 client_id: Option<ClientId>,
957 metadata: Option<AHashMap<String, String>>,
959 bar_spec: Option<BarSpecification>,
961 bar_types: Option<Vec<String>>,
963 #[builder(default)]
965 optimize_file_loading: bool,
966 #[builder(default = true)]
968 batch_deltas: bool,
969}
970
971impl<S: backtest_data_config_builder::IsComplete> BacktestDataConfigBuilder<S> {
972 pub fn build(self) -> ConfigResult<BacktestDataConfig> {
978 let config = self.build_inner();
979 config.validate()?;
980 Ok(config)
981 }
982}
983
984impl BacktestDataConfig {
985 pub fn validate(&self) -> ConfigResult<()> {
992 let mut errors = ConfigErrorCollector::new();
993
994 errors.check(
995 matches!(
996 self.data_type,
997 NautilusDataType::OrderBookDelta
998 | NautilusDataType::OrderBookDepth
999 | NautilusDataType::QuoteTick
1000 | NautilusDataType::TradeTick
1001 | NautilusDataType::Bar
1002 | NautilusDataType::MarkPriceUpdate
1003 | NautilusDataType::IndexPriceUpdate
1004 | NautilusDataType::FundingRateUpdate
1005 | NautilusDataType::OptionGreeks
1006 | NautilusDataType::InstrumentStatus
1007 | NautilusDataType::InstrumentClose
1008 | NautilusDataType::Instrument
1009 ),
1010 ConfigError::unsupported_value(
1011 "data_type",
1012 format!("{} is not supported by BacktestDataConfig", self.data_type),
1013 ),
1014 );
1015
1016 #[cfg(feature = "streaming")]
1017 {
1018 if self.catalog.path().trim().is_empty() {
1019 errors.push(ConfigError::empty_field("catalog.path"));
1020 }
1021
1022 errors.collect(self.catalog.validate());
1023 }
1024
1025 if let (Some(start), Some(end)) = (self.start_time, self.end_time) {
1026 errors.check(
1027 start <= end,
1028 ConfigError::range(
1029 "start_time",
1030 format!("must be <= end_time, was {start} > {end}"),
1031 ),
1032 );
1033 }
1034
1035 let has_identifier = self.instrument_id.is_some()
1036 || self
1037 .instrument_ids
1038 .as_ref()
1039 .is_some_and(|ids| !ids.is_empty())
1040 || self.bar_types.as_ref().is_some_and(|bars| !bars.is_empty());
1041 errors.check(
1042 has_identifier,
1043 ConfigError::required_one_of(["instrument_id", "instrument_ids", "bar_types"]),
1044 );
1045
1046 errors.into_result()
1047 }
1048
1049 #[must_use]
1050 pub const fn data_type(&self) -> &NautilusDataType {
1051 &self.data_type
1052 }
1053
1054 #[must_use]
1056 #[cfg(feature = "streaming")]
1057 pub const fn catalog(&self) -> &DataCatalogConfig {
1058 &self.catalog
1059 }
1060
1061 #[must_use]
1062 pub fn instrument_id(&self) -> Option<InstrumentId> {
1063 self.instrument_id
1064 }
1065
1066 #[must_use]
1067 pub fn instrument_ids(&self) -> Option<&[InstrumentId]> {
1068 self.instrument_ids.as_deref()
1069 }
1070
1071 #[must_use]
1072 pub fn start_time(&self) -> Option<UnixNanos> {
1073 self.start_time
1074 }
1075
1076 #[must_use]
1077 pub fn end_time(&self) -> Option<UnixNanos> {
1078 self.end_time
1079 }
1080
1081 #[must_use]
1082 pub fn filter_expr(&self) -> Option<&str> {
1083 self.filter_expr.as_deref()
1084 }
1085
1086 #[must_use]
1087 pub fn client_id(&self) -> Option<ClientId> {
1088 self.client_id
1089 }
1090
1091 #[must_use]
1092 pub fn metadata(&self) -> Option<&AHashMap<String, String>> {
1093 self.metadata.as_ref()
1094 }
1095
1096 #[must_use]
1097 pub fn bar_spec(&self) -> Option<BarSpecification> {
1098 self.bar_spec
1099 }
1100
1101 #[must_use]
1102 pub fn bar_types(&self) -> Option<&[String]> {
1103 self.bar_types.as_deref()
1104 }
1105
1106 #[must_use]
1107 pub fn optimize_file_loading(&self) -> bool {
1108 self.optimize_file_loading
1109 }
1110
1111 #[must_use]
1112 pub fn batch_deltas(&self) -> bool {
1113 self.batch_deltas
1114 }
1115
1116 #[must_use]
1122 pub fn query_identifiers(&self) -> Option<Vec<String>> {
1123 if self.data_type == NautilusDataType::Bar {
1124 if let Some(bar_types) = &self.bar_types
1125 && !bar_types.is_empty()
1126 {
1127 return Some(bar_types.clone());
1128 }
1129
1130 if let Some(bar_spec) = &self.bar_spec {
1132 if let Some(id) = self.instrument_id {
1133 return Some(vec![format!("{id}-{bar_spec}-EXTERNAL")]);
1134 }
1135
1136 if let Some(ids) = &self.instrument_ids {
1137 let bar_types: Vec<String> = ids
1138 .iter()
1139 .map(|id| format!("{id}-{bar_spec}-EXTERNAL"))
1140 .collect();
1141
1142 if !bar_types.is_empty() {
1143 return Some(bar_types);
1144 }
1145 }
1146 }
1147 }
1148
1149 if let Some(id) = self.instrument_id {
1151 return Some(vec![id.to_string()]);
1152 }
1153
1154 if let Some(ids) = &self.instrument_ids {
1155 let strs: Vec<String> = ids.iter().map(ToString::to_string).collect();
1156 if !strs.is_empty() {
1157 return Some(strs);
1158 }
1159 }
1160
1161 None
1162 }
1163
1164 pub fn get_instrument_ids(&self) -> anyhow::Result<Vec<InstrumentId>> {
1172 if let Some(id) = self.instrument_id {
1173 return Ok(vec![id]);
1174 }
1175
1176 if let Some(ids) = &self.instrument_ids {
1177 return Ok(ids.clone());
1178 }
1179
1180 if let Some(bar_types) = &self.bar_types {
1181 let ids = bar_types
1182 .iter()
1183 .map(|bt| {
1184 bt.parse::<BarType>()
1185 .map(|b| b.instrument_id())
1186 .map_err(|_| anyhow::anyhow!("Invalid bar type string: '{bt}'"))
1187 })
1188 .collect::<anyhow::Result<Vec<_>>>()?;
1189 return Ok(ids);
1190 }
1191 Ok(Vec::new())
1192 }
1193}
1194
1195#[derive(Debug, Clone, bon::Builder)]
1198#[builder(finish_fn(name = build_inner, vis = ""))]
1199#[cfg_attr(
1200 feature = "python",
1201 pyo3::pyclass(module = "nautilus_trader.backtest", from_py_object, unsendable)
1202)]
1203#[cfg_attr(
1204 feature = "python",
1205 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
1206)]
1207pub struct BacktestRunConfig {
1208 #[builder(default = UUID4::new().to_string())]
1210 id: String,
1211 venues: Vec<BacktestVenueConfig>,
1213 data: Vec<BacktestDataConfig>,
1215 #[builder(default)]
1217 engine: BacktestEngineConfig,
1218 chunk_size: Option<usize>,
1222 #[builder(default)]
1224 raise_exception: bool,
1225 #[builder(default = true)]
1229 dispose_on_completion: bool,
1230 start: Option<UnixNanos>,
1233 end: Option<UnixNanos>,
1236}
1237
1238impl<S: backtest_run_config_builder::IsComplete> BacktestRunConfigBuilder<S> {
1239 pub fn build(self) -> ConfigResult<BacktestRunConfig> {
1245 let config = self.build_inner();
1246 config.validate()?;
1247 Ok(config)
1248 }
1249}
1250
1251impl BacktestRunConfig {
1252 pub fn validate(&self) -> ConfigResult<()> {
1259 let mut errors = ConfigErrorCollector::new();
1260
1261 if self.venues.is_empty() {
1262 errors.push(ConfigError::empty_field("venues"));
1263 }
1264
1265 if let (Some(start), Some(end)) = (self.start, self.end) {
1266 errors.check(
1267 start <= end,
1268 ConfigError::range("start", format!("must be <= end, was {start} > {end}")),
1269 );
1270 }
1271
1272 if let Some(chunk_size) = self.chunk_size {
1273 errors.check(
1274 (1..=MAX_BACKTEST_CHUNK_SIZE).contains(&chunk_size),
1275 ConfigError::range(
1276 "chunk_size",
1277 format!("must be in range [1, {MAX_BACKTEST_CHUNK_SIZE}], was {chunk_size}"),
1278 ),
1279 );
1280 }
1281
1282 errors.into_result()
1283 }
1284
1285 #[must_use]
1286 pub fn id(&self) -> &str {
1287 &self.id
1288 }
1289
1290 #[must_use]
1291 pub fn venues(&self) -> &[BacktestVenueConfig] {
1292 &self.venues
1293 }
1294
1295 #[must_use]
1296 pub fn data(&self) -> &[BacktestDataConfig] {
1297 &self.data
1298 }
1299
1300 #[must_use]
1301 pub fn engine(&self) -> &BacktestEngineConfig {
1302 &self.engine
1303 }
1304
1305 #[must_use]
1306 pub fn chunk_size(&self) -> Option<usize> {
1307 self.chunk_size
1308 }
1309
1310 #[must_use]
1311 pub fn raise_exception(&self) -> bool {
1312 self.raise_exception
1313 }
1314
1315 #[must_use]
1316 pub fn dispose_on_completion(&self) -> bool {
1317 self.dispose_on_completion
1318 }
1319
1320 #[must_use]
1321 pub fn start(&self) -> Option<UnixNanos> {
1322 self.start
1323 }
1324
1325 #[must_use]
1326 pub fn end(&self) -> Option<UnixNanos> {
1327 self.end
1328 }
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333 #[cfg(feature = "streaming")]
1334 use nautilus_core::{
1335 Params,
1336 string::secret::{REDACTED, SecretString},
1337 };
1338 use nautilus_execution::models::fee::MakerTakerFeeModel;
1339 #[cfg(feature = "streaming")]
1340 use nautilus_persistence::config::{CatalogBackendType, CatalogCompression};
1341 #[cfg(feature = "python")]
1342 use pyo3::{
1343 Python,
1344 types::{PyAnyMethods, PyDict, PyDictMethods},
1345 };
1346 use rstest::rstest;
1347
1348 use super::*;
1349
1350 macro_rules! minimal_builder {
1351 () => {
1352 BacktestVenueConfig::builder()
1353 .name("SIM")
1354 .oms_type(OmsType::Netting)
1355 .account_type(AccountType::Margin)
1356 .book_type(BookType::L1_MBP)
1357 };
1358 }
1359
1360 macro_rules! data_builder {
1361 ($data_type:expr, $catalog_path:expr) => {{
1362 let builder = BacktestDataConfig::builder().data_type($data_type);
1363 #[cfg(feature = "streaming")]
1364 let builder = builder.catalog(DataCatalogConfig::new($catalog_path, None, None));
1365 builder
1366 }};
1367 }
1368
1369 #[rstest]
1370 #[case(NautilusDataType::OrderBookDelta)]
1371 #[case(NautilusDataType::OrderBookDepth)]
1372 #[case(NautilusDataType::QuoteTick)]
1373 #[case(NautilusDataType::TradeTick)]
1374 #[case(NautilusDataType::Bar)]
1375 #[case(NautilusDataType::MarkPriceUpdate)]
1376 #[case(NautilusDataType::IndexPriceUpdate)]
1377 #[case(NautilusDataType::FundingRateUpdate)]
1378 #[case(NautilusDataType::OptionGreeks)]
1379 #[case(NautilusDataType::InstrumentStatus)]
1380 #[case(NautilusDataType::InstrumentClose)]
1381 fn test_data_config_accepts_supported_family(#[case] data_type: NautilusDataType) {
1382 let config = data_builder!(data_type.clone(), "/tmp/catalog".to_string())
1383 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1384 .build()
1385 .unwrap();
1386
1387 assert_eq!(config.data_type(), &data_type);
1388 }
1389
1390 #[rstest]
1391 fn test_data_config_accepts_the_instrument_family() {
1392 let config = data_builder!(NautilusDataType::Instrument, "/tmp/catalog".to_string())
1393 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1394 .build()
1395 .unwrap();
1396
1397 assert_eq!(config.data_type(), &NautilusDataType::Instrument);
1398 }
1399
1400 #[rstest]
1401 #[case(NautilusDataType::Custom { type_name: "Signal".to_string() })]
1402 fn test_data_config_rejects_unsupported_family(#[case] data_type: NautilusDataType) {
1403 let error = data_builder!(data_type.clone(), "/tmp/catalog".to_string())
1404 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1405 .build()
1406 .unwrap_err();
1407
1408 assert_eq!(
1409 error,
1410 ConfigError::unsupported_value(
1411 "data_type",
1412 format!("{data_type} is not supported by BacktestDataConfig"),
1413 ),
1414 );
1415 }
1416
1417 macro_rules! minimal_simulated_builder {
1418 () => {
1419 SimulatedVenueConfig::builder()
1420 .venue(Venue::from("SIM"))
1421 .oms_type(OmsType::Netting)
1422 .account_type(AccountType::Margin)
1423 .book_type(BookType::L1_MBP)
1424 .starting_balances(vec![Money::from("1_000_000 USD")])
1425 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1426 };
1427 }
1428
1429 #[cfg(feature = "streaming")]
1430 #[rstest]
1431 fn test_venue_config_forwards_runtime_policy() {
1432 let instrument_id = InstrumentId::from("EUR/USD.SIM");
1433 let config = minimal_builder!()
1434 .starting_balances(vec!["12_345 USD".to_string()])
1435 .base_currency(Currency::USD())
1436 .default_leverage(Decimal::new(25, 1))
1437 .leverages(AHashMap::from_iter([(instrument_id, Decimal::new(35, 1))]))
1438 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()))
1439 .routing(true)
1440 .reject_stop_orders(false)
1441 .support_gtd_orders(false)
1442 .support_contingent_orders(false)
1443 .use_position_ids(false)
1444 .use_random_ids(true)
1445 .use_reduce_only(false)
1446 .use_market_order_acks(true)
1447 .bar_execution(false)
1448 .bar_adaptive_high_low_ordering(true)
1449 .trade_execution(false)
1450 .liquidity_consumption(true)
1451 .allow_cash_borrowing(true)
1452 .frozen_account(true)
1453 .queue_position(true)
1454 .oto_trigger_mode(OtoTriggerMode::Full)
1455 .price_protection_points(7)
1456 .liquidation_enabled(true)
1457 .liquidation_trigger_ratio(1.5)
1458 .liquidation_cancel_open_orders(false)
1459 .order_priority_reset_policy(OrderPriorityResetPolicy::AnyModify)
1460 .build()
1461 .unwrap();
1462
1463 let runtime = config.to_simulated().unwrap();
1464
1465 assert_eq!(runtime.venue, Venue::from("SIM"));
1466 assert_eq!(runtime.oms_type, OmsType::Netting);
1467 assert_eq!(runtime.account_type, AccountType::Margin);
1468 assert_eq!(runtime.book_type, BookType::L1_MBP);
1469 assert_eq!(runtime.starting_balances, vec![Money::from("12_345 USD")]);
1470 assert_eq!(runtime.base_currency, Some(Currency::USD()));
1471 assert_eq!(runtime.default_leverage, Some(Decimal::new(25, 1)));
1472 assert_eq!(
1473 runtime.leverages,
1474 AHashMap::from_iter([(instrument_id, Decimal::new(35, 1))])
1475 );
1476 assert_eq!(
1477 (
1478 runtime.routing,
1479 runtime.reject_stop_orders,
1480 runtime.support_gtd_orders,
1481 runtime.support_contingent_orders,
1482 runtime.use_position_ids,
1483 runtime.use_random_ids,
1484 runtime.use_reduce_only,
1485 runtime.use_message_queue,
1486 runtime.use_market_order_acks
1487 ),
1488 (true, false, false, false, false, true, false, true, true),
1489 );
1490 assert_eq!(
1491 (
1492 runtime.bar_execution,
1493 runtime.bar_adaptive_high_low_ordering,
1494 runtime.trade_execution,
1495 runtime.liquidity_consumption,
1496 runtime.allow_cash_borrowing,
1497 runtime.frozen_account,
1498 runtime.queue_position,
1499 runtime.oto_full_trigger,
1500 runtime.defer_option_settlement
1501 ),
1502 (false, true, false, true, true, true, true, true, true),
1503 );
1504 assert_eq!(runtime.price_protection_points, 7);
1505 assert!(runtime.liquidation_enabled);
1506 assert_eq!(
1507 runtime.liquidation_trigger_ratio.to_bits(),
1508 1.5_f64.to_bits()
1509 );
1510 assert!(!runtime.liquidation_cancel_open_orders);
1511 assert_eq!(
1512 runtime.order_priority_reset_policy,
1513 OrderPriorityResetPolicy::AnyModify
1514 );
1515 }
1516
1517 #[rstest]
1518 fn test_minimal_config_is_valid() {
1519 assert!(minimal_builder!().build().is_ok());
1520 }
1521
1522 #[cfg(feature = "python")]
1523 #[rstest]
1524 fn test_order_priority_reset_policy_python_keyword(
1525 #[values(
1526 OrderPriorityResetPolicy::PriceChange,
1527 OrderPriorityResetPolicy::PriceOrQuantityIncrease,
1528 OrderPriorityResetPolicy::AnyModify
1529 )]
1530 policy: OrderPriorityResetPolicy,
1531 ) {
1532 Python::initialize();
1533 Python::attach(|py| {
1534 let kwargs = PyDict::new(py);
1535 kwargs
1536 .set_item("order_priority_reset_policy", policy)
1537 .unwrap();
1538 let config = py
1539 .get_type::<BacktestVenueConfig>()
1540 .call(
1541 ("SIM", "NETTING", "MARGIN", vec!["1_000 USD"]),
1542 Some(&kwargs),
1543 )
1544 .unwrap();
1545 assert_eq!(
1546 config
1547 .getattr("order_priority_reset_policy")
1548 .unwrap()
1549 .extract::<OrderPriorityResetPolicy>()
1550 .unwrap(),
1551 policy
1552 );
1553 let config = config.extract::<BacktestVenueConfig>().unwrap();
1554 assert_eq!(config.order_priority_reset_policy(), policy);
1555 });
1556 }
1557
1558 #[rstest]
1559 fn test_order_priority_reset_policy_defaults_and_builder() {
1560 let defaults = minimal_builder!().build().unwrap();
1561 assert_eq!(
1562 defaults.order_priority_reset_policy(),
1563 OrderPriorityResetPolicy::PriceChange
1564 );
1565 assert_eq!(
1566 minimal_simulated_builder!()
1567 .build()
1568 .unwrap()
1569 .order_priority_reset_policy,
1570 OrderPriorityResetPolicy::PriceChange
1571 );
1572 let config = minimal_builder!()
1573 .order_priority_reset_policy(OrderPriorityResetPolicy::AnyModify)
1574 .build()
1575 .unwrap();
1576 assert_eq!(
1577 config.order_priority_reset_policy(),
1578 OrderPriorityResetPolicy::AnyModify
1579 );
1580 }
1581
1582 #[rstest]
1583 fn test_default_leverage_is_optional() {
1584 let config = minimal_builder!().build().unwrap();
1585
1586 assert_eq!(config.default_leverage(), None);
1587 }
1588
1589 #[rstest]
1590 fn test_empty_name_rejected() {
1591 let result = BacktestVenueConfig::builder()
1592 .name("")
1593 .oms_type(OmsType::Netting)
1594 .account_type(AccountType::Margin)
1595 .book_type(BookType::L1_MBP)
1596 .build();
1597 assert!(matches!(result, Err(ConfigError::EmptyField { field }) if field == "name"));
1598 }
1599
1600 #[rstest]
1601 #[case(" ")]
1602 #[case("vénue")]
1603 fn test_invalid_venue_name_rejected(#[case] name: &str) {
1604 let result = BacktestVenueConfig::builder()
1605 .name(name)
1606 .oms_type(OmsType::Netting)
1607 .account_type(AccountType::Margin)
1608 .book_type(BookType::L1_MBP)
1609 .build();
1610 assert!(matches!(result, Err(ConfigError::InvalidValue { field, .. }) if field == "name"));
1611 }
1612
1613 #[rstest]
1614 #[case(Decimal::ZERO)]
1615 #[case(Decimal::from(-1))]
1616 fn test_non_positive_default_leverage_rejected(#[case] leverage: Decimal) {
1617 let result = minimal_builder!().default_leverage(leverage).build();
1618 assert!(
1619 matches!(result, Err(ConfigError::Range { field, .. }) if field == "default_leverage")
1620 );
1621 }
1622
1623 #[rstest]
1624 fn test_non_positive_instrument_leverage_rejected() {
1625 let mut leverages = AHashMap::new();
1626 leverages.insert(InstrumentId::from("ESZ21.GLBX"), Decimal::ZERO);
1627 let result = minimal_builder!().leverages(leverages).build();
1628 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "leverages"));
1629 }
1630
1631 #[rstest]
1632 #[case(Decimal::ZERO)]
1633 #[case(Decimal::from(-1))]
1634 fn test_simulated_non_positive_instrument_leverage_rejected(#[case] leverage: Decimal) {
1635 let mut leverages = AHashMap::new();
1636 leverages.insert(InstrumentId::from("ESZ21.GLBX"), leverage);
1637 let result = minimal_simulated_builder!().leverages(leverages).build();
1638 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "leverages"));
1639 }
1640
1641 #[rstest]
1642 fn test_simulated_positive_instrument_leverage_accepted() {
1643 let mut leverages = AHashMap::new();
1644 leverages.insert(InstrumentId::from("ESZ21.GLBX"), Decimal::from(10));
1645 let result = minimal_simulated_builder!().leverages(leverages).build();
1646 assert!(result.is_ok());
1647 }
1648
1649 #[rstest]
1650 #[case(0.0)]
1651 #[case(-1.0)]
1652 #[case(f64::INFINITY)]
1653 #[case(f64::NAN)]
1654 fn test_invalid_liquidation_trigger_ratio_rejected(#[case] ratio: f64) {
1655 let result = minimal_builder!().liquidation_trigger_ratio(ratio).build();
1656 assert!(
1657 matches!(result, Err(ConfigError::Range { field, .. }) if field == "liquidation_trigger_ratio")
1658 );
1659 }
1660
1661 #[rstest]
1662 fn test_unparsable_starting_balance_rejected() {
1663 let result = minimal_builder!()
1664 .starting_balances(vec!["not a balance".to_string()])
1665 .build();
1666 assert!(
1667 matches!(result, Err(ConfigError::InvalidFormat { field, .. }) if field == "starting_balances")
1668 );
1669 }
1670
1671 #[rstest]
1672 fn test_valid_starting_balance_accepted() {
1673 let result = minimal_builder!()
1674 .starting_balances(vec!["1_000_000 USD".to_string()])
1675 .build();
1676 assert!(result.is_ok());
1677 }
1678
1679 #[rstest]
1680 fn test_multiple_violations_collected() {
1681 let result = BacktestVenueConfig::builder()
1682 .name("")
1683 .oms_type(OmsType::Netting)
1684 .account_type(AccountType::Margin)
1685 .book_type(BookType::L1_MBP)
1686 .default_leverage(Decimal::ZERO)
1687 .starting_balances(vec!["bad".to_string()])
1688 .build();
1689 let ConfigError::Multiple { errors } = result.unwrap_err() else {
1690 panic!("expected ConfigError::Multiple");
1691 };
1692 assert_eq!(errors.len(), 3);
1693 assert!(
1694 errors
1695 .iter()
1696 .any(|e| matches!(e, ConfigError::EmptyField { field } if field == "name"))
1697 );
1698 assert!(
1699 errors.iter().any(
1700 |e| matches!(e, ConfigError::Range { field, .. } if field == "default_leverage")
1701 )
1702 );
1703 assert!(errors.iter().any(
1704 |e| matches!(e, ConfigError::InvalidFormat { field, .. } if field == "starting_balances")
1705 ));
1706 }
1707
1708 #[rstest]
1709 fn test_minimal_data_config_is_valid() {
1710 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1711 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1712 .build();
1713 assert!(result.is_ok());
1714 }
1715
1716 #[cfg(feature = "streaming")]
1717 #[rstest]
1718 #[case("")]
1719 #[case(" ")]
1720 fn test_empty_catalog_path_rejected(#[case] catalog_path: &str) {
1721 let result = data_builder!(NautilusDataType::QuoteTick, catalog_path.to_string())
1722 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1723 .build();
1724 assert!(
1725 matches!(result, Err(ConfigError::EmptyField { field }) if field == "catalog.path")
1726 );
1727 }
1728
1729 #[rstest]
1730 fn test_inverted_time_range_rejected() {
1731 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1732 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1733 .start_time(UnixNanos::from(5_000_000_000u64))
1734 .end_time(UnixNanos::from(1_000_000_000u64))
1735 .build();
1736 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "start_time"));
1737 }
1738
1739 #[rstest]
1740 fn test_equal_time_range_accepted() {
1741 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1742 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1743 .start_time(UnixNanos::from(1_000_000_000u64))
1744 .end_time(UnixNanos::from(1_000_000_000u64))
1745 .build();
1746 assert!(result.is_ok());
1747 }
1748
1749 #[rstest]
1750 fn test_missing_identifier_rejected() {
1751 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string()).build();
1752 assert!(matches!(result, Err(ConfigError::RequiredOneOf { fields }) if fields.len() == 3));
1753 }
1754
1755 #[rstest]
1756 fn test_empty_instrument_ids_rejected() {
1757 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1758 .instrument_ids(vec![])
1759 .build();
1760 assert!(matches!(result, Err(ConfigError::RequiredOneOf { .. })));
1761 }
1762
1763 #[rstest]
1764 fn test_bar_types_satisfies_identifier_requirement() {
1765 let result = data_builder!(NautilusDataType::Bar, "/tmp/catalog".to_string())
1766 .bar_types(vec!["ETH/USDT.BINANCE-1-MINUTE-LAST-EXTERNAL".to_string()])
1767 .build();
1768 assert!(result.is_ok());
1769 }
1770
1771 #[rstest]
1772 fn test_data_config_multiple_violations_collected() {
1773 let result = data_builder!(NautilusDataType::QuoteTick, String::new())
1774 .start_time(UnixNanos::from(5_000_000_000u64))
1775 .end_time(UnixNanos::from(1_000_000_000u64))
1776 .build();
1777 let ConfigError::Multiple { errors } = result.unwrap_err() else {
1778 panic!("expected ConfigError::Multiple");
1779 };
1780
1781 assert_eq!(errors.len(), 2 + usize::from(cfg!(feature = "streaming")));
1782 }
1783
1784 #[cfg(feature = "streaming")]
1785 #[rstest]
1786 #[case::local("/data/catalog", "file", "file:///data/catalog")]
1787 #[case::object_store("bucket/history", "s3", "s3://bucket/history")]
1788 fn test_data_config_preserves_catalog_connection_settings(
1789 #[case] path: &str,
1790 #[case] protocol: &str,
1791 #[case] uri: &str,
1792 ) {
1793 let options =
1794 AHashMap::from([("region".to_string(), SecretString::from("ap-southeast-2"))]);
1795
1796 let params = Params::new(indexmap::IndexMap::from([(
1797 "snapshot_id".to_string(),
1798 serde_json::json!(7),
1799 )]));
1800 let catalog = DataCatalogConfig::builder()
1801 .path(path.to_string())
1802 .name("history".to_string())
1803 .fs_protocol(protocol.to_string())
1804 .catalog_backend(CatalogBackendType::External("Research".to_string()))
1805 .batch_size(512)
1806 .compression(CatalogCompression::Snappy)
1807 .max_row_group_size(2048)
1808 .params(params.clone())
1809 .fs_rust_storage_options(options.clone())
1810 .read_only(true)
1811 .build()
1812 .unwrap();
1813 let config = BacktestDataConfig::builder()
1814 .data_type(NautilusDataType::QuoteTick)
1815 .catalog(catalog.clone())
1816 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1817 .build()
1818 .unwrap();
1819 let connect = config.catalog().connect_config();
1820
1821 assert_eq!(config.catalog(), &catalog);
1822 assert_eq!(config.catalog().fs_rust_storage_options(), Some(&options));
1823 assert_eq!(connect.uri, uri);
1824 assert_eq!(
1825 connect.storage_options,
1826 Some(AHashMap::from([(
1827 "region".to_string(),
1828 "ap-southeast-2".to_string()
1829 )]))
1830 );
1831 assert_eq!(connect.batch_size, Some(512));
1832 assert_eq!(connect.compression, Some(CatalogCompression::Snappy));
1833 assert_eq!(connect.max_row_group_size, Some(2048));
1834 assert_eq!(connect.params, Some(params));
1835 }
1836
1837 #[cfg(feature = "streaming")]
1838 #[rstest]
1839 #[case::batch_size("batch_size")]
1840 #[case::row_group("max_row_group_size")]
1841 fn test_data_config_validates_deserialized_catalog(#[case] field: &str) {
1842 let catalog: DataCatalogConfig = serde_json::from_value(serde_json::json!({
1843 "path": "/data/catalog",
1844 (field): 0,
1845 }))
1846 .unwrap();
1847 let error = BacktestDataConfig::builder()
1848 .data_type(NautilusDataType::QuoteTick)
1849 .catalog(catalog)
1850 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1851 .build()
1852 .unwrap_err();
1853
1854 assert_eq!(
1855 error,
1856 ConfigError::range(
1857 field,
1858 "must be a positive number of rows; omit the field for the backend default",
1859 )
1860 );
1861 }
1862
1863 #[cfg(feature = "streaming")]
1864 #[rstest]
1865 fn test_data_config_debug_redacts_storage_option_values() {
1866 let catalog = DataCatalogConfig::builder()
1867 .path("/tmp/catalog".to_string())
1868 .fs_rust_storage_options(AHashMap::from([(
1869 "aws_secret_access_key".to_string(),
1870 SecretString::from("rust-secret-sentinel"),
1871 )]))
1872 .build()
1873 .unwrap();
1874 let config = BacktestDataConfig::builder()
1875 .data_type(NautilusDataType::QuoteTick)
1876 .catalog(catalog)
1877 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1878 .build()
1879 .unwrap();
1880
1881 let debug_output = format!("{config:?}");
1882
1883 assert!(!debug_output.contains("rust-secret-sentinel"));
1884 assert!(debug_output.contains(&format!(
1885 "fs_rust_storage_options: Some({{\"aws_secret_access_key\": {REDACTED}}})"
1886 )));
1887 }
1888
1889 macro_rules! minimal_sim_builder {
1890 () => {
1891 SimulatedVenueConfig::builder()
1892 .venue(Venue::from("SIM"))
1893 .oms_type(OmsType::Netting)
1894 .account_type(AccountType::Margin)
1895 .book_type(BookType::L1_MBP)
1896 .starting_balances(vec![Money::from("1_000_000 USD")])
1897 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1898 };
1899 }
1900
1901 #[rstest]
1902 fn test_minimal_sim_config_is_valid() {
1903 let config = minimal_sim_builder!().build().unwrap();
1904 assert!(config.defer_option_settlement);
1905 }
1906
1907 #[rstest]
1908 fn test_empty_starting_balances_rejected() {
1909 let result = SimulatedVenueConfig::builder()
1910 .venue(Venue::from("SIM"))
1911 .oms_type(OmsType::Netting)
1912 .account_type(AccountType::Margin)
1913 .book_type(BookType::L1_MBP)
1914 .starting_balances(vec![])
1915 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1916 .build();
1917 assert!(
1918 matches!(result, Err(ConfigError::EmptyField { field }) if field == "starting_balances")
1919 );
1920 }
1921
1922 #[rstest]
1923 #[case(Decimal::ZERO)]
1924 #[case(Decimal::from(-1))]
1925 fn test_non_positive_sim_default_leverage_rejected(#[case] leverage: Decimal) {
1926 let result = minimal_sim_builder!().default_leverage(leverage).build();
1927 assert!(
1928 matches!(result, Err(ConfigError::Range { field, .. }) if field == "default_leverage")
1929 );
1930 }
1931
1932 #[rstest]
1933 fn test_positive_sim_default_leverage_accepted() {
1934 assert!(
1935 minimal_sim_builder!()
1936 .default_leverage(Decimal::from(5))
1937 .build()
1938 .is_ok()
1939 );
1940 }
1941
1942 #[rstest]
1943 #[case(0.0)]
1944 #[case(-1.0)]
1945 #[case(f64::INFINITY)]
1946 #[case(f64::NAN)]
1947 fn test_invalid_sim_liquidation_trigger_ratio_rejected(#[case] ratio: f64) {
1948 let result = minimal_sim_builder!()
1949 .liquidation_trigger_ratio(ratio)
1950 .build();
1951 assert!(
1952 matches!(result, Err(ConfigError::Range { field, .. }) if field == "liquidation_trigger_ratio")
1953 );
1954 }
1955
1956 fn minimal_venue() -> BacktestVenueConfig {
1957 minimal_builder!().build().unwrap()
1958 }
1959
1960 #[rstest]
1961 fn test_minimal_run_config_is_valid() {
1962 let result = BacktestRunConfig::builder()
1963 .venues(vec![minimal_venue()])
1964 .data(vec![])
1965 .build();
1966 assert!(result.is_ok());
1967 }
1968
1969 #[rstest]
1970 fn test_run_config_requires_venues() {
1971 let result = BacktestRunConfig::builder()
1972 .venues(vec![])
1973 .data(vec![])
1974 .build();
1975 assert!(matches!(result, Err(ConfigError::EmptyField { field }) if field == "venues"));
1976 }
1977
1978 #[rstest]
1979 fn test_run_config_inverted_time_range_rejected() {
1980 let result = BacktestRunConfig::builder()
1981 .venues(vec![minimal_venue()])
1982 .data(vec![])
1983 .start(UnixNanos::from(5_000_000_000u64))
1984 .end(UnixNanos::from(1_000_000_000u64))
1985 .build();
1986 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "start"));
1987 }
1988
1989 #[rstest]
1990 fn test_run_config_equal_time_range_accepted() {
1991 let result = BacktestRunConfig::builder()
1992 .venues(vec![minimal_venue()])
1993 .data(vec![])
1994 .start(UnixNanos::from(1_000_000_000u64))
1995 .end(UnixNanos::from(1_000_000_000u64))
1996 .build();
1997 assert!(result.is_ok());
1998 }
1999
2000 #[rstest]
2001 fn test_run_config_accepts_chunk_size() {
2002 let config = BacktestRunConfig::builder()
2003 .venues(vec![minimal_venue()])
2004 .data(vec![])
2005 .chunk_size(10)
2006 .build()
2007 .unwrap();
2008 assert_eq!(config.chunk_size(), Some(10));
2009 }
2010
2011 #[rstest]
2012 fn test_run_config_accepts_maximum_chunk_size() {
2013 let config = BacktestRunConfig::builder()
2014 .venues(vec![minimal_venue()])
2015 .data(vec![])
2016 .chunk_size(MAX_BACKTEST_CHUNK_SIZE)
2017 .build()
2018 .unwrap();
2019
2020 assert_eq!(config.chunk_size(), Some(MAX_BACKTEST_CHUNK_SIZE));
2021 }
2022
2023 #[rstest]
2024 fn test_run_config_zero_chunk_size_rejected() {
2025 let result = BacktestRunConfig::builder()
2026 .venues(vec![minimal_venue()])
2027 .data(vec![])
2028 .chunk_size(0)
2029 .build();
2030 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "chunk_size"));
2031 }
2032
2033 #[rstest]
2034 #[case(MAX_BACKTEST_CHUNK_SIZE + 1)]
2035 #[case(usize::MAX)]
2036 fn test_run_config_rejects_oversized_chunk_size(#[case] chunk_size: usize) {
2037 let result = BacktestRunConfig::builder()
2038 .venues(vec![minimal_venue()])
2039 .data(vec![])
2040 .chunk_size(chunk_size)
2041 .build();
2042
2043 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "chunk_size"));
2044 }
2045
2046 #[rstest]
2047 fn test_run_config_multiple_violations_collected() {
2048 let result = BacktestRunConfig::builder()
2049 .venues(vec![])
2050 .data(vec![])
2051 .start(UnixNanos::from(5_000_000_000u64))
2052 .end(UnixNanos::from(1_000_000_000u64))
2053 .build();
2054 let ConfigError::Multiple { errors } = result.unwrap_err() else {
2055 panic!("expected ConfigError::Multiple");
2056 };
2057 assert_eq!(errors.len(), 2);
2058 }
2059}