nautilus-common 0.65.0

Common functionality and machinery for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Client factory traits and registries shared by live, sandbox, and backtest runtimes.
//!
//! The traits in this module describe how to construct adapter [`DataClient`] and
//! [`ExecutionClient`] instances from a configuration object, without coupling the
//! definition site to any particular runtime (tokio, native threads, simulated time).
//! Adapters implement these traits in their own crates; the live system kernel and
//! any future backtest registry consume them via the registries below.

use std::{any::Any, cell::RefCell, fmt::Debug, rc::Rc};

use ahash::AHashMap;
use nautilus_model::identifiers::TraderId;

use crate::{
    cache::{Cache, CacheView},
    clients::{DataClient, ExecutionClient},
    clock::Clock,
};

/// Configuration for creating client instances.
///
/// This trait allows different client types to provide their configuration
/// in a type-safe manner while still being usable in generic factory contexts.
pub trait ClientConfig: Debug {
    /// Return the configuration as a trait object.
    fn as_any(&self) -> &dyn Any;
}

/// Factory trait for creating data client instances.
///
/// Implementations of this trait should create specific data client types
/// (e.g., Binance, Bybit, Databento) based on the provided configuration.
pub trait DataClientFactory: Debug {
    /// Create a new data client instance.
    ///
    /// Data clients receive a read-only cache view so adapters can query platform state during
    /// construction without mutating the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if client creation fails.
    fn create(
        &self,
        name: &str,
        config: &dyn ClientConfig,
        cache: CacheView,
        clock: Rc<RefCell<dyn Clock>>,
    ) -> anyhow::Result<Box<dyn DataClient>>;

    /// Returns the name of this factory.
    fn name(&self) -> &str;

    /// Returns the supported configuration type name for this factory.
    fn config_type(&self) -> &str;
}

/// Factory trait for creating execution client instances.
///
/// Implementations of this trait should create specific execution client types
/// (e.g., Binance, Bybit, Interactive Brokers) based on the provided configuration.
pub trait ExecutionClientFactory: Debug {
    /// Create a new execution client instance.
    ///
    /// Execution clients receive a read-only cache view so venue adapters can query platform state
    /// during construction without mutating the cache. The trader ID and clock come from the owning node.
    ///
    /// # Errors
    ///
    /// Returns an error if client creation fails.
    fn create(
        &self,
        trader_id: TraderId,
        name: &str,
        config: &dyn ClientConfig,
        cache: CacheView,
        clock: Rc<RefCell<dyn Clock>>,
    ) -> anyhow::Result<Box<dyn ExecutionClient>>;

    /// Returns the name of this factory.
    fn name(&self) -> &str;

    /// Returns the supported configuration type name for this factory.
    fn config_type(&self) -> &str;
}

/// Factory trait for simulated execution clients owned by the sync core.
///
/// Simulated execution clients may need the mutable cache handle because they host the matching
/// engine and therefore own cache updates that a live venue adapter must not perform.
pub trait SimulatedExecutionClientFactory: Debug {
    /// Create a new simulated execution client instance.
    ///
    /// # Errors
    ///
    /// Returns an error if client creation fails.
    fn create(
        &self,
        trader_id: TraderId,
        name: &str,
        config: &dyn ClientConfig,
        cache: Rc<RefCell<Cache>>,
    ) -> anyhow::Result<Box<dyn ExecutionClient>>;

    /// Returns the name of this factory.
    fn name(&self) -> &str;

    /// Returns the supported configuration type name for this factory.
    fn config_type(&self) -> &str;
}

/// Registry for managing data client factories.
///
/// Allows dynamic registration and lookup of factories by name,
/// enabling a plugin-like architecture for different data providers.
#[derive(Debug, Default)]
pub struct DataClientFactoryRegistry {
    factories: AHashMap<String, Box<dyn DataClientFactory>>,
}

impl DataClientFactoryRegistry {
    /// Creates a new empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            factories: AHashMap::new(),
        }
    }

    /// Registers a data client factory.
    ///
    /// # Errors
    ///
    /// Returns an error if a factory with the same name is already registered.
    pub fn register(
        &mut self,
        name: String,
        factory: Box<dyn DataClientFactory>,
    ) -> anyhow::Result<()> {
        if self.factories.contains_key(&name) {
            anyhow::bail!("Data client factory '{name}' is already registered");
        }

        self.factories.insert(name, factory);
        Ok(())
    }

    /// Gets a registered factory by name.
    ///
    /// # Returns
    ///
    /// The factory if found, None otherwise.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&dyn DataClientFactory> {
        self.factories.get(name).map(std::convert::AsRef::as_ref)
    }

    /// Gets a list of all registered factory names.
    #[must_use]
    pub fn names(&self) -> Vec<&String> {
        self.factories.keys().collect()
    }

    /// Checks if a factory is registered.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.factories.contains_key(name)
    }
}

/// Registry for managing execution client factories.
///
/// Allows dynamic registration and lookup of factories by name,
/// enabling a plugin-like architecture for different execution providers.
#[derive(Debug, Default)]
pub struct ExecutionClientFactoryRegistry {
    factories: AHashMap<String, Box<dyn ExecutionClientFactory>>,
}

impl ExecutionClientFactoryRegistry {
    /// Creates a new empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            factories: AHashMap::new(),
        }
    }

    /// Registers an execution client factory.
    ///
    /// # Errors
    ///
    /// Returns an error if a factory with the same name is already registered.
    pub fn register(
        &mut self,
        name: String,
        factory: Box<dyn ExecutionClientFactory>,
    ) -> anyhow::Result<()> {
        if self.factories.contains_key(&name) {
            anyhow::bail!("Execution client factory '{name}' is already registered");
        }

        self.factories.insert(name, factory);
        Ok(())
    }

    /// Gets a registered factory by name (if found).
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&dyn ExecutionClientFactory> {
        self.factories.get(name).map(std::convert::AsRef::as_ref)
    }

    /// Gets a list of all registered factory names.
    #[must_use]
    pub fn names(&self) -> Vec<&String> {
        self.factories.keys().collect()
    }

    /// Checks if a factory is registered.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.factories.contains_key(name)
    }
}

#[allow(dead_code)]
#[cfg(test)]
mod tests {
    use std::any::Any;

    use rstest::*;

    use super::*;

    #[derive(Debug)]
    struct MockConfig {
        #[allow(dead_code)]
        value: String,
    }

    impl ClientConfig for MockConfig {
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[derive(Debug)]
    struct MockDataClientFactory;

    impl DataClientFactory for MockDataClientFactory {
        fn create(
            &self,
            _name: &str,
            _config: &dyn ClientConfig,
            _cache: CacheView,
            _clock: Rc<RefCell<dyn Clock>>,
        ) -> anyhow::Result<Box<dyn DataClient>> {
            Err(anyhow::anyhow!("Mock factory - not implemented"))
        }

        fn name(&self) -> &'static str {
            "mock"
        }

        fn config_type(&self) -> &'static str {
            "MockConfig"
        }
    }

    #[derive(Debug)]
    struct MockExecutionClientFactory;

    impl ExecutionClientFactory for MockExecutionClientFactory {
        fn create(
            &self,
            _trader_id: TraderId,
            _name: &str,
            _config: &dyn ClientConfig,
            _cache: CacheView,
            _clock: Rc<RefCell<dyn Clock>>,
        ) -> anyhow::Result<Box<dyn ExecutionClient>> {
            Err(anyhow::anyhow!("Mock factory - not implemented"))
        }

        fn name(&self) -> &'static str {
            "mock-exec"
        }

        fn config_type(&self) -> &'static str {
            "MockConfig"
        }
    }

    #[rstest]
    fn test_data_client_factory_registry() {
        let mut registry = DataClientFactoryRegistry::new();

        assert!(registry.names().is_empty());
        assert!(!registry.contains("mock"));
        assert!(registry.get("mock").is_none());

        let factory = Box::new(MockDataClientFactory);
        registry.register("mock".to_string(), factory).unwrap();

        assert_eq!(registry.names().len(), 1);
        assert!(registry.contains("mock"));
        assert!(registry.get("mock").is_some());

        let factory2 = Box::new(MockDataClientFactory);
        let error = registry.register("mock".to_string(), factory2).unwrap_err();
        assert_eq!(
            error.to_string(),
            "Data client factory 'mock' is already registered"
        );
        assert_eq!(
            registry.names().len(),
            1,
            "rejected registration must not be stored"
        );
    }

    #[rstest]
    fn test_execution_client_factory_registry() {
        let mut registry = ExecutionClientFactoryRegistry::new();

        assert!(registry.names().is_empty());
        assert!(!registry.contains("mock-exec"));
        assert!(registry.get("mock-exec").is_none());

        registry
            .register(
                "mock-exec".to_string(),
                Box::new(MockExecutionClientFactory),
            )
            .unwrap();

        assert_eq!(registry.names(), vec![&"mock-exec".to_string()]);
        assert!(registry.contains("mock-exec"));
        assert_eq!(registry.get("mock-exec").unwrap().name(), "mock-exec");
        assert_eq!(
            registry.get("mock-exec").unwrap().config_type(),
            "MockConfig"
        );

        let error = registry
            .register(
                "mock-exec".to_string(),
                Box::new(MockExecutionClientFactory),
            )
            .unwrap_err();

        assert_eq!(
            error.to_string(),
            "Execution client factory 'mock-exec' is already registered"
        );
        assert_eq!(
            registry.names().len(),
            1,
            "rejected registration must not be stored"
        );
    }

    #[rstest]
    fn test_registries_do_not_match_unregistered_names() {
        let mut data_registry = DataClientFactoryRegistry::new();
        let mut execution_registry = ExecutionClientFactoryRegistry::new();

        data_registry
            .register("mock".to_string(), Box::new(MockDataClientFactory))
            .unwrap();
        execution_registry
            .register(
                "mock-exec".to_string(),
                Box::new(MockExecutionClientFactory),
            )
            .unwrap();

        assert!(!data_registry.contains("mock-exec"));
        assert!(data_registry.get("mock-exec").is_none());
        assert!(!execution_registry.contains("mock"));
        assert!(execution_registry.get("mock").is_none());
    }

    #[rstest]
    fn test_default_registries_are_empty() {
        assert!(DataClientFactoryRegistry::default().names().is_empty());
        assert!(ExecutionClientFactoryRegistry::default().names().is_empty());
    }
}