Skip to main content

nautilus_okx/
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 OKX adapter.
17
18use nautilus_common::config::{ConfigError, ConfigResult, check_range, check_unique_values};
19use nautilus_core::string::secret::SecretString;
20use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
21use nautilus_model::{enums::OmsType, identifiers::AccountId};
22use nautilus_network::websocket::TransportBackend;
23use serde::{Deserialize, Serialize};
24
25use crate::common::{
26    credential::credential_env_vars,
27    enums::{
28        OKXContractType, OKXEnvironment, OKXInstrumentType, OKXMarginMode, OKXRegion, OKXVipLevel,
29    },
30    urls::{
31        get_http_base_url, get_ws_base_url_business, get_ws_base_url_private,
32        get_ws_base_url_public,
33    },
34};
35
36/// Configuration for the OKX data client.
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.okx", from_py_object)
42)]
43#[cfg_attr(
44    feature = "python",
45    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
46)]
47pub struct OKXDataClientConfig {
48    /// Optional API key for authenticated endpoints.
49    pub api_key: Option<SecretString>,
50    /// Optional API secret for authenticated endpoints.
51    pub api_secret: Option<SecretString>,
52    /// Optional API passphrase for authenticated endpoints.
53    pub api_passphrase: Option<SecretString>,
54    /// Instrument types to load and subscribe to.
55    #[builder(default = vec![OKXInstrumentType::Spot])]
56    pub instrument_types: Vec<OKXInstrumentType>,
57    /// Contract type filter applied to loaded instruments.
58    pub contract_types: Option<Vec<OKXContractType>>,
59    /// Whether to load spread trading instruments from the separate spread endpoint.
60    #[builder(default)]
61    pub load_spreads: bool,
62    /// Instrument families to load (e.g., "BTC-USD", "ETH-USD").
63    /// Required for OPTION; optional for FUTURES/SWAP. For EVENTS, values are series IDs.
64    /// Filtered EVENTS and derivatives require separate clients. Ignored for SPOT/MARGIN.
65    pub instrument_families: Option<Vec<String>>,
66    /// The API environment (live or demo).
67    #[builder(default)]
68    pub environment: OKXEnvironment,
69    /// The API region (global, EEA, or US).
70    #[builder(default)]
71    pub region: OKXRegion,
72    /// Optional override for the HTTP base URL.
73    pub base_url_http: Option<String>,
74    /// Optional override for the public WebSocket URL.
75    pub base_url_ws_public: Option<String>,
76    /// Optional override for the business WebSocket URL.
77    pub base_url_ws_business: Option<String>,
78    /// Optional proxy URL for HTTP and WebSocket transports.
79    pub proxy_url: Option<SecretString>,
80    /// Timeout per HTTP attempt in seconds.
81    /// The retry budget is the greater of this timeout and 180 seconds.
82    #[builder(default = 60)]
83    pub http_timeout_secs: u64,
84    /// Maximum retry attempts for requests.
85    #[builder(default = 3)]
86    pub max_retries: u32,
87    /// Initial retry delay in milliseconds.
88    #[builder(default = 1_000)]
89    pub retry_delay_initial_ms: u64,
90    /// Maximum retry delay in milliseconds.
91    #[builder(default = 10_000)]
92    pub retry_delay_max_ms: u64,
93    /// Interval for reconciling instruments from the REST API in minutes.
94    ///
95    /// Set to 0 to disable periodic reconciliation. WebSocket instrument
96    /// updates are always applied regardless of this interval.
97    #[builder(default = 60)]
98    pub update_instruments_interval_mins: u64,
99    /// Interval for checking order book feed staleness in seconds.
100    #[builder(default = 5)]
101    pub book_stale_check_interval_secs: u64,
102    /// Maximum time without order book updates before emitting a stale signal in seconds.
103    ///
104    /// Set to 0 to disable. Quiet markets can idle without book changes.
105    #[builder(default = 30)]
106    pub book_stale_threshold_secs: u64,
107    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
108    /// snapshot in seconds.
109    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
110    pub book_snapshot_timeout_secs: u64,
111    /// Optional VIP level that selects book channels.
112    /// VIP4 and above require complete API credentials and venue permission.
113    pub vip_level: Option<OKXVipLevel>,
114    /// WebSocket transport backend (defaults to `Sockudo`).
115    #[builder(default)]
116    pub transport_backend: TransportBackend,
117}
118
119#[cfg(feature = "python")]
120nautilus_core::impl_pyo3_config_getters!(OKXDataClientConfig {
121    instrument_types: Vec<OKXInstrumentType>,
122    contract_types: Option<Vec<OKXContractType>>,
123    instrument_families: Option<Vec<String>>,
124    environment: OKXEnvironment,
125    region: OKXRegion,
126    base_url_http: Option<String>,
127    base_url_ws_public: Option<String>,
128    base_url_ws_business: Option<String>,
129    http_timeout_secs: u64,
130    max_retries: u32,
131    retry_delay_initial_ms: u64,
132    retry_delay_max_ms: u64,
133    update_instruments_interval_mins: u64,
134    book_stale_check_interval_secs: u64,
135    book_stale_threshold_secs: u64,
136    book_snapshot_timeout_secs: u64,
137    vip_level: Option<OKXVipLevel>,
138    load_spreads: bool,
139    transport_backend: TransportBackend,
140});
141
142impl Default for OKXDataClientConfig {
143    fn default() -> Self {
144        Self::builder().build()
145    }
146}
147
148impl OKXDataClientConfig {
149    /// Creates a new configuration with default settings.
150    #[must_use]
151    pub fn new() -> Self {
152        Self::default()
153    }
154
155    /// Validates instrument selections, authentication requirements, and retry delays.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if selections are duplicated, blank, or conflicting, required settings
160    /// are missing, or retry delays are invalid.
161    pub fn validate(&self) -> ConfigResult<()> {
162        validate_instrument_selections(
163            &self.instrument_types,
164            self.contract_types.as_deref(),
165            self.instrument_families.as_deref(),
166        )?;
167        validate_retry_delays(self.retry_delay_initial_ms, self.retry_delay_max_ms)?;
168
169        if self
170            .vip_level
171            .is_some_and(|level| level >= OKXVipLevel::Vip4)
172            && !self.has_api_credentials()
173        {
174            return Err(ConfigError::dependency(
175                "vip_level",
176                "api_key, api_secret, api_passphrase",
177                "VIP book channels require authentication",
178            ));
179        }
180
181        Ok(())
182    }
183
184    /// Returns whether all credential fields have non-blank config or environment values.
185    /// Explicit blank values do not fall back to environment variables.
186    #[must_use]
187    pub fn has_api_credentials(&self) -> bool {
188        let (key_var, secret_var, passphrase_var) = credential_env_vars();
189        let has_key = has_credential(self.api_key.as_ref(), key_var);
190        let has_secret = has_credential(self.api_secret.as_ref(), secret_var);
191        let has_passphrase = has_credential(self.api_passphrase.as_ref(), passphrase_var);
192        has_key && has_secret && has_passphrase
193    }
194
195    /// Returns the HTTP base URL, falling back to the region default when unset.
196    #[must_use]
197    pub fn http_base_url(&self) -> String {
198        self.base_url_http
199            .clone()
200            .unwrap_or_else(|| get_http_base_url(self.region).to_string())
201    }
202
203    /// Returns the public WebSocket URL, respecting the region, environment, and overrides.
204    #[must_use]
205    pub fn ws_public_url(&self) -> String {
206        self.base_url_ws_public
207            .clone()
208            .unwrap_or_else(|| get_ws_base_url_public(self.region, self.environment).to_string())
209    }
210
211    /// Returns the business WebSocket URL, respecting the region, environment, and overrides.
212    #[must_use]
213    pub fn ws_business_url(&self) -> String {
214        self.base_url_ws_business
215            .clone()
216            .unwrap_or_else(|| get_ws_base_url_business(self.region, self.environment).to_string())
217    }
218
219    /// Returns `true` when the business WebSocket should be instantiated.
220    ///
221    /// The business WebSocket carries public candle data and does not
222    /// require authentication, so it is always needed.
223    #[must_use]
224    pub fn requires_business_ws(&self) -> bool {
225        true
226    }
227}
228
229/// Configuration for the OKX execution client.
230#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
231#[serde(default, deny_unknown_fields)]
232#[cfg_attr(
233    feature = "python",
234    pyo3::pyclass(module = "nautilus_trader.adapters.okx", from_py_object)
235)]
236#[cfg_attr(
237    feature = "python",
238    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
239)]
240pub struct OKXExecutionClientConfig {
241    /// The account ID for the client.
242    #[builder(default = AccountId::from("OKX-001"))]
243    pub account_id: AccountId,
244    /// Optional OMS override for the client.
245    /// Defaults to netting with any derivative instrument type, otherwise hedging.
246    pub oms_type: Option<OmsType>,
247    /// Optional API key for authenticated endpoints.
248    pub api_key: Option<SecretString>,
249    /// Optional API secret for authenticated endpoints.
250    pub api_secret: Option<SecretString>,
251    /// Optional API passphrase for authenticated endpoints.
252    pub api_passphrase: Option<SecretString>,
253    /// Instrument types the execution client should support.
254    #[builder(default = vec![OKXInstrumentType::Spot])]
255    pub instrument_types: Vec<OKXInstrumentType>,
256    /// Contract type filter applied to instrument discovery.
257    pub contract_types: Option<Vec<OKXContractType>>,
258    /// Instrument families to load (e.g., "BTC-USD", "ETH-USD").
259    /// Required for OPTION; optional for FUTURES/SWAP. For EVENTS, values are series IDs.
260    /// Filtered EVENTS and derivatives require separate clients. Ignored for SPOT/MARGIN.
261    pub instrument_families: Option<Vec<String>>,
262    /// The API environment (live or demo).
263    #[builder(default)]
264    pub environment: OKXEnvironment,
265    /// The API region (global, EEA, or US).
266    #[builder(default)]
267    pub region: OKXRegion,
268    /// Optional override for the HTTP base URL.
269    pub base_url_http: Option<String>,
270    /// Optional override for the private WebSocket URL.
271    pub base_url_ws_private: Option<String>,
272    /// Optional override for the business WebSocket URL.
273    pub base_url_ws_business: Option<String>,
274    /// Optional proxy URL for HTTP and WebSocket transports.
275    pub proxy_url: Option<SecretString>,
276    /// Timeout per HTTP attempt in seconds.
277    /// The retry budget is the greater of this timeout and 180 seconds.
278    #[builder(default = 60)]
279    pub http_timeout_secs: u64,
280    /// Whether to subscribe to spread order updates from the separate spread channel.
281    #[builder(default)]
282    pub load_spreads: bool,
283    /// Selects MMP-only family cancellation, which is unsupported for ordinary orders.
284    /// Must remain false; true fails validation.
285    #[builder(default)]
286    pub use_mm_mass_cancel: bool,
287    /// Maximum retry attempts for requests.
288    #[builder(default = 3)]
289    pub max_retries: u32,
290    /// Initial retry delay in milliseconds.
291    #[builder(default = 1_000)]
292    pub retry_delay_initial_ms: u64,
293    /// Maximum retry delay in milliseconds.
294    #[builder(default = 10_000)]
295    pub retry_delay_max_ms: u64,
296    /// Optional margin mode (CROSS or ISOLATED) for margin/derivative accounts.
297    pub margin_mode: Option<OKXMarginMode>,
298    /// Enables margin/leverage for SPOT trading when true.
299    /// Selecting MARGIN in `instrument_types` also enables spot margin.
300    #[builder(default)]
301    pub use_spot_margin: bool,
302    /// Optional SPOT `tradeQuoteCcy` override sent on order payloads.
303    ///
304    /// Unset omits the field so OKX uses the quote currency in `instId` (USDC
305    /// on `Crypto-USDC` instruments). Set to `"USD"` to keep trading in USD
306    /// after the USD-to-USDC spot migration. The value must appear in that
307    /// instrument's `tradeQuoteCcyList`.
308    pub spot_trade_quote_ccy: Option<String>,
309    /// Optional WebSocket authentication timeout (seconds), defaulting to
310    /// `AUTHENTICATION_TIMEOUT_SECS` when unset.
311    pub auth_timeout_secs: Option<u64>,
312    /// WebSocket transport backend (defaults to `Sockudo`).
313    #[builder(default)]
314    pub transport_backend: TransportBackend,
315    /// Maximum pages per startup reconciliation history query, capped at 50.
316    ///
317    /// `None` keeps the default cap; `Some(0)` skips history. Pending orders,
318    /// live algo orders, and positions are unaffected. Skipped or truncated
319    /// history marks reports incomplete and reduces recovery coverage.
320    pub max_reconciliation_history_pages: Option<u32>,
321}
322
323#[cfg(feature = "python")]
324nautilus_core::impl_pyo3_config_getters!(OKXExecutionClientConfig {
325    account_id: AccountId,
326    oms_type: Option<OmsType>,
327    instrument_types: Vec<OKXInstrumentType>,
328    contract_types: Option<Vec<OKXContractType>>,
329    instrument_families: Option<Vec<String>>,
330    use_spot_margin: bool,
331    environment: OKXEnvironment,
332    region: OKXRegion,
333    base_url_http: Option<String>,
334    base_url_ws_private: Option<String>,
335    base_url_ws_business: Option<String>,
336    http_timeout_secs: u64,
337    max_retries: u32,
338    retry_delay_initial_ms: u64,
339    retry_delay_max_ms: u64,
340    margin_mode: Option<OKXMarginMode>,
341    load_spreads: bool,
342    auth_timeout_secs: Option<u64>,
343    transport_backend: TransportBackend,
344    spot_trade_quote_ccy: Option<String>,
345    max_reconciliation_history_pages: Option<u32>,
346});
347
348impl Default for OKXExecutionClientConfig {
349    fn default() -> Self {
350        Self::builder().build()
351    }
352}
353
354impl OKXExecutionClientConfig {
355    /// Creates a new configuration with default settings.
356    #[must_use]
357    pub fn new() -> Self {
358        Self::default()
359    }
360
361    /// Validates instrument selections, cancellation support, and retry delays.
362    ///
363    /// # Errors
364    ///
365    /// Returns an error if selections are duplicated, blank, or conflicting, required settings
366    /// are missing, retry delays are invalid, or MMP cancellation is enabled.
367    pub fn validate(&self) -> ConfigResult<()> {
368        validate_instrument_selections(
369            &self.instrument_types,
370            self.contract_types.as_deref(),
371            self.instrument_families.as_deref(),
372        )?;
373        validate_retry_delays(self.retry_delay_initial_ms, self.retry_delay_max_ms)?;
374
375        if self.use_mm_mass_cancel {
376            return Err(ConfigError::unsupported_value(
377                "use_mm_mass_cancel",
378                "MMP-only family cancellation does not cancel ordinary orders",
379            ));
380        }
381
382        Ok(())
383    }
384
385    pub(crate) fn has_instrument_filters(&self) -> bool {
386        self.instrument_families
387            .as_ref()
388            .is_some_and(|values| !values.is_empty())
389            || self
390                .contract_types
391                .as_ref()
392                .is_some_and(|values| !values.is_empty())
393    }
394
395    pub(crate) fn uses_spot_margin(&self) -> bool {
396        self.use_spot_margin || self.instrument_types.contains(&OKXInstrumentType::Margin)
397    }
398
399    /// Returns whether all credential fields have non-blank config or environment values.
400    /// Explicit blank values do not fall back to environment variables.
401    #[must_use]
402    pub fn has_api_credentials(&self) -> bool {
403        let (key_var, secret_var, passphrase_var) = credential_env_vars();
404        let has_key = has_credential(self.api_key.as_ref(), key_var);
405        let has_secret = has_credential(self.api_secret.as_ref(), secret_var);
406        let has_passphrase = has_credential(self.api_passphrase.as_ref(), passphrase_var);
407        has_key && has_secret && has_passphrase
408    }
409
410    /// Returns the HTTP base URL, falling back to the region default when unset.
411    #[must_use]
412    pub fn http_base_url(&self) -> String {
413        self.base_url_http
414            .clone()
415            .unwrap_or_else(|| get_http_base_url(self.region).to_string())
416    }
417
418    /// Returns the private WebSocket URL, respecting the region, environment, and overrides.
419    #[must_use]
420    pub fn ws_private_url(&self) -> String {
421        self.base_url_ws_private
422            .clone()
423            .unwrap_or_else(|| get_ws_base_url_private(self.region, self.environment).to_string())
424    }
425
426    /// Returns the business WebSocket URL, respecting the region, environment, and overrides.
427    #[must_use]
428    pub fn ws_business_url(&self) -> String {
429        self.base_url_ws_business
430            .clone()
431            .unwrap_or_else(|| get_ws_base_url_business(self.region, self.environment).to_string())
432    }
433}
434
435fn validate_instrument_selections(
436    instrument_types: &[OKXInstrumentType],
437    contract_types: Option<&[OKXContractType]>,
438    instrument_families: Option<&[String]>,
439) -> ConfigResult<()> {
440    check_unique_values("instrument_types", instrument_types)?;
441
442    if let Some(values) = contract_types {
443        check_unique_values("contract_types", values)?;
444    }
445
446    if let Some(values) = instrument_families {
447        check_unique_values("instrument_families", values)?;
448        if values.iter().any(|value| value.trim().is_empty()) {
449            return Err(ConfigError::invalid_value(
450                "instrument_families",
451                "entries must not be blank",
452            ));
453        }
454    }
455
456    if instrument_types.contains(&OKXInstrumentType::Option)
457        && instrument_families.is_none_or(<[String]>::is_empty)
458    {
459        return Err(ConfigError::dependency(
460            "instrument_types",
461            "instrument_families",
462            "OPTION requires at least one family",
463        ));
464    }
465
466    if instrument_types.contains(&OKXInstrumentType::Events)
467        && instrument_types.iter().any(|value| {
468            matches!(
469                value,
470                OKXInstrumentType::Option | OKXInstrumentType::Swap | OKXInstrumentType::Futures
471            )
472        })
473        && instrument_families.is_some_and(|values| !values.is_empty())
474    {
475        return Err(ConfigError::invalid_value(
476            "instrument_families",
477            "EVENTS series and derivative families require separate clients",
478        ));
479    }
480
481    Ok(())
482}
483
484pub(crate) fn validate_retry_delays(initial_ms: u64, max_ms: u64) -> ConfigResult<()> {
485    check_range("retry_delay_initial_ms", initial_ms > 0, "must be positive")?;
486    check_range(
487        "retry_delay_max_ms",
488        max_ms >= initial_ms,
489        "must be >= retry_delay_initial_ms",
490    )?;
491    check_range(
492        "retry_delay_max_ms",
493        max_ms <= u64::MAX / 1_000_000,
494        "exceeds maximum representable backoff duration",
495    )
496}
497
498fn has_credential(value: Option<&SecretString>, env_var: &str) -> bool {
499    value.map_or_else(
500        || std::env::var(env_var).is_ok_and(|value| !value.trim().is_empty()),
501        |value| !value.expose_secret().trim().is_empty(),
502    )
503}