nautilus-okx 0.61.0

OKX exchange integration adapter 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Configuration structures for the OKX adapter.

use nautilus_model::identifiers::{AccountId, TraderId};
use nautilus_network::websocket::TransportBackend;
use serde::{Deserialize, Serialize};

use crate::common::{
    credential::credential_env_vars,
    enums::{
        OKXContractType, OKXEnvironment, OKXInstrumentType, OKXMarginMode, OKXRegion, OKXVipLevel,
    },
    urls::{
        get_http_base_url, get_ws_base_url_business, get_ws_base_url_private,
        get_ws_base_url_public,
    },
};

/// Configuration for the OKX data client.
#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.okx", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
)]
pub struct OKXDataClientConfig {
    /// Optional API key for authenticated endpoints.
    pub api_key: Option<String>,
    /// Optional API secret for authenticated endpoints.
    pub api_secret: Option<String>,
    /// Optional API passphrase for authenticated endpoints.
    pub api_passphrase: Option<String>,
    /// Instrument types to load and subscribe to.
    #[builder(default = vec![OKXInstrumentType::Spot])]
    pub instrument_types: Vec<OKXInstrumentType>,
    /// Contract type filter applied to loaded instruments.
    pub contract_types: Option<Vec<OKXContractType>>,
    /// Whether to load spread trading instruments from the separate spread endpoint.
    #[builder(default)]
    pub load_spreads: bool,
    /// Instrument families to load (e.g., "BTC-USD", "ETH-USD").
    /// Required for OPTIONS. Optional for FUTURES/SWAP. Not applicable for SPOT/MARGIN.
    pub instrument_families: Option<Vec<String>>,
    /// Optional override for the HTTP base URL.
    pub base_url_http: Option<String>,
    /// Optional override for the public WebSocket URL.
    pub base_url_ws_public: Option<String>,
    /// Optional override for the business WebSocket URL.
    pub base_url_ws_business: Option<String>,
    /// Optional proxy URL for HTTP and WebSocket transports.
    pub proxy_url: Option<String>,
    /// The API environment (live or demo).
    #[builder(default)]
    pub environment: OKXEnvironment,
    /// The API region (global, EEA, or US).
    #[builder(default)]
    pub region: OKXRegion,
    /// HTTP timeout in seconds.
    #[builder(default = 60)]
    pub http_timeout_secs: u64,
    /// Maximum retry attempts for requests.
    #[builder(default = 3)]
    pub max_retries: u32,
    /// Initial retry delay in milliseconds.
    #[builder(default = 1_000)]
    pub retry_delay_initial_ms: u64,
    /// Maximum retry delay in milliseconds.
    #[builder(default = 10_000)]
    pub retry_delay_max_ms: u64,
    /// Interval for refreshing instruments in minutes.
    #[builder(default = 60)]
    pub update_instruments_interval_mins: u64,
    /// Interval for checking order book feed staleness in seconds.
    #[builder(default = 5)]
    pub book_stale_check_interval_secs: u64,
    /// Maximum time without order book updates before emitting a stale signal in seconds.
    ///
    /// Set to 0 to disable. Quiet markets can idle without book changes.
    #[builder(default = 30)]
    pub book_stale_threshold_secs: u64,
    /// Maximum time to wait for a post-reconnect order book snapshot in seconds.
    #[builder(default = 3)]
    pub book_snapshot_timeout_secs: u64,
    /// Optional VIP level that unlocks additional subscriptions.
    pub vip_level: Option<OKXVipLevel>,
    /// WebSocket transport backend (defaults to `Tungstenite`).
    #[builder(default)]
    pub transport_backend: TransportBackend,
}

#[cfg(feature = "python")]
nautilus_core::impl_pyo3_config_getters!(OKXDataClientConfig {
    instrument_types: Vec<OKXInstrumentType>,
    environment: OKXEnvironment,
    region: OKXRegion,
    base_url_http: Option<String>,
    base_url_ws_public: Option<String>,
    base_url_ws_business: Option<String>,
    http_timeout_secs: u64,
    max_retries: u32,
    retry_delay_initial_ms: u64,
    retry_delay_max_ms: u64,
    update_instruments_interval_mins: u64,
    book_stale_check_interval_secs: u64,
    book_stale_threshold_secs: u64,
    book_snapshot_timeout_secs: u64,
    vip_level: Option<OKXVipLevel>,
    load_spreads: bool,
    transport_backend: TransportBackend,
});

impl Default for OKXDataClientConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

impl OKXDataClientConfig {
    /// Creates a new configuration with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns `true` when all API credential fields are available (in config or env vars).
    #[must_use]
    pub fn has_api_credentials(&self) -> bool {
        let (key_var, secret_var, passphrase_var) = credential_env_vars();
        let has_key = self.api_key.is_some() || std::env::var(key_var).is_ok();
        let has_secret = self.api_secret.is_some() || std::env::var(secret_var).is_ok();
        let has_passphrase = self.api_passphrase.is_some() || std::env::var(passphrase_var).is_ok();
        has_key && has_secret && has_passphrase
    }

    /// Returns the HTTP base URL, falling back to the region default when unset.
    #[must_use]
    pub fn http_base_url(&self) -> String {
        self.base_url_http
            .clone()
            .unwrap_or_else(|| get_http_base_url(self.region).to_string())
    }

    /// Returns the public WebSocket URL, respecting the region, environment, and overrides.
    #[must_use]
    pub fn ws_public_url(&self) -> String {
        self.base_url_ws_public
            .clone()
            .unwrap_or_else(|| get_ws_base_url_public(self.region, self.environment).to_string())
    }

    /// Returns the business WebSocket URL, respecting the region, environment, and overrides.
    #[must_use]
    pub fn ws_business_url(&self) -> String {
        self.base_url_ws_business
            .clone()
            .unwrap_or_else(|| get_ws_base_url_business(self.region, self.environment).to_string())
    }

    /// Returns `true` when the business WebSocket should be instantiated.
    ///
    /// The business WebSocket carries public candle data and does not
    /// require authentication, so it is always needed.
    #[must_use]
    pub fn requires_business_ws(&self) -> bool {
        true
    }
}

/// Configuration for the OKX execution client.
#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.okx", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
)]
pub struct OKXExecClientConfig {
    /// The trader ID for the client.
    #[builder(default = TraderId::from("TRADER-001"))]
    pub trader_id: TraderId,
    /// The account ID for the client.
    #[builder(default = AccountId::from("OKX-001"))]
    pub account_id: AccountId,
    /// Optional API key for authenticated endpoints.
    pub api_key: Option<String>,
    /// Optional API secret for authenticated endpoints.
    pub api_secret: Option<String>,
    /// Optional API passphrase for authenticated endpoints.
    pub api_passphrase: Option<String>,
    /// Instrument types the execution client should support.
    #[builder(default = vec![OKXInstrumentType::Spot])]
    pub instrument_types: Vec<OKXInstrumentType>,
    /// Contract type filter applied to operations.
    pub contract_types: Option<Vec<OKXContractType>>,
    /// Instrument families to load (e.g., "BTC-USD", "ETH-USD").
    /// Required for OPTIONS. Optional for FUTURES/SWAP. Not applicable for SPOT/MARGIN.
    pub instrument_families: Option<Vec<String>>,
    /// Optional override for the HTTP base URL.
    pub base_url_http: Option<String>,
    /// Optional override for the private WebSocket URL.
    pub base_url_ws_private: Option<String>,
    /// Optional override for the business WebSocket URL.
    pub base_url_ws_business: Option<String>,
    /// Optional proxy URL for HTTP and WebSocket transports.
    pub proxy_url: Option<String>,
    /// The API environment (live or demo).
    #[builder(default)]
    pub environment: OKXEnvironment,
    /// The API region (global, EEA, or US).
    #[builder(default)]
    pub region: OKXRegion,
    /// HTTP timeout in seconds.
    #[builder(default = 60)]
    pub http_timeout_secs: u64,
    /// Enables consumption of the fills WebSocket channel when true.
    #[builder(default)]
    pub use_fills_channel: bool,
    /// Whether to subscribe to spread order updates from the separate spread channel.
    #[builder(default)]
    pub load_spreads: bool,
    /// Enables mass-cancel support when true.
    #[builder(default)]
    pub use_mm_mass_cancel: bool,
    /// Maximum retry attempts for requests.
    #[builder(default = 3)]
    pub max_retries: u32,
    /// Initial retry delay in milliseconds.
    #[builder(default = 1_000)]
    pub retry_delay_initial_ms: u64,
    /// Maximum retry delay in milliseconds.
    #[builder(default = 10_000)]
    pub retry_delay_max_ms: u64,
    /// Optional margin mode (CROSS or ISOLATED) for margin/derivative accounts.
    pub margin_mode: Option<OKXMarginMode>,
    /// Enables margin/leverage for SPOT trading when true.
    #[builder(default)]
    pub use_spot_margin: bool,
    /// Optional WebSocket authentication timeout (seconds), defaulting to
    /// `AUTHENTICATION_TIMEOUT_SECS` when unset.
    pub auth_timeout_secs: Option<u64>,
    /// WebSocket transport backend (defaults to `Tungstenite`).
    #[builder(default)]
    pub transport_backend: TransportBackend,
}

#[cfg(feature = "python")]
nautilus_core::impl_pyo3_config_getters!(OKXExecClientConfig {
    trader_id: TraderId,
    account_id: AccountId,
    instrument_types: Vec<OKXInstrumentType>,
    environment: OKXEnvironment,
    region: OKXRegion,
    base_url_http: Option<String>,
    base_url_ws_private: Option<String>,
    base_url_ws_business: Option<String>,
    http_timeout_secs: u64,
    max_retries: u32,
    retry_delay_initial_ms: u64,
    retry_delay_max_ms: u64,
    margin_mode: Option<OKXMarginMode>,
    load_spreads: bool,
    auth_timeout_secs: Option<u64>,
    transport_backend: TransportBackend,
});

impl Default for OKXExecClientConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

impl OKXExecClientConfig {
    /// Creates a new configuration with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns `true` when all API credential fields are available (in config or env vars).
    #[must_use]
    pub fn has_api_credentials(&self) -> bool {
        let (key_var, secret_var, passphrase_var) = credential_env_vars();
        let has_key = self.api_key.is_some() || std::env::var(key_var).is_ok();
        let has_secret = self.api_secret.is_some() || std::env::var(secret_var).is_ok();
        let has_passphrase = self.api_passphrase.is_some() || std::env::var(passphrase_var).is_ok();
        has_key && has_secret && has_passphrase
    }

    /// Returns the HTTP base URL, falling back to the region default when unset.
    #[must_use]
    pub fn http_base_url(&self) -> String {
        self.base_url_http
            .clone()
            .unwrap_or_else(|| get_http_base_url(self.region).to_string())
    }

    /// Returns the private WebSocket URL, respecting the region, environment, and overrides.
    #[must_use]
    pub fn ws_private_url(&self) -> String {
        self.base_url_ws_private
            .clone()
            .unwrap_or_else(|| get_ws_base_url_private(self.region, self.environment).to_string())
    }

    /// Returns the business WebSocket URL, respecting the region, environment, and overrides.
    #[must_use]
    pub fn ws_business_url(&self) -> String {
        self.base_url_ws_business
            .clone()
            .unwrap_or_else(|| get_ws_base_url_business(self.region, self.environment).to_string())
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    fn test_data_config_toml_minimal() {
        let config: OKXDataClientConfig = toml::from_str(
            r#"
environment = "demo"
instrument_types = ["SPOT", "SWAP"]
http_timeout_secs = 90
"#,
        )
        .unwrap();

        assert_eq!(config.environment, OKXEnvironment::Demo);
        assert_eq!(
            config.instrument_types,
            vec![OKXInstrumentType::Spot, OKXInstrumentType::Swap]
        );
        assert_eq!(config.http_timeout_secs, 90);
        assert!(!config.load_spreads);
        assert_eq!(config.book_stale_check_interval_secs, 5);
        assert_eq!(config.book_stale_threshold_secs, 30);
        assert_eq!(config.book_snapshot_timeout_secs, 3);
    }

    #[rstest]
    fn test_data_config_toml_load_spreads() {
        let config: OKXDataClientConfig = toml::from_str(
            "
load_spreads = true
",
        )
        .unwrap();

        assert!(config.load_spreads);
    }

    #[rstest]
    fn test_data_config_toml_book_stale_settings() {
        let config: OKXDataClientConfig = toml::from_str(
            "
book_stale_check_interval_secs = 2
book_stale_threshold_secs = 7
book_snapshot_timeout_secs = 4
",
        )
        .unwrap();

        assert_eq!(config.book_stale_check_interval_secs, 2);
        assert_eq!(config.book_stale_threshold_secs, 7);
        assert_eq!(config.book_snapshot_timeout_secs, 4);
    }

    #[rstest]
    fn test_exec_config_toml_empty_uses_defaults() {
        let config: OKXExecClientConfig = toml::from_str("").unwrap();
        let expected = OKXExecClientConfig::default();

        assert_eq!(config.trader_id, expected.trader_id);
        assert_eq!(config.account_id, expected.account_id);
        assert_eq!(config.environment, expected.environment);
        assert_eq!(config.instrument_types, expected.instrument_types);
        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
        assert_eq!(config.use_fills_channel, expected.use_fills_channel);
        assert_eq!(config.load_spreads, expected.load_spreads);
        assert_eq!(config.use_mm_mass_cancel, expected.use_mm_mass_cancel);
        assert_eq!(config.transport_backend, expected.transport_backend);
    }

    #[rstest]
    fn test_exec_config_toml_load_spreads() {
        let config: OKXExecClientConfig = toml::from_str(
            "
load_spreads = true
",
        )
        .unwrap();

        assert!(config.load_spreads);
    }

    #[rstest]
    fn test_data_config_default_region_is_global() {
        let config = OKXDataClientConfig::default();

        assert_eq!(config.region, OKXRegion::Global);
        assert_eq!(config.http_base_url(), "https://www.okx.com");
        assert_eq!(config.ws_public_url(), "wss://ws.okx.com:8443/ws/v5/public");
    }

    #[rstest]
    fn test_data_config_eea_region_urls() {
        let config = OKXDataClientConfig::builder()
            .region(OKXRegion::Eea)
            .build();

        assert_eq!(config.http_base_url(), "https://eea.okx.com");
        assert_eq!(
            config.ws_public_url(),
            "wss://wseea.okx.com:8443/ws/v5/public"
        );
        assert_eq!(
            config.ws_business_url(),
            "wss://wseea.okx.com:8443/ws/v5/business"
        );
    }

    #[rstest]
    fn test_exec_config_eea_region_urls() {
        let config = OKXExecClientConfig::builder()
            .region(OKXRegion::Eea)
            .build();

        assert_eq!(config.http_base_url(), "https://eea.okx.com");
        assert_eq!(
            config.ws_private_url(),
            "wss://wseea.okx.com:8443/ws/v5/private"
        );
        assert_eq!(
            config.ws_business_url(),
            "wss://wseea.okx.com:8443/ws/v5/business"
        );
    }

    #[rstest]
    fn test_config_region_override_takes_precedence() {
        let config = OKXDataClientConfig::builder()
            .region(OKXRegion::Eea)
            .base_url_http("https://custom.proxy".to_string())
            .build();

        assert_eq!(config.http_base_url(), "https://custom.proxy");
    }

    #[rstest]
    fn test_data_config_toml_region() {
        let config: OKXDataClientConfig = toml::from_str(
            r#"
region = "eea"
"#,
        )
        .unwrap();

        assert_eq!(config.region, OKXRegion::Eea);
    }

    #[rstest]
    fn test_exec_config_auth_timeout_secs() {
        assert_eq!(OKXExecClientConfig::default().auth_timeout_secs, None);

        let exec = OKXExecClientConfig::builder().auth_timeout_secs(4).build();
        assert_eq!(exec.auth_timeout_secs, Some(4));

        let exec: OKXExecClientConfig = toml::from_str("auth_timeout_secs = 8\n").unwrap();
        assert_eq!(exec.auth_timeout_secs, Some(8));
    }
}