Skip to main content

nautilus_execution/engine/
config.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use nautilus_common::config::{ConfigError, ConfigErrorCollector, ConfigResult};
17use nautilus_core::{DurationNanos, serialization::default_true};
18use nautilus_model::identifiers::ClientId;
19use serde::{Deserialize, Serialize};
20
21/// Configuration for `ExecutionEngine` instances.
22#[cfg_attr(
23    feature = "python",
24    pyo3::pyclass(module = "nautilus_trader.execution", from_py_object)
25)]
26#[cfg_attr(
27    feature = "python",
28    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
29)]
30#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
31#[builder(finish_fn(name = build_inner, vis = ""))]
32#[serde(deny_unknown_fields)]
33pub struct ExecutionEngineConfig {
34    /// If the cache should be loaded on initialization.
35    #[serde(default = "default_true")]
36    #[builder(default = true)]
37    pub load_cache: bool,
38    /// If the execution engine should maintain own/user order books based on commands and events.
39    #[serde(default)]
40    #[builder(default)]
41    pub manage_own_order_books: bool,
42    /// If order state snapshot lists are persisted to a backing database.
43    /// Snapshots will be taken at every order state update (when events are applied).
44    #[serde(default)]
45    #[builder(default)]
46    pub snapshot_orders: bool,
47    /// If position state snapshot lists are persisted to a backing database.
48    /// Snapshots will be taken at position opened, changed, and closed (when events are applied).
49    #[serde(default)]
50    #[builder(default)]
51    pub snapshot_positions: bool,
52    /// The interval (seconds) at which additional position state snapshots are persisted.
53    /// If `None` then no additional snapshots will be taken.
54    #[serde(default)]
55    pub snapshot_positions_interval_secs: Option<f64>,
56    /// If position replay events and fill voids are carried across NETTING close/reopen cycles.
57    /// Enable to keep fills from earlier cycles correctable by an `OrderFillVoided`.
58    #[serde(default)]
59    #[builder(default)]
60    pub carry_replay_events_on_reopen: bool,
61    /// If order fills exceeding order quantity are allowed (logs warning instead of raising).
62    /// Useful when position reconciliation races with exchange fill events.
63    #[serde(default)]
64    #[builder(default)]
65    pub allow_overfills: bool,
66    /// If unclaimed venue orders should be filtered during execution reconciliation.
67    #[serde(default)]
68    #[builder(default)]
69    pub filter_unclaimed_external_orders: bool,
70    /// The client IDs declared for external stream processing.
71    ///
72    /// The execution engine will not attempt to send trading commands to these
73    /// client IDs, assuming an external process will consume the serialized
74    /// command messages from the bus and handle execution.
75    #[serde(default)]
76    pub external_clients: Option<Vec<ClientId>>,
77    /// The interval (minutes) between purging closed orders from the in-memory cache.
78    #[serde(default)]
79    pub purge_closed_orders_interval_mins: Option<u32>,
80    /// The time buffer (minutes) before closed orders can be purged.
81    #[serde(default)]
82    pub purge_closed_orders_buffer_mins: Option<u32>,
83    /// The interval (minutes) between purging closed positions from the in-memory cache.
84    #[serde(default)]
85    pub purge_closed_positions_interval_mins: Option<u32>,
86    /// The time buffer (minutes) before closed positions can be purged.
87    #[serde(default)]
88    pub purge_closed_positions_buffer_mins: Option<u32>,
89    /// The interval (minutes) between purging account events from the in-memory cache.
90    #[serde(default)]
91    pub purge_account_events_interval_mins: Option<u32>,
92    /// The time buffer (minutes) before account events can be purged.
93    #[serde(default)]
94    pub purge_account_events_lookback_mins: Option<u32>,
95    /// If purging also deletes orders and positions from the backing database.
96    /// Redis and PostgreSQL retain persisted account events for replay.
97    #[serde(default)]
98    #[builder(default)]
99    pub purge_from_database: bool,
100    /// If debug mode is active (will provide extra debug logging).
101    #[serde(default)]
102    #[builder(default)]
103    pub debug: bool,
104}
105
106impl<S: execution_engine_config_builder::IsComplete> ExecutionEngineConfigBuilder<S> {
107    /// Validates and builds the [`ExecutionEngineConfig`].
108    ///
109    /// # Errors
110    ///
111    /// Returns an error if any field fails validation (see [`ExecutionEngineConfig::validate`]).
112    pub fn build(self) -> ConfigResult<ExecutionEngineConfig> {
113        let config = self.build_inner();
114        config.validate()?;
115        Ok(config)
116    }
117}
118
119impl ExecutionEngineConfig {
120    /// Validates the execution engine configuration, collecting every field violation.
121    ///
122    /// # Errors
123    ///
124    /// Returns an error if any field fails validation. Multiple validation failures are collected
125    /// into one error.
126    pub fn validate(&self) -> ConfigResult<()> {
127        let mut errors = ConfigErrorCollector::new();
128
129        if let Some(secs) = self.snapshot_positions_interval_secs {
130            errors.check(
131                secs.is_finite() && secs > 0.0,
132                ConfigError::range(
133                    "snapshot_positions_interval_secs",
134                    format!("must be a positive finite value, was {secs}"),
135                ),
136            );
137        }
138
139        for (field, value) in [
140            (
141                "purge_closed_orders_interval_mins",
142                self.purge_closed_orders_interval_mins,
143            ),
144            (
145                "purge_closed_positions_interval_mins",
146                self.purge_closed_positions_interval_mins,
147            ),
148            (
149                "purge_account_events_interval_mins",
150                self.purge_account_events_interval_mins,
151            ),
152        ] {
153            if let Some(mins) = value {
154                let reason = if mins == 0 {
155                    format!("must be a positive number of minutes, was {mins}")
156                } else {
157                    format!("must be positive and fit in `u64` nanoseconds, was {mins} minutes")
158                };
159                errors.check(
160                    mins > 0 && DurationNanos::try_from_mins(u64::from(mins)).is_ok(),
161                    ConfigError::range(field, reason),
162                );
163            }
164        }
165
166        for (field, value) in [
167            (
168                "purge_closed_orders_buffer_mins",
169                self.purge_closed_orders_buffer_mins,
170            ),
171            (
172                "purge_closed_positions_buffer_mins",
173                self.purge_closed_positions_buffer_mins,
174            ),
175            (
176                "purge_account_events_lookback_mins",
177                self.purge_account_events_lookback_mins,
178            ),
179        ] {
180            if let Some(mins) = value {
181                errors.check(
182                    DurationNanos::try_from_mins(u64::from(mins)).is_ok(),
183                    ConfigError::range(
184                        field,
185                        format!("must fit in `u64` nanoseconds, was {mins} minutes"),
186                    ),
187                );
188            }
189        }
190
191        errors.into_result()
192    }
193}
194
195impl Default for ExecutionEngineConfig {
196    fn default() -> Self {
197        Self::builder()
198            .build()
199            .expect("default `ExecutionEngineConfig` should be valid")
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use rstest::rstest;
206
207    use super::*;
208
209    #[rstest]
210    fn test_default_config_values() {
211        let config = ExecutionEngineConfig::default();
212
213        assert!(config.load_cache);
214        assert!(!config.manage_own_order_books);
215        assert!(!config.snapshot_orders);
216        assert!(!config.snapshot_positions);
217        assert_eq!(config.snapshot_positions_interval_secs, None);
218        assert!(!config.carry_replay_events_on_reopen);
219        assert!(!config.allow_overfills);
220        assert!(!config.filter_unclaimed_external_orders);
221        assert_eq!(config.external_clients, None);
222        assert_eq!(config.purge_closed_orders_interval_mins, None);
223        assert_eq!(config.purge_closed_orders_buffer_mins, None);
224        assert_eq!(config.purge_closed_positions_interval_mins, None);
225        assert_eq!(config.purge_closed_positions_buffer_mins, None);
226        assert_eq!(config.purge_account_events_interval_mins, None);
227        assert_eq!(config.purge_account_events_lookback_mins, None);
228        assert!(!config.purge_from_database);
229        assert!(!config.debug);
230    }
231
232    #[rstest]
233    fn test_carry_replay_events_on_reopen_defaults_false() {
234        assert!(!ExecutionEngineConfig::default().carry_replay_events_on_reopen);
235
236        let config: ExecutionEngineConfig =
237            serde_json::from_str("{}").expect("empty config should deserialize");
238        assert!(!config.carry_replay_events_on_reopen);
239
240        let config = ExecutionEngineConfig::builder()
241            .carry_replay_events_on_reopen(true)
242            .build()
243            .unwrap();
244        assert!(config.carry_replay_events_on_reopen);
245    }
246
247    #[rstest]
248    #[case(0.0)]
249    #[case(-1.0)]
250    #[case(f64::INFINITY)]
251    #[case(f64::NAN)]
252    fn test_invalid_snapshot_positions_interval_secs_rejected(#[case] secs: f64) {
253        let result = ExecutionEngineConfig::builder()
254            .snapshot_positions_interval_secs(secs)
255            .build();
256        assert!(
257            matches!(result, Err(ConfigError::Range { field, .. }) if field == "snapshot_positions_interval_secs")
258        );
259    }
260
261    #[rstest]
262    fn test_positive_snapshot_positions_interval_secs_accepted() {
263        let result = ExecutionEngineConfig::builder()
264            .snapshot_positions_interval_secs(5.0)
265            .build();
266        assert!(result.is_ok());
267    }
268
269    #[rstest]
270    #[case("purge_closed_orders_interval_mins")]
271    #[case("purge_closed_positions_interval_mins")]
272    #[case("purge_account_events_interval_mins")]
273    fn test_zero_purge_interval_rejected(#[case] field: &str) {
274        let mut config = ExecutionEngineConfig::default();
275
276        match field {
277            "purge_closed_orders_interval_mins" => {
278                config.purge_closed_orders_interval_mins = Some(0);
279            }
280            "purge_closed_positions_interval_mins" => {
281                config.purge_closed_positions_interval_mins = Some(0);
282            }
283            "purge_account_events_interval_mins" => {
284                config.purge_account_events_interval_mins = Some(0);
285            }
286            _ => unreachable!(),
287        }
288
289        assert_eq!(
290            config.validate().unwrap_err(),
291            ConfigError::range(field, "must be a positive number of minutes, was 0"),
292        );
293    }
294
295    #[rstest]
296    fn test_positive_purge_intervals_accepted() {
297        // A zero buffer is valid (no grace period), only the intervals must be positive
298        let result = ExecutionEngineConfig::builder()
299            .purge_closed_orders_interval_mins(10)
300            .purge_closed_positions_interval_mins(10)
301            .purge_account_events_interval_mins(10)
302            .purge_closed_orders_buffer_mins(0)
303            .build();
304        assert!(result.is_ok());
305    }
306
307    #[rstest]
308    fn test_overflowing_purge_intervals_rejected() {
309        let result = ExecutionEngineConfig::builder()
310            .purge_closed_orders_interval_mins(u32::MAX)
311            .purge_closed_positions_interval_mins(u32::MAX)
312            .purge_account_events_interval_mins(u32::MAX)
313            .build();
314        assert_eq!(
315            result.unwrap_err(),
316            ConfigError::Multiple {
317                errors: vec![
318                    ConfigError::range(
319                        "purge_closed_orders_interval_mins",
320                        "must be positive and fit in `u64` nanoseconds, was 4294967295 minutes",
321                    ),
322                    ConfigError::range(
323                        "purge_closed_positions_interval_mins",
324                        "must be positive and fit in `u64` nanoseconds, was 4294967295 minutes",
325                    ),
326                    ConfigError::range(
327                        "purge_account_events_interval_mins",
328                        "must be positive and fit in `u64` nanoseconds, was 4294967295 minutes",
329                    ),
330                ],
331            }
332        );
333    }
334
335    #[rstest]
336    #[case("purge_closed_orders_buffer_mins", 0)]
337    #[case("purge_closed_orders_buffer_mins", 307_445_734)]
338    #[case("purge_closed_positions_buffer_mins", 0)]
339    #[case("purge_closed_positions_buffer_mins", 307_445_734)]
340    #[case("purge_account_events_lookback_mins", 0)]
341    #[case("purge_account_events_lookback_mins", 307_445_734)]
342    fn test_purge_retention_minute_boundaries_accepted(#[case] field: &str, #[case] mins: u32) {
343        let mut config = ExecutionEngineConfig::default();
344
345        match field {
346            "purge_closed_orders_buffer_mins" => {
347                config.purge_closed_orders_buffer_mins = Some(mins);
348            }
349            "purge_closed_positions_buffer_mins" => {
350                config.purge_closed_positions_buffer_mins = Some(mins);
351            }
352            "purge_account_events_lookback_mins" => {
353                config.purge_account_events_lookback_mins = Some(mins);
354            }
355            _ => unreachable!(),
356        }
357
358        assert!(config.validate().is_ok());
359    }
360
361    #[rstest]
362    #[case("purge_closed_orders_buffer_mins")]
363    #[case("purge_closed_positions_buffer_mins")]
364    #[case("purge_account_events_lookback_mins")]
365    fn test_overflowing_purge_retention_minutes_rejected(#[case] field: &str) {
366        let mut config = ExecutionEngineConfig::default();
367
368        match field {
369            "purge_closed_orders_buffer_mins" => {
370                config.purge_closed_orders_buffer_mins = Some(307_445_735);
371            }
372            "purge_closed_positions_buffer_mins" => {
373                config.purge_closed_positions_buffer_mins = Some(307_445_735);
374            }
375            "purge_account_events_lookback_mins" => {
376                config.purge_account_events_lookback_mins = Some(307_445_735);
377            }
378            _ => unreachable!(),
379        }
380
381        assert!(matches!(
382            config.validate(),
383            Err(ConfigError::Range { field: error_field, .. }) if error_field == field
384        ));
385    }
386
387    #[rstest]
388    fn test_multiple_violations_collected() {
389        let result = ExecutionEngineConfig::builder()
390            .snapshot_positions_interval_secs(0.0)
391            .purge_closed_orders_interval_mins(0)
392            .build();
393        let ConfigError::Multiple { errors } = result.unwrap_err() else {
394            panic!("expected ConfigError::Multiple");
395        };
396        assert_eq!(errors.len(), 2);
397        assert!(errors.iter().any(
398            |e| matches!(e, ConfigError::Range { field, .. } if field == "snapshot_positions_interval_secs")
399        ));
400        assert!(errors.iter().any(
401            |e| matches!(e, ConfigError::Range { field, .. } if field == "purge_closed_orders_interval_mins")
402        ));
403    }
404}