1use std::{collections::HashMap, fmt::Display, str::FromStr, time::Duration};
19
20use nautilus_common::{
21 cache::CacheConfig, enums::Environment, logging::logger::LoggerConfig,
22 msgbus::MessageBusConfig, python::config_error_to_pyvalue_err,
23};
24use nautilus_core::{
25 UUID4, UnixNanos,
26 python::{to_pytype_err, to_pyvalue_err},
27};
28use nautilus_data::engine::config::DataEngineConfig;
29use nautilus_execution::{
30 engine::config::ExecutionEngineConfig,
31 matching_engine::config::OrderPriorityResetPolicy,
32 python::{
33 fee::{fee_model_any_to_pyobject, pyobject_to_fee_model_any},
34 fill::{fill_model_any_to_pyobject, pyobject_to_fill_model_any},
35 latency::{latency_model_any_to_pyobject, pyobject_to_latency_model_any},
36 },
37};
38use nautilus_model::{
39 data::BarSpecification,
40 enums::{AccountType, BookType, OmsType, OtoTriggerMode},
41 identifiers::{ClientId, InstrumentId, TraderId},
42 python::{
43 account::margin_model::{margin_model_any_to_pyobject, pyobject_to_margin_model_any},
44 data::PyNautilusDataType,
45 },
46 types::Currency,
47};
48use nautilus_persistence::config::{DataCatalogConfig, StreamingConfig};
49use nautilus_portfolio::config::PortfolioConfig;
50use nautilus_risk::engine::config::RiskEngineConfig;
51use nautilus_trading::ImportableControllerConfig;
52use pyo3::{Bound, Py, PyAny, PyResult, Python, types::PyAnyMethods};
53use rust_decimal::Decimal;
54use ustr::Ustr;
55
56use super::modules::{pyobject_to_simulation_module_any, simulation_module_any_to_pyobject};
57use crate::config::{
58 BacktestDataConfig, BacktestEngineConfig, BacktestRunConfig, BacktestVenueConfig,
59};
60
61#[pyo3_stub_gen::derive::gen_stub_pymethods]
62#[pyo3::pymethods]
63impl BacktestEngineConfig {
64 #[new]
66 #[pyo3(signature = (
67 trader_id = None,
68 load_state = None,
69 save_state = None,
70 shutdown_on_error = None,
71 bypass_logging = None,
72 run_analysis = None,
73 timeout_connection = None,
74 timeout_reconciliation = None,
75 timeout_portfolio = None,
76 timeout_disconnection = None,
77 delay_post_stop = None,
78 timeout_shutdown = None,
79 logging = None,
80 instance_id = None,
81 cache = None,
82 msgbus = None,
83 data_engine = None,
84 risk_engine = None,
85 exec_engine = None,
86 portfolio = None,
87 controller = None,
88 streaming = None,
89 catalogs = None,
90 ))]
91 #[expect(clippy::too_many_arguments)]
92 fn py_new(
93 trader_id: Option<TraderId>,
94 load_state: Option<bool>,
95 save_state: Option<bool>,
96 shutdown_on_error: Option<bool>,
97 bypass_logging: Option<bool>,
98 run_analysis: Option<bool>,
99 timeout_connection: Option<u64>,
100 timeout_reconciliation: Option<u64>,
101 timeout_portfolio: Option<u64>,
102 timeout_disconnection: Option<u64>,
103 delay_post_stop: Option<u64>,
104 timeout_shutdown: Option<u64>,
105 logging: Option<LoggerConfig>,
106 instance_id: Option<UUID4>,
107 cache: Option<CacheConfig>,
108 msgbus: Option<MessageBusConfig>,
109 data_engine: Option<DataEngineConfig>,
110 risk_engine: Option<RiskEngineConfig>,
111 exec_engine: Option<ExecutionEngineConfig>,
112 portfolio: Option<PortfolioConfig>,
113 controller: Option<ImportableControllerConfig>,
114 streaming: Option<StreamingConfig>,
115 catalogs: Option<Vec<DataCatalogConfig>>,
116 ) -> Self {
117 let defaults = Self::default();
118 Self {
119 environment: Environment::Backtest,
120 trader_id: trader_id.unwrap_or_default(),
121 load_state: load_state.unwrap_or(defaults.load_state),
122 save_state: save_state.unwrap_or(defaults.save_state),
123 shutdown_on_error: shutdown_on_error.unwrap_or(defaults.shutdown_on_error),
124 bypass_logging: bypass_logging.unwrap_or(defaults.bypass_logging),
125 run_analysis: run_analysis.unwrap_or(defaults.run_analysis),
126 timeout_connection: Duration::from_secs(timeout_connection.unwrap_or(60)),
127 timeout_reconciliation: Duration::from_secs(timeout_reconciliation.unwrap_or(30)),
128 timeout_portfolio: Duration::from_secs(timeout_portfolio.unwrap_or(10)),
129 timeout_disconnection: Duration::from_secs(timeout_disconnection.unwrap_or(10)),
130 delay_post_stop: Duration::from_secs(delay_post_stop.unwrap_or(10)),
131 timeout_shutdown: Duration::from_secs(timeout_shutdown.unwrap_or(5)),
132 logging: logging.unwrap_or_default(),
133 instance_id,
134 cache,
135 msgbus,
136 data_engine,
137 risk_engine,
138 exec_engine,
139 portfolio,
140 controller,
141 streaming,
142 catalogs: catalogs.unwrap_or_default(),
143 }
144 }
145
146 #[getter]
147 #[pyo3(name = "trader_id")]
148 fn py_trader_id(&self) -> TraderId {
149 self.trader_id
150 }
151
152 #[getter]
153 #[pyo3(name = "load_state")]
154 const fn py_load_state(&self) -> bool {
155 self.load_state
156 }
157
158 #[getter]
159 #[pyo3(name = "save_state")]
160 const fn py_save_state(&self) -> bool {
161 self.save_state
162 }
163
164 #[getter]
165 #[pyo3(name = "shutdown_on_error")]
166 const fn py_shutdown_on_error(&self) -> bool {
167 self.shutdown_on_error
168 }
169
170 #[getter]
171 #[pyo3(name = "bypass_logging")]
172 const fn py_bypass_logging(&self) -> bool {
173 self.bypass_logging
174 }
175
176 #[getter]
177 #[pyo3(name = "run_analysis")]
178 const fn py_run_analysis(&self) -> bool {
179 self.run_analysis
180 }
181
182 #[getter]
183 #[pyo3(name = "timeout_connection")]
184 fn py_timeout_connection(&self) -> f64 {
185 self.timeout_connection.as_secs_f64()
186 }
187
188 #[getter]
189 #[pyo3(name = "timeout_reconciliation")]
190 fn py_timeout_reconciliation(&self) -> f64 {
191 self.timeout_reconciliation.as_secs_f64()
192 }
193
194 #[getter]
195 #[pyo3(name = "timeout_portfolio")]
196 fn py_timeout_portfolio(&self) -> f64 {
197 self.timeout_portfolio.as_secs_f64()
198 }
199
200 #[getter]
201 #[pyo3(name = "timeout_disconnection")]
202 fn py_timeout_disconnection(&self) -> f64 {
203 self.timeout_disconnection.as_secs_f64()
204 }
205
206 #[getter]
207 #[pyo3(name = "delay_post_stop")]
208 fn py_delay_post_stop(&self) -> f64 {
209 self.delay_post_stop.as_secs_f64()
210 }
211
212 #[getter]
213 #[pyo3(name = "timeout_shutdown")]
214 fn py_timeout_shutdown(&self) -> f64 {
215 self.timeout_shutdown.as_secs_f64()
216 }
217
218 #[getter]
219 #[pyo3(name = "logging")]
220 fn py_logging(&self) -> LoggerConfig {
221 self.logging.clone()
222 }
223
224 #[getter]
225 #[pyo3(name = "instance_id")]
226 const fn py_instance_id(&self) -> Option<UUID4> {
227 self.instance_id
228 }
229
230 #[getter]
231 #[pyo3(name = "cache")]
232 fn py_cache(&self) -> Option<CacheConfig> {
233 self.cache.clone()
234 }
235
236 #[getter]
237 #[pyo3(name = "msgbus")]
238 fn py_msgbus(&self) -> Option<MessageBusConfig> {
239 self.msgbus.clone()
240 }
241
242 #[getter]
243 #[pyo3(name = "data_engine")]
244 fn py_data_engine(&self) -> Option<DataEngineConfig> {
245 self.data_engine.clone()
246 }
247
248 #[getter]
249 #[pyo3(name = "risk_engine")]
250 fn py_risk_engine(&self) -> Option<RiskEngineConfig> {
251 self.risk_engine.clone()
252 }
253
254 #[getter]
255 #[pyo3(name = "exec_engine")]
256 fn py_exec_engine(&self) -> Option<ExecutionEngineConfig> {
257 self.exec_engine.clone()
258 }
259
260 #[getter]
261 #[pyo3(name = "portfolio")]
262 const fn py_portfolio(&self) -> Option<PortfolioConfig> {
263 self.portfolio
264 }
265
266 #[getter]
267 #[pyo3(name = "controller")]
268 fn py_controller(&self) -> Option<ImportableControllerConfig> {
269 self.controller.clone()
270 }
271
272 #[getter]
273 #[pyo3(name = "streaming")]
274 fn py_streaming(&self) -> Option<StreamingConfig> {
275 self.streaming.clone()
276 }
277
278 #[getter]
279 #[pyo3(name = "catalogs")]
280 fn py_catalogs(&self) -> Vec<DataCatalogConfig> {
281 self.catalogs.clone()
282 }
283
284 fn __repr__(&self) -> String {
285 format!("{self:?}")
286 }
287}
288
289#[pyo3_stub_gen::derive::gen_stub_pymethods]
290#[pyo3::pymethods]
291impl BacktestVenueConfig {
292 #[new]
294 #[pyo3(signature = (
295 name,
296 oms_type,
297 account_type,
298 starting_balances,
299 book_type = None,
300 routing = None,
301 frozen_account = None,
302 reject_stop_orders = None,
303 support_gtd_orders = None,
304 support_contingent_orders = None,
305 use_position_ids = None,
306 use_random_ids = None,
307 use_reduce_only = None,
308 bar_execution = None,
309 bar_adaptive_high_low_ordering = None,
310 trade_execution = None,
311 use_market_order_acks = None,
312 liquidity_consumption = None,
313 allow_cash_borrowing = None,
314 queue_position = None,
315 oto_trigger_mode = None,
316 base_currency = None,
317 default_leverage = None,
318 leverages = None,
319 fill_model = None,
320 fee_model = None,
321 margin_model = None,
322 latency_model = None,
323 modules = None,
324 price_protection_points = None,
325 liquidation_enabled = None,
326 liquidation_trigger_ratio = None,
327 liquidation_cancel_open_orders = None,
328 order_priority_reset_policy = None,
329 ))]
330 #[expect(clippy::too_many_arguments)]
331 fn py_new(
332 name: &str,
333 #[gen_stub(override_type(type_repr = "model.OmsType | str"))] oms_type: &Bound<'_, PyAny>,
334 #[gen_stub(override_type(type_repr = "model.AccountType | str"))] account_type: &Bound<
335 '_,
336 PyAny,
337 >,
338 starting_balances: Vec<String>,
339 #[gen_stub(override_type(type_repr = "model.BookType | str | None"))] book_type: Option<
340 &Bound<'_, PyAny>,
341 >,
342 routing: Option<bool>,
343 frozen_account: Option<bool>,
344 reject_stop_orders: Option<bool>,
345 support_gtd_orders: Option<bool>,
346 support_contingent_orders: Option<bool>,
347 use_position_ids: Option<bool>,
348 use_random_ids: Option<bool>,
349 use_reduce_only: Option<bool>,
350 bar_execution: Option<bool>,
351 bar_adaptive_high_low_ordering: Option<bool>,
352 trade_execution: Option<bool>,
353 use_market_order_acks: Option<bool>,
354 liquidity_consumption: Option<bool>,
355 allow_cash_borrowing: Option<bool>,
356 queue_position: Option<bool>,
357 #[gen_stub(override_type(type_repr = "model.OtoTriggerMode | str | None"))]
358 oto_trigger_mode: Option<&Bound<'_, PyAny>>,
359 base_currency: Option<Currency>,
360 default_leverage: Option<Decimal>,
361 leverages: Option<HashMap<InstrumentId, Decimal>>,
362 fill_model: Option<Py<PyAny>>,
363 fee_model: Option<Py<PyAny>>,
364 margin_model: Option<Py<PyAny>>,
365 latency_model: Option<Py<PyAny>>,
366 modules: Option<Vec<Py<PyAny>>>,
367 price_protection_points: Option<u32>,
368 liquidation_enabled: Option<bool>,
369 liquidation_trigger_ratio: Option<f64>,
370 liquidation_cancel_open_orders: Option<bool>,
371 order_priority_reset_policy: Option<OrderPriorityResetPolicy>,
372 ) -> pyo3::PyResult<Self> {
373 let oms_type = enum_from_python(oms_type)?;
374 let account_type = enum_from_python(account_type)?;
375 let book_type = book_type
376 .map(enum_from_python)
377 .transpose()?
378 .unwrap_or(BookType::L1_MBP);
379 let oto_trigger_mode = oto_trigger_mode.map(enum_from_python).transpose()?;
380 let fill_model = fill_model
381 .map(|obj| Python::attach(|py| pyobject_to_fill_model_any(obj.bind(py))))
382 .transpose()?;
383
384 let fee_model = fee_model
385 .map(|obj| Python::attach(|py| pyobject_to_fee_model_any(obj.bind(py))))
386 .transpose()?;
387
388 let margin_model = margin_model
389 .map(|obj| Python::attach(|py| pyobject_to_margin_model_any(obj.bind(py))))
390 .transpose()?;
391
392 let latency_model = latency_model
393 .map(|obj| Python::attach(|py| pyobject_to_latency_model_any(obj.bind(py))))
394 .transpose()?;
395
396 let modules = modules
397 .map(|objs| {
398 objs.into_iter()
399 .map(|obj| Python::attach(|py| pyobject_to_simulation_module_any(obj.bind(py))))
400 .collect::<pyo3::PyResult<Vec<_>>>()
401 })
402 .transpose()?
403 .unwrap_or_default();
404
405 Self::builder()
406 .name(Ustr::from(name))
407 .oms_type(oms_type)
408 .account_type(account_type)
409 .book_type(book_type)
410 .starting_balances(starting_balances)
411 .maybe_routing(routing)
412 .maybe_frozen_account(frozen_account)
413 .maybe_reject_stop_orders(reject_stop_orders)
414 .maybe_support_gtd_orders(support_gtd_orders)
415 .maybe_support_contingent_orders(support_contingent_orders)
416 .maybe_use_position_ids(use_position_ids)
417 .maybe_use_random_ids(use_random_ids)
418 .maybe_use_reduce_only(use_reduce_only)
419 .maybe_bar_execution(bar_execution)
420 .maybe_bar_adaptive_high_low_ordering(bar_adaptive_high_low_ordering)
421 .maybe_trade_execution(trade_execution)
422 .maybe_use_market_order_acks(use_market_order_acks)
423 .maybe_liquidity_consumption(liquidity_consumption)
424 .maybe_allow_cash_borrowing(allow_cash_borrowing)
425 .maybe_queue_position(queue_position)
426 .maybe_order_priority_reset_policy(order_priority_reset_policy)
427 .maybe_oto_trigger_mode(oto_trigger_mode)
428 .maybe_base_currency(base_currency)
429 .maybe_default_leverage(default_leverage)
430 .maybe_leverages(leverages.map(|m| m.into_iter().collect()))
431 .maybe_fill_model(fill_model)
432 .maybe_fee_model(fee_model)
433 .maybe_margin_model(margin_model)
434 .maybe_latency_model(latency_model)
435 .modules(modules)
436 .maybe_price_protection_points(price_protection_points)
437 .maybe_liquidation_enabled(liquidation_enabled)
438 .maybe_liquidation_trigger_ratio(liquidation_trigger_ratio)
439 .maybe_liquidation_cancel_open_orders(liquidation_cancel_open_orders)
440 .build()
441 .map_err(config_error_to_pyvalue_err)
442 }
443
444 #[getter]
445 #[pyo3(name = "name")]
446 fn py_name(&self) -> &str {
447 self.name().as_str()
448 }
449
450 #[getter]
451 #[pyo3(name = "oms_type")]
452 fn py_oms_type(&self) -> OmsType {
453 self.oms_type()
454 }
455
456 #[getter]
457 #[pyo3(name = "account_type")]
458 fn py_account_type(&self) -> AccountType {
459 self.account_type()
460 }
461
462 #[getter]
463 #[pyo3(name = "book_type")]
464 fn py_book_type(&self) -> BookType {
465 self.book_type()
466 }
467
468 #[getter]
469 #[pyo3(name = "starting_balances")]
470 fn py_starting_balances(&self) -> Vec<String> {
471 self.starting_balances().to_vec()
472 }
473
474 #[getter]
475 #[pyo3(name = "routing")]
476 fn py_routing(&self) -> bool {
477 self.routing()
478 }
479
480 #[getter]
481 #[pyo3(name = "frozen_account")]
482 fn py_frozen_account(&self) -> bool {
483 self.frozen_account()
484 }
485
486 #[getter]
487 #[pyo3(name = "reject_stop_orders")]
488 fn py_reject_stop_orders(&self) -> bool {
489 self.reject_stop_orders()
490 }
491
492 #[getter]
493 #[pyo3(name = "support_gtd_orders")]
494 fn py_support_gtd_orders(&self) -> bool {
495 self.support_gtd_orders()
496 }
497
498 #[getter]
499 #[pyo3(name = "support_contingent_orders")]
500 fn py_support_contingent_orders(&self) -> bool {
501 self.support_contingent_orders()
502 }
503
504 #[getter]
505 #[pyo3(name = "use_position_ids")]
506 fn py_use_position_ids(&self) -> bool {
507 self.use_position_ids()
508 }
509
510 #[getter]
511 #[pyo3(name = "use_random_ids")]
512 fn py_use_random_ids(&self) -> bool {
513 self.use_random_ids()
514 }
515
516 #[getter]
517 #[pyo3(name = "use_reduce_only")]
518 fn py_use_reduce_only(&self) -> bool {
519 self.use_reduce_only()
520 }
521
522 #[getter]
523 #[pyo3(name = "bar_execution")]
524 fn py_bar_execution(&self) -> bool {
525 self.bar_execution()
526 }
527
528 #[getter]
529 #[pyo3(name = "trade_execution")]
530 fn py_trade_execution(&self) -> bool {
531 self.trade_execution()
532 }
533
534 #[getter]
535 #[pyo3(name = "bar_adaptive_high_low_ordering")]
536 fn py_bar_adaptive_high_low_ordering(&self) -> bool {
537 self.bar_adaptive_high_low_ordering()
538 }
539
540 #[getter]
541 #[pyo3(name = "use_market_order_acks")]
542 fn py_use_market_order_acks(&self) -> bool {
543 self.use_market_order_acks()
544 }
545
546 #[getter]
547 #[pyo3(name = "liquidity_consumption")]
548 fn py_liquidity_consumption(&self) -> bool {
549 self.liquidity_consumption()
550 }
551
552 #[getter]
553 #[pyo3(name = "allow_cash_borrowing")]
554 fn py_allow_cash_borrowing(&self) -> bool {
555 self.allow_cash_borrowing()
556 }
557
558 #[getter]
559 #[pyo3(name = "order_priority_reset_policy")]
560 fn py_order_priority_reset_policy(&self) -> OrderPriorityResetPolicy {
561 self.order_priority_reset_policy()
562 }
563
564 #[getter]
565 #[pyo3(name = "queue_position")]
566 fn py_queue_position(&self) -> bool {
567 self.queue_position()
568 }
569
570 #[getter]
571 #[pyo3(name = "oto_trigger_mode")]
572 fn py_oto_trigger_mode(&self) -> OtoTriggerMode {
573 self.oto_trigger_mode()
574 }
575
576 #[getter]
577 #[pyo3(name = "base_currency")]
578 fn py_base_currency(&self) -> Option<Currency> {
579 self.base_currency()
580 }
581
582 #[getter]
583 #[pyo3(name = "default_leverage")]
584 fn py_default_leverage(&self) -> Option<Decimal> {
585 self.default_leverage()
586 }
587
588 #[getter]
589 #[pyo3(name = "leverages")]
590 fn py_leverages(&self) -> Option<HashMap<InstrumentId, Decimal>> {
591 self.leverages().map(|leverages| {
592 leverages
593 .iter()
594 .map(|(key, value)| (*key, *value))
595 .collect()
596 })
597 }
598
599 #[getter]
600 #[pyo3(name = "fill_model")]
601 fn py_fill_model(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
602 self.fill_model()
603 .map(|model| fill_model_any_to_pyobject(py, model))
604 .transpose()
605 }
606
607 #[getter]
608 #[pyo3(name = "fee_model")]
609 fn py_fee_model(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
610 self.fee_model()
611 .map(|model| fee_model_any_to_pyobject(py, model))
612 .transpose()
613 }
614
615 #[getter]
616 #[pyo3(name = "margin_model")]
617 fn py_margin_model(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
618 self.margin_model()
619 .map(|model| margin_model_any_to_pyobject(py, model))
620 .transpose()
621 }
622
623 #[getter]
624 #[pyo3(name = "latency_model")]
625 fn py_latency_model(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
626 self.latency_model()
627 .map(|model| latency_model_any_to_pyobject(py, model))
628 .transpose()
629 }
630
631 #[getter]
632 #[pyo3(name = "modules")]
633 fn py_modules(&self, py: Python<'_>) -> PyResult<Vec<Py<PyAny>>> {
634 self.modules()
635 .iter()
636 .map(|module| simulation_module_any_to_pyobject(py, module))
637 .collect()
638 }
639
640 #[getter]
641 #[pyo3(name = "price_protection_points")]
642 fn py_price_protection_points(&self) -> u32 {
643 self.price_protection_points()
644 }
645
646 #[getter]
647 #[pyo3(name = "liquidation_enabled")]
648 fn py_liquidation_enabled(&self) -> bool {
649 self.liquidation_enabled()
650 }
651
652 #[getter]
653 #[pyo3(name = "liquidation_trigger_ratio")]
654 fn py_liquidation_trigger_ratio(&self) -> f64 {
655 self.liquidation_trigger_ratio()
656 }
657
658 #[getter]
659 #[pyo3(name = "liquidation_cancel_open_orders")]
660 fn py_liquidation_cancel_open_orders(&self) -> bool {
661 self.liquidation_cancel_open_orders()
662 }
663
664 fn __repr__(&self) -> String {
665 format!("{self:?}")
666 }
667}
668
669#[pyo3_stub_gen::derive::gen_stub_pymethods]
670#[pyo3::pymethods]
671impl BacktestDataConfig {
672 #[new]
674 #[pyo3(signature = (
675 data_type,
676 catalog,
677 instrument_id = None,
678 instrument_ids = None,
679 start_time = None,
680 end_time = None,
681 filter_expr = None,
682 client_id = None,
683 metadata = None,
684 bar_spec = None,
685 bar_types = None,
686 optimize_file_loading = None,
687 batch_deltas = None,
688 ))]
689 #[expect(clippy::too_many_arguments)]
690 fn py_new(
691 #[gen_stub(override_type(type_repr = "model.NautilusDataType"))] data_type: &Bound<
692 '_,
693 PyAny,
694 >,
695 catalog: DataCatalogConfig,
696 instrument_id: Option<InstrumentId>,
697 instrument_ids: Option<Vec<InstrumentId>>,
698 #[gen_stub(override_type(
699 type_repr = "int | str | datetime.datetime | pd.Timestamp | None",
700 imports = ("datetime", "pandas as pd")
701 ))]
702 start_time: Option<Py<PyAny>>,
703 #[gen_stub(override_type(
704 type_repr = "int | str | datetime.datetime | pd.Timestamp | None",
705 imports = ("datetime", "pandas as pd")
706 ))]
707 end_time: Option<Py<PyAny>>,
708 filter_expr: Option<String>,
709 client_id: Option<ClientId>,
710 metadata: Option<HashMap<String, String>>,
711 bar_spec: Option<BarSpecification>,
712 bar_types: Option<Vec<String>>,
713 optimize_file_loading: Option<bool>,
714 batch_deltas: Option<bool>,
715 ) -> pyo3::PyResult<Self> {
716 let data_type = data_type
717 .extract::<pyo3::PyRef<'_, PyNautilusDataType>>()
718 .map(|data_type| data_type.inner())
719 .map_err(|_| to_pytype_err("data_type must be NautilusDataType"))?;
720 let start_time = timestamp_from_python(start_time)?;
721 let end_time = timestamp_from_python(end_time)?;
722 Self::builder()
723 .data_type(data_type)
724 .catalog(catalog)
725 .maybe_instrument_id(instrument_id)
726 .maybe_instrument_ids(instrument_ids)
727 .maybe_start_time(start_time)
728 .maybe_end_time(end_time)
729 .maybe_filter_expr(filter_expr)
730 .maybe_client_id(client_id)
731 .maybe_metadata(metadata.map(|m| m.into_iter().collect()))
732 .maybe_bar_spec(bar_spec)
733 .maybe_bar_types(bar_types)
734 .maybe_optimize_file_loading(optimize_file_loading)
735 .maybe_batch_deltas(batch_deltas)
736 .build()
737 .map_err(config_error_to_pyvalue_err)
738 }
739
740 #[getter]
742 #[pyo3(name = "catalog")]
743 fn py_catalog(&self) -> DataCatalogConfig {
744 self.catalog().clone()
745 }
746
747 #[getter]
748 #[pyo3(name = "data_type")]
749 fn py_data_type(&self) -> PyNautilusDataType {
750 PyNautilusDataType::new(self.data_type().clone())
751 }
752
753 #[getter]
754 #[pyo3(name = "instrument_id")]
755 fn py_instrument_id(&self) -> Option<InstrumentId> {
756 self.instrument_id()
757 }
758
759 #[getter]
760 #[pyo3(name = "instrument_ids")]
761 fn py_instrument_ids(&self) -> Option<Vec<InstrumentId>> {
762 self.instrument_ids().map(<[InstrumentId]>::to_vec)
763 }
764
765 #[getter]
766 #[pyo3(name = "start_time")]
767 fn py_start_time(&self) -> Option<u64> {
768 self.start_time().map(|timestamp| timestamp.as_u64())
769 }
770
771 #[getter]
772 #[pyo3(name = "end_time")]
773 fn py_end_time(&self) -> Option<u64> {
774 self.end_time().map(|timestamp| timestamp.as_u64())
775 }
776
777 #[getter]
778 #[pyo3(name = "filter_expr")]
779 fn py_filter_expr(&self) -> Option<&str> {
780 self.filter_expr()
781 }
782
783 #[getter]
784 #[pyo3(name = "client_id")]
785 fn py_client_id(&self) -> Option<ClientId> {
786 self.client_id()
787 }
788
789 #[getter]
790 #[pyo3(name = "metadata")]
791 fn py_metadata(&self) -> Option<HashMap<String, String>> {
792 self.metadata().map(|metadata| {
793 metadata
794 .iter()
795 .map(|(key, value)| (key.clone(), value.clone()))
796 .collect()
797 })
798 }
799
800 #[getter]
801 #[pyo3(name = "bar_spec")]
802 fn py_bar_spec(&self) -> Option<BarSpecification> {
803 self.bar_spec()
804 }
805
806 #[getter]
807 #[pyo3(name = "bar_types")]
808 fn py_bar_types(&self) -> Option<Vec<String>> {
809 self.bar_types().map(<[String]>::to_vec)
810 }
811
812 #[getter]
813 #[pyo3(name = "optimize_file_loading")]
814 fn py_optimize_file_loading(&self) -> bool {
815 self.optimize_file_loading()
816 }
817
818 #[getter]
819 #[pyo3(name = "batch_deltas")]
820 fn py_batch_deltas(&self) -> bool {
821 self.batch_deltas()
822 }
823
824 fn __repr__(&self) -> String {
825 format!("{self:?}")
826 }
827}
828
829#[pyo3_stub_gen::derive::gen_stub_pymethods]
830#[pyo3::pymethods]
831impl BacktestRunConfig {
832 #[new]
835 #[pyo3(signature = (
836 venues,
837 data,
838 engine = None,
839 id = None,
840 chunk_size = None,
841 raise_exception = None,
842 dispose_on_completion = None,
843 start = None,
844 end = None,
845 ))]
846 #[expect(clippy::too_many_arguments)]
847 fn py_new(
848 venues: Vec<BacktestVenueConfig>,
849 data: Vec<BacktestDataConfig>,
850 engine: Option<BacktestEngineConfig>,
851 id: Option<String>,
852 chunk_size: Option<usize>,
853 raise_exception: Option<bool>,
854 dispose_on_completion: Option<bool>,
855 #[gen_stub(override_type(
856 type_repr = "int | str | datetime.datetime | pd.Timestamp | None",
857 imports = ("datetime", "pandas as pd")
858 ))]
859 start: Option<Py<PyAny>>,
860 #[gen_stub(override_type(
861 type_repr = "int | str | datetime.datetime | pd.Timestamp | None",
862 imports = ("datetime", "pandas as pd")
863 ))]
864 end: Option<Py<PyAny>>,
865 ) -> pyo3::PyResult<Self> {
866 let start = timestamp_from_python(start)?;
867 let end = timestamp_from_python(end)?;
868 Self::builder()
869 .venues(venues)
870 .data(data)
871 .maybe_engine(engine)
872 .maybe_id(id)
873 .maybe_chunk_size(chunk_size)
874 .maybe_raise_exception(raise_exception)
875 .maybe_dispose_on_completion(dispose_on_completion)
876 .maybe_start(start)
877 .maybe_end(end)
878 .build()
879 .map_err(config_error_to_pyvalue_err)
880 }
881
882 #[getter]
883 #[pyo3(name = "id")]
884 fn py_id(&self) -> &str {
885 self.id()
886 }
887
888 #[getter]
889 #[pyo3(name = "venues")]
890 fn py_venues(&self) -> Vec<BacktestVenueConfig> {
891 self.venues().to_vec()
892 }
893
894 #[getter]
895 #[pyo3(name = "data")]
896 fn py_data(&self) -> Vec<BacktestDataConfig> {
897 self.data().to_vec()
898 }
899
900 #[getter]
901 #[pyo3(name = "engine")]
902 fn py_engine(&self) -> BacktestEngineConfig {
903 self.engine().clone()
904 }
905
906 #[getter]
907 #[pyo3(name = "chunk_size")]
908 fn py_chunk_size(&self) -> Option<usize> {
909 self.chunk_size()
910 }
911
912 #[getter]
913 #[pyo3(name = "raise_exception")]
914 fn py_raise_exception(&self) -> bool {
915 self.raise_exception()
916 }
917
918 #[getter]
919 #[pyo3(name = "dispose_on_completion")]
920 fn py_dispose_on_completion(&self) -> bool {
921 self.dispose_on_completion()
922 }
923
924 #[getter]
925 #[pyo3(name = "start")]
926 fn py_start(&self) -> Option<u64> {
927 self.start().map(|timestamp| timestamp.as_u64())
928 }
929
930 #[getter]
931 #[pyo3(name = "end")]
932 fn py_end(&self) -> Option<u64> {
933 self.end().map(|timestamp| timestamp.as_u64())
934 }
935
936 fn __repr__(&self) -> String {
937 format!("{self:?}")
938 }
939}
940
941fn timestamp_from_python(value: Option<Py<PyAny>>) -> PyResult<Option<UnixNanos>> {
942 value
943 .map(|value| {
944 Python::attach(|py| {
945 py.import("nautilus_trader.core.datetime")?
946 .getattr("dt_to_unix_nanos")?
947 .call1((value,))?
948 .extract::<u64>()
949 .map(UnixNanos::from)
950 })
951 })
952 .transpose()
953}
954
955fn enum_from_python<'py, E>(value: &Bound<'py, PyAny>) -> PyResult<E>
956where
957 E: pyo3::conversion::FromPyObjectOwned<'py> + FromStr,
958 E::Err: Display,
959{
960 if let Ok(value) = value.extract::<E>() {
961 return Ok(value);
962 }
963 value
964 .extract::<String>()?
965 .parse::<E>()
966 .map_err(to_pyvalue_err)
967}
968
969#[cfg(test)]
970mod tests {
971 use ahash::AHashMap;
972 use nautilus_core::string::secret::SecretString;
973 use nautilus_model::data::NautilusDataType;
974 use rstest::rstest;
975
976 use super::*;
977
978 #[rstest]
979 fn test_data_config_py_new_keeps_catalog_storage_option_values() {
980 Python::initialize();
981
982 let config = Python::attach(|py| {
983 let data_type =
984 Bound::new(py, PyNautilusDataType::new(NautilusDataType::QuoteTick)).unwrap();
985 BacktestDataConfig::py_new(
986 data_type.as_any(),
987 DataCatalogConfig::new("bucket/catalog".to_string(), Some("s3".to_string()), None)
988 .with_storage_options(Some(AHashMap::from([(
989 "aws_secret_access_key".to_string(),
990 SecretString::from("rust-secret"),
991 )]))),
992 Some(InstrumentId::from("EUR/USD.SIM")),
993 None,
994 None,
995 None,
996 None,
997 None,
998 None,
999 None,
1000 None,
1001 None,
1002 None,
1003 )
1004 .unwrap()
1005 });
1006
1007 assert_eq!(
1008 config.catalog().fs_rust_storage_options(),
1009 Some(&AHashMap::from([(
1010 "aws_secret_access_key".to_string(),
1011 SecretString::from("rust-secret"),
1012 )]))
1013 );
1014 }
1015
1016 #[rstest]
1017 #[case::default(None, true)]
1018 #[case::disabled(Some(false), false)]
1019 #[case::enabled(Some(true), true)]
1020 fn test_data_config_py_new_sets_batch_deltas(
1021 #[case] batch_deltas: Option<bool>,
1022 #[case] expected: bool,
1023 ) {
1024 Python::initialize();
1025
1026 let config = Python::attach(|py| {
1027 let data_type = Bound::new(
1028 py,
1029 PyNautilusDataType::new(NautilusDataType::OrderBookDelta),
1030 )
1031 .unwrap();
1032 BacktestDataConfig::py_new(
1033 data_type.as_any(),
1034 DataCatalogConfig::new("catalog".to_string(), None, None),
1035 Some(InstrumentId::from("EUR/USD.SIM")),
1036 None,
1037 None,
1038 None,
1039 None,
1040 None,
1041 None,
1042 None,
1043 None,
1044 None,
1045 batch_deltas,
1046 )
1047 .unwrap()
1048 });
1049
1050 assert_eq!(config.batch_deltas(), expected);
1051 assert_eq!(config.py_batch_deltas(), expected);
1052 }
1053}