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
569impl BacktestVenueConfig {
570 pub fn validate(&self) -> ConfigResult<()> {
577 let mut errors = ConfigErrorCollector::new();
578
579 if self.name.is_empty() {
580 errors.push(ConfigError::empty_field("name"));
581 } else if let Err(e) = Venue::new_checked(self.name.as_str()) {
582 errors.push(ConfigError::invalid_value(
583 "name",
584 format!("must be a valid venue identifier ({e})"),
585 ));
586 }
587
588 if let Some(default_leverage) = self.default_leverage {
589 errors.check(
590 default_leverage > Decimal::ZERO,
591 ConfigError::range(
592 "default_leverage",
593 format!("must be positive, was {default_leverage}"),
594 ),
595 );
596 }
597
598 if let Some(leverages) = &self.leverages {
599 for (instrument_id, leverage) in leverages {
600 errors.check(
601 *leverage > Decimal::ZERO,
602 ConfigError::range(
603 "leverages",
604 format!("leverage for {instrument_id} must be positive, was {leverage}"),
605 ),
606 );
607 }
608 }
609 errors.check(
610 self.liquidation_trigger_ratio.is_finite() && self.liquidation_trigger_ratio > 0.0,
611 ConfigError::range(
612 "liquidation_trigger_ratio",
613 format!(
614 "must be a positive finite value, was {}",
615 self.liquidation_trigger_ratio
616 ),
617 ),
618 );
619
620 for balance in &self.starting_balances {
621 if let Err(reason) = balance.parse::<Money>() {
622 errors.push(ConfigError::invalid_format(
623 "starting_balances",
624 format!("a valid money string, was '{balance}' ({reason})"),
625 ));
626 }
627 }
628
629 errors.into_result()
630 }
631
632 #[must_use]
633 pub fn name(&self) -> Ustr {
634 self.name
635 }
636
637 #[must_use]
638 pub fn oms_type(&self) -> OmsType {
639 self.oms_type
640 }
641
642 #[must_use]
643 pub fn account_type(&self) -> AccountType {
644 self.account_type
645 }
646
647 #[must_use]
648 pub fn book_type(&self) -> BookType {
649 self.book_type
650 }
651
652 #[must_use]
653 pub fn starting_balances(&self) -> &[String] {
654 &self.starting_balances
655 }
656
657 #[must_use]
658 pub fn routing(&self) -> bool {
659 self.routing
660 }
661
662 #[must_use]
663 pub fn frozen_account(&self) -> bool {
664 self.frozen_account
665 }
666
667 #[must_use]
668 pub fn reject_stop_orders(&self) -> bool {
669 self.reject_stop_orders
670 }
671
672 #[must_use]
673 pub fn support_gtd_orders(&self) -> bool {
674 self.support_gtd_orders
675 }
676
677 #[must_use]
678 pub fn support_contingent_orders(&self) -> bool {
679 self.support_contingent_orders
680 }
681
682 #[must_use]
683 pub fn use_position_ids(&self) -> bool {
684 self.use_position_ids
685 }
686
687 #[must_use]
688 pub fn use_random_ids(&self) -> bool {
689 self.use_random_ids
690 }
691
692 #[must_use]
693 pub fn use_reduce_only(&self) -> bool {
694 self.use_reduce_only
695 }
696
697 #[must_use]
698 pub fn bar_execution(&self) -> bool {
699 self.bar_execution
700 }
701
702 #[must_use]
703 pub fn bar_adaptive_high_low_ordering(&self) -> bool {
704 self.bar_adaptive_high_low_ordering
705 }
706
707 #[must_use]
708 pub fn trade_execution(&self) -> bool {
709 self.trade_execution
710 }
711
712 #[must_use]
713 pub fn use_market_order_acks(&self) -> bool {
714 self.use_market_order_acks
715 }
716
717 #[must_use]
718 pub fn liquidity_consumption(&self) -> bool {
719 self.liquidity_consumption
720 }
721
722 #[must_use]
723 pub fn allow_cash_borrowing(&self) -> bool {
724 self.allow_cash_borrowing
725 }
726
727 #[must_use]
728 pub fn order_priority_reset_policy(&self) -> OrderPriorityResetPolicy {
729 self.order_priority_reset_policy
730 }
731
732 #[must_use]
733 pub fn queue_position(&self) -> bool {
734 self.queue_position
735 }
736
737 #[must_use]
738 pub fn oto_trigger_mode(&self) -> OtoTriggerMode {
739 self.oto_trigger_mode
740 }
741
742 #[must_use]
743 pub fn base_currency(&self) -> Option<Currency> {
744 self.base_currency
745 }
746
747 #[must_use]
748 pub fn default_leverage(&self) -> Option<Decimal> {
749 self.default_leverage
750 }
751
752 #[must_use]
753 pub fn leverages(&self) -> Option<&AHashMap<InstrumentId, Decimal>> {
754 self.leverages.as_ref()
755 }
756
757 #[must_use]
758 pub fn fill_model(&self) -> Option<&FillModelAny> {
759 self.fill_model.as_ref()
760 }
761
762 #[must_use]
763 pub fn fee_model(&self) -> Option<&FeeModelAny> {
764 self.fee_model.as_ref()
765 }
766
767 #[must_use]
768 pub fn margin_model(&self) -> Option<&MarginModelAny> {
769 self.margin_model.as_ref()
770 }
771
772 #[must_use]
773 pub fn latency_model(&self) -> Option<&LatencyModelAny> {
774 self.latency_model.as_ref()
775 }
776
777 #[must_use]
778 pub fn modules(&self) -> &[SimulationModuleAny] {
779 &self.modules
780 }
781
782 #[must_use]
783 pub fn price_protection_points(&self) -> u32 {
784 self.price_protection_points
785 }
786
787 #[must_use]
788 pub fn liquidation_enabled(&self) -> bool {
789 self.liquidation_enabled
790 }
791
792 #[must_use]
793 pub fn liquidation_trigger_ratio(&self) -> f64 {
794 self.liquidation_trigger_ratio
795 }
796
797 #[must_use]
798 pub fn liquidation_cancel_open_orders(&self) -> bool {
799 self.liquidation_cancel_open_orders
800 }
801}
802
803#[derive(Debug, Clone, bon::Builder)]
805#[builder(finish_fn(name = build_inner, vis = ""))]
806#[cfg_attr(
807 feature = "python",
808 pyo3::pyclass(module = "nautilus_trader.backtest", from_py_object, unsendable)
809)]
810#[cfg_attr(
811 feature = "python",
812 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
813)]
814pub struct BacktestDataConfig {
815 data_type: NautilusDataType,
817 #[cfg(feature = "streaming")]
819 catalog: DataCatalogConfig,
820 instrument_id: Option<InstrumentId>,
822 instrument_ids: Option<Vec<InstrumentId>>,
824 start_time: Option<UnixNanos>,
826 end_time: Option<UnixNanos>,
828 filter_expr: Option<String>,
830 client_id: Option<ClientId>,
832 metadata: Option<AHashMap<String, String>>,
834 bar_spec: Option<BarSpecification>,
836 bar_types: Option<Vec<String>>,
838 #[builder(default)]
840 optimize_file_loading: bool,
841 #[builder(default = true)]
843 batch_deltas: bool,
844}
845
846impl<S: backtest_data_config_builder::IsComplete> BacktestDataConfigBuilder<S> {
847 pub fn build(self) -> ConfigResult<BacktestDataConfig> {
853 let config = self.build_inner();
854 config.validate()?;
855 Ok(config)
856 }
857}
858
859impl BacktestDataConfig {
860 pub fn validate(&self) -> ConfigResult<()> {
867 let mut errors = ConfigErrorCollector::new();
868
869 errors.check(
870 matches!(
871 self.data_type,
872 NautilusDataType::OrderBookDelta
873 | NautilusDataType::OrderBookDepth
874 | NautilusDataType::QuoteTick
875 | NautilusDataType::TradeTick
876 | NautilusDataType::Bar
877 | NautilusDataType::MarkPriceUpdate
878 | NautilusDataType::IndexPriceUpdate
879 | NautilusDataType::FundingRateUpdate
880 | NautilusDataType::OptionGreeks
881 | NautilusDataType::InstrumentStatus
882 | NautilusDataType::InstrumentClose
883 | NautilusDataType::Instrument
884 ),
885 ConfigError::unsupported_value(
886 "data_type",
887 format!("{} is not supported by BacktestDataConfig", self.data_type),
888 ),
889 );
890
891 #[cfg(feature = "streaming")]
892 {
893 if self.catalog.path().trim().is_empty() {
894 errors.push(ConfigError::empty_field("catalog.path"));
895 }
896
897 errors.collect(self.catalog.validate());
898 }
899
900 if let (Some(start), Some(end)) = (self.start_time, self.end_time) {
901 errors.check(
902 start <= end,
903 ConfigError::range(
904 "start_time",
905 format!("must be <= end_time, was {start} > {end}"),
906 ),
907 );
908 }
909
910 let has_identifier = self.instrument_id.is_some()
911 || self
912 .instrument_ids
913 .as_ref()
914 .is_some_and(|ids| !ids.is_empty())
915 || self.bar_types.as_ref().is_some_and(|bars| !bars.is_empty());
916 errors.check(
917 has_identifier,
918 ConfigError::required_one_of(["instrument_id", "instrument_ids", "bar_types"]),
919 );
920
921 errors.into_result()
922 }
923
924 #[must_use]
925 pub const fn data_type(&self) -> &NautilusDataType {
926 &self.data_type
927 }
928
929 #[must_use]
931 #[cfg(feature = "streaming")]
932 pub const fn catalog(&self) -> &DataCatalogConfig {
933 &self.catalog
934 }
935
936 #[must_use]
937 pub fn instrument_id(&self) -> Option<InstrumentId> {
938 self.instrument_id
939 }
940
941 #[must_use]
942 pub fn instrument_ids(&self) -> Option<&[InstrumentId]> {
943 self.instrument_ids.as_deref()
944 }
945
946 #[must_use]
947 pub fn start_time(&self) -> Option<UnixNanos> {
948 self.start_time
949 }
950
951 #[must_use]
952 pub fn end_time(&self) -> Option<UnixNanos> {
953 self.end_time
954 }
955
956 #[must_use]
957 pub fn filter_expr(&self) -> Option<&str> {
958 self.filter_expr.as_deref()
959 }
960
961 #[must_use]
962 pub fn client_id(&self) -> Option<ClientId> {
963 self.client_id
964 }
965
966 #[must_use]
967 pub fn metadata(&self) -> Option<&AHashMap<String, String>> {
968 self.metadata.as_ref()
969 }
970
971 #[must_use]
972 pub fn bar_spec(&self) -> Option<BarSpecification> {
973 self.bar_spec
974 }
975
976 #[must_use]
977 pub fn bar_types(&self) -> Option<&[String]> {
978 self.bar_types.as_deref()
979 }
980
981 #[must_use]
982 pub fn optimize_file_loading(&self) -> bool {
983 self.optimize_file_loading
984 }
985
986 #[must_use]
987 pub fn batch_deltas(&self) -> bool {
988 self.batch_deltas
989 }
990
991 #[must_use]
997 pub fn query_identifiers(&self) -> Option<Vec<String>> {
998 if self.data_type == NautilusDataType::Bar {
999 if let Some(bar_types) = &self.bar_types
1000 && !bar_types.is_empty()
1001 {
1002 return Some(bar_types.clone());
1003 }
1004
1005 if let Some(bar_spec) = &self.bar_spec {
1007 if let Some(id) = self.instrument_id {
1008 return Some(vec![format!("{id}-{bar_spec}-EXTERNAL")]);
1009 }
1010
1011 if let Some(ids) = &self.instrument_ids {
1012 let bar_types: Vec<String> = ids
1013 .iter()
1014 .map(|id| format!("{id}-{bar_spec}-EXTERNAL"))
1015 .collect();
1016
1017 if !bar_types.is_empty() {
1018 return Some(bar_types);
1019 }
1020 }
1021 }
1022 }
1023
1024 if let Some(id) = self.instrument_id {
1026 return Some(vec![id.to_string()]);
1027 }
1028
1029 if let Some(ids) = &self.instrument_ids {
1030 let strs: Vec<String> = ids.iter().map(ToString::to_string).collect();
1031 if !strs.is_empty() {
1032 return Some(strs);
1033 }
1034 }
1035
1036 None
1037 }
1038
1039 pub fn get_instrument_ids(&self) -> anyhow::Result<Vec<InstrumentId>> {
1047 if let Some(id) = self.instrument_id {
1048 return Ok(vec![id]);
1049 }
1050
1051 if let Some(ids) = &self.instrument_ids {
1052 return Ok(ids.clone());
1053 }
1054
1055 if let Some(bar_types) = &self.bar_types {
1056 let ids = bar_types
1057 .iter()
1058 .map(|bt| {
1059 bt.parse::<BarType>()
1060 .map(|b| b.instrument_id())
1061 .map_err(|_| anyhow::anyhow!("Invalid bar type string: '{bt}'"))
1062 })
1063 .collect::<anyhow::Result<Vec<_>>>()?;
1064 return Ok(ids);
1065 }
1066 Ok(Vec::new())
1067 }
1068}
1069
1070#[derive(Debug, Clone, bon::Builder)]
1073#[builder(finish_fn(name = build_inner, vis = ""))]
1074#[cfg_attr(
1075 feature = "python",
1076 pyo3::pyclass(module = "nautilus_trader.backtest", from_py_object, unsendable)
1077)]
1078#[cfg_attr(
1079 feature = "python",
1080 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")
1081)]
1082pub struct BacktestRunConfig {
1083 #[builder(default = UUID4::new().to_string())]
1085 id: String,
1086 venues: Vec<BacktestVenueConfig>,
1088 data: Vec<BacktestDataConfig>,
1090 #[builder(default)]
1092 engine: BacktestEngineConfig,
1093 chunk_size: Option<usize>,
1097 #[builder(default)]
1099 raise_exception: bool,
1100 #[builder(default = true)]
1104 dispose_on_completion: bool,
1105 start: Option<UnixNanos>,
1108 end: Option<UnixNanos>,
1111}
1112
1113impl<S: backtest_run_config_builder::IsComplete> BacktestRunConfigBuilder<S> {
1114 pub fn build(self) -> ConfigResult<BacktestRunConfig> {
1120 let config = self.build_inner();
1121 config.validate()?;
1122 Ok(config)
1123 }
1124}
1125
1126impl BacktestRunConfig {
1127 pub fn validate(&self) -> ConfigResult<()> {
1134 let mut errors = ConfigErrorCollector::new();
1135
1136 if self.venues.is_empty() {
1137 errors.push(ConfigError::empty_field("venues"));
1138 }
1139
1140 if let (Some(start), Some(end)) = (self.start, self.end) {
1141 errors.check(
1142 start <= end,
1143 ConfigError::range("start", format!("must be <= end, was {start} > {end}")),
1144 );
1145 }
1146
1147 if let Some(chunk_size) = self.chunk_size {
1148 errors.check(
1149 (1..=MAX_BACKTEST_CHUNK_SIZE).contains(&chunk_size),
1150 ConfigError::range(
1151 "chunk_size",
1152 format!("must be in range [1, {MAX_BACKTEST_CHUNK_SIZE}], was {chunk_size}"),
1153 ),
1154 );
1155 }
1156
1157 errors.into_result()
1158 }
1159
1160 #[must_use]
1161 pub fn id(&self) -> &str {
1162 &self.id
1163 }
1164
1165 #[must_use]
1166 pub fn venues(&self) -> &[BacktestVenueConfig] {
1167 &self.venues
1168 }
1169
1170 #[must_use]
1171 pub fn data(&self) -> &[BacktestDataConfig] {
1172 &self.data
1173 }
1174
1175 #[must_use]
1176 pub fn engine(&self) -> &BacktestEngineConfig {
1177 &self.engine
1178 }
1179
1180 #[must_use]
1181 pub fn chunk_size(&self) -> Option<usize> {
1182 self.chunk_size
1183 }
1184
1185 #[must_use]
1186 pub fn raise_exception(&self) -> bool {
1187 self.raise_exception
1188 }
1189
1190 #[must_use]
1191 pub fn dispose_on_completion(&self) -> bool {
1192 self.dispose_on_completion
1193 }
1194
1195 #[must_use]
1196 pub fn start(&self) -> Option<UnixNanos> {
1197 self.start
1198 }
1199
1200 #[must_use]
1201 pub fn end(&self) -> Option<UnixNanos> {
1202 self.end
1203 }
1204}
1205
1206#[cfg(test)]
1207mod tests {
1208 #[cfg(feature = "streaming")]
1209 use nautilus_core::{
1210 Params,
1211 string::secret::{REDACTED, SecretString},
1212 };
1213 use nautilus_execution::models::fee::MakerTakerFeeModel;
1214 #[cfg(feature = "streaming")]
1215 use nautilus_persistence::config::{CatalogBackendType, CatalogCompression};
1216 #[cfg(feature = "python")]
1217 use pyo3::{
1218 Python,
1219 types::{PyAnyMethods, PyDict, PyDictMethods},
1220 };
1221 use rstest::rstest;
1222
1223 use super::*;
1224
1225 macro_rules! minimal_builder {
1226 () => {
1227 BacktestVenueConfig::builder()
1228 .name("SIM")
1229 .oms_type(OmsType::Netting)
1230 .account_type(AccountType::Margin)
1231 .book_type(BookType::L1_MBP)
1232 };
1233 }
1234
1235 macro_rules! data_builder {
1236 ($data_type:expr, $catalog_path:expr) => {{
1237 let builder = BacktestDataConfig::builder().data_type($data_type);
1238 #[cfg(feature = "streaming")]
1239 let builder = builder.catalog(DataCatalogConfig::new($catalog_path, None, None));
1240 builder
1241 }};
1242 }
1243
1244 #[rstest]
1245 #[case(NautilusDataType::OrderBookDelta)]
1246 #[case(NautilusDataType::OrderBookDepth)]
1247 #[case(NautilusDataType::QuoteTick)]
1248 #[case(NautilusDataType::TradeTick)]
1249 #[case(NautilusDataType::Bar)]
1250 #[case(NautilusDataType::MarkPriceUpdate)]
1251 #[case(NautilusDataType::IndexPriceUpdate)]
1252 #[case(NautilusDataType::FundingRateUpdate)]
1253 #[case(NautilusDataType::OptionGreeks)]
1254 #[case(NautilusDataType::InstrumentStatus)]
1255 #[case(NautilusDataType::InstrumentClose)]
1256 fn test_data_config_accepts_supported_family(#[case] data_type: NautilusDataType) {
1257 let config = data_builder!(data_type.clone(), "/tmp/catalog".to_string())
1258 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1259 .build()
1260 .unwrap();
1261
1262 assert_eq!(config.data_type(), &data_type);
1263 }
1264
1265 #[rstest]
1266 fn test_data_config_accepts_the_instrument_family() {
1267 let config = data_builder!(NautilusDataType::Instrument, "/tmp/catalog".to_string())
1268 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1269 .build()
1270 .unwrap();
1271
1272 assert_eq!(config.data_type(), &NautilusDataType::Instrument);
1273 }
1274
1275 #[rstest]
1276 #[case(NautilusDataType::Custom { type_name: "Signal".to_string() })]
1277 fn test_data_config_rejects_unsupported_family(#[case] data_type: NautilusDataType) {
1278 let error = data_builder!(data_type.clone(), "/tmp/catalog".to_string())
1279 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1280 .build()
1281 .unwrap_err();
1282
1283 assert_eq!(
1284 error,
1285 ConfigError::unsupported_value(
1286 "data_type",
1287 format!("{data_type} is not supported by BacktestDataConfig"),
1288 ),
1289 );
1290 }
1291
1292 macro_rules! minimal_simulated_builder {
1293 () => {
1294 SimulatedVenueConfig::builder()
1295 .venue(Venue::from("SIM"))
1296 .oms_type(OmsType::Netting)
1297 .account_type(AccountType::Margin)
1298 .book_type(BookType::L1_MBP)
1299 .starting_balances(vec![Money::from("1_000_000 USD")])
1300 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1301 };
1302 }
1303
1304 #[rstest]
1305 fn test_minimal_config_is_valid() {
1306 assert!(minimal_builder!().build().is_ok());
1307 }
1308
1309 #[cfg(feature = "python")]
1310 #[rstest]
1311 fn test_order_priority_reset_policy_python_keyword(
1312 #[values(
1313 OrderPriorityResetPolicy::PriceChange,
1314 OrderPriorityResetPolicy::PriceOrQuantityIncrease,
1315 OrderPriorityResetPolicy::AnyModify
1316 )]
1317 policy: OrderPriorityResetPolicy,
1318 ) {
1319 Python::initialize();
1320 Python::attach(|py| {
1321 let kwargs = PyDict::new(py);
1322 kwargs
1323 .set_item("order_priority_reset_policy", policy)
1324 .unwrap();
1325 let config = py
1326 .get_type::<BacktestVenueConfig>()
1327 .call(
1328 ("SIM", "NETTING", "MARGIN", vec!["1_000 USD"]),
1329 Some(&kwargs),
1330 )
1331 .unwrap();
1332 assert_eq!(
1333 config
1334 .getattr("order_priority_reset_policy")
1335 .unwrap()
1336 .extract::<OrderPriorityResetPolicy>()
1337 .unwrap(),
1338 policy
1339 );
1340 let config = config.extract::<BacktestVenueConfig>().unwrap();
1341 assert_eq!(config.order_priority_reset_policy(), policy);
1342 });
1343 }
1344
1345 #[rstest]
1346 fn test_order_priority_reset_policy_defaults_and_builder() {
1347 let defaults = minimal_builder!().build().unwrap();
1348 assert_eq!(
1349 defaults.order_priority_reset_policy(),
1350 OrderPriorityResetPolicy::PriceChange
1351 );
1352 assert_eq!(
1353 minimal_simulated_builder!()
1354 .build()
1355 .unwrap()
1356 .order_priority_reset_policy,
1357 OrderPriorityResetPolicy::PriceChange
1358 );
1359 let config = minimal_builder!()
1360 .order_priority_reset_policy(OrderPriorityResetPolicy::AnyModify)
1361 .build()
1362 .unwrap();
1363 assert_eq!(
1364 config.order_priority_reset_policy(),
1365 OrderPriorityResetPolicy::AnyModify
1366 );
1367 }
1368
1369 #[rstest]
1370 fn test_default_leverage_is_optional() {
1371 let config = minimal_builder!().build().unwrap();
1372
1373 assert_eq!(config.default_leverage(), None);
1374 }
1375
1376 #[rstest]
1377 fn test_empty_name_rejected() {
1378 let result = BacktestVenueConfig::builder()
1379 .name("")
1380 .oms_type(OmsType::Netting)
1381 .account_type(AccountType::Margin)
1382 .book_type(BookType::L1_MBP)
1383 .build();
1384 assert!(matches!(result, Err(ConfigError::EmptyField { field }) if field == "name"));
1385 }
1386
1387 #[rstest]
1388 #[case(" ")]
1389 #[case("vénue")]
1390 fn test_invalid_venue_name_rejected(#[case] name: &str) {
1391 let result = BacktestVenueConfig::builder()
1392 .name(name)
1393 .oms_type(OmsType::Netting)
1394 .account_type(AccountType::Margin)
1395 .book_type(BookType::L1_MBP)
1396 .build();
1397 assert!(matches!(result, Err(ConfigError::InvalidValue { field, .. }) if field == "name"));
1398 }
1399
1400 #[rstest]
1401 #[case(Decimal::ZERO)]
1402 #[case(Decimal::from(-1))]
1403 fn test_non_positive_default_leverage_rejected(#[case] leverage: Decimal) {
1404 let result = minimal_builder!().default_leverage(leverage).build();
1405 assert!(
1406 matches!(result, Err(ConfigError::Range { field, .. }) if field == "default_leverage")
1407 );
1408 }
1409
1410 #[rstest]
1411 fn test_non_positive_instrument_leverage_rejected() {
1412 let mut leverages = AHashMap::new();
1413 leverages.insert(InstrumentId::from("ESZ21.GLBX"), Decimal::ZERO);
1414 let result = minimal_builder!().leverages(leverages).build();
1415 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "leverages"));
1416 }
1417
1418 #[rstest]
1419 #[case(Decimal::ZERO)]
1420 #[case(Decimal::from(-1))]
1421 fn test_simulated_non_positive_instrument_leverage_rejected(#[case] leverage: Decimal) {
1422 let mut leverages = AHashMap::new();
1423 leverages.insert(InstrumentId::from("ESZ21.GLBX"), leverage);
1424 let result = minimal_simulated_builder!().leverages(leverages).build();
1425 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "leverages"));
1426 }
1427
1428 #[rstest]
1429 fn test_simulated_positive_instrument_leverage_accepted() {
1430 let mut leverages = AHashMap::new();
1431 leverages.insert(InstrumentId::from("ESZ21.GLBX"), Decimal::from(10));
1432 let result = minimal_simulated_builder!().leverages(leverages).build();
1433 assert!(result.is_ok());
1434 }
1435
1436 #[rstest]
1437 #[case(0.0)]
1438 #[case(-1.0)]
1439 #[case(f64::INFINITY)]
1440 #[case(f64::NAN)]
1441 fn test_invalid_liquidation_trigger_ratio_rejected(#[case] ratio: f64) {
1442 let result = minimal_builder!().liquidation_trigger_ratio(ratio).build();
1443 assert!(
1444 matches!(result, Err(ConfigError::Range { field, .. }) if field == "liquidation_trigger_ratio")
1445 );
1446 }
1447
1448 #[rstest]
1449 fn test_unparsable_starting_balance_rejected() {
1450 let result = minimal_builder!()
1451 .starting_balances(vec!["not a balance".to_string()])
1452 .build();
1453 assert!(
1454 matches!(result, Err(ConfigError::InvalidFormat { field, .. }) if field == "starting_balances")
1455 );
1456 }
1457
1458 #[rstest]
1459 fn test_valid_starting_balance_accepted() {
1460 let result = minimal_builder!()
1461 .starting_balances(vec!["1_000_000 USD".to_string()])
1462 .build();
1463 assert!(result.is_ok());
1464 }
1465
1466 #[rstest]
1467 fn test_multiple_violations_collected() {
1468 let result = BacktestVenueConfig::builder()
1469 .name("")
1470 .oms_type(OmsType::Netting)
1471 .account_type(AccountType::Margin)
1472 .book_type(BookType::L1_MBP)
1473 .default_leverage(Decimal::ZERO)
1474 .starting_balances(vec!["bad".to_string()])
1475 .build();
1476 let ConfigError::Multiple { errors } = result.unwrap_err() else {
1477 panic!("expected ConfigError::Multiple");
1478 };
1479 assert_eq!(errors.len(), 3);
1480 assert!(
1481 errors
1482 .iter()
1483 .any(|e| matches!(e, ConfigError::EmptyField { field } if field == "name"))
1484 );
1485 assert!(
1486 errors.iter().any(
1487 |e| matches!(e, ConfigError::Range { field, .. } if field == "default_leverage")
1488 )
1489 );
1490 assert!(errors.iter().any(
1491 |e| matches!(e, ConfigError::InvalidFormat { field, .. } if field == "starting_balances")
1492 ));
1493 }
1494
1495 #[rstest]
1496 fn test_minimal_data_config_is_valid() {
1497 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1498 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1499 .build();
1500 assert!(result.is_ok());
1501 }
1502
1503 #[cfg(feature = "streaming")]
1504 #[rstest]
1505 #[case("")]
1506 #[case(" ")]
1507 fn test_empty_catalog_path_rejected(#[case] catalog_path: &str) {
1508 let result = data_builder!(NautilusDataType::QuoteTick, catalog_path.to_string())
1509 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1510 .build();
1511 assert!(
1512 matches!(result, Err(ConfigError::EmptyField { field }) if field == "catalog.path")
1513 );
1514 }
1515
1516 #[rstest]
1517 fn test_inverted_time_range_rejected() {
1518 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1519 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1520 .start_time(UnixNanos::from(5_000_000_000u64))
1521 .end_time(UnixNanos::from(1_000_000_000u64))
1522 .build();
1523 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "start_time"));
1524 }
1525
1526 #[rstest]
1527 fn test_equal_time_range_accepted() {
1528 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1529 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1530 .start_time(UnixNanos::from(1_000_000_000u64))
1531 .end_time(UnixNanos::from(1_000_000_000u64))
1532 .build();
1533 assert!(result.is_ok());
1534 }
1535
1536 #[rstest]
1537 fn test_missing_identifier_rejected() {
1538 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string()).build();
1539 assert!(matches!(result, Err(ConfigError::RequiredOneOf { fields }) if fields.len() == 3));
1540 }
1541
1542 #[rstest]
1543 fn test_empty_instrument_ids_rejected() {
1544 let result = data_builder!(NautilusDataType::QuoteTick, "/tmp/catalog".to_string())
1545 .instrument_ids(vec![])
1546 .build();
1547 assert!(matches!(result, Err(ConfigError::RequiredOneOf { .. })));
1548 }
1549
1550 #[rstest]
1551 fn test_bar_types_satisfies_identifier_requirement() {
1552 let result = data_builder!(NautilusDataType::Bar, "/tmp/catalog".to_string())
1553 .bar_types(vec!["ETH/USDT.BINANCE-1-MINUTE-LAST-EXTERNAL".to_string()])
1554 .build();
1555 assert!(result.is_ok());
1556 }
1557
1558 #[rstest]
1559 fn test_data_config_multiple_violations_collected() {
1560 let result = data_builder!(NautilusDataType::QuoteTick, String::new())
1561 .start_time(UnixNanos::from(5_000_000_000u64))
1562 .end_time(UnixNanos::from(1_000_000_000u64))
1563 .build();
1564 let ConfigError::Multiple { errors } = result.unwrap_err() else {
1565 panic!("expected ConfigError::Multiple");
1566 };
1567
1568 assert_eq!(errors.len(), 2 + usize::from(cfg!(feature = "streaming")));
1569 }
1570
1571 #[cfg(feature = "streaming")]
1572 #[rstest]
1573 #[case::local("/data/catalog", "file", "file:///data/catalog")]
1574 #[case::object_store("bucket/history", "s3", "s3://bucket/history")]
1575 fn test_data_config_preserves_catalog_connection_settings(
1576 #[case] path: &str,
1577 #[case] protocol: &str,
1578 #[case] uri: &str,
1579 ) {
1580 let options =
1581 AHashMap::from([("region".to_string(), SecretString::from("ap-southeast-2"))]);
1582
1583 let params = Params::new(indexmap::IndexMap::from([(
1584 "snapshot_id".to_string(),
1585 serde_json::json!(7),
1586 )]));
1587 let catalog = DataCatalogConfig::builder()
1588 .path(path.to_string())
1589 .name("history".to_string())
1590 .fs_protocol(protocol.to_string())
1591 .catalog_backend(CatalogBackendType::External("Research".to_string()))
1592 .batch_size(512)
1593 .compression(CatalogCompression::Snappy)
1594 .max_row_group_size(2048)
1595 .params(params.clone())
1596 .fs_rust_storage_options(options.clone())
1597 .read_only(true)
1598 .build()
1599 .unwrap();
1600 let config = BacktestDataConfig::builder()
1601 .data_type(NautilusDataType::QuoteTick)
1602 .catalog(catalog.clone())
1603 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1604 .build()
1605 .unwrap();
1606 let connect = config.catalog().connect_config();
1607
1608 assert_eq!(config.catalog(), &catalog);
1609 assert_eq!(config.catalog().fs_rust_storage_options(), Some(&options));
1610 assert_eq!(connect.uri, uri);
1611 assert_eq!(
1612 connect.storage_options,
1613 Some(AHashMap::from([(
1614 "region".to_string(),
1615 "ap-southeast-2".to_string()
1616 )]))
1617 );
1618 assert_eq!(connect.batch_size, Some(512));
1619 assert_eq!(connect.compression, Some(CatalogCompression::Snappy));
1620 assert_eq!(connect.max_row_group_size, Some(2048));
1621 assert_eq!(connect.params, Some(params));
1622 }
1623
1624 #[cfg(feature = "streaming")]
1625 #[rstest]
1626 #[case::batch_size("batch_size")]
1627 #[case::row_group("max_row_group_size")]
1628 fn test_data_config_validates_deserialized_catalog(#[case] field: &str) {
1629 let catalog: DataCatalogConfig = serde_json::from_value(serde_json::json!({
1630 "path": "/data/catalog",
1631 (field): 0,
1632 }))
1633 .unwrap();
1634 let error = BacktestDataConfig::builder()
1635 .data_type(NautilusDataType::QuoteTick)
1636 .catalog(catalog)
1637 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1638 .build()
1639 .unwrap_err();
1640
1641 assert_eq!(
1642 error,
1643 ConfigError::range(
1644 field,
1645 "must be a positive number of rows; omit the field for the backend default",
1646 )
1647 );
1648 }
1649
1650 #[cfg(feature = "streaming")]
1651 #[rstest]
1652 fn test_data_config_debug_redacts_storage_option_values() {
1653 let catalog = DataCatalogConfig::builder()
1654 .path("/tmp/catalog".to_string())
1655 .fs_rust_storage_options(AHashMap::from([(
1656 "aws_secret_access_key".to_string(),
1657 SecretString::from("rust-secret-sentinel"),
1658 )]))
1659 .build()
1660 .unwrap();
1661 let config = BacktestDataConfig::builder()
1662 .data_type(NautilusDataType::QuoteTick)
1663 .catalog(catalog)
1664 .instrument_id(InstrumentId::from("ETH/USDT.BINANCE"))
1665 .build()
1666 .unwrap();
1667
1668 let debug_output = format!("{config:?}");
1669
1670 assert!(!debug_output.contains("rust-secret-sentinel"));
1671 assert!(debug_output.contains(&format!(
1672 "fs_rust_storage_options: Some({{\"aws_secret_access_key\": {REDACTED}}})"
1673 )));
1674 }
1675
1676 macro_rules! minimal_sim_builder {
1677 () => {
1678 SimulatedVenueConfig::builder()
1679 .venue(Venue::from("SIM"))
1680 .oms_type(OmsType::Netting)
1681 .account_type(AccountType::Margin)
1682 .book_type(BookType::L1_MBP)
1683 .starting_balances(vec![Money::from("1_000_000 USD")])
1684 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1685 };
1686 }
1687
1688 #[rstest]
1689 fn test_minimal_sim_config_is_valid() {
1690 let config = minimal_sim_builder!().build().unwrap();
1691 assert!(config.defer_option_settlement);
1692 }
1693
1694 #[rstest]
1695 fn test_empty_starting_balances_rejected() {
1696 let result = SimulatedVenueConfig::builder()
1697 .venue(Venue::from("SIM"))
1698 .oms_type(OmsType::Netting)
1699 .account_type(AccountType::Margin)
1700 .book_type(BookType::L1_MBP)
1701 .starting_balances(vec![])
1702 .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1703 .build();
1704 assert!(
1705 matches!(result, Err(ConfigError::EmptyField { field }) if field == "starting_balances")
1706 );
1707 }
1708
1709 #[rstest]
1710 #[case(Decimal::ZERO)]
1711 #[case(Decimal::from(-1))]
1712 fn test_non_positive_sim_default_leverage_rejected(#[case] leverage: Decimal) {
1713 let result = minimal_sim_builder!().default_leverage(leverage).build();
1714 assert!(
1715 matches!(result, Err(ConfigError::Range { field, .. }) if field == "default_leverage")
1716 );
1717 }
1718
1719 #[rstest]
1720 fn test_positive_sim_default_leverage_accepted() {
1721 assert!(
1722 minimal_sim_builder!()
1723 .default_leverage(Decimal::from(5))
1724 .build()
1725 .is_ok()
1726 );
1727 }
1728
1729 #[rstest]
1730 #[case(0.0)]
1731 #[case(-1.0)]
1732 #[case(f64::INFINITY)]
1733 #[case(f64::NAN)]
1734 fn test_invalid_sim_liquidation_trigger_ratio_rejected(#[case] ratio: f64) {
1735 let result = minimal_sim_builder!()
1736 .liquidation_trigger_ratio(ratio)
1737 .build();
1738 assert!(
1739 matches!(result, Err(ConfigError::Range { field, .. }) if field == "liquidation_trigger_ratio")
1740 );
1741 }
1742
1743 fn minimal_venue() -> BacktestVenueConfig {
1744 minimal_builder!().build().unwrap()
1745 }
1746
1747 #[rstest]
1748 fn test_minimal_run_config_is_valid() {
1749 let result = BacktestRunConfig::builder()
1750 .venues(vec![minimal_venue()])
1751 .data(vec![])
1752 .build();
1753 assert!(result.is_ok());
1754 }
1755
1756 #[rstest]
1757 fn test_run_config_requires_venues() {
1758 let result = BacktestRunConfig::builder()
1759 .venues(vec![])
1760 .data(vec![])
1761 .build();
1762 assert!(matches!(result, Err(ConfigError::EmptyField { field }) if field == "venues"));
1763 }
1764
1765 #[rstest]
1766 fn test_run_config_inverted_time_range_rejected() {
1767 let result = BacktestRunConfig::builder()
1768 .venues(vec![minimal_venue()])
1769 .data(vec![])
1770 .start(UnixNanos::from(5_000_000_000u64))
1771 .end(UnixNanos::from(1_000_000_000u64))
1772 .build();
1773 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "start"));
1774 }
1775
1776 #[rstest]
1777 fn test_run_config_equal_time_range_accepted() {
1778 let result = BacktestRunConfig::builder()
1779 .venues(vec![minimal_venue()])
1780 .data(vec![])
1781 .start(UnixNanos::from(1_000_000_000u64))
1782 .end(UnixNanos::from(1_000_000_000u64))
1783 .build();
1784 assert!(result.is_ok());
1785 }
1786
1787 #[rstest]
1788 fn test_run_config_accepts_chunk_size() {
1789 let config = BacktestRunConfig::builder()
1790 .venues(vec![minimal_venue()])
1791 .data(vec![])
1792 .chunk_size(10)
1793 .build()
1794 .unwrap();
1795 assert_eq!(config.chunk_size(), Some(10));
1796 }
1797
1798 #[rstest]
1799 fn test_run_config_accepts_maximum_chunk_size() {
1800 let config = BacktestRunConfig::builder()
1801 .venues(vec![minimal_venue()])
1802 .data(vec![])
1803 .chunk_size(MAX_BACKTEST_CHUNK_SIZE)
1804 .build()
1805 .unwrap();
1806
1807 assert_eq!(config.chunk_size(), Some(MAX_BACKTEST_CHUNK_SIZE));
1808 }
1809
1810 #[rstest]
1811 fn test_run_config_zero_chunk_size_rejected() {
1812 let result = BacktestRunConfig::builder()
1813 .venues(vec![minimal_venue()])
1814 .data(vec![])
1815 .chunk_size(0)
1816 .build();
1817 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "chunk_size"));
1818 }
1819
1820 #[rstest]
1821 #[case(MAX_BACKTEST_CHUNK_SIZE + 1)]
1822 #[case(usize::MAX)]
1823 fn test_run_config_rejects_oversized_chunk_size(#[case] chunk_size: usize) {
1824 let result = BacktestRunConfig::builder()
1825 .venues(vec![minimal_venue()])
1826 .data(vec![])
1827 .chunk_size(chunk_size)
1828 .build();
1829
1830 assert!(matches!(result, Err(ConfigError::Range { field, .. }) if field == "chunk_size"));
1831 }
1832
1833 #[rstest]
1834 fn test_run_config_multiple_violations_collected() {
1835 let result = BacktestRunConfig::builder()
1836 .venues(vec![])
1837 .data(vec![])
1838 .start(UnixNanos::from(5_000_000_000u64))
1839 .end(UnixNanos::from(1_000_000_000u64))
1840 .build();
1841 let ConfigError::Multiple { errors } = result.unwrap_err() else {
1842 panic!("expected ConfigError::Multiple");
1843 };
1844 assert_eq!(errors.len(), 2);
1845 }
1846}