Skip to main content

nautilus_sandbox/
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
16//! Configuration for sandbox execution client.
17
18use ahash::AHashMap;
19use nautilus_common::config::{ConfigResult, check_unique_values};
20use nautilus_execution::{
21    matching_engine::config::{OrderMatchingEngineConfig, OrderPriorityResetPolicy},
22    models::{fee::FeeModelAny, fill::FillModelAny, latency::LatencyModelAny},
23};
24use nautilus_model::{
25    accounts::margin_model::MarginModelAny,
26    enums::{AccountType, BookType, OmsType},
27    identifiers::{AccountId, InstrumentId, Venue},
28    types::{Currency, Money},
29};
30use rust_decimal::Decimal;
31use serde::{
32    Deserialize, Deserializer, Serialize, Serializer,
33    de::{self, IgnoredAny},
34};
35
36/// Configuration for `SandboxExecutionClient` instances.
37#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
38#[serde(default, deny_unknown_fields)]
39#[cfg_attr(
40    feature = "python",
41    pyo3::pyclass(module = "nautilus_trader.adapters.sandbox", from_py_object)
42)]
43#[cfg_attr(
44    feature = "python",
45    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.sandbox")
46)]
47pub struct SandboxExecutionClientConfig {
48    /// The account ID for this client.
49    #[builder(default = AccountId::from("SANDBOX-001"))]
50    pub account_id: AccountId,
51    /// The venue for this sandbox execution client.
52    #[builder(default = Venue::new("SANDBOX"))]
53    pub venue: Venue,
54    /// The starting balances for this sandbox venue.
55    #[builder(default)]
56    pub starting_balances: Vec<Money>,
57    /// The base currency for this venue (None for multi-currency).
58    pub base_currency: Option<Currency>,
59    /// The order management system type used by the exchange.
60    #[builder(default = OmsType::Netting)]
61    pub oms_type: OmsType,
62    /// The account type for the client.
63    #[builder(default = AccountType::Margin)]
64    pub account_type: AccountType,
65    /// The account default leverage (for margin accounts).
66    #[builder(default = Decimal::ONE)]
67    pub default_leverage: Decimal,
68    /// Per-instrument leverage overrides.
69    #[builder(default)]
70    pub leverages: AHashMap<InstrumentId, Decimal>,
71    /// The order book type for the matching engine.
72    #[builder(default = BookType::L1_MBP)]
73    pub book_type: BookType,
74    /// The fill model for sandbox matching engines.
75    #[serde(
76        default,
77        skip_serializing_if = "Option::is_none",
78        serialize_with = "serialize_fill_model",
79        deserialize_with = "deserialize_fill_model"
80    )]
81    pub fill_model: Option<FillModelAny>,
82    /// The fee model for sandbox matching engines.
83    #[serde(
84        default,
85        skip_serializing_if = "Option::is_none",
86        serialize_with = "serialize_fee_model",
87        deserialize_with = "deserialize_fee_model"
88    )]
89    pub fee_model: Option<FeeModelAny>,
90    /// The margin model for the sandbox margin account.
91    #[serde(
92        default,
93        skip_serializing_if = "Option::is_none",
94        serialize_with = "serialize_margin_model",
95        deserialize_with = "deserialize_margin_model"
96    )]
97    pub margin_model: Option<MarginModelAny>,
98    /// The latency model for sandbox matching engines.
99    #[serde(
100        default,
101        skip_serializing_if = "Option::is_none",
102        serialize_with = "serialize_latency_model",
103        deserialize_with = "deserialize_latency_model"
104    )]
105    pub latency_model: Option<LatencyModelAny>,
106    /// If True, account balances won't change (frozen).
107    #[builder(default)]
108    pub frozen_account: bool,
109    /// If bars should be processed by the matching engine (and move the market).
110    #[builder(default = true)]
111    pub bar_execution: bool,
112    /// If trades should be processed by the matching engine (and move the market).
113    #[builder(default = true)]
114    pub trade_execution: bool,
115    /// If stop orders are rejected on submission if trigger price is in the market.
116    #[builder(default = true)]
117    pub reject_stop_orders: bool,
118    /// If orders with GTD time in force will be supported by the venue.
119    #[builder(default = true)]
120    pub support_gtd_orders: bool,
121    /// If contingent orders will be supported/respected by the venue.
122    #[builder(default = true)]
123    pub support_contingent_orders: bool,
124    /// If venue position IDs will be generated on order fills.
125    #[builder(default = true)]
126    pub use_position_ids: bool,
127    /// If venue order IDs and position IDs will be random UUID4's.
128    /// Trade IDs are always deterministic and not affected by this flag.
129    #[builder(default)]
130    pub use_random_ids: bool,
131    /// If the `reduce_only` execution instruction on orders will be enforced.
132    /// If false, reduce-only orders are rejected.
133    #[builder(default = true)]
134    pub use_reduce_only: bool,
135    /// If limit order queue position tracking is enabled during trade execution.
136    #[builder(default)]
137    pub queue_position: bool,
138    /// If order book liquidity consumption should be tracked per level.
139    #[builder(default)]
140    pub liquidity_consumption: bool,
141    /// If bar high/low processing order adapts to the bar's shape.
142    #[builder(default)]
143    pub bar_adaptive_high_low_ordering: bool,
144    /// If `OrderAccepted` events should be generated for market orders.
145    #[builder(default)]
146    pub use_market_order_acks: bool,
147    /// If OTO child orders wait for a full parent fill before release.
148    #[builder(default)]
149    pub oto_full_trigger: bool,
150    /// Exchange-calculated price boundary for aggressive market fills.
151    ///
152    /// A value of `0` disables protection.
153    #[builder(default)]
154    pub price_protection_points: u32,
155    /// The queue-priority reset policy for successful modify commands.
156    #[builder(default)]
157    pub order_priority_reset_policy: OrderPriorityResetPolicy,
158}
159
160impl SandboxExecutionClientConfig {
161    /// Validates that starting balances use distinct currencies.
162    ///
163    /// # Errors
164    ///
165    /// Returns an error if a starting-balance currency repeats.
166    pub fn validate(&self) -> ConfigResult<()> {
167        let currencies: Vec<_> = self
168            .starting_balances
169            .iter()
170            .map(|balance| balance.currency)
171            .collect();
172        check_unique_values("starting_balances", &currencies)
173    }
174
175    /// Creates an [`OrderMatchingEngineConfig`] from this sandbox config.
176    #[must_use]
177    pub fn to_matching_engine_config(&self) -> OrderMatchingEngineConfig {
178        let price_protection = if self.price_protection_points == 0 {
179            None
180        } else {
181            Some(self.price_protection_points)
182        };
183
184        OrderMatchingEngineConfig::builder()
185            .bar_execution(self.bar_execution)
186            .bar_adaptive_high_low_ordering(self.bar_adaptive_high_low_ordering)
187            .trade_execution(self.trade_execution)
188            .liquidity_consumption(self.liquidity_consumption)
189            .reject_stop_orders(self.reject_stop_orders)
190            .support_gtd_orders(self.support_gtd_orders)
191            .support_contingent_orders(self.support_contingent_orders)
192            .use_position_ids(self.use_position_ids)
193            .use_random_ids(self.use_random_ids)
194            .use_reduce_only(self.use_reduce_only)
195            .use_market_order_acks(self.use_market_order_acks)
196            .queue_position(self.queue_position)
197            .order_priority_reset_policy(self.order_priority_reset_policy)
198            .oto_full_trigger(self.oto_full_trigger)
199            .maybe_price_protection_points(price_protection)
200            .build()
201    }
202}
203
204impl Default for SandboxExecutionClientConfig {
205    fn default() -> Self {
206        Self::builder().build()
207    }
208}
209
210fn serialize_fill_model<S>(
211    fill_model: &Option<FillModelAny>,
212    serializer: S,
213) -> Result<S::Ok, S::Error>
214where
215    S: Serializer,
216{
217    match fill_model {
218        None => serializer.serialize_none(),
219        Some(_) => Err(serde::ser::Error::custom(
220            "SandboxExecutionClientConfig.fill_model is runtime-only and cannot be serialized",
221        )),
222    }
223}
224
225fn deserialize_fill_model<'de, D>(deserializer: D) -> Result<Option<FillModelAny>, D::Error>
226where
227    D: Deserializer<'de>,
228{
229    let value = Option::<IgnoredAny>::deserialize(deserializer)?;
230
231    match value {
232        None => Ok(None),
233        Some(_) => Err(de::Error::custom(
234            "SandboxExecutionClientConfig.fill_model must be configured at runtime, not deserialized",
235        )),
236    }
237}
238
239fn serialize_fee_model<S>(fee_model: &Option<FeeModelAny>, serializer: S) -> Result<S::Ok, S::Error>
240where
241    S: Serializer,
242{
243    match fee_model {
244        None => serializer.serialize_none(),
245        Some(_) => Err(serde::ser::Error::custom(
246            "SandboxExecutionClientConfig.fee_model is runtime-only and cannot be serialized",
247        )),
248    }
249}
250
251fn deserialize_fee_model<'de, D>(deserializer: D) -> Result<Option<FeeModelAny>, D::Error>
252where
253    D: Deserializer<'de>,
254{
255    let value = Option::<IgnoredAny>::deserialize(deserializer)?;
256
257    match value {
258        None => Ok(None),
259        Some(_) => Err(de::Error::custom(
260            "SandboxExecutionClientConfig.fee_model must be configured at runtime, not deserialized",
261        )),
262    }
263}
264
265fn serialize_margin_model<S>(
266    margin_model: &Option<MarginModelAny>,
267    serializer: S,
268) -> Result<S::Ok, S::Error>
269where
270    S: Serializer,
271{
272    match margin_model {
273        None => serializer.serialize_none(),
274        Some(_) => Err(serde::ser::Error::custom(
275            "SandboxExecutionClientConfig.margin_model is runtime-only and cannot be serialized",
276        )),
277    }
278}
279
280fn deserialize_margin_model<'de, D>(deserializer: D) -> Result<Option<MarginModelAny>, D::Error>
281where
282    D: Deserializer<'de>,
283{
284    let value = Option::<IgnoredAny>::deserialize(deserializer)?;
285    match value {
286        None => Ok(None),
287        Some(_) => Err(de::Error::custom(
288            "SandboxExecutionClientConfig.margin_model must be configured at runtime, not deserialized",
289        )),
290    }
291}
292
293fn serialize_latency_model<S>(
294    latency_model: &Option<LatencyModelAny>,
295    serializer: S,
296) -> Result<S::Ok, S::Error>
297where
298    S: Serializer,
299{
300    match latency_model {
301        None => serializer.serialize_none(),
302        Some(_) => Err(serde::ser::Error::custom(
303            "SandboxExecutionClientConfig.latency_model is runtime-only and cannot be serialized",
304        )),
305    }
306}
307
308fn deserialize_latency_model<'de, D>(deserializer: D) -> Result<Option<LatencyModelAny>, D::Error>
309where
310    D: Deserializer<'de>,
311{
312    let value = Option::<IgnoredAny>::deserialize(deserializer)?;
313
314    match value {
315        None => Ok(None),
316        Some(_) => Err(de::Error::custom(
317            "SandboxExecutionClientConfig.latency_model must be configured at runtime, not deserialized",
318        )),
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use nautilus_common::config::ConfigError;
325    use nautilus_core::DurationNanos;
326    use nautilus_execution::models::{
327        fee::{FeeModelAny, ProbabilityPriceFeeModel},
328        fill::FillModelAny,
329        latency::{LatencyModelAny, StaticLatencyModel},
330    };
331    use rstest::rstest;
332    use rust_decimal_macros::dec;
333
334    use super::*;
335
336    #[rstest]
337    fn test_exec_config_toml_empty_uses_defaults() {
338        let config: SandboxExecutionClientConfig = toml::from_str("").unwrap();
339        let expected = SandboxExecutionClientConfig::default();
340        assert_eq!(config.account_id, expected.account_id);
341        assert_eq!(config.venue, expected.venue);
342        assert_eq!(config.oms_type, expected.oms_type);
343        assert_eq!(config.account_type, expected.account_type);
344        assert_eq!(config.default_leverage, expected.default_leverage);
345        assert_eq!(config.book_type, expected.book_type);
346        assert!(config.fill_model.is_none());
347        assert!(config.fee_model.is_none());
348        assert!(config.margin_model.is_none());
349        assert!(config.latency_model.is_none());
350        assert_eq!(config.bar_execution, expected.bar_execution);
351        assert_eq!(config.trade_execution, expected.trade_execution);
352        assert_eq!(config.use_position_ids, expected.use_position_ids);
353        assert!(!config.queue_position);
354        assert_eq!(
355            config.order_priority_reset_policy,
356            OrderPriorityResetPolicy::PriceChange
357        );
358        assert!(!config.liquidity_consumption);
359        assert!(!config.bar_adaptive_high_low_ordering);
360        assert!(!config.use_market_order_acks);
361        assert!(!config.oto_full_trigger);
362        assert_eq!(config.price_protection_points, 0);
363    }
364
365    #[rstest]
366    fn test_to_matching_engine_config_forwards_matching_knobs() {
367        let config = SandboxExecutionClientConfig {
368            queue_position: true,
369            order_priority_reset_policy: OrderPriorityResetPolicy::AnyModify,
370            liquidity_consumption: true,
371            bar_adaptive_high_low_ordering: true,
372            use_market_order_acks: true,
373            oto_full_trigger: true,
374            price_protection_points: 100,
375            ..SandboxExecutionClientConfig::default()
376        };
377        let engine_config = config.to_matching_engine_config();
378
379        assert!(engine_config.queue_position);
380        assert_eq!(
381            engine_config.order_priority_reset_policy,
382            OrderPriorityResetPolicy::AnyModify
383        );
384        assert!(engine_config.liquidity_consumption);
385        assert!(engine_config.bar_adaptive_high_low_ordering);
386        assert!(engine_config.use_market_order_acks);
387        assert!(engine_config.oto_full_trigger);
388        assert_eq!(engine_config.price_protection_points, Some(100));
389    }
390
391    #[rstest]
392    fn test_exec_config_toml_margin_model_is_runtime_only() {
393        let deserialized =
394            toml::from_str::<SandboxExecutionClientConfig>("margin_model = 'custom'");
395
396        let config = SandboxExecutionClientConfig {
397            margin_model: Some(MarginModelAny::default()),
398            ..Default::default()
399        };
400
401        let serialized = toml::Value::try_from(&config);
402
403        assert!(
404            deserialized
405                .unwrap_err()
406                .to_string()
407                .contains("margin_model must be configured at runtime")
408        );
409        assert!(
410            serialized
411                .unwrap_err()
412                .to_string()
413                .contains("margin_model is runtime-only")
414        );
415    }
416
417    #[rstest]
418    fn test_exec_config_toml_rejects_fill_model_field() {
419        let result =
420            toml::from_str::<SandboxExecutionClientConfig>("fill_model = \"runtime-only\"");
421
422        assert!(result.is_err());
423    }
424
425    #[rstest]
426    fn test_exec_config_toml_rejects_fee_model_field() {
427        let result = toml::from_str::<SandboxExecutionClientConfig>("fee_model = \"runtime-only\"");
428
429        assert!(result.is_err());
430    }
431
432    #[rstest]
433    fn test_exec_config_toml_rejects_latency_model_field() {
434        let result =
435            toml::from_str::<SandboxExecutionClientConfig>("latency_model = \"runtime-only\"");
436
437        assert!(result.is_err());
438    }
439
440    #[rstest]
441    fn test_exec_config_toml_rejects_serializing_runtime_fee_model() {
442        let config = SandboxExecutionClientConfig {
443            fee_model: Some(FeeModelAny::ProbabilityPrice(
444                ProbabilityPriceFeeModel::new(dec!(0.01), dec!(0.02)),
445            )),
446            ..SandboxExecutionClientConfig::default()
447        };
448
449        let result = toml::Value::try_from(&config);
450
451        assert!(result.is_err());
452    }
453
454    #[rstest]
455    fn test_exec_config_toml_rejects_serializing_runtime_fill_model() {
456        let config = SandboxExecutionClientConfig {
457            fill_model: Some(FillModelAny::Default(Default::default())),
458            ..SandboxExecutionClientConfig::default()
459        };
460
461        let result = toml::Value::try_from(&config);
462
463        assert!(result.is_err());
464    }
465
466    #[rstest]
467    fn test_exec_config_toml_rejects_serializing_runtime_latency_model() {
468        let config = SandboxExecutionClientConfig {
469            latency_model: Some(LatencyModelAny::Static(StaticLatencyModel::new(
470                DurationNanos::ZERO,
471                DurationNanos::ZERO,
472                DurationNanos::ZERO,
473                DurationNanos::ZERO,
474            ))),
475            ..SandboxExecutionClientConfig::default()
476        };
477
478        let result = toml::Value::try_from(&config);
479
480        assert!(result.is_err());
481    }
482
483    #[rstest]
484    #[case::same_currency(vec![Money::from("100 USD"), Money::from("200 USD")], true)]
485    #[case::same_balance(vec![Money::from("100 USD"), Money::from("100 USD")], true)]
486    #[case::distinct(vec![Money::from("100 USD"), Money::from("200 EUR")], false)]
487    #[case::empty(vec![], false)]
488    fn test_starting_balance_currency_uniqueness(
489        #[case] starting_balances: Vec<Money>,
490        #[case] duplicate: bool,
491    ) {
492        let config = SandboxExecutionClientConfig {
493            starting_balances: starting_balances.clone(),
494            ..Default::default()
495        };
496
497        let expected = if duplicate {
498            Err(ConfigError::duplicate("starting_balances", None))
499        } else {
500            Ok(())
501        };
502
503        assert_eq!(config.validate(), expected);
504        assert_eq!(config.starting_balances, starting_balances);
505    }
506}