Skip to main content

nautilus_architect_ax/
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 structures for the AX Exchange adapter.
17
18#[cfg(test)]
19use nautilus_core::string::secret::REDACTED;
20use nautilus_core::string::secret::SecretString;
21use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
22use nautilus_model::identifiers::AccountId;
23use nautilus_network::{
24    transport::TransportError,
25    websocket::{TransportBackend, proxy::ProxyUrl},
26};
27use serde::{Deserialize, Serialize};
28
29use crate::common::{credential::credential_env_vars, enums::AxEnvironment};
30
31fn validate_proxy_url(value: Option<&SecretString>) -> Result<(), TransportError> {
32    if let Some(value) = value {
33        ProxyUrl::parse(value.expose_secret().to_owned())?;
34    }
35
36    Ok(())
37}
38
39/// Configuration for the AX Exchange live data client.
40#[cfg_attr(
41    feature = "python",
42    pyo3::pyclass(module = "nautilus_trader.adapters.architect_ax", from_py_object)
43)]
44#[cfg_attr(
45    feature = "python",
46    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.architect_ax")
47)]
48#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
49#[serde(default, deny_unknown_fields)]
50pub struct AxDataClientConfig {
51    /// Optional API key for authenticated REST/WebSocket requests.
52    pub api_key: Option<SecretString>,
53    /// Optional API secret for authenticated REST/WebSocket requests.
54    pub api_secret: Option<SecretString>,
55    /// Trading environment (Sandbox or Production).
56    #[builder(default)]
57    pub environment: AxEnvironment,
58    /// Optional override for the REST base URL.
59    pub base_url_http: Option<String>,
60    /// Optional override for the public WebSocket URL.
61    pub base_url_ws_public: Option<String>,
62    /// Reserved and unused. Configure the private WebSocket on `AxExecutionClientConfig`.
63    pub base_url_ws_private: Option<String>,
64    /// Optional proxy URL for HTTP and WebSocket transports.
65    pub proxy_url: Option<SecretString>,
66    /// REST timeout in seconds.
67    #[builder(default = 60)]
68    pub http_timeout_secs: u64,
69    /// Maximum retry attempts for REST requests.
70    #[builder(default = 3)]
71    pub max_retries: u32,
72    /// Initial retry backoff in milliseconds.
73    #[builder(default = 1_000)]
74    pub retry_delay_initial_ms: u64,
75    /// Maximum retry backoff in milliseconds.
76    #[builder(default = 10_000)]
77    pub retry_delay_max_ms: u64,
78    /// Heartbeat interval (seconds) for WebSocket clients.
79    #[builder(default = 20)]
80    pub heartbeat_interval_secs: u64,
81    /// Reserved and unused; AX bearer authentication sends no receive window.
82    #[builder(default = 5_000)]
83    pub recv_window_ms: u64,
84    /// Interval (minutes) for instrument refresh from REST.
85    #[builder(default = 60)]
86    pub update_instruments_interval_mins: u64,
87    /// Funding rate poll interval in minutes.
88    #[builder(default = 15)]
89    pub funding_rate_poll_interval_mins: u64,
90    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
91    /// snapshot in seconds.
92    ///
93    /// Set to 0 to disable snapshot deadlines.
94    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
95    pub book_snapshot_timeout_secs: u64,
96    /// WebSocket transport backend.
97    ///
98    /// Defaults to `Sockudo` when `transport-sockudo` is enabled, otherwise `Tungstenite`.
99    #[builder(default)]
100    pub transport_backend: TransportBackend,
101}
102
103#[cfg(feature = "python")]
104nautilus_core::impl_pyo3_config_getters!(AxDataClientConfig {
105    environment: AxEnvironment,
106    base_url_http: Option<String>,
107    base_url_ws_public: Option<String>,
108    base_url_ws_private: Option<String>,
109    http_timeout_secs: u64,
110    max_retries: u32,
111    retry_delay_initial_ms: u64,
112    retry_delay_max_ms: u64,
113    heartbeat_interval_secs: u64,
114    recv_window_ms: u64,
115    update_instruments_interval_mins: u64,
116    funding_rate_poll_interval_mins: u64,
117    book_snapshot_timeout_secs: u64,
118    transport_backend: TransportBackend,
119});
120
121impl Default for AxDataClientConfig {
122    fn default() -> Self {
123        Self::builder().build()
124    }
125}
126
127impl AxDataClientConfig {
128    /// Creates a configuration with default values.
129    #[must_use]
130    pub fn new() -> Self {
131        Self::default()
132    }
133
134    pub(crate) fn validate_proxy_url(&self) -> Result<(), TransportError> {
135        validate_proxy_url(self.proxy_url.as_ref())
136    }
137
138    /// Returns `true` if both API key and secret are available.
139    #[must_use]
140    pub fn has_api_credentials(&self) -> bool {
141        let (key_var, secret_var) = credential_env_vars();
142        let has_key = self.api_key.is_some() || std::env::var(key_var).is_ok();
143        let has_secret = self.api_secret.is_some() || std::env::var(secret_var).is_ok();
144        has_key && has_secret
145    }
146
147    /// Returns the REST base URL, considering overrides and environment.
148    #[must_use]
149    pub fn http_base_url(&self) -> String {
150        self.base_url_http
151            .clone()
152            .unwrap_or_else(|| self.environment.http_url().to_string())
153    }
154
155    /// Returns the public WebSocket URL, considering overrides and environment.
156    #[must_use]
157    pub fn ws_public_url(&self) -> String {
158        self.base_url_ws_public
159            .clone()
160            .unwrap_or_else(|| self.environment.ws_md_url().to_string())
161    }
162
163    /// Returns the private WebSocket URL, considering overrides and environment.
164    #[must_use]
165    pub fn ws_private_url(&self) -> String {
166        self.base_url_ws_private
167            .clone()
168            .unwrap_or_else(|| self.environment.ws_orders_url().to_string())
169    }
170}
171
172/// Configuration for the AX Exchange live execution client.
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)]
181#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
182#[serde(default, deny_unknown_fields)]
183pub struct AxExecutionClientConfig {
184    /// The account ID for the client.
185    #[builder(default = AccountId::from("AX-001"))]
186    pub account_id: AccountId,
187    /// API key for authenticated requests.
188    pub api_key: Option<SecretString>,
189    /// API secret for authenticated requests.
190    pub api_secret: Option<SecretString>,
191    /// Trading environment (Sandbox or Production).
192    #[builder(default)]
193    pub environment: AxEnvironment,
194    /// Optional override for the REST base URL.
195    pub base_url_http: Option<String>,
196    /// Optional override for the orders REST base URL.
197    pub base_url_orders: Option<String>,
198    /// Optional override for the private WebSocket URL.
199    pub base_url_ws_private: Option<String>,
200    /// Optional proxy URL for HTTP and WebSocket transports.
201    pub proxy_url: Option<SecretString>,
202    /// REST timeout in seconds.
203    #[builder(default = 60)]
204    pub http_timeout_secs: u64,
205    /// Maximum retry attempts for REST requests.
206    #[builder(default = 3)]
207    pub max_retries: u32,
208    /// Initial retry backoff in milliseconds.
209    #[builder(default = 1_000)]
210    pub retry_delay_initial_ms: u64,
211    /// Maximum retry backoff in milliseconds.
212    #[builder(default = 10_000)]
213    pub retry_delay_max_ms: u64,
214    /// Heartbeat interval (seconds) for WebSocket clients.
215    #[builder(default = 30)]
216    pub heartbeat_interval_secs: u64,
217    /// Reserved and unused; AX bearer authentication sends no receive window.
218    #[builder(default = 5_000)]
219    pub recv_window_ms: u64,
220    /// Cancel all open orders when the orders WebSocket disconnects.
221    #[builder(default)]
222    pub cancel_on_disconnect: bool,
223    /// WebSocket transport backend.
224    ///
225    /// Defaults to `Sockudo` when `transport-sockudo` is enabled, otherwise `Tungstenite`.
226    #[builder(default)]
227    pub transport_backend: TransportBackend,
228}
229
230#[cfg(feature = "python")]
231nautilus_core::impl_pyo3_config_getters!(AxExecutionClientConfig {
232    account_id: AccountId,
233    environment: AxEnvironment,
234    base_url_http: Option<String>,
235    base_url_orders: Option<String>,
236    base_url_ws_private: Option<String>,
237    http_timeout_secs: u64,
238    max_retries: u32,
239    retry_delay_initial_ms: u64,
240    retry_delay_max_ms: u64,
241    heartbeat_interval_secs: u64,
242    recv_window_ms: u64,
243    cancel_on_disconnect: bool,
244    transport_backend: TransportBackend,
245});
246
247impl Default for AxExecutionClientConfig {
248    fn default() -> Self {
249        Self::builder().build()
250    }
251}
252
253impl AxExecutionClientConfig {
254    /// Creates a configuration with default values.
255    #[must_use]
256    pub fn new() -> Self {
257        Self::default()
258    }
259
260    pub(crate) fn validate_proxy_url(&self) -> Result<(), TransportError> {
261        validate_proxy_url(self.proxy_url.as_ref())
262    }
263
264    /// Returns `true` if both API key and secret are available.
265    #[must_use]
266    pub fn has_api_credentials(&self) -> bool {
267        let (key_var, secret_var) = credential_env_vars();
268        let has_key = self.api_key.is_some() || std::env::var(key_var).is_ok();
269        let has_secret = self.api_secret.is_some() || std::env::var(secret_var).is_ok();
270        has_key && has_secret
271    }
272
273    /// Returns the REST base URL, considering overrides and environment.
274    #[must_use]
275    pub fn http_base_url(&self) -> String {
276        self.base_url_http
277            .clone()
278            .unwrap_or_else(|| self.environment.http_url().to_string())
279    }
280
281    /// Returns the orders REST base URL, considering overrides and environment.
282    #[must_use]
283    pub fn orders_base_url(&self) -> String {
284        self.base_url_orders
285            .clone()
286            .unwrap_or_else(|| self.environment.orders_url().to_string())
287    }
288
289    /// Returns the private WebSocket URL, considering overrides and environment.
290    #[must_use]
291    pub fn ws_private_url(&self) -> String {
292        self.base_url_ws_private
293            .clone()
294            .unwrap_or_else(|| self.environment.ws_orders_url().to_string())
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use rstest::rstest;
301
302    use super::*;
303    use crate::common::consts::{
304        AX_HTTP_SANDBOX_URL, AX_HTTP_URL, AX_ORDERS_SANDBOX_URL, AX_ORDERS_URL, AX_WS_PRIVATE_URL,
305        AX_WS_PUBLIC_URL, AX_WS_SANDBOX_PRIVATE_URL, AX_WS_SANDBOX_PUBLIC_URL,
306    };
307
308    #[rstest]
309    fn test_data_config_sandbox_urls_match_consts() {
310        let config = AxDataClientConfig::builder()
311            .environment(AxEnvironment::Sandbox)
312            .build();
313        assert_eq!(config.http_base_url(), AX_HTTP_SANDBOX_URL);
314        assert_eq!(config.ws_public_url(), AX_WS_SANDBOX_PUBLIC_URL);
315        assert_eq!(config.ws_private_url(), AX_WS_SANDBOX_PRIVATE_URL);
316    }
317
318    #[rstest]
319    fn test_data_config_production_urls_match_consts() {
320        let config = AxDataClientConfig::builder()
321            .environment(AxEnvironment::Production)
322            .build();
323        assert_eq!(config.http_base_url(), AX_HTTP_URL);
324        assert_eq!(config.ws_public_url(), AX_WS_PUBLIC_URL);
325        assert_eq!(config.ws_private_url(), AX_WS_PRIVATE_URL);
326    }
327
328    #[rstest]
329    fn test_data_config_url_overrides() {
330        let config = AxDataClientConfig::builder()
331            .base_url_http("http://custom".to_string())
332            .base_url_ws_public("ws://custom-pub".to_string())
333            .base_url_ws_private("ws://custom-priv".to_string())
334            .build();
335        assert_eq!(config.http_base_url(), "http://custom");
336        assert_eq!(config.ws_public_url(), "ws://custom-pub");
337        assert_eq!(config.ws_private_url(), "ws://custom-priv");
338    }
339
340    #[rstest]
341    fn test_exec_config_sandbox_urls_match_consts() {
342        let config = AxExecutionClientConfig::builder()
343            .environment(AxEnvironment::Sandbox)
344            .build();
345        assert_eq!(config.http_base_url(), AX_HTTP_SANDBOX_URL);
346        assert_eq!(config.orders_base_url(), AX_ORDERS_SANDBOX_URL);
347        assert_eq!(config.ws_private_url(), AX_WS_SANDBOX_PRIVATE_URL);
348    }
349
350    #[rstest]
351    fn test_exec_config_production_urls_match_consts() {
352        let config = AxExecutionClientConfig::builder()
353            .environment(AxEnvironment::Production)
354            .build();
355        assert_eq!(config.http_base_url(), AX_HTTP_URL);
356        assert_eq!(config.orders_base_url(), AX_ORDERS_URL);
357        assert_eq!(config.ws_private_url(), AX_WS_PRIVATE_URL);
358    }
359
360    #[rstest]
361    fn test_exec_config_cancel_on_disconnect_default_false() {
362        let config = AxExecutionClientConfig::default();
363        assert!(!config.cancel_on_disconnect);
364    }
365
366    #[rstest]
367    fn test_exec_config_cancel_on_disconnect_enabled() {
368        let config = AxExecutionClientConfig::builder()
369            .cancel_on_disconnect(true)
370            .build();
371        assert!(config.cancel_on_disconnect);
372    }
373
374    #[rstest]
375    fn test_default_environment_is_sandbox() {
376        let data = AxDataClientConfig::default();
377        assert_eq!(data.environment, AxEnvironment::Sandbox);
378
379        let exec = AxExecutionClientConfig::default();
380        assert_eq!(exec.environment, AxEnvironment::Sandbox);
381    }
382
383    #[rstest]
384    fn test_data_config_toml_minimal() {
385        let config: AxDataClientConfig = toml::from_str(
386            r#"
387environment = "PRODUCTION"
388http_timeout_secs = 30
389heartbeat_interval_secs = 10
390update_instruments_interval_mins = 5
391book_snapshot_timeout_secs = 4
392"#,
393        )
394        .unwrap();
395
396        assert_eq!(config.environment, AxEnvironment::Production);
397        assert_eq!(config.http_timeout_secs, 30);
398        assert_eq!(config.heartbeat_interval_secs, 10);
399        assert_eq!(config.update_instruments_interval_mins, 5);
400        assert_eq!(config.book_snapshot_timeout_secs, 4);
401    }
402
403    #[rstest]
404    fn test_data_config_toml_empty_uses_book_snapshot_timeout_default() {
405        let config: AxDataClientConfig = toml::from_str("").unwrap();
406
407        assert_eq!(config.book_snapshot_timeout_secs, 10);
408    }
409
410    #[rstest]
411    fn test_exec_config_toml_empty_uses_defaults() {
412        let config: AxExecutionClientConfig = toml::from_str("").unwrap();
413        let expected = AxExecutionClientConfig::default();
414        assert_eq!(config.account_id, expected.account_id);
415        assert_eq!(config.environment, expected.environment);
416        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
417        assert_eq!(
418            config.heartbeat_interval_secs,
419            expected.heartbeat_interval_secs,
420        );
421        assert_eq!(config.recv_window_ms, expected.recv_window_ms);
422        assert_eq!(config.cancel_on_disconnect, expected.cancel_on_disconnect);
423        assert_eq!(config.transport_backend, expected.transport_backend);
424    }
425
426    #[rstest]
427    #[case("socks5://127.0.0.1:1080")]
428    #[case("socks5h://127.0.0.1:1080")]
429    #[case("socks4://127.0.0.1:1080")]
430    #[case("socks4a://127.0.0.1:1080")]
431    fn test_managed_configs_reject_socks_proxies(#[case] proxy_url: &str) {
432        let data = AxDataClientConfig {
433            proxy_url: Some(proxy_url.into()),
434            ..Default::default()
435        };
436
437        let execution = AxExecutionClientConfig {
438            proxy_url: Some(proxy_url.into()),
439            ..Default::default()
440        };
441
442        assert!(data.validate_proxy_url().is_err());
443        assert!(execution.validate_proxy_url().is_err());
444    }
445
446    #[rstest]
447    fn test_managed_configs_accept_http_proxy() {
448        let data = AxDataClientConfig {
449            proxy_url: Some("http://127.0.0.1:8080".into()),
450            ..Default::default()
451        };
452
453        let execution = AxExecutionClientConfig {
454            proxy_url: Some("http://127.0.0.1:8080".into()),
455            ..Default::default()
456        };
457
458        assert!(data.validate_proxy_url().is_ok());
459        assert!(execution.validate_proxy_url().is_ok());
460    }
461
462    #[rstest]
463    fn test_config_debug_redacts_credentials() {
464        let data = AxDataClientConfig {
465            api_key: Some("data-key".into()),
466            api_secret: Some("data-secret".into()),
467            proxy_url: Some("http://user:data-proxy@localhost".into()),
468            ..Default::default()
469        };
470        let execution = AxExecutionClientConfig {
471            api_key: Some("exec-key".into()),
472            api_secret: Some("exec-secret".into()),
473            proxy_url: Some("http://user:exec-proxy@localhost".into()),
474            ..Default::default()
475        };
476
477        let formatted = format!("{data:?} {execution:?}");
478
479        assert_eq!(formatted.matches(REDACTED).count(), 6);
480
481        for secret in [
482            "data-key",
483            "data-secret",
484            "data-proxy",
485            "exec-key",
486            "exec-secret",
487            "exec-proxy",
488        ] {
489            assert!(!formatted.contains(secret));
490        }
491    }
492}