Skip to main content

nautilus_sandbox/
factory.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//! Factory for creating sandbox execution clients.
17
18use std::{any::Any, cell::RefCell, rc::Rc};
19
20use nautilus_common::{
21    cache::Cache,
22    clients::ExecutionClient,
23    clock::Clock,
24    factories::{ClientConfig, SimulatedExecutionClientFactory},
25    live::clock::LiveClock,
26};
27use nautilus_execution::{client::core::ExecutionClientCore, models::fee::FeeModelHandle};
28use nautilus_model::identifiers::{ClientId, TraderId};
29
30use crate::{config::SandboxExecutionClientConfig, execution::SandboxExecutionClient};
31
32impl ClientConfig for SandboxExecutionClientConfig {
33    fn as_any(&self) -> &dyn Any {
34        self
35    }
36}
37
38/// Factory for creating sandbox execution clients.
39#[derive(Debug, Default, Clone)]
40#[cfg_attr(
41    feature = "python",
42    pyo3::pyclass(
43        module = "nautilus_trader.adapters.sandbox",
44        unsendable,
45        from_py_object
46    )
47)]
48#[cfg_attr(
49    feature = "python",
50    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.sandbox")
51)]
52pub struct SandboxExecutionClientFactory;
53
54impl SandboxExecutionClientFactory {
55    /// Creates a new [`SandboxExecutionClientFactory`] instance.
56    #[must_use]
57    pub const fn new() -> Self {
58        Self
59    }
60
61    /// Returns a factory using the runtime fee model factory, overriding `config.fee_model`.
62    ///
63    /// The function is called once per client and should return a fresh model
64    /// handle to keep account-specific state isolated.
65    #[must_use]
66    pub const fn with_fee_model_factory(
67        self,
68        factory: fn() -> FeeModelHandle,
69    ) -> impl SimulatedExecutionClientFactory + Clone {
70        ConfiguredSandboxExecutionClientFactory {
71            fee_model_factory: Some(factory),
72        }
73    }
74}
75
76impl SimulatedExecutionClientFactory for SandboxExecutionClientFactory {
77    fn create(
78        &self,
79        trader_id: TraderId,
80        name: &str,
81        config: &dyn ClientConfig,
82        cache: Rc<RefCell<Cache>>,
83    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
84        ConfiguredSandboxExecutionClientFactory {
85            fee_model_factory: None,
86        }
87        .create(trader_id, name, config, cache)
88    }
89
90    fn name(&self) -> &'static str {
91        "SANDBOX"
92    }
93
94    fn config_type(&self) -> &'static str {
95        "SandboxExecutionClientConfig"
96    }
97}
98
99#[derive(Debug, Clone)]
100struct ConfiguredSandboxExecutionClientFactory {
101    fee_model_factory: Option<fn() -> FeeModelHandle>,
102}
103
104impl SimulatedExecutionClientFactory for ConfiguredSandboxExecutionClientFactory {
105    fn create(
106        &self,
107        trader_id: TraderId,
108        name: &str,
109        config: &dyn ClientConfig,
110        cache: Rc<RefCell<Cache>>,
111    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
112        let sandbox_config = config
113            .as_any()
114            .downcast_ref::<SandboxExecutionClientConfig>()
115            .ok_or_else(|| {
116                anyhow::anyhow!(
117                    "Invalid config type for SandboxExecutionClientFactory. Expected SandboxExecutionClientConfig, was {config:?}",
118                )
119            })?
120            .clone();
121
122        let client_id = ClientId::from(name);
123        let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(LiveClock::default()));
124
125        let core = ExecutionClientCore::new(
126            trader_id,
127            client_id,
128            sandbox_config.venue,
129            sandbox_config.oms_type,
130            sandbox_config.account_id,
131            sandbox_config.account_type,
132            sandbox_config.base_currency,
133            cache.clone(),
134        );
135
136        let client = match self.fee_model_factory {
137            Some(factory) => SandboxExecutionClient::new_with_fee_model(
138                core,
139                sandbox_config,
140                clock,
141                cache,
142                factory(),
143            )?,
144            None => SandboxExecutionClient::new(core, sandbox_config, clock, cache)?,
145        };
146        Ok(Box::new(client))
147    }
148
149    fn name(&self) -> &'static str {
150        SandboxExecutionClientFactory.name()
151    }
152
153    fn config_type(&self) -> &'static str {
154        SandboxExecutionClientFactory.config_type()
155    }
156}