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#[expect(
231    clippy::struct_excessive_bools,
232    reason = "independent venue options exposed as flat config fields"
233)]
234#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
235#[serde(default, deny_unknown_fields)]
236#[cfg_attr(
237    feature = "python",
238    pyo3::pyclass(module = "nautilus_trader.adapters.okx", from_py_object)
239)]
240#[cfg_attr(
241    feature = "python",
242    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
243)]
244pub struct OKXExecutionClientConfig {
245    /// The account ID for the client.
246    #[builder(default = AccountId::from("OKX-001"))]
247    pub account_id: AccountId,
248    /// Optional OMS override for the client.
249    /// Defaults to netting with any derivative instrument type, otherwise hedging.
250    pub oms_type: Option<OmsType>,
251    /// Optional API key for authenticated endpoints.
252    pub api_key: Option<SecretString>,
253    /// Optional API secret for authenticated endpoints.
254    pub api_secret: Option<SecretString>,
255    /// Optional API passphrase for authenticated endpoints.
256    pub api_passphrase: Option<SecretString>,
257    /// Instrument types the execution client should support.
258    #[builder(default = vec![OKXInstrumentType::Spot])]
259    pub instrument_types: Vec<OKXInstrumentType>,
260    /// Contract type filter applied to instrument discovery.
261    pub contract_types: Option<Vec<OKXContractType>>,
262    /// Instrument families to load (e.g., "BTC-USD", "ETH-USD").
263    /// Required for OPTION; optional for FUTURES/SWAP. For EVENTS, values are series IDs.
264    /// Filtered EVENTS and derivatives require separate clients. Ignored for SPOT/MARGIN.
265    pub instrument_families: Option<Vec<String>>,
266    /// The API environment (live or demo).
267    #[builder(default)]
268    pub environment: OKXEnvironment,
269    /// The API region (global, EEA, or US).
270    #[builder(default)]
271    pub region: OKXRegion,
272    /// Optional override for the HTTP base URL.
273    pub base_url_http: Option<String>,
274    /// Optional override for the private WebSocket URL.
275    pub base_url_ws_private: Option<String>,
276    /// Optional override for the business WebSocket URL.
277    pub base_url_ws_business: Option<String>,
278    /// Optional proxy URL for HTTP and WebSocket transports.
279    pub proxy_url: Option<SecretString>,
280    /// Timeout per HTTP attempt in seconds.
281    /// The retry budget is the greater of this timeout and 180 seconds.
282    #[builder(default = 60)]
283    pub http_timeout_secs: u64,
284    /// Whether to subscribe to spread order updates from the separate spread channel.
285    #[builder(default)]
286    pub load_spreads: bool,
287    /// Selects MMP-only family cancellation, which is unsupported for ordinary orders.
288    /// Must remain false; true fails validation.
289    #[builder(default)]
290    pub use_mm_mass_cancel: bool,
291    /// Maximum retry attempts for requests.
292    #[builder(default = 3)]
293    pub max_retries: u32,
294    /// Initial retry delay in milliseconds.
295    #[builder(default = 1_000)]
296    pub retry_delay_initial_ms: u64,
297    /// Maximum retry delay in milliseconds.
298    #[builder(default = 10_000)]
299    pub retry_delay_max_ms: u64,
300    /// Optional margin mode (CROSS or ISOLATED) for margin/derivative accounts.
301    pub margin_mode: Option<OKXMarginMode>,
302    /// Enables margin/leverage for SPOT trading when true.
303    /// Selecting MARGIN in `instrument_types` also enables spot margin.
304    #[builder(default)]
305    pub use_spot_margin: bool,
306    /// Optional SPOT `tradeQuoteCcy` override sent on order payloads.
307    ///
308    /// Unset omits the field so OKX uses the quote currency in `instId` (USDC
309    /// on `Crypto-USDC` instruments). Set to `"USD"` to keep trading in USD
310    /// after the USD-to-USDC spot migration. The value must appear in that
311    /// instrument's `tradeQuoteCcyList`.
312    pub spot_trade_quote_ccy: Option<String>,
313    /// Whether to report net spot wallet balances as positions.
314    ///
315    /// Each cached spot pair quoted in `spot_positions_quote_currency` reports the signed `cashBal`
316    /// of its base currency as `LONG` or `SHORT`. The client declares no bulk position coverage for
317    /// those pairs, so a pair without a report keeps its cached position. The client requires a
318    /// NETTING OMS, which a spot-only client must set through `oms_type`.
319    #[builder(default)]
320    pub use_spot_position_reports: bool,
321    /// Quote currency of the spot pairs that report wallet-derived positions.
322    ///
323    /// Only relevant when `use_spot_position_reports` is `true`. A balance is reported on the
324    /// pair quoted in this currency and on no other pair.
325    #[builder(default = "USDT".to_string())]
326    pub spot_positions_quote_currency: String,
327    /// Optional WebSocket authentication timeout (seconds), defaulting to
328    /// `AUTHENTICATION_TIMEOUT_SECS` when unset.
329    pub auth_timeout_secs: Option<u64>,
330    /// WebSocket transport backend (defaults to `Sockudo`).
331    #[builder(default)]
332    pub transport_backend: TransportBackend,
333    /// Maximum pages per startup reconciliation history query, capped at 50.
334    ///
335    /// `None` keeps the default cap; `Some(0)` skips history. Pending orders,
336    /// live algo orders, and positions are unaffected. Skipped or truncated
337    /// history marks reports incomplete and reduces recovery coverage.
338    pub max_reconciliation_history_pages: Option<u32>,
339    /// Optional TTL (milliseconds) for WebSocket place and amend requests, sent to OKX as
340    /// `expTime`.
341    ///
342    /// Each request carries `expTime = now + ttl`, computed from the local clock when the
343    /// request is built, so time spent waiting for rate limits or a reconnect counts against
344    /// it. OKX does not process a request once its server time is past `expTime`. Allow for
345    /// clock skew between the local host and OKX. `None` omits `expTime`. Must be positive.
346    pub order_request_ttl_ms: Option<u64>,
347}
348
349#[cfg(feature = "python")]
350nautilus_core::impl_pyo3_config_getters!(OKXExecutionClientConfig {
351    account_id: AccountId,
352    oms_type: Option<OmsType>,
353    instrument_types: Vec<OKXInstrumentType>,
354    contract_types: Option<Vec<OKXContractType>>,
355    instrument_families: Option<Vec<String>>,
356    use_spot_margin: bool,
357    environment: OKXEnvironment,
358    region: OKXRegion,
359    base_url_http: Option<String>,
360    base_url_ws_private: Option<String>,
361    base_url_ws_business: Option<String>,
362    http_timeout_secs: u64,
363    max_retries: u32,
364    retry_delay_initial_ms: u64,
365    retry_delay_max_ms: u64,
366    margin_mode: Option<OKXMarginMode>,
367    load_spreads: bool,
368    auth_timeout_secs: Option<u64>,
369    transport_backend: TransportBackend,
370    spot_trade_quote_ccy: Option<String>,
371    use_spot_position_reports: bool,
372    spot_positions_quote_currency: String,
373    max_reconciliation_history_pages: Option<u32>,
374    order_request_ttl_ms: Option<u64>,
375});
376
377impl Default for OKXExecutionClientConfig {
378    fn default() -> Self {
379        Self::builder().build()
380    }
381}
382
383impl OKXExecutionClientConfig {
384    /// Creates a new configuration with default settings.
385    #[must_use]
386    pub fn new() -> Self {
387        Self::default()
388    }
389
390    /// Validates instrument selections, cancellation support, and retry delays.
391    ///
392    /// # Errors
393    ///
394    /// Returns an error if selections are duplicated, blank, or conflicting, required settings
395    /// are missing, retry delays or the order request TTL are invalid, MMP cancellation
396    /// is enabled, or spot position reports use a quote currency that is not an uppercase code.
397    pub fn validate(&self) -> ConfigResult<()> {
398        validate_instrument_selections(
399            &self.instrument_types,
400            self.contract_types.as_deref(),
401            self.instrument_families.as_deref(),
402        )?;
403        validate_retry_delays(self.retry_delay_initial_ms, self.retry_delay_max_ms)?;
404
405        if let Some(ttl_ms) = self.order_request_ttl_ms {
406            check_range("order_request_ttl_ms", ttl_ms > 0, "must be positive")?;
407            check_range(
408                "order_request_ttl_ms",
409                ttl_ms <= MAX_ORDER_REQUEST_TTL_MS,
410                format!("must be at most {MAX_ORDER_REQUEST_TTL_MS}"),
411            )?;
412        }
413
414        if self.use_mm_mass_cancel {
415            return Err(ConfigError::unsupported_value(
416                "use_mm_mass_cancel",
417                "MMP-only family cancellation does not cancel ordinary orders",
418            ));
419        }
420
421        if self.use_spot_position_reports {
422            let quote_currency = &self.spot_positions_quote_currency;
423            if quote_currency.is_empty()
424                || !quote_currency
425                    .bytes()
426                    .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
427            {
428                return Err(ConfigError::invalid_value(
429                    "spot_positions_quote_currency",
430                    "must be an uppercase currency code such as USDT",
431                ));
432            }
433        }
434
435        Ok(())
436    }
437
438    pub(crate) fn has_instrument_filters(&self) -> bool {
439        self.instrument_families
440            .as_ref()
441            .is_some_and(|values| !values.is_empty())
442            || self
443                .contract_types
444                .as_ref()
445                .is_some_and(|values| !values.is_empty())
446    }
447
448    pub(crate) fn uses_spot_margin(&self) -> bool {
449        self.use_spot_margin || self.instrument_types.contains(&OKXInstrumentType::Margin)
450    }
451
452    /// Returns whether all credential fields have non-blank config or environment values.
453    /// Explicit blank values do not fall back to environment variables.
454    #[must_use]
455    pub fn has_api_credentials(&self) -> bool {
456        let (key_var, secret_var, passphrase_var) = credential_env_vars();
457        let has_key = has_credential(self.api_key.as_ref(), key_var);
458        let has_secret = has_credential(self.api_secret.as_ref(), secret_var);
459        let has_passphrase = has_credential(self.api_passphrase.as_ref(), passphrase_var);
460        has_key && has_secret && has_passphrase
461    }
462
463    /// Returns the HTTP base URL, falling back to the region default when unset.
464    #[must_use]
465    pub fn http_base_url(&self) -> String {
466        self.base_url_http
467            .clone()
468            .unwrap_or_else(|| get_http_base_url(self.region).to_string())
469    }
470
471    /// Returns the private WebSocket URL, respecting the region, environment, and overrides.
472    #[must_use]
473    pub fn ws_private_url(&self) -> String {
474        self.base_url_ws_private
475            .clone()
476            .unwrap_or_else(|| get_ws_base_url_private(self.region, self.environment).to_string())
477    }
478
479    /// Returns the business WebSocket URL, respecting the region, environment, and overrides.
480    #[must_use]
481    pub fn ws_business_url(&self) -> String {
482        self.base_url_ws_business
483            .clone()
484            .unwrap_or_else(|| get_ws_base_url_business(self.region, self.environment).to_string())
485    }
486}
487
488fn validate_instrument_selections(
489    instrument_types: &[OKXInstrumentType],
490    contract_types: Option<&[OKXContractType]>,
491    instrument_families: Option<&[String]>,
492) -> ConfigResult<()> {
493    check_unique_values("instrument_types", instrument_types)?;
494
495    if let Some(values) = contract_types {
496        check_unique_values("contract_types", values)?;
497    }
498
499    if let Some(values) = instrument_families {
500        check_unique_values("instrument_families", values)?;
501        if values.iter().any(|value| value.trim().is_empty()) {
502            return Err(ConfigError::invalid_value(
503                "instrument_families",
504                "entries must not be blank",
505            ));
506        }
507    }
508
509    if instrument_types.contains(&OKXInstrumentType::Option)
510        && instrument_families.is_none_or(<[String]>::is_empty)
511    {
512        return Err(ConfigError::dependency(
513            "instrument_types",
514            "instrument_families",
515            "OPTION requires at least one family",
516        ));
517    }
518
519    if instrument_types.contains(&OKXInstrumentType::Events)
520        && instrument_types.iter().any(|value| {
521            matches!(
522                value,
523                OKXInstrumentType::Option | OKXInstrumentType::Swap | OKXInstrumentType::Futures
524            )
525        })
526        && instrument_families.is_some_and(|values| !values.is_empty())
527    {
528        return Err(ConfigError::invalid_value(
529            "instrument_families",
530            "EVENTS series and derivative families require separate clients",
531        ));
532    }
533
534    Ok(())
535}
536
537/// Upper bound for `order_request_ttl_ms`.
538const MAX_ORDER_REQUEST_TTL_MS: u64 = 9_999_999_999_999;
539
540pub(crate) fn validate_retry_delays(initial_ms: u64, max_ms: u64) -> ConfigResult<()> {
541    check_range("retry_delay_initial_ms", initial_ms > 0, "must be positive")?;
542    check_range(
543        "retry_delay_max_ms",
544        max_ms >= initial_ms,
545        "must be >= retry_delay_initial_ms",
546    )?;
547    check_range(
548        "retry_delay_max_ms",
549        max_ms <= u64::MAX / 1_000_000,
550        "exceeds maximum representable backoff duration",
551    )
552}
553
554fn has_credential(value: Option<&SecretString>, env_var: &str) -> bool {
555    value.map_or_else(
556        || std::env::var(env_var).is_ok_and(|value| !value.trim().is_empty()),
557        |value| !value.expose_secret().trim().is_empty(),
558    )
559}