Skip to main content

nautilus_architect_ax/
factories.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 functions for creating AX Exchange clients and components.
17
18use std::{any::Any, cell::RefCell, rc::Rc};
19
20use nautilus_common::{
21    cache::CacheView,
22    clients::{DataClient, ExecutionClient},
23    clock::Clock,
24    factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
25    live::runner::try_get_exec_event_sender,
26};
27use nautilus_live::ExecutionClientCore;
28use nautilus_model::{
29    enums::{AccountType, OmsType},
30    identifiers::{ClientId, TraderId},
31};
32
33use crate::{
34    common::{
35        consts::{AX, AX_VENUE},
36        credential::Credential,
37    },
38    config::{AxDataClientConfig, AxExecutionClientConfig},
39    data::AxDataClient,
40    execution::AxExecutionClient,
41    http::client::AxHttpClient,
42    websocket::data::AxMdWebSocketClient,
43};
44
45impl ClientConfig for AxDataClientConfig {
46    fn as_any(&self) -> &dyn Any {
47        self
48    }
49}
50
51impl ClientConfig for AxExecutionClientConfig {
52    fn as_any(&self) -> &dyn Any {
53        self
54    }
55}
56
57/// Factory for creating AX Exchange data clients.
58#[derive(Debug, Clone)]
59#[cfg_attr(
60    feature = "python",
61    pyo3::pyclass(module = "nautilus_trader.adapters.architect_ax", from_py_object)
62)]
63#[cfg_attr(
64    feature = "python",
65    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.architect_ax")
66)]
67pub struct AxDataClientFactory;
68
69impl AxDataClientFactory {
70    /// Creates a new [`AxDataClientFactory`] instance.
71    #[must_use]
72    pub const fn new() -> Self {
73        Self
74    }
75}
76
77impl Default for AxDataClientFactory {
78    fn default() -> Self {
79        Self::new()
80    }
81}
82
83impl DataClientFactory for AxDataClientFactory {
84    fn create(
85        &self,
86        name: &str,
87        config: &dyn ClientConfig,
88        _cache: CacheView,
89        _clock: Rc<RefCell<dyn Clock>>,
90    ) -> anyhow::Result<Box<dyn DataClient>> {
91        let ax_config = config
92            .as_any()
93            .downcast_ref::<AxDataClientConfig>()
94            .ok_or_else(|| {
95                anyhow::anyhow!(
96                    "Invalid config type for AxDataClientFactory. Expected AxDataClientConfig, was {config:?}",
97                )
98            })?
99            .clone();
100
101        ax_config
102            .validate_proxy_url()
103            .map_err(|e| anyhow::anyhow!("Invalid AX proxy URL: {e}"))?;
104
105        let client_id = ClientId::from(name);
106
107        let http_client = if ax_config.has_api_credentials() {
108            let credential = Credential::resolve(
109                ax_config.api_key.clone().map(|value| value.into_inner()),
110                ax_config.api_secret.clone().map(|value| value.into_inner()),
111            )
112            .ok_or_else(|| anyhow::anyhow!("API credentials not configured"))?;
113
114            AxHttpClient::with_credentials(
115                credential.api_key().to_string(),
116                credential.api_secret().to_string(),
117                Some(ax_config.http_base_url()),
118                None, // orders_base_url
119                ax_config.http_timeout_secs,
120                ax_config.max_retries,
121                ax_config.retry_delay_initial_ms,
122                ax_config.retry_delay_max_ms,
123                ax_config
124                    .proxy_url
125                    .as_ref()
126                    .map(|url| url.expose_secret().to_owned()),
127            )
128            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?
129        } else {
130            AxHttpClient::new(
131                Some(ax_config.http_base_url()),
132                None, // orders_base_url
133                ax_config.http_timeout_secs,
134                ax_config.max_retries,
135                ax_config.retry_delay_initial_ms,
136                ax_config.retry_delay_max_ms,
137                ax_config
138                    .proxy_url
139                    .as_ref()
140                    .map(|url| url.expose_secret().to_owned()),
141            )
142            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?
143        };
144
145        let ws_url = ax_config.ws_public_url();
146
147        // Token set during connect
148        let ws_client = AxMdWebSocketClient::without_auth(
149            ws_url,
150            ax_config.heartbeat_interval_secs,
151            ax_config.transport_backend,
152            ax_config
153                .proxy_url
154                .as_ref()
155                .map(|url| url.expose_secret().to_owned()),
156        );
157
158        let client = AxDataClient::new(client_id, ax_config, http_client, ws_client)?;
159        Ok(Box::new(client))
160    }
161
162    fn name(&self) -> &'static str {
163        AX
164    }
165
166    fn config_type(&self) -> &'static str {
167        "AxDataClientConfig"
168    }
169}
170
171/// Factory for creating AX Exchange execution clients.
172#[derive(Debug, Clone)]
173#[cfg_attr(
174    feature = "python",
175    pyo3::pyclass(module = "nautilus_trader.adapters.architect_ax", from_py_object)
176)]
177#[cfg_attr(
178    feature = "python",
179    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.architect_ax")
180)]
181pub struct AxExecutionClientFactory;
182
183impl AxExecutionClientFactory {
184    /// Creates a new [`AxExecutionClientFactory`] instance.
185    #[must_use]
186    pub const fn new() -> Self {
187        Self
188    }
189}
190
191impl Default for AxExecutionClientFactory {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197impl ExecutionClientFactory for AxExecutionClientFactory {
198    fn create(
199        &self,
200        trader_id: TraderId,
201        name: &str,
202        config: &dyn ClientConfig,
203        cache: CacheView,
204        _clock: Rc<RefCell<dyn Clock>>,
205    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
206        let ax_config = config
207            .as_any()
208            .downcast_ref::<AxExecutionClientConfig>()
209            .ok_or_else(|| {
210                anyhow::anyhow!(
211                    "Invalid config type for AxExecutionClientFactory. Expected AxExecutionClientConfig, was {config:?}",
212                )
213            })?
214            .clone();
215
216        // AX uses netting for perpetual futures
217        let oms_type = OmsType::Netting;
218        let account_type = AccountType::Margin;
219
220        let core = ExecutionClientCore::new(
221            trader_id,
222            ClientId::from(name),
223            *AX_VENUE,
224            oms_type,
225            ax_config.account_id,
226            account_type,
227            None, // base_currency
228            cache,
229        );
230
231        let mut client = AxExecutionClient::new(core, ax_config)?;
232
233        if let Some(sender) = try_get_exec_event_sender() {
234            client.set_event_sender(sender);
235        }
236
237        Ok(Box::new(client))
238    }
239
240    fn name(&self) -> &'static str {
241        AX
242    }
243
244    fn config_type(&self) -> &'static str {
245        "AxExecutionClientConfig"
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use nautilus_common::{
252        cache::Cache,
253        clock::VirtualClock,
254        factories::ClientConfig,
255        live::runner::{replace_exec_event_sender, set_data_event_sender},
256        messages::ExecutionEvent,
257    };
258    use nautilus_core::UnixNanos;
259    use nautilus_model::{
260        identifiers::AccountId,
261        types::{AccountBalance, Money},
262    };
263    use rstest::rstest;
264
265    use super::*;
266    use crate::config::AxDataClientConfig;
267
268    #[rstest]
269    fn test_ax_data_client_config_implements_client_config() {
270        let config = AxDataClientConfig::default();
271
272        let boxed_config: Box<dyn ClientConfig> = Box::new(config);
273        let downcasted = boxed_config.as_any().downcast_ref::<AxDataClientConfig>();
274
275        assert!(downcasted.is_some());
276    }
277
278    #[rstest]
279    fn test_ax_data_client_factory_creation() {
280        let factory = AxDataClientFactory::new();
281        assert_eq!(factory.name(), AX);
282        assert_eq!(factory.config_type(), "AxDataClientConfig");
283    }
284
285    #[rstest]
286    fn test_ax_data_client_factory_default() {
287        let factory = AxDataClientFactory;
288        assert_eq!(factory.name(), AX);
289    }
290
291    #[rstest]
292    fn test_managed_factories_reject_socks_proxy() {
293        let proxy_url = Some("socks5://127.0.0.1:1080".into());
294
295        let data_config = AxDataClientConfig {
296            proxy_url: proxy_url.clone(),
297            ..Default::default()
298        };
299
300        let execution_config = AxExecutionClientConfig {
301            proxy_url,
302            ..Default::default()
303        };
304
305        let cache = Rc::new(RefCell::new(Cache::default()));
306        let clock = Rc::new(RefCell::new(VirtualClock::new()));
307        let (data_sender, _data_receiver) = tokio::sync::mpsc::unbounded_channel();
308        set_data_event_sender(data_sender);
309
310        let data_result = AxDataClientFactory::new().create(
311            "AX",
312            &data_config,
313            cache.clone().into(),
314            clock.clone(),
315        );
316
317        let data_error = match data_result {
318            Err(e) => e,
319            Ok(_) => panic!("Expected data factory to reject SOCKS proxy"),
320        };
321
322        let execution_result = AxExecutionClientFactory::new().create(
323            TraderId::from("TESTER-002"),
324            "AX",
325            &execution_config,
326            cache.into(),
327            clock,
328        );
329
330        let execution_error = match execution_result {
331            Err(e) => e,
332            Ok(_) => panic!("Expected execution factory to reject SOCKS proxy"),
333        };
334
335        assert!(data_error.to_string().contains("Invalid AX proxy URL"));
336        assert!(execution_error.to_string().contains("Invalid AX proxy URL"));
337    }
338
339    #[rstest]
340    #[case(false)]
341    #[case(true)]
342    fn test_ax_execution_client_factory_sender(#[case] sender_bound: bool) {
343        std::thread::spawn(move || {
344            let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
345            if sender_bound {
346                replace_exec_event_sender(sender.clone());
347            }
348
349            let account_id = AccountId::from("AX-FACTORY-002");
350            let config = AxExecutionClientConfig {
351                account_id,
352                api_key: Some("test_api_key".into()),
353                api_secret: Some("test_api_secret".into()),
354                ..Default::default()
355            };
356            let cache = Rc::new(RefCell::new(Cache::default()));
357            let clock = Rc::new(RefCell::new(VirtualClock::new()));
358            let mut client = AxExecutionClientFactory::new()
359                .create(
360                    TraderId::from("TESTER-002"),
361                    "AX",
362                    &config,
363                    cache.into(),
364                    clock,
365                )
366                .unwrap();
367            let balances = vec![AccountBalance::new(
368                Money::from("1234.50 USD"),
369                Money::from("234.25 USD"),
370                Money::from("1000.25 USD"),
371            )];
372            let ts_event = UnixNanos::from(123_456);
373
374            if !sender_bound {
375                assert!(try_get_exec_event_sender().is_none());
376                replace_exec_event_sender(sender);
377                client.start().unwrap();
378            }
379
380            client
381                .generate_account_state(balances.clone(), vec![], true, ts_event, None)
382                .unwrap();
383
384            let ExecutionEvent::Account(state) = receiver.try_recv().unwrap() else {
385                panic!("Expected account state");
386            };
387            assert_eq!(state.account_id, account_id);
388            assert_eq!(state.account_type, AccountType::Margin);
389            assert_eq!(state.base_currency, None);
390            assert_eq!(state.balances, balances);
391            assert_eq!(state.margins, vec![]);
392            assert!(state.is_reported);
393            assert_eq!(state.ts_event, ts_event);
394            assert_eq!(state.info, None);
395            assert_eq!(
396                receiver.try_recv().unwrap_err(),
397                tokio::sync::mpsc::error::TryRecvError::Empty
398            );
399        })
400        .join()
401        .unwrap();
402    }
403}