1use std::{collections::HashMap, str::FromStr, time::Duration};
19
20use ahash::AHashMap;
21use indexmap::IndexSet;
22use nautilus_common::{
23 cache::CacheConfig,
24 config::{
25 ConfigError, ConfigErrorCollector, ConfigResult, check_non_empty_field, check_range,
26 check_supported_field, check_valid_format,
27 },
28 enums::Environment,
29 logging::logger::LoggerConfig,
30 msgbus::MessageBusConfig,
31 throttler::RateLimit,
32};
33use nautilus_core::{
34 DurationNanos, UUID4,
35 datetime::{get_timezone, secs_to_nanos},
36};
37use nautilus_data::engine::config::DataEngineConfig;
38use nautilus_execution::{
39 engine::config::ExecutionEngineConfig, order_emulator::config::OrderEmulatorConfig,
40};
41use nautilus_model::{
42 enums::{BarAggregation, BarIntervalType},
43 identifiers::{ClientId, ClientOrderId, InstrumentId, TraderId, Venue},
44};
45use nautilus_portfolio::config::PortfolioConfig;
46use nautilus_risk::engine::config::RiskEngineConfig;
47#[cfg(feature = "streaming")]
48use nautilus_system::config::{DataCatalogConfig, StreamingConfig};
49use nautilus_system::{config::NautilusKernelConfig, event_store::EventStoreConfig};
50use nautilus_trading::ImportableControllerConfig;
51use rust_decimal::Decimal;
52use serde::{Deserialize, Serialize};
53
54pub use super::queue::QueueMonitorConfig;
55use crate::execution::manager::ExecutionManagerConfig;
56pub use crate::execution::submission::SubmissionRecoveryPolicy;
57
58const DEFAULT_ORDER_RATE_LIMIT: &str = "100/00:00:01";
60const RUST_RUNTIME_UNSUPPORTED: &str = "not supported by the Rust live runtime yet";
61const RATE_LIMIT_FORMAT: &str = "expected 'limit/HH:MM:SS'";
62
63const DELAY_MAX_SECS: f64 = 86_400.0;
65
66pub(crate) fn validate_live_environment(environment: Environment) -> anyhow::Result<()> {
67 match environment {
68 Environment::Sandbox | Environment::Live => Ok(()),
69 Environment::Backtest => {
70 anyhow::bail!("LiveNode cannot be used with Backtest environment")
71 }
72 }
73}
74
75#[cfg_attr(
77 feature = "python",
78 pyo3::pyclass(module = "nautilus_trader.live", from_py_object)
79)]
80#[cfg_attr(
81 feature = "python",
82 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
83)]
84#[expect(
85 clippy::struct_excessive_bools,
86 reason = "config fields mirror the existing Python live data engine surface"
87)]
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
89#[serde(default, deny_unknown_fields)]
90pub struct LiveDataEngineConfig {
91 #[builder(default = true)]
93 pub time_bars_build_with_no_updates: bool,
94 #[builder(default = true)]
97 pub time_bars_timestamp_on_close: bool,
98 #[builder(default)]
100 pub time_bars_skip_first_non_full_bar: bool,
101 #[builder(default = BarIntervalType::LeftOpen)]
103 pub time_bars_interval_type: BarIntervalType,
104 #[builder(default)]
106 pub time_bars_build_delay: u64,
107 #[builder(default)]
111 pub time_bars_origin_offset: HashMap<String, u64>,
112 pub time_bars_time_zone: Option<String>,
114 #[builder(default)]
116 pub validate_data_sequence: bool,
117 #[builder(default)]
119 pub buffer_deltas: bool,
120 #[builder(default)]
122 pub emit_quotes_from_book: bool,
123 #[builder(default)]
125 pub emit_quotes_from_book_depths: bool,
126 pub external_clients: Option<Vec<ClientId>>,
130 #[builder(default)]
132 pub debug: bool,
133 #[builder(default = 100_000)]
138 pub qsize: u32,
139}
140
141impl Default for LiveDataEngineConfig {
142 fn default() -> Self {
143 Self::builder().build()
144 }
145}
146
147impl From<LiveDataEngineConfig> for DataEngineConfig {
148 fn from(config: LiveDataEngineConfig) -> Self {
149 let time_bars_origin_offset = config
150 .time_bars_origin_offset
151 .into_iter()
152 .map(|(agg, nanos)| {
153 let agg = BarAggregation::from_str(&agg)
154 .expect("validate_runtime_support must run before DataEngineConfig conversion");
155 (agg, Duration::from_nanos(nanos))
156 })
157 .collect();
158
159 Self {
160 time_bars_build_with_no_updates: config.time_bars_build_with_no_updates,
161 time_bars_timestamp_on_close: config.time_bars_timestamp_on_close,
162 time_bars_skip_first_non_full_bar: config.time_bars_skip_first_non_full_bar,
163 time_bars_interval_type: config.time_bars_interval_type,
164 time_bars_build_delay: config.time_bars_build_delay,
165 time_bars_origin_offset,
166 time_bars_time_zone: config.time_bars_time_zone,
167 validate_data_sequence: config.validate_data_sequence,
168 buffer_deltas: config.buffer_deltas,
169 emit_quotes_from_book: config.emit_quotes_from_book,
170 emit_quotes_from_book_depths: config.emit_quotes_from_book_depths,
171 disable_historical_cache: false,
172 external_clients: config.external_clients,
173 debug: config.debug,
174 }
175 }
176}
177
178#[cfg_attr(
180 feature = "python",
181 pyo3::pyclass(module = "nautilus_trader.live", from_py_object)
182)]
183#[cfg_attr(
184 feature = "python",
185 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
186)]
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
188#[serde(default, deny_unknown_fields)]
189pub struct LiveRiskEngineConfig {
190 #[builder(default)]
192 pub bypass: bool,
193 #[builder(default = DEFAULT_ORDER_RATE_LIMIT.to_string())]
195 pub max_order_submit_rate: String,
196 #[builder(default = DEFAULT_ORDER_RATE_LIMIT.to_string())]
198 pub max_order_modify_rate: String,
199 #[builder(default)]
203 pub max_notional_per_order: HashMap<String, String>,
204 #[builder(default)]
208 pub full_position_exit_venues: Vec<Venue>,
209 #[builder(default)]
211 pub debug: bool,
212 #[builder(default = 100_000)]
217 pub qsize: u32,
218}
219
220impl Default for LiveRiskEngineConfig {
221 fn default() -> Self {
222 Self::builder().build()
223 }
224}
225
226impl From<LiveRiskEngineConfig> for RiskEngineConfig {
227 fn from(config: LiveRiskEngineConfig) -> Self {
228 let max_notional_per_order = config
229 .max_notional_per_order
230 .into_iter()
231 .map(|(instrument_id, notional)| {
232 let instrument_id = InstrumentId::from_str(&instrument_id)
233 .expect("validate_runtime_support must run before RiskEngineConfig conversion");
234 let notional = Decimal::from_str(¬ional)
235 .expect("validate_runtime_support must run before RiskEngineConfig conversion");
236 (instrument_id, notional)
237 })
238 .collect::<AHashMap<_, _>>();
239
240 let full_position_exit_venues = config.full_position_exit_venues.into_iter().collect();
241
242 Self {
243 bypass: config.bypass,
244 max_order_submit: parse_rate_limit(
245 "LiveRiskEngineConfig.max_order_submit_rate",
246 &config.max_order_submit_rate,
247 )
248 .expect("validate_runtime_support must run before RiskEngineConfig conversion"),
249 max_order_modify: parse_rate_limit(
250 "LiveRiskEngineConfig.max_order_modify_rate",
251 &config.max_order_modify_rate,
252 )
253 .expect("validate_runtime_support must run before RiskEngineConfig conversion"),
254 max_notional_per_order,
255 full_position_exit_venues,
256 debug: config.debug,
257 }
258 }
259}
260
261pub(crate) fn parse_rate_limit(field: impl Into<String>, input: &str) -> ConfigResult<RateLimit> {
262 let field = field.into();
263 let (limit, interval) = input
264 .split_once('/')
265 .ok_or_else(|| ConfigError::invalid_format(field.clone(), RATE_LIMIT_FORMAT))?;
266
267 let limit = limit
268 .parse::<usize>()
269 .map_err(|e| ConfigError::invalid_format(field.clone(), format!("limit: {e}")))?;
270
271 let mut parts = interval.split(':');
272
273 let mut next = |label: &str| -> ConfigResult<u64> {
274 parts
275 .next()
276 .ok_or_else(|| {
277 ConfigError::invalid_format(field.clone(), format!("missing {label} component"))
278 })?
279 .parse::<u64>()
280 .map_err(|e| ConfigError::invalid_format(field.clone(), format!("{label}: {e}")))
281 };
282
283 let hours = next("hours")?;
284 let minutes = next("minutes")?;
285 let seconds = next("seconds")?;
286
287 check_valid_format(field.clone(), parts.next().is_none(), RATE_LIMIT_FORMAT)?;
288
289 let interval_secs = hours
290 .checked_mul(3_600)
291 .and_then(|total| {
292 minutes
293 .checked_mul(60)
294 .and_then(|mins| total.checked_add(mins))
295 })
296 .and_then(|total| total.checked_add(seconds))
297 .ok_or_else(|| ConfigError::range(field.clone(), "interval exceeds the supported range"))?;
298
299 let interval_ns = DurationNanos::try_from_secs(interval_secs)
300 .map_err(|e| ConfigError::range(field.clone(), e.to_string()))?;
301
302 RateLimit::new_checked(limit, interval_ns).map_err(|e| ConfigError::range(field, e.to_string()))
303}
304
305pub(crate) fn validate_max_notional_per_order(
306 field: &str,
307 max_notional_per_order: &HashMap<String, String>,
308) -> ConfigResult<()> {
309 let mut collector = ConfigErrorCollector::new();
310
311 for (instrument_id, notional) in max_notional_per_order {
312 let entry_path = format!("{field}[{instrument_id}]");
313
314 if let Err(e) = InstrumentId::from_str(instrument_id) {
315 collector.push(ConfigError::invalid_reference(
316 entry_path.clone(),
317 "instrument ID",
318 e.to_string(),
319 ));
320 }
321
322 if let Err(e) = Decimal::from_str(notional) {
323 collector.push(ConfigError::invalid_value(
324 entry_path,
325 format!("invalid notional: {e}"),
326 ));
327 }
328 }
329
330 collector.into_result()
331}
332
333pub(crate) fn validate_instrument_id_strings(field: &str, values: &[String]) -> ConfigResult<()> {
334 let mut collector = ConfigErrorCollector::new();
335
336 for (index, value) in values.iter().enumerate() {
337 if let Err(e) = InstrumentId::from_str(value) {
338 collector.push(ConfigError::invalid_reference(
339 format!("{field}[{index}]"),
340 "instrument ID",
341 e.to_string(),
342 ));
343 }
344 }
345
346 collector.into_result()
347}
348
349pub(crate) fn validate_client_order_id_strings(field: &str, values: &[String]) -> ConfigResult<()> {
350 let mut collector = ConfigErrorCollector::new();
351
352 for (index, value) in values.iter().enumerate() {
353 if let Err(e) = ClientOrderId::new_checked(value) {
354 collector.push(ConfigError::invalid_reference(
355 format!("{field}[{index}]"),
356 "client order ID",
357 e.to_string(),
358 ));
359 }
360 }
361
362 collector.into_result()
363}
364
365pub(crate) fn validate_delay_secs(field: &str, value: f64) -> ConfigResult<()> {
366 check_range(
367 field,
368 value.is_finite() && (0.0..=DELAY_MAX_SECS).contains(&value),
369 format!("{value} (must be finite, non-negative, and <= {DELAY_MAX_SECS})"),
370 )
371}
372
373pub(crate) fn validate_positive_interval_secs(field: &str, value: f64) -> ConfigResult<()> {
374 check_range(
375 field,
376 value.is_finite() && value > 0.0,
377 format!("{value} (must be a positive finite number)"),
378 )?;
379 let nanos = secs_to_nanos(value).map_err(|e| ConfigError::range(field, e.to_string()))?;
380 check_range(
381 field,
382 nanos > 0,
383 format!("{value} (must be at least one nanosecond)"),
384 )
385}
386
387#[cfg(feature = "python")]
388pub(crate) fn duration_from_secs_f64(field: &str, value: f64) -> ConfigResult<Duration> {
389 validate_delay_secs(field, value)?;
390
391 Ok(Duration::from_secs_f64(value))
392}
393
394#[cfg_attr(
396 feature = "python",
397 pyo3::pyclass(module = "nautilus_trader.live", from_py_object)
398)]
399#[cfg_attr(
400 feature = "python",
401 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
402)]
403#[expect(
404 clippy::struct_excessive_bools,
405 reason = "config fields mirror the existing Python live execution engine surface"
406)]
407#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, bon::Builder)]
408#[serde(default, deny_unknown_fields)]
409pub struct LiveExecutionEngineConfig {
410 #[builder(default = true)]
412 pub load_cache: bool,
413 #[builder(default)]
417 pub snapshot_orders: bool,
418 #[builder(default)]
423 pub snapshot_positions: bool,
424 pub snapshot_positions_interval_secs: Option<f64>,
428 pub external_clients: Option<Vec<ClientId>>,
433 #[builder(default)]
435 pub debug: bool,
436 #[builder(default = true)]
438 pub reconciliation: bool,
439 #[builder(default = 10.0)]
441 pub reconciliation_startup_delay_secs: f64,
442 pub reconciliation_lookback_mins: Option<u32>,
444 pub reconciliation_instrument_ids: Option<Vec<String>>,
446 #[builder(default)]
448 pub filter_unclaimed_external_orders: bool,
449 #[builder(default)]
451 pub filter_position_reports: bool,
452 pub filtered_client_order_ids: Option<Vec<String>>,
454 #[builder(default = true)]
456 pub generate_missing_orders: bool,
457 #[builder(default = 2_000)]
459 pub inflight_check_interval_ms: u32,
460 #[builder(default = 5_000)]
462 pub inflight_check_threshold_ms: u32,
463 #[builder(default = 5)]
465 pub inflight_check_retries: u32,
466 #[builder(default)]
468 pub submission_recovery_policy: SubmissionRecoveryPolicy,
469 pub open_check_interval_secs: Option<f64>,
471 pub open_check_lookback_mins: Option<u32>,
474 #[builder(default = 5_000)]
476 pub open_check_threshold_ms: u32,
477 #[builder(default = 5)]
479 pub open_check_missing_retries: u32,
480 #[builder(default = true)]
482 pub open_check_open_only: bool,
483 #[builder(default = 10)]
485 pub max_single_order_queries_per_cycle: u32,
486 #[builder(default = 100)]
488 pub single_order_query_delay_ms: u32,
489 pub position_check_interval_secs: Option<f64>,
491 #[builder(default = 60)]
493 pub position_check_lookback_mins: u32,
494 #[builder(default = 5_000)]
496 pub position_check_threshold_ms: u32,
497 #[builder(default = 3)]
499 pub position_check_retries: u32,
500 pub purge_closed_orders_interval_mins: Option<u32>,
502 pub purge_closed_orders_buffer_mins: Option<u32>,
504 pub purge_closed_positions_interval_mins: Option<u32>,
506 pub purge_closed_positions_buffer_mins: Option<u32>,
508 pub purge_account_events_interval_mins: Option<u32>,
510 pub purge_account_events_lookback_mins: Option<u32>,
512 #[builder(default)]
515 pub purge_from_database: bool,
516 pub own_books_audit_interval_secs: Option<f64>,
519 #[builder(default = 100_000)]
521 pub qsize: u32,
522 #[builder(default)]
525 pub allow_overfills: bool,
526 #[builder(default)]
528 pub manage_own_order_books: bool,
529}
530
531impl Default for LiveExecutionEngineConfig {
532 fn default() -> Self {
533 Self {
534 open_check_lookback_mins: Some(60),
535 ..Self::builder().build()
536 }
537 }
538}
539
540impl From<LiveExecutionEngineConfig> for ExecutionEngineConfig {
541 fn from(config: LiveExecutionEngineConfig) -> Self {
542 Self {
543 load_cache: config.load_cache,
544 manage_own_order_books: config.manage_own_order_books,
545 snapshot_orders: config.snapshot_orders,
546 snapshot_positions: config.snapshot_positions,
547 snapshot_positions_interval_secs: config.snapshot_positions_interval_secs,
548 carry_replay_events_on_reopen: true,
550 allow_overfills: config.allow_overfills,
551 filter_unclaimed_external_orders: config.filter_unclaimed_external_orders,
552 external_clients: config.external_clients,
553 purge_closed_orders_interval_mins: config.purge_closed_orders_interval_mins,
558 purge_closed_orders_buffer_mins: config.purge_closed_orders_buffer_mins,
559 purge_closed_positions_interval_mins: config.purge_closed_positions_interval_mins,
560 purge_closed_positions_buffer_mins: config.purge_closed_positions_buffer_mins,
561 purge_account_events_interval_mins: config.purge_account_events_interval_mins,
562 purge_account_events_lookback_mins: config.purge_account_events_lookback_mins,
563 purge_from_database: config.purge_from_database,
564 debug: config.debug,
565 }
566 }
567}
568
569impl From<&LiveExecutionEngineConfig> for ExecutionManagerConfig {
570 fn from(config: &LiveExecutionEngineConfig) -> Self {
571 let filtered_client_order_ids: IndexSet<ClientOrderId> = config
572 .filtered_client_order_ids
573 .clone()
574 .unwrap_or_default()
575 .into_iter()
576 .map(|value| ClientOrderId::from(value.as_str()))
577 .collect();
578
579 let reconciliation_instrument_ids: IndexSet<InstrumentId> = config
580 .reconciliation_instrument_ids
581 .clone()
582 .unwrap_or_default()
583 .into_iter()
584 .map(InstrumentId::from)
585 .collect();
586
587 let open_check_threshold_ns =
588 DurationNanos::from_millis(u64::from(config.open_check_threshold_ms));
589 let position_check_threshold_ns =
590 DurationNanos::from_millis(u64::from(config.position_check_threshold_ms));
591
592 Self {
593 trader_id: TraderId::default(),
594 lookback_mins: config.reconciliation_lookback_mins.map(u64::from),
595 reconciliation_instrument_ids,
596 filter_unclaimed_external: config.filter_unclaimed_external_orders,
597 filter_position_reports: config.filter_position_reports,
598 filtered_client_order_ids,
599 generate_missing_orders: config.generate_missing_orders,
600 inflight_threshold_ms: u64::from(config.inflight_check_threshold_ms),
601 inflight_max_retries: config.inflight_check_retries,
602 submission_recovery_policy: config.submission_recovery_policy,
603 open_check_lookback_mins: config.open_check_lookback_mins.map(u64::from),
604 open_check_threshold_ns,
605 open_check_missing_retries: config.open_check_missing_retries,
606 open_check_open_only: config.open_check_open_only,
607 max_single_order_queries_per_cycle: config.max_single_order_queries_per_cycle,
608 single_order_query_delay_ms: config.single_order_query_delay_ms,
609 position_check_lookback_mins: u64::from(config.position_check_lookback_mins),
610 position_check_threshold_ns,
611 position_check_retries: config.position_check_retries,
612 purge_closed_orders_buffer_mins: config.purge_closed_orders_buffer_mins,
613 purge_closed_positions_buffer_mins: config.purge_closed_positions_buffer_mins,
614 purge_account_events_lookback_mins: config.purge_account_events_lookback_mins,
615 purge_from_database: config.purge_from_database,
616 }
617 }
618}
619
620#[cfg_attr(
622 feature = "python",
623 pyo3::pyclass(module = "nautilus_trader.live", from_py_object)
624)]
625#[cfg_attr(
626 feature = "python",
627 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
628)]
629#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, bon::Builder)]
630#[serde(default, deny_unknown_fields)]
631pub struct RoutingConfig {
632 #[builder(default)]
634 pub default: bool,
635 pub venues: Option<Vec<String>>,
637}
638
639#[cfg_attr(
641 feature = "python",
642 pyo3::pyclass(module = "nautilus_trader.live", from_py_object)
643)]
644#[cfg_attr(
645 feature = "python",
646 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
647)]
648#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, bon::Builder)]
649#[serde(default, deny_unknown_fields)]
650pub struct InstrumentProviderConfig {
651 #[builder(default)]
653 pub load_all: bool,
654 pub load_ids: Option<Vec<String>>,
656 #[builder(default)]
658 pub filters: HashMap<String, serde_json::Value>,
659 pub filter_callable: Option<String>,
661 #[builder(default = true)]
663 pub log_warnings: bool,
664}
665
666impl Default for InstrumentProviderConfig {
667 fn default() -> Self {
668 Self::builder().build()
669 }
670}
671
672#[cfg_attr(
674 feature = "python",
675 pyo3::pyclass(module = "nautilus_trader.live", subclass, from_py_object)
676)]
677#[cfg_attr(
678 feature = "python",
679 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
680)]
681#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, bon::Builder)]
682#[serde(default, deny_unknown_fields)]
683pub struct DataClientConfig {
684 #[builder(default)]
686 pub handle_revised_bars: bool,
687 #[builder(default)]
689 pub instrument_provider: InstrumentProviderConfig,
690 #[builder(default)]
692 pub routing: RoutingConfig,
693}
694
695#[cfg_attr(
697 feature = "python",
698 pyo3::pyclass(module = "nautilus_trader.live", subclass, from_py_object)
699)]
700#[cfg_attr(
701 feature = "python",
702 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
703)]
704#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, bon::Builder)]
705#[serde(default, deny_unknown_fields)]
706pub struct ExecutionClientConfig {
707 #[builder(default)]
709 pub instrument_provider: InstrumentProviderConfig,
710 #[builder(default)]
712 pub routing: RoutingConfig,
713}
714
715#[cfg_attr(
717 feature = "python",
718 pyo3::pyclass(module = "nautilus_trader.live", from_py_object)
719)]
720#[cfg_attr(
721 feature = "python",
722 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
723)]
724#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, bon::Builder)]
725#[serde(default, deny_unknown_fields)]
726pub struct PluginConfig {
727 pub path: String,
729 pub type_name: String,
731 #[builder(default)]
733 pub config: HashMap<String, serde_json::Value>,
734 pub sha256: Option<String>,
736}
737
738impl Default for PluginConfig {
739 fn default() -> Self {
740 Self::builder()
741 .path(String::new())
742 .type_name(String::new())
743 .build()
744 }
745}
746
747#[cfg_attr(
749 feature = "python",
750 pyo3::pyclass(module = "nautilus_trader.live", dict, from_py_object)
751)]
752#[cfg_attr(
753 feature = "python",
754 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")
755)]
756#[expect(
757 clippy::struct_excessive_bools,
758 reason = "config fields mirror the existing Python live node surface"
759)]
760#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
761#[serde(default, deny_unknown_fields)]
762pub struct LiveNodeConfig {
763 #[builder(default = Environment::Live)]
765 pub environment: Environment,
766 #[builder(default = TraderId::from("TRADER-001"))]
768 pub trader_id: TraderId,
769 #[builder(default)]
771 pub load_state: bool,
772 #[builder(default)]
774 pub save_state: bool,
775 #[builder(default)]
779 pub shutdown_on_error: bool,
780 #[builder(default)]
782 pub logging: LoggerConfig,
783 pub instance_id: Option<UUID4>,
785 #[builder(default = Duration::from_mins(1))]
787 pub timeout_connection: Duration,
788 #[builder(default = Duration::from_secs(30))]
790 pub timeout_reconciliation: Duration,
791 #[builder(default = Duration::from_secs(10))]
793 pub timeout_portfolio: Duration,
794 #[builder(default = Duration::from_secs(10))]
796 pub timeout_disconnection: Duration,
797 #[builder(default = Duration::from_secs(10))]
800 pub delay_post_stop: Duration,
801 #[builder(default = Duration::from_secs(5))]
803 pub timeout_shutdown: Duration,
804 pub cache: Option<CacheConfig>,
806 pub msgbus: Option<MessageBusConfig>,
808 pub portfolio: Option<PortfolioConfig>,
810 pub emulator: Option<OrderEmulatorConfig>,
812 #[cfg(feature = "streaming")]
814 pub streaming: Option<StreamingConfig>,
815 #[cfg(feature = "streaming")]
817 #[builder(default)]
818 pub catalogs: Vec<DataCatalogConfig>,
819 pub queue_monitor: Option<QueueMonitorConfig>,
821 pub event_store: Option<EventStoreConfig>,
827 #[builder(default)]
829 pub loop_debug: bool,
830 #[builder(default)]
832 pub data_engine: LiveDataEngineConfig,
833 #[builder(default)]
835 pub risk_engine: LiveRiskEngineConfig,
836 #[builder(default)]
838 pub exec_engine: LiveExecutionEngineConfig,
839 #[builder(default)]
841 pub data_clients: HashMap<String, DataClientConfig>,
842 #[builder(default)]
844 pub exec_clients: HashMap<String, ExecutionClientConfig>,
845 pub controller: Option<ImportableControllerConfig>,
847 #[builder(default)]
849 pub plugins: Vec<PluginConfig>,
850}
851
852impl Default for LiveNodeConfig {
853 fn default() -> Self {
854 Self::builder().build()
855 }
856}
857
858impl LiveNodeConfig {
859 pub(crate) fn validate_runtime_support(&self) -> ConfigResult<()> {
867 let mut collector = ConfigErrorCollector::new();
868
869 collector.collect(check_supported_field(
870 "LiveNodeConfig.emulator",
871 self.emulator.is_none(),
872 RUST_RUNTIME_UNSUPPORTED,
873 ));
874 collector.collect(check_supported_field(
875 "LiveNodeConfig.loop_debug",
876 !self.loop_debug,
877 RUST_RUNTIME_UNSUPPORTED,
878 ));
879 collector.collect(self.data_engine.validate_runtime_support());
880 collector.collect(self.risk_engine.validate_runtime_support());
881 collector.collect(self.exec_engine.validate_runtime_support());
882
883 if let Some(queue_monitor) = &self.queue_monitor {
884 collector.collect(queue_monitor.validate());
885 }
886
887 collector.collect(self.validate_plugin_configs());
888
889 collector.into_result()
890 }
891
892 fn validate_plugin_configs(&self) -> ConfigResult<()> {
893 let mut collector = ConfigErrorCollector::new();
894
895 for (index, plugin) in self.plugins.iter().enumerate() {
896 collector.collect(plugin.validate_runtime_support(index));
897 }
898
899 collector.into_result()
900 }
901}
902
903impl PluginConfig {
904 pub(crate) fn validate_runtime_support(&self, index: usize) -> ConfigResult<()> {
905 let mut collector = ConfigErrorCollector::with_capacity(3);
906
907 collector.collect(check_non_empty_field(
908 format!("LiveNodeConfig.plugins[{index}].path"),
909 &self.path,
910 ));
911 collector.collect(check_non_empty_field(
912 format!("LiveNodeConfig.plugins[{index}].type_name"),
913 &self.type_name,
914 ));
915
916 if let Some(sha256) = &self.sha256 {
917 let valid = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
918 collector.collect(check_valid_format(
919 format!("LiveNodeConfig.plugins[{index}].sha256"),
920 valid,
921 "must be a 64-character hex digest",
922 ));
923 }
924
925 collector.into_result()
926 }
927}
928
929impl LiveDataEngineConfig {
930 fn validate_runtime_support(&self) -> ConfigResult<()> {
931 let mut collector = ConfigErrorCollector::new();
932 if let Some(name) = &self.time_bars_time_zone
933 && let Err(e) = get_timezone(name)
934 {
935 collector.push(ConfigError::invalid_reference(
936 "LiveDataEngineConfig.time_bars_time_zone",
937 "IANA time zone",
938 e.to_string(),
939 ));
940 }
941
942 for agg_str in self.time_bars_origin_offset.keys() {
943 if let Err(e) = BarAggregation::from_str(agg_str) {
944 collector.push(ConfigError::invalid_reference(
945 format!("LiveDataEngineConfig.time_bars_origin_offset[{agg_str}]"),
946 "bar aggregation",
947 e.to_string(),
948 ));
949 }
950 }
951
952 let default = Self::default();
953 collector.collect(check_supported_field(
954 "LiveDataEngineConfig.qsize",
955 self.qsize == default.qsize,
956 RUST_RUNTIME_UNSUPPORTED,
957 ));
958
959 collector.into_result()
960 }
961}
962
963impl LiveRiskEngineConfig {
964 fn validate_runtime_support(&self) -> ConfigResult<()> {
965 let mut collector = ConfigErrorCollector::new();
966
967 collector.collect(
968 parse_rate_limit(
969 "LiveRiskEngineConfig.max_order_submit_rate",
970 &self.max_order_submit_rate,
971 )
972 .map(|_| ()),
973 );
974 collector.collect(
975 parse_rate_limit(
976 "LiveRiskEngineConfig.max_order_modify_rate",
977 &self.max_order_modify_rate,
978 )
979 .map(|_| ()),
980 );
981 collector.collect(validate_max_notional_per_order(
982 "LiveRiskEngineConfig.max_notional_per_order",
983 &self.max_notional_per_order,
984 ));
985
986 let default = Self::default();
987 collector.collect(check_supported_field(
988 "LiveRiskEngineConfig.qsize",
989 self.qsize == default.qsize,
990 RUST_RUNTIME_UNSUPPORTED,
991 ));
992
993 collector.into_result()
994 }
995}
996
997impl LiveExecutionEngineConfig {
998 pub(crate) fn validate_runtime_support(&self) -> ConfigResult<()> {
999 let mut collector = ConfigErrorCollector::new();
1000
1001 collector.collect(validate_delay_secs(
1005 "LiveExecutionEngineConfig.reconciliation_startup_delay_secs",
1006 self.reconciliation_startup_delay_secs,
1007 ));
1008
1009 for (field, value) in [
1010 (
1011 "LiveExecutionEngineConfig.snapshot_positions_interval_secs",
1012 self.snapshot_positions_interval_secs,
1013 ),
1014 (
1015 "LiveExecutionEngineConfig.open_check_interval_secs",
1016 self.open_check_interval_secs,
1017 ),
1018 (
1019 "LiveExecutionEngineConfig.position_check_interval_secs",
1020 self.position_check_interval_secs,
1021 ),
1022 (
1023 "LiveExecutionEngineConfig.own_books_audit_interval_secs",
1024 self.own_books_audit_interval_secs,
1025 ),
1026 ] {
1027 if let Some(value) = value {
1028 collector.collect(validate_positive_interval_secs(field, value));
1029 }
1030 }
1031
1032 for (field, value) in [
1033 (
1034 "LiveExecutionEngineConfig.open_check_lookback_mins",
1035 self.open_check_lookback_mins,
1036 ),
1037 (
1038 "LiveExecutionEngineConfig.purge_closed_orders_interval_mins",
1039 self.purge_closed_orders_interval_mins,
1040 ),
1041 (
1042 "LiveExecutionEngineConfig.purge_closed_positions_interval_mins",
1043 self.purge_closed_positions_interval_mins,
1044 ),
1045 (
1046 "LiveExecutionEngineConfig.purge_account_events_interval_mins",
1047 self.purge_account_events_interval_mins,
1048 ),
1049 (
1050 "LiveExecutionEngineConfig.purge_closed_orders_buffer_mins",
1051 self.purge_closed_orders_buffer_mins,
1052 ),
1053 (
1054 "LiveExecutionEngineConfig.purge_closed_positions_buffer_mins",
1055 self.purge_closed_positions_buffer_mins,
1056 ),
1057 (
1058 "LiveExecutionEngineConfig.purge_account_events_lookback_mins",
1059 self.purge_account_events_lookback_mins,
1060 ),
1061 ] {
1062 if let Some(mins) = value {
1063 collector.collect(check_range(
1064 field,
1065 DurationNanos::try_from_mins(u64::from(mins)).is_ok(),
1066 format!("{mins} minutes (must fit in `u64` nanoseconds)"),
1067 ));
1068 }
1069 }
1070
1071 if let Some(instrument_ids) = &self.reconciliation_instrument_ids {
1072 collector.collect(validate_instrument_id_strings(
1073 "LiveExecutionEngineConfig.reconciliation_instrument_ids",
1074 instrument_ids,
1075 ));
1076 }
1077
1078 if let Some(client_order_ids) = &self.filtered_client_order_ids {
1079 collector.collect(validate_client_order_id_strings(
1080 "LiveExecutionEngineConfig.filtered_client_order_ids",
1081 client_order_ids,
1082 ));
1083 }
1084
1085 let default = Self::default();
1086 collector.collect(check_supported_field(
1087 "LiveExecutionEngineConfig.qsize",
1088 self.qsize == default.qsize,
1089 RUST_RUNTIME_UNSUPPORTED,
1090 ));
1091
1092 collector.into_result()
1093 }
1094}
1095
1096impl NautilusKernelConfig for LiveNodeConfig {
1097 fn environment(&self) -> Environment {
1098 self.environment
1099 }
1100
1101 fn trader_id(&self) -> TraderId {
1102 self.trader_id
1103 }
1104
1105 fn load_state(&self) -> bool {
1106 self.load_state
1107 }
1108
1109 fn save_state(&self) -> bool {
1110 self.save_state
1111 }
1112
1113 fn shutdown_on_error(&self) -> bool {
1114 self.shutdown_on_error
1115 }
1116
1117 fn logging(&self) -> LoggerConfig {
1118 self.logging.clone()
1119 }
1120
1121 fn instance_id(&self) -> Option<UUID4> {
1122 self.instance_id
1123 }
1124
1125 fn timeout_connection(&self) -> Duration {
1126 self.timeout_connection
1127 }
1128
1129 fn timeout_reconciliation(&self) -> Duration {
1130 self.timeout_reconciliation
1131 }
1132
1133 fn timeout_portfolio(&self) -> Duration {
1134 self.timeout_portfolio
1135 }
1136
1137 fn timeout_disconnection(&self) -> Duration {
1138 self.timeout_disconnection
1139 }
1140
1141 fn delay_post_stop(&self) -> Duration {
1142 self.delay_post_stop
1143 }
1144
1145 fn timeout_shutdown(&self) -> Duration {
1146 self.timeout_shutdown
1147 }
1148
1149 fn cache(&self) -> Option<CacheConfig> {
1150 self.cache.clone()
1151 }
1152
1153 fn msgbus(&self) -> Option<MessageBusConfig> {
1154 self.msgbus.clone()
1155 }
1156
1157 fn data_engine(&self) -> Option<DataEngineConfig> {
1158 Some(self.data_engine.clone().into())
1159 }
1160
1161 fn risk_engine(&self) -> Option<RiskEngineConfig> {
1162 Some(self.risk_engine.clone().into())
1163 }
1164
1165 fn exec_engine(&self) -> Option<ExecutionEngineConfig> {
1166 Some(self.exec_engine.clone().into())
1167 }
1168
1169 fn portfolio(&self) -> Option<PortfolioConfig> {
1170 self.portfolio
1171 }
1172
1173 #[cfg(feature = "streaming")]
1174 fn catalogs(&self) -> Vec<DataCatalogConfig> {
1175 self.catalogs.clone()
1176 }
1177
1178 #[cfg(feature = "streaming")]
1179 fn streaming(&self) -> Option<StreamingConfig> {
1180 self.streaming.clone()
1181 }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186 #[cfg(feature = "streaming")]
1187 use nautilus_system::config::RotationConfig;
1188 use rstest::rstest;
1189
1190 use super::*;
1191
1192 #[rstest]
1193 #[case(None)]
1194 #[case(Some("America/New_York"))]
1195 #[case(Some("UTC"))]
1196 fn test_calendar_time_zone_config_reaches_data_engine(#[case] name: Option<&str>) {
1197 let config = LiveDataEngineConfig::builder()
1198 .maybe_time_bars_time_zone(name.map(str::to_owned))
1199 .build();
1200 assert_eq!(config.validate_runtime_support(), Ok(()));
1201 let converted: DataEngineConfig = config.into();
1202 assert_eq!(converted.time_bars_time_zone, name.map(str::to_owned));
1203 }
1204
1205 #[rstest]
1206 fn test_calendar_time_zone_config_rejects_unknown_zone() {
1207 let config = LiveDataEngineConfig::builder()
1208 .time_bars_time_zone("Not/A_Zone".to_owned())
1209 .build();
1210 let error = config.validate_runtime_support().unwrap_err();
1211 let expected = ConfigError::invalid_reference(
1212 "LiveDataEngineConfig.time_bars_time_zone",
1213 "IANA time zone",
1214 get_timezone("Not/A_Zone").unwrap_err().to_string(),
1215 );
1216 assert_eq!(error, expected);
1217 }
1218
1219 #[rstest]
1220 fn test_trading_node_config_default() {
1221 let config = LiveNodeConfig::default();
1222
1223 assert_eq!(config.environment, Environment::Live);
1224 assert_eq!(config.trader_id, TraderId::from("TRADER-001"));
1225 assert_eq!(config.data_engine.qsize, 100_000);
1226 assert_eq!(config.risk_engine.qsize, 100_000);
1227 assert_eq!(config.exec_engine.qsize, 100_000);
1228 assert_eq!(config.timeout_connection, Duration::from_mins(1));
1229 assert!(config.exec_engine.reconciliation);
1230 assert!(!config.exec_engine.filter_unclaimed_external_orders);
1231 assert!(config.data_clients.is_empty());
1232 assert!(config.exec_clients.is_empty());
1233 assert!(config.plugins.is_empty());
1234 assert!(config.queue_monitor.is_none());
1235 }
1236
1237 #[rstest]
1238 fn test_live_node_queue_monitor_config_serde_roundtrip() {
1239 let config: LiveNodeConfig = toml::from_str(
1240 "
1241[queue_monitor]
1242queue_depth_trigger = 100
1243queue_depth_clear = 60
1244mean_dispatch_ns_trigger = 1000
1245mean_dispatch_ns_clear = 700
1246",
1247 )
1248 .unwrap();
1249
1250 let expected = Some(
1251 QueueMonitorConfig::builder()
1252 .queue_depth_trigger(100)
1253 .queue_depth_clear(60)
1254 .mean_dispatch_ns_trigger(1_000)
1255 .mean_dispatch_ns_clear(700)
1256 .build(),
1257 );
1258 let json = serde_json::to_string(&config).unwrap();
1259 let restored: LiveNodeConfig = serde_json::from_str(&json).unwrap();
1260
1261 assert_eq!(config.queue_monitor, expected);
1262 assert_eq!(restored.queue_monitor, expected);
1263 }
1264
1265 #[rstest]
1266 #[case(
1267 QueueMonitorConfig {
1268 queue_depth_trigger: 10,
1269 queue_depth_clear: 10,
1270 mean_dispatch_ns_trigger: 100,
1271 mean_dispatch_ns_clear: 50,
1272 },
1273 "invalid LiveNodeConfig.queue_monitor.queue_depth: clear threshold 10 must be lower than trigger threshold 10"
1274 )]
1275 #[case(
1276 QueueMonitorConfig {
1277 queue_depth_trigger: 10,
1278 queue_depth_clear: 5,
1279 mean_dispatch_ns_trigger: 50,
1280 mean_dispatch_ns_clear: 50,
1281 },
1282 "invalid LiveNodeConfig.queue_monitor.mean_dispatch_ns: clear threshold 50 must be lower than trigger threshold 50"
1283 )]
1284 fn test_live_node_queue_monitor_config_validates_hysteresis(
1285 #[case] queue_monitor: QueueMonitorConfig,
1286 #[case] expected: &str,
1287 ) {
1288 let config = LiveNodeConfig {
1289 queue_monitor: Some(queue_monitor),
1290 ..Default::default()
1291 };
1292
1293 assert_eq!(
1294 config.validate_runtime_support().unwrap_err().to_string(),
1295 expected
1296 );
1297 }
1298
1299 #[rstest]
1300 fn test_trading_node_config_as_kernel_config() {
1301 let config = LiveNodeConfig::default();
1302
1303 assert_eq!(config.environment(), Environment::Live);
1304 assert_eq!(config.trader_id(), TraderId::from("TRADER-001"));
1305 assert!(config.data_engine().is_some());
1306 assert!(config.risk_engine().is_some());
1307 assert!(config.exec_engine().is_some());
1308 assert!(!config.load_state());
1309 assert!(!config.save_state());
1310 }
1311
1312 #[rstest]
1313 fn test_validate_runtime_support_with_defaults() {
1314 let config = LiveNodeConfig::default();
1315
1316 assert!(config.validate_runtime_support().is_ok());
1317 }
1318
1319 #[rstest]
1320 fn test_validate_runtime_support_accepts_database_purge() {
1321 let config = LiveNodeConfig {
1322 exec_engine: LiveExecutionEngineConfig {
1323 purge_from_database: true,
1324 ..Default::default()
1325 },
1326 ..Default::default()
1327 };
1328
1329 assert!(config.validate_runtime_support().is_ok());
1330 }
1331
1332 #[rstest]
1333 fn test_validate_runtime_support_accepts_msgbus_config() {
1334 let config = LiveNodeConfig {
1335 msgbus: Some(MessageBusConfig::default()),
1336 ..Default::default()
1337 };
1338
1339 assert!(config.validate_runtime_support().is_ok());
1340 }
1341
1342 #[rstest]
1343 fn test_validate_runtime_support_accepts_msgbus_external_streams() {
1344 let config = LiveNodeConfig {
1345 msgbus: Some(MessageBusConfig {
1346 external_streams: Some(vec!["stream".to_string()]),
1347 ..Default::default()
1348 }),
1349 ..Default::default()
1350 };
1351
1352 assert!(config.validate_runtime_support().is_ok());
1353 }
1354
1355 #[rstest]
1356 #[cfg(feature = "streaming")]
1357 fn test_validate_runtime_support_accepts_streaming_config() {
1358 let config = LiveNodeConfig {
1359 streaming: Some(StreamingConfig::new(
1360 "stream".to_string(),
1361 None,
1362 1_000,
1363 false,
1364 RotationConfig::NoRotation,
1365 )),
1366 ..Default::default()
1367 };
1368
1369 assert_eq!(config.validate_runtime_support(), Ok(()));
1370 }
1371
1372 #[rstest]
1373 fn test_validate_runtime_support_collects_multiple_errors() {
1374 let config = LiveNodeConfig {
1375 msgbus: Some(MessageBusConfig {
1376 external_streams: Some(vec!["stream".to_string()]),
1377 ..Default::default()
1378 }),
1379 emulator: Some(OrderEmulatorConfig::default()),
1380 loop_debug: true,
1381 ..Default::default()
1382 };
1383
1384 let error = config.validate_runtime_support().unwrap_err();
1385
1386 match error {
1387 ConfigError::Multiple { errors } => {
1388 assert_eq!(errors.len(), 2);
1389 assert_eq!(
1390 errors[0],
1391 ConfigError::UnsupportedField {
1392 field: "LiveNodeConfig.emulator".to_string(),
1393 reason: RUST_RUNTIME_UNSUPPORTED.to_string(),
1394 },
1395 );
1396 assert_eq!(
1397 errors[1],
1398 ConfigError::UnsupportedField {
1399 field: "LiveNodeConfig.loop_debug".to_string(),
1400 reason: RUST_RUNTIME_UNSUPPORTED.to_string(),
1401 },
1402 );
1403 }
1404 _ => panic!("Expected multiple config errors, received {error:?}"),
1405 }
1406 }
1407
1408 #[rstest]
1409 fn test_validate_runtime_support_rejects_data_engine_qsize() {
1410 let config = LiveNodeConfig {
1411 data_engine: LiveDataEngineConfig {
1412 qsize: 1,
1413 ..Default::default()
1414 },
1415 ..Default::default()
1416 };
1417
1418 let error = config.validate_runtime_support().unwrap_err();
1419 assert_eq!(
1420 error.to_string(),
1421 "LiveDataEngineConfig.qsize is not supported by the Rust live runtime yet"
1422 );
1423 }
1424
1425 #[rstest]
1426 fn test_validate_runtime_support_rejects_risk_engine_qsize() {
1427 let config = LiveNodeConfig {
1428 risk_engine: LiveRiskEngineConfig {
1429 qsize: 1,
1430 ..Default::default()
1431 },
1432 ..Default::default()
1433 };
1434
1435 let error = config.validate_runtime_support().unwrap_err();
1436 assert_eq!(
1437 error.to_string(),
1438 "LiveRiskEngineConfig.qsize is not supported by the Rust live runtime yet"
1439 );
1440 }
1441
1442 #[rstest]
1443 fn test_live_data_engine_config_converts_to_data_engine_config() {
1444 let config = LiveDataEngineConfig {
1445 time_bars_build_with_no_updates: false,
1446 time_bars_timestamp_on_close: false,
1447 time_bars_skip_first_non_full_bar: true,
1448 time_bars_interval_type: BarIntervalType::RightOpen,
1449 time_bars_build_delay: 1_500,
1450 validate_data_sequence: true,
1451 buffer_deltas: true,
1452 external_clients: Some(vec![ClientId::from("EXTERNAL")]),
1453 debug: true,
1454 ..Default::default()
1455 };
1456
1457 let converted: DataEngineConfig = config.into();
1458
1459 assert!(!converted.time_bars_build_with_no_updates);
1460 assert!(!converted.time_bars_timestamp_on_close);
1461 assert!(converted.time_bars_skip_first_non_full_bar);
1462 assert_eq!(
1463 converted.time_bars_interval_type,
1464 BarIntervalType::RightOpen,
1465 );
1466 assert_eq!(converted.time_bars_build_delay, 1_500);
1467 assert!(converted.time_bars_origin_offset.is_empty());
1468 assert!(converted.validate_data_sequence);
1469 assert!(converted.buffer_deltas);
1470 assert!(!converted.emit_quotes_from_book);
1471 assert!(!converted.emit_quotes_from_book_depths);
1472 assert_eq!(
1473 converted.external_clients,
1474 Some(vec![ClientId::from("EXTERNAL")]),
1475 );
1476 assert!(converted.debug);
1477 }
1478
1479 #[rstest]
1480 fn test_live_data_engine_config_converts_time_bars_origin_offset() {
1481 let config = LiveDataEngineConfig {
1482 time_bars_origin_offset: HashMap::from([("Minute".to_string(), 5_000_000_000)]),
1483 emit_quotes_from_book: true,
1484 emit_quotes_from_book_depths: true,
1485 ..Default::default()
1486 };
1487
1488 let converted: DataEngineConfig = config.into();
1489
1490 assert_eq!(converted.time_bars_origin_offset.len(), 1);
1491 assert_eq!(
1492 converted.time_bars_origin_offset[&BarAggregation::Minute],
1493 Duration::from_secs(5),
1494 );
1495 assert!(converted.emit_quotes_from_book);
1496 assert!(converted.emit_quotes_from_book_depths);
1497 }
1498
1499 #[rstest]
1500 fn test_live_exec_engine_config_converts_to_exec_engine_config() {
1501 let config = LiveExecutionEngineConfig {
1502 load_cache: false,
1503 snapshot_orders: true,
1504 snapshot_positions_interval_secs: Some(30.0),
1505 filter_unclaimed_external_orders: true,
1506 purge_closed_orders_interval_mins: Some(5),
1507 purge_closed_orders_buffer_mins: Some(1),
1508 purge_closed_positions_interval_mins: Some(10),
1509 purge_closed_positions_buffer_mins: Some(2),
1510 purge_account_events_interval_mins: Some(15),
1511 purge_account_events_lookback_mins: Some(3),
1512 ..Default::default()
1513 };
1514
1515 let converted: ExecutionEngineConfig = config.into();
1516
1517 assert!(!converted.load_cache);
1518 assert!(converted.snapshot_orders);
1519 assert_eq!(converted.snapshot_positions_interval_secs, Some(30.0));
1520 assert!(converted.filter_unclaimed_external_orders);
1521 assert_eq!(converted.purge_closed_orders_interval_mins, Some(5));
1522 assert_eq!(converted.purge_closed_orders_buffer_mins, Some(1));
1523 assert_eq!(converted.purge_closed_positions_interval_mins, Some(10));
1524 assert_eq!(converted.purge_closed_positions_buffer_mins, Some(2));
1525 assert_eq!(converted.purge_account_events_interval_mins, Some(15));
1526 assert_eq!(converted.purge_account_events_lookback_mins, Some(3));
1527 assert!(converted.carry_replay_events_on_reopen);
1529 }
1530
1531 #[rstest]
1532 fn test_live_exec_engine_config_converts_to_execution_manager_config() {
1533 let config = LiveExecutionEngineConfig {
1534 reconciliation: false,
1535 reconciliation_lookback_mins: Some(45),
1536 reconciliation_instrument_ids: Some(vec![
1537 "ETHUSDT.BINANCE".to_string(),
1538 "BTCUSDT.BINANCE".to_string(),
1539 ]),
1540 filter_unclaimed_external_orders: true,
1541 filter_position_reports: true,
1542 filtered_client_order_ids: Some(vec!["O-001".to_string(), "O-002".to_string()]),
1543 generate_missing_orders: false,
1544 inflight_check_interval_ms: 321,
1545 inflight_check_threshold_ms: 654,
1546 inflight_check_retries: 7,
1547 open_check_interval_secs: Some(1.5),
1548 open_check_lookback_mins: Some(9),
1549 open_check_threshold_ms: 234,
1550 open_check_missing_retries: 4,
1551 open_check_open_only: false,
1552 max_single_order_queries_per_cycle: 8,
1553 single_order_query_delay_ms: 76,
1554 position_check_interval_secs: Some(2.5),
1555 position_check_lookback_mins: 11,
1556 position_check_threshold_ms: 345,
1557 position_check_retries: 6,
1558 purge_closed_orders_buffer_mins: Some(12),
1559 purge_closed_positions_buffer_mins: Some(13),
1560 purge_account_events_lookback_mins: Some(14),
1561 purge_from_database: true,
1562 ..Default::default()
1563 };
1564
1565 let converted = ExecutionManagerConfig::from(&config);
1566
1567 assert_eq!(converted.lookback_mins, Some(45));
1568 assert_eq!(converted.reconciliation_instrument_ids.len(), 2);
1569 assert!(
1570 converted
1571 .reconciliation_instrument_ids
1572 .contains(&InstrumentId::from("ETHUSDT.BINANCE"))
1573 );
1574 assert!(
1575 converted
1576 .reconciliation_instrument_ids
1577 .contains(&InstrumentId::from("BTCUSDT.BINANCE"))
1578 );
1579 assert!(converted.filter_unclaimed_external);
1580 assert!(converted.filter_position_reports);
1581 assert_eq!(converted.filtered_client_order_ids.len(), 2);
1582 assert!(
1583 converted
1584 .filtered_client_order_ids
1585 .contains(&ClientOrderId::from("O-001"))
1586 );
1587 assert!(
1588 converted
1589 .filtered_client_order_ids
1590 .contains(&ClientOrderId::from("O-002"))
1591 );
1592 assert!(!converted.generate_missing_orders);
1593 assert_eq!(converted.inflight_threshold_ms, 654);
1594 assert_eq!(converted.inflight_max_retries, 7);
1595 assert_eq!(converted.open_check_lookback_mins, Some(9));
1596 assert_eq!(
1597 converted.open_check_threshold_ns,
1598 DurationNanos::from_millis(234)
1599 );
1600 assert_eq!(converted.open_check_missing_retries, 4);
1601 assert!(!converted.open_check_open_only);
1602 assert_eq!(converted.max_single_order_queries_per_cycle, 8);
1603 assert_eq!(converted.single_order_query_delay_ms, 76);
1604 assert_eq!(converted.position_check_lookback_mins, 11);
1605 assert_eq!(
1606 converted.position_check_threshold_ns,
1607 DurationNanos::from_millis(345)
1608 );
1609 assert_eq!(converted.position_check_retries, 6);
1610 assert_eq!(converted.purge_closed_orders_buffer_mins, Some(12));
1611 assert_eq!(converted.purge_closed_positions_buffer_mins, Some(13));
1612 assert_eq!(converted.purge_account_events_lookback_mins, Some(14));
1613 assert!(converted.purge_from_database);
1614 }
1615
1616 #[rstest]
1617 fn test_live_risk_engine_config_converts_to_risk_engine_config() {
1618 let config = LiveRiskEngineConfig {
1619 bypass: true,
1620 max_order_submit_rate: "12/00:00:03".to_string(),
1621 max_order_modify_rate: "7/00:00:05".to_string(),
1622 max_notional_per_order: HashMap::from([(
1623 "ETHUSDT.BINANCE".to_string(),
1624 "1000.5".to_string(),
1625 )]),
1626 full_position_exit_venues: vec![Venue::from("BINANCE")],
1627 debug: true,
1628 ..Default::default()
1629 };
1630
1631 let converted: RiskEngineConfig = config.into();
1632
1633 assert!(converted.bypass);
1634 assert_eq!(
1635 converted.max_order_submit,
1636 RateLimit::new(12, DurationNanos::from_secs(3))
1637 );
1638 assert_eq!(
1639 converted.max_order_modify,
1640 RateLimit::new(7, DurationNanos::from_secs(5))
1641 );
1642 assert_eq!(
1643 converted.max_notional_per_order[&"ETHUSDT.BINANCE".parse::<InstrumentId>().unwrap()],
1644 Decimal::from_str("1000.5").unwrap(),
1645 );
1646 assert_eq!(
1647 converted.full_position_exit_venues,
1648 [Venue::from("BINANCE")].into_iter().collect(),
1649 );
1650 assert!(converted.debug);
1651 }
1652
1653 #[rstest]
1654 fn test_validate_runtime_support_accepts_exec_engine_snapshot_orders() {
1655 let config = LiveNodeConfig {
1656 exec_engine: LiveExecutionEngineConfig {
1657 snapshot_orders: true,
1658 ..Default::default()
1659 },
1660 ..Default::default()
1661 };
1662
1663 assert!(config.validate_runtime_support().is_ok());
1664 }
1665
1666 #[rstest]
1667 fn test_validate_runtime_support_accepts_exec_engine_snapshot_positions() {
1668 let config = LiveNodeConfig {
1669 exec_engine: LiveExecutionEngineConfig {
1670 snapshot_positions: true,
1671 ..Default::default()
1672 },
1673 ..Default::default()
1674 };
1675
1676 assert!(config.validate_runtime_support().is_ok());
1677 }
1678
1679 #[rstest]
1680 fn test_validate_runtime_support_rejects_overflowing_minute_fields() {
1681 let config = LiveNodeConfig {
1682 exec_engine: LiveExecutionEngineConfig {
1683 open_check_lookback_mins: Some(u32::MAX),
1684 purge_closed_orders_interval_mins: Some(u32::MAX),
1685 purge_closed_positions_interval_mins: Some(u32::MAX),
1686 purge_account_events_interval_mins: Some(u32::MAX),
1687 ..Default::default()
1688 },
1689 ..Default::default()
1690 };
1691
1692 let error = config.validate_runtime_support().unwrap_err();
1693 assert_eq!(
1694 error,
1695 ConfigError::Multiple {
1696 errors: vec![
1697 ConfigError::range(
1698 "LiveExecutionEngineConfig.open_check_lookback_mins",
1699 "4294967295 minutes (must fit in `u64` nanoseconds)",
1700 ),
1701 ConfigError::range(
1702 "LiveExecutionEngineConfig.purge_closed_orders_interval_mins",
1703 "4294967295 minutes (must fit in `u64` nanoseconds)",
1704 ),
1705 ConfigError::range(
1706 "LiveExecutionEngineConfig.purge_closed_positions_interval_mins",
1707 "4294967295 minutes (must fit in `u64` nanoseconds)",
1708 ),
1709 ConfigError::range(
1710 "LiveExecutionEngineConfig.purge_account_events_interval_mins",
1711 "4294967295 minutes (must fit in `u64` nanoseconds)",
1712 ),
1713 ],
1714 }
1715 );
1716 }
1717
1718 #[rstest]
1719 #[case(0)]
1720 #[case(307_445_734)]
1721 fn test_validate_runtime_support_accepts_purge_retention_boundaries(#[case] mins: u32) {
1722 let config = LiveNodeConfig {
1723 exec_engine: LiveExecutionEngineConfig {
1724 purge_closed_orders_buffer_mins: Some(mins),
1725 purge_closed_positions_buffer_mins: Some(mins),
1726 purge_account_events_lookback_mins: Some(mins),
1727 ..Default::default()
1728 },
1729 ..Default::default()
1730 };
1731
1732 assert!(config.validate_runtime_support().is_ok());
1733 }
1734
1735 #[rstest]
1736 fn test_validate_runtime_support_rejects_overflowing_purge_retention_minutes() {
1737 let config = LiveNodeConfig {
1738 exec_engine: LiveExecutionEngineConfig {
1739 purge_closed_orders_buffer_mins: Some(307_445_735),
1740 purge_closed_positions_buffer_mins: Some(307_445_735),
1741 purge_account_events_lookback_mins: Some(307_445_735),
1742 ..Default::default()
1743 },
1744 ..Default::default()
1745 };
1746
1747 let error = config.validate_runtime_support().unwrap_err();
1748
1749 let ConfigError::Multiple { errors } = error else {
1750 panic!("Expected multiple config errors, received {error:?}");
1751 };
1752
1753 assert_eq!(errors.len(), 3);
1754
1755 for field in [
1756 "LiveExecutionEngineConfig.purge_closed_orders_buffer_mins",
1757 "LiveExecutionEngineConfig.purge_closed_positions_buffer_mins",
1758 "LiveExecutionEngineConfig.purge_account_events_lookback_mins",
1759 ] {
1760 assert!(errors.iter().any(
1761 |e| matches!(e, ConfigError::Range { field: error_field, .. } if error_field == field)
1762 ));
1763 }
1764 }
1765
1766 #[rstest]
1767 fn test_validate_runtime_support_rejects_invalid_rate_limit() {
1768 let config = LiveNodeConfig {
1769 risk_engine: LiveRiskEngineConfig {
1770 max_order_submit_rate: "bad-rate".to_string(),
1771 ..Default::default()
1772 },
1773 ..Default::default()
1774 };
1775
1776 let error = config.validate_runtime_support().unwrap_err().to_string();
1777 assert!(error.contains("LiveRiskEngineConfig.max_order_submit_rate"));
1778 }
1779
1780 #[rstest]
1781 fn test_parse_rate_limit_rejects_invalid_format_with_field_path() {
1782 let error =
1783 parse_rate_limit("LiveRiskEngineConfig.max_order_submit_rate", "bad-rate").unwrap_err();
1784
1785 assert_eq!(
1786 error,
1787 ConfigError::InvalidFormat {
1788 field: "LiveRiskEngineConfig.max_order_submit_rate".to_string(),
1789 expected: RATE_LIMIT_FORMAT.to_string(),
1790 },
1791 );
1792 }
1793
1794 #[rstest]
1795 fn test_validate_max_notional_per_order_collects_entry_errors() {
1796 let error = validate_max_notional_per_order(
1797 "LiveRiskEngineConfig.max_notional_per_order",
1798 &HashMap::from([("INVALID".to_string(), "not-a-decimal".to_string())]),
1799 )
1800 .unwrap_err();
1801
1802 match error {
1803 ConfigError::Multiple { errors } => {
1804 assert_eq!(errors.len(), 2);
1805 assert!(matches!(
1806 &errors[0],
1807 ConfigError::InvalidReference {
1808 field,
1809 reference,
1810 ..
1811 } if field == "LiveRiskEngineConfig.max_notional_per_order[INVALID]"
1812 && reference == "instrument ID"
1813 ));
1814 assert!(matches!(
1815 &errors[1],
1816 ConfigError::InvalidValue { field, reason }
1817 if field == "LiveRiskEngineConfig.max_notional_per_order[INVALID]"
1818 && reason.contains("invalid notional")
1819 ));
1820 }
1821 _ => panic!("Expected multiple config errors, received {error:?}"),
1822 }
1823 }
1824
1825 #[rstest]
1826 #[case(-1.0)]
1827 #[case(f64::NAN)]
1828 #[case(f64::INFINITY)]
1829 #[case(f64::NEG_INFINITY)]
1830 #[case::above_max(DELAY_MAX_SECS + 1.0)]
1831 #[case::overflows_instant(1e19)]
1832 #[case::overflows_duration(1e20)]
1833 fn test_validate_runtime_support_rejects_hostile_startup_delay(#[case] value: f64) {
1834 let config = LiveNodeConfig {
1835 exec_engine: LiveExecutionEngineConfig {
1836 reconciliation_startup_delay_secs: value,
1837 ..Default::default()
1838 },
1839 ..Default::default()
1840 };
1841
1842 let error = config.validate_runtime_support().unwrap_err().to_string();
1843 assert!(error.contains("reconciliation_startup_delay_secs"));
1844 }
1845
1846 #[rstest]
1847 #[case(0.0)]
1848 #[case(10.0)]
1849 #[case::at_max(DELAY_MAX_SECS)]
1850 fn test_validate_runtime_support_accepts_bounded_startup_delay(#[case] value: f64) {
1851 let config = LiveNodeConfig {
1852 exec_engine: LiveExecutionEngineConfig {
1853 reconciliation_startup_delay_secs: value,
1854 ..Default::default()
1855 },
1856 ..Default::default()
1857 };
1858
1859 assert_eq!(config.validate_runtime_support(), Ok(()));
1860
1861 let delay = Duration::from_secs_f64(value);
1863 assert!(std::time::Instant::now().checked_add(delay).is_some());
1864 }
1865
1866 #[rstest]
1867 #[case(0.0)]
1868 #[case(0.5e-9)]
1869 #[case(-1.0)]
1870 #[case(f64::NAN)]
1871 #[case(f64::INFINITY)]
1872 #[case(f64::NEG_INFINITY)]
1873 #[case(f64::MAX)]
1874 fn test_validate_runtime_support_rejects_invalid_exec_intervals(#[case] value: f64) {
1875 let configs = [
1876 (
1877 "LiveExecutionEngineConfig.snapshot_positions_interval_secs",
1878 LiveExecutionEngineConfig {
1879 snapshot_positions_interval_secs: Some(value),
1880 ..Default::default()
1881 },
1882 ),
1883 (
1884 "LiveExecutionEngineConfig.open_check_interval_secs",
1885 LiveExecutionEngineConfig {
1886 open_check_interval_secs: Some(value),
1887 ..Default::default()
1888 },
1889 ),
1890 (
1891 "LiveExecutionEngineConfig.position_check_interval_secs",
1892 LiveExecutionEngineConfig {
1893 position_check_interval_secs: Some(value),
1894 ..Default::default()
1895 },
1896 ),
1897 (
1898 "LiveExecutionEngineConfig.own_books_audit_interval_secs",
1899 LiveExecutionEngineConfig {
1900 own_books_audit_interval_secs: Some(value),
1901 ..Default::default()
1902 },
1903 ),
1904 ];
1905
1906 for (expected_field, config) in configs {
1907 let error = config.validate_runtime_support().unwrap_err();
1908
1909 assert!(matches!(
1910 error,
1911 ConfigError::Range { field, .. } if field == expected_field
1912 ));
1913 }
1914 }
1915
1916 #[rstest]
1917 fn test_validate_runtime_support_accepts_valid_exec_intervals() {
1918 let config = LiveExecutionEngineConfig {
1919 snapshot_positions_interval_secs: Some(1.25),
1920 open_check_interval_secs: Some(2.5),
1921 position_check_interval_secs: Some(3.75),
1922 own_books_audit_interval_secs: Some(4.5),
1923 ..Default::default()
1924 };
1925
1926 assert!(config.validate_runtime_support().is_ok());
1927 }
1928
1929 #[cfg(feature = "python")]
1930 #[rstest]
1931 fn test_duration_from_secs_f64_accepts_valid_value() {
1932 let duration = duration_from_secs_f64("LiveNodeConfig.timeout_connection", 1.5).unwrap();
1933
1934 assert_eq!(duration, Duration::from_millis(1_500));
1935 }
1936
1937 #[cfg(feature = "python")]
1938 #[rstest]
1939 #[case(-1.0)]
1940 #[case(f64::NAN)]
1941 #[case(f64::INFINITY)]
1942 #[case(86_400.1)]
1943 fn test_duration_from_secs_f64_rejects_invalid_values(#[case] value: f64) {
1944 let error = duration_from_secs_f64("LiveNodeConfig.timeout_connection", value).unwrap_err();
1945
1946 match error {
1947 ConfigError::Range { field, reason } => {
1948 assert_eq!(field, "LiveNodeConfig.timeout_connection");
1949 assert!(reason.contains("must be finite, non-negative, and <= 86400"));
1950 }
1951 _ => panic!("Expected range config error, received {error:?}"),
1952 }
1953 }
1954
1955 #[rstest]
1956 fn test_validate_runtime_support_rejects_invalid_reconciliation_instrument_id() {
1957 let config = LiveNodeConfig {
1958 exec_engine: LiveExecutionEngineConfig {
1959 reconciliation_instrument_ids: Some(vec!["INVALID".to_string()]),
1960 ..Default::default()
1961 },
1962 ..Default::default()
1963 };
1964
1965 let error = config.validate_runtime_support().unwrap_err().to_string();
1966 assert!(error.contains("reconciliation_instrument_ids"));
1967 }
1968
1969 #[rstest]
1970 fn test_parse_rate_limit_happy_path() {
1971 let limit = parse_rate_limit("test.rate_limit", "150/00:00:02").unwrap();
1972 assert_eq!(limit, RateLimit::new(150, DurationNanos::from_secs(2)));
1973 }
1974
1975 #[rstest]
1976 fn test_parse_rate_limit_rejects_interval_overflow() {
1977 let err = parse_rate_limit("test.rate_limit", &format!("10/{:02}:00:00", u64::MAX))
1978 .unwrap_err()
1979 .to_string();
1980 assert!(err.contains("interval exceeds the supported range"));
1981 }
1982
1983 #[rstest]
1984 fn test_parse_rate_limit_rejects_trailing_component() {
1985 let err = parse_rate_limit("test.rate_limit", "10/00:00:01:99")
1986 .unwrap_err()
1987 .to_string();
1988 assert!(err.contains("expected 'limit/HH:MM:SS'"));
1989 }
1990
1991 #[rstest]
1992 fn test_parse_rate_limit_rejects_zero_limit() {
1993 let err = parse_rate_limit("test.rate_limit", "0/00:00:01")
1994 .unwrap_err()
1995 .to_string();
1996 assert!(err.contains("Invalid limit"));
1997 assert!(err.contains("must be non-zero"));
1998 }
1999
2000 #[rstest]
2001 fn test_parse_rate_limit_rejects_zero_interval() {
2002 let err = parse_rate_limit("test.rate_limit", "100/00:00:00")
2003 .unwrap_err()
2004 .to_string();
2005 assert!(err.contains("Invalid interval_ns"));
2006 assert!(err.contains("must be non-zero"));
2007 }
2008
2009 #[rstest]
2010 fn test_validate_runtime_support_rejects_exec_engine_qsize() {
2011 let config = LiveNodeConfig {
2012 exec_engine: LiveExecutionEngineConfig {
2013 qsize: 1,
2014 ..Default::default()
2015 },
2016 ..Default::default()
2017 };
2018
2019 let error = config.validate_runtime_support().unwrap_err();
2020 assert_eq!(
2021 error.to_string(),
2022 "LiveExecutionEngineConfig.qsize is not supported by the Rust live runtime yet"
2023 );
2024 }
2025
2026 #[rstest]
2027 fn test_validate_runtime_support_rejects_emulator() {
2028 let config = LiveNodeConfig {
2029 emulator: Some(OrderEmulatorConfig::default()),
2030 ..Default::default()
2031 };
2032
2033 let error = config.validate_runtime_support().unwrap_err().to_string();
2034 assert!(error.contains("emulator"));
2035 }
2036
2037 #[rstest]
2038 fn test_validate_runtime_support_rejects_loop_debug() {
2039 let config = LiveNodeConfig {
2040 loop_debug: true,
2041 ..Default::default()
2042 };
2043
2044 let error = config.validate_runtime_support().unwrap_err().to_string();
2045 assert!(error.contains("loop_debug"));
2046 }
2047
2048 #[rstest]
2049 fn test_validate_runtime_support_accepts_file_config() {
2050 use nautilus_common::logging::writer::FileWriterConfig;
2051
2052 let config = LiveNodeConfig {
2053 logging: LoggerConfig {
2054 file_config: Some(FileWriterConfig::default()),
2055 ..Default::default()
2056 },
2057 ..Default::default()
2058 };
2059
2060 assert!(config.validate_runtime_support().is_ok());
2061 }
2062
2063 #[rstest]
2064 fn test_validate_runtime_support_accepts_clear_log_file() {
2065 let config = LiveNodeConfig {
2066 logging: LoggerConfig {
2067 clear_log_file: true,
2068 ..Default::default()
2069 },
2070 ..Default::default()
2071 };
2072
2073 assert!(config.validate_runtime_support().is_ok());
2074 }
2075
2076 #[rstest]
2077 fn test_validate_runtime_support_rejects_invalid_time_bars_origin_offset_key() {
2078 let config = LiveNodeConfig {
2079 data_engine: LiveDataEngineConfig {
2080 time_bars_origin_offset: HashMap::from([("INVALID".to_string(), 1_000)]),
2081 ..Default::default()
2082 },
2083 ..Default::default()
2084 };
2085
2086 let error = config.validate_runtime_support().unwrap_err().to_string();
2087 assert!(error.contains("time_bars_origin_offset"));
2088 }
2089
2090 #[rstest]
2091 fn test_validate_runtime_support_rejects_empty_plugin_path() {
2092 let config = LiveNodeConfig {
2093 plugins: vec![PluginConfig {
2094 type_name: "ExampleActor".to_string(),
2095 ..Default::default()
2096 }],
2097 ..Default::default()
2098 };
2099
2100 let error = config.validate_runtime_support().unwrap_err().to_string();
2101 assert!(error.contains("plugins[0].path"));
2102 }
2103
2104 #[rstest]
2105 fn test_validate_runtime_support_rejects_empty_plugin_type_name() {
2106 let config = LiveNodeConfig {
2107 plugins: vec![PluginConfig {
2108 path: "./libexample.so".to_string(),
2109 ..Default::default()
2110 }],
2111 ..Default::default()
2112 };
2113
2114 let error = config.validate_runtime_support().unwrap_err().to_string();
2115 assert!(error.contains("plugins[0].type_name"));
2116 }
2117
2118 #[rstest]
2119 fn test_validate_runtime_support_rejects_invalid_plugin_sha256() {
2120 let config = LiveNodeConfig {
2121 plugins: vec![PluginConfig {
2122 path: "./libexample.so".to_string(),
2123 type_name: "ExampleActor".to_string(),
2124 sha256: Some("not-a-digest".to_string()),
2125 ..Default::default()
2126 }],
2127 ..Default::default()
2128 };
2129
2130 let error = config.validate_runtime_support().unwrap_err().to_string();
2131 assert!(error.contains("sha256"));
2132 }
2133
2134 #[rstest]
2135 #[allow(
2137 clippy::float_cmp,
2138 reason = "asserts the exact configured default with no arithmetic involved"
2139 )]
2140 fn test_live_exec_engine_config_defaults() {
2141 let config = LiveExecutionEngineConfig::default();
2142
2143 assert!(config.load_cache);
2144 assert!(!config.snapshot_orders);
2145 assert!(!config.snapshot_positions);
2146 assert_eq!(config.snapshot_positions_interval_secs, None);
2147 assert_eq!(config.external_clients, None);
2148 assert!(!config.debug);
2149 assert!(!config.manage_own_order_books);
2150 assert!(!config.allow_overfills);
2151 assert!(config.reconciliation);
2152 assert_eq!(config.reconciliation_startup_delay_secs, 10.0);
2153 assert_eq!(config.reconciliation_lookback_mins, None);
2154 assert_eq!(config.reconciliation_instrument_ids, None);
2155 assert_eq!(config.filtered_client_order_ids, None);
2156 assert!(!config.filter_unclaimed_external_orders);
2157 assert!(!config.filter_position_reports);
2158 assert!(config.generate_missing_orders);
2159 assert_eq!(config.inflight_check_interval_ms, 2_000);
2160 assert_eq!(config.inflight_check_threshold_ms, 5_000);
2161 assert_eq!(config.inflight_check_retries, 5);
2162 assert_eq!(
2163 config.submission_recovery_policy,
2164 SubmissionRecoveryPolicy::ResolveLocally,
2165 );
2166 assert_eq!(config.open_check_threshold_ms, 5_000);
2167 assert_eq!(config.open_check_lookback_mins, Some(60));
2168 assert_eq!(config.open_check_missing_retries, 5);
2169 assert!(config.open_check_open_only);
2170 assert_eq!(config.max_single_order_queries_per_cycle, 10);
2171 assert_eq!(config.position_check_threshold_ms, 5_000);
2172 assert_eq!(config.position_check_retries, 3);
2173 assert!(!config.purge_from_database);
2174 assert_eq!(config.qsize, 100_000);
2175 }
2176
2177 #[rstest]
2178 fn test_submission_recovery_policy_omitted() {
2179 let deserialized: LiveExecutionEngineConfig = serde_json::from_str("{}").unwrap();
2180 let built = LiveExecutionEngineConfig::builder().build();
2181
2182 assert_eq!(
2183 deserialized.submission_recovery_policy,
2184 SubmissionRecoveryPolicy::ResolveLocally,
2185 );
2186 assert_eq!(
2187 built.submission_recovery_policy,
2188 SubmissionRecoveryPolicy::ResolveLocally,
2189 );
2190 }
2191
2192 #[rstest]
2193 #[case(SubmissionRecoveryPolicy::ResolveLocally, "resolve_locally")]
2194 #[case(SubmissionRecoveryPolicy::RetainUnresolved, "retain_unresolved")]
2195 fn test_submission_recovery_policy_config_round_trip(
2196 #[case] policy: SubmissionRecoveryPolicy,
2197 #[case] serialized_policy: &str,
2198 ) {
2199 let config = LiveExecutionEngineConfig::builder()
2200 .submission_recovery_policy(policy)
2201 .build();
2202 let serialized = serde_json::to_value(&config).unwrap();
2203 let deserialized: LiveExecutionEngineConfig =
2204 serde_json::from_value(serialized.clone()).unwrap();
2205 let manager_config = ExecutionManagerConfig::from(&deserialized);
2206
2207 assert_eq!(serialized["submission_recovery_policy"], serialized_policy);
2208 assert_eq!(deserialized, config);
2209 assert_eq!(manager_config.submission_recovery_policy, policy);
2210 }
2211
2212 #[rstest]
2213 #[case(r#"{"submission_recovery_policy":"retry_forever"}"#)]
2214 #[case(r#"{"submission_recovery_policy":"RETAIN_UNRESOLVED"}"#)]
2215 #[case(r#"{"submission_recovery_policy":1}"#)]
2216 #[case(r#"{"submission_recovery_policy":null}"#)]
2217 fn test_submission_recovery_policy_rejects_invalid_json(#[case] json: &str) {
2218 assert!(serde_json::from_str::<LiveExecutionEngineConfig>(json).is_err());
2219 }
2220
2221 #[rstest]
2222 fn test_live_data_engine_config_defaults() {
2223 let config = LiveDataEngineConfig::default();
2224
2225 assert!(config.time_bars_build_with_no_updates);
2226 assert!(config.time_bars_timestamp_on_close);
2227 assert!(!config.time_bars_skip_first_non_full_bar);
2228 assert_eq!(config.time_bars_interval_type, BarIntervalType::LeftOpen);
2229 assert_eq!(config.time_bars_build_delay, 0);
2230 assert!(config.time_bars_origin_offset.is_empty());
2231 assert!(!config.validate_data_sequence);
2232 assert!(!config.buffer_deltas);
2233 assert!(!config.emit_quotes_from_book);
2234 assert!(!config.emit_quotes_from_book_depths);
2235 assert_eq!(config.external_clients, None);
2236 assert!(!config.debug);
2237 assert_eq!(config.qsize, 100_000);
2238 }
2239
2240 #[rstest]
2241 fn test_live_risk_engine_config_defaults() {
2242 let config = LiveRiskEngineConfig::default();
2243
2244 assert!(!config.bypass);
2245 assert_eq!(config.max_order_submit_rate, DEFAULT_ORDER_RATE_LIMIT);
2246 assert_eq!(config.max_order_modify_rate, DEFAULT_ORDER_RATE_LIMIT);
2247 assert!(config.max_notional_per_order.is_empty());
2248 assert!(config.full_position_exit_venues.is_empty());
2249 assert!(!config.debug);
2250 assert_eq!(config.qsize, 100_000);
2251 }
2252
2253 #[rstest]
2254 fn test_routing_config_default() {
2255 let config = RoutingConfig::default();
2256
2257 assert!(!config.default);
2258 assert_eq!(config.venues, None);
2259 }
2260
2261 #[rstest]
2262 fn test_data_client_config_default() {
2263 let config = DataClientConfig::default();
2264
2265 assert!(!config.handle_revised_bars);
2266 assert!(!config.instrument_provider.load_all);
2267 assert!(config.instrument_provider.load_ids.is_none());
2268 assert!(config.instrument_provider.filters.is_empty());
2269 assert!(config.instrument_provider.filter_callable.is_none());
2270 assert!(config.instrument_provider.log_warnings);
2271 assert!(!config.routing.default);
2272 }
2273
2274 #[rstest]
2275 fn test_data_client_config_rejects_unknown_field() {
2276 let error = serde_json::from_str::<DataClientConfig>(
2277 r#"{"handle_revised_bars":true,"unexpected":true}"#,
2278 )
2279 .unwrap_err();
2280
2281 assert!(error.to_string().contains("unknown field `unexpected`"));
2282 }
2283
2284 #[rstest]
2285 fn test_data_client_config_rejects_unknown_nested_field() {
2286 let error = serde_json::from_str::<DataClientConfig>(
2287 r#"{"instrument_provider":{"load_all":true,"instrument_provider":{"load_all":false}}}"#,
2288 )
2289 .unwrap_err();
2290
2291 assert!(
2292 error
2293 .to_string()
2294 .contains("unknown field `instrument_provider`")
2295 );
2296 }
2297
2298 #[rstest]
2299 fn test_live_node_config_toml_minimal() {
2300 let config: LiveNodeConfig = toml::from_str(
2301 r#"
2302environment = "Live"
2303trader_id = "TRADER-042"
2304
2305[data_engine]
2306debug = true
2307
2308[risk_engine]
2309bypass = false
2310
2311[exec_engine]
2312reconciliation = false
2313
2314[data_clients.hyperliquid]
2315handle_revised_bars = true
2316
2317[exec_clients.hyperliquid]
2318routing = { default = true, venues = ["HYPERLIQUID"] }
2319instrument_provider = { load_all = true }
2320
2321[[plugins]]
2322path = "./target/debug/examples/libcustom_data_plugin.so"
2323type_name = "ExampleStrategy"
2324config = { strategy_id = "ExampleStrategy-001", threshold = 10 }
2325"#,
2326 )
2327 .unwrap();
2328
2329 assert_eq!(config.environment, Environment::Live);
2330 assert_eq!(config.trader_id, TraderId::from("TRADER-042"));
2331 assert!(config.data_engine.debug);
2332 assert!(!config.risk_engine.bypass);
2333 assert!(!config.exec_engine.reconciliation);
2334 assert!(config.data_clients["hyperliquid"].handle_revised_bars);
2335 let exec_client = &config.exec_clients["hyperliquid"];
2336 assert!(exec_client.routing.default);
2337 assert_eq!(
2338 exec_client.routing.venues,
2339 Some(vec!["HYPERLIQUID".to_string()]),
2340 );
2341 assert!(exec_client.instrument_provider.load_all);
2342 assert_eq!(config.plugins.len(), 1);
2343 assert_eq!(
2344 config.plugins[0].path,
2345 "./target/debug/examples/libcustom_data_plugin.so"
2346 );
2347 assert_eq!(config.plugins[0].type_name, "ExampleStrategy");
2348 assert_eq!(
2349 config.plugins[0].config["strategy_id"],
2350 serde_json::json!("ExampleStrategy-001")
2351 );
2352 assert_eq!(config.plugins[0].config["threshold"], serde_json::json!(10));
2353 }
2354
2355 #[rstest]
2356 fn live_node_config_serde_roundtrip_with_event_store() {
2357 let config = LiveNodeConfig {
2358 event_store: Some(EventStoreConfig {
2359 channel_capacity: 5_000,
2360 ..Default::default()
2361 }),
2362 ..Default::default()
2363 };
2364
2365 let json = serde_json::to_string(&config).expect("serialize");
2366 let restored: LiveNodeConfig = serde_json::from_str(&json).expect("deserialize");
2367
2368 let restored_event_store = restored.event_store.expect("event_store present");
2369 assert_eq!(restored_event_store.channel_capacity, 5_000);
2370 }
2371
2372 #[rstest]
2373 fn live_node_config_default_has_no_event_store() {
2374 let config = LiveNodeConfig::default();
2375 assert!(config.event_store.is_none());
2376 }
2377}