1use 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#[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 pub api_key: Option<SecretString>,
50 pub api_secret: Option<SecretString>,
52 pub api_passphrase: Option<SecretString>,
54 #[builder(default = vec![OKXInstrumentType::Spot])]
56 pub instrument_types: Vec<OKXInstrumentType>,
57 pub contract_types: Option<Vec<OKXContractType>>,
59 #[builder(default)]
61 pub load_spreads: bool,
62 pub instrument_families: Option<Vec<String>>,
66 #[builder(default)]
68 pub environment: OKXEnvironment,
69 #[builder(default)]
71 pub region: OKXRegion,
72 pub base_url_http: Option<String>,
74 pub base_url_ws_public: Option<String>,
76 pub base_url_ws_business: Option<String>,
78 pub proxy_url: Option<SecretString>,
80 #[builder(default = 60)]
83 pub http_timeout_secs: u64,
84 #[builder(default = 3)]
86 pub max_retries: u32,
87 #[builder(default = 1_000)]
89 pub retry_delay_initial_ms: u64,
90 #[builder(default = 10_000)]
92 pub retry_delay_max_ms: u64,
93 #[builder(default = 60)]
98 pub update_instruments_interval_mins: u64,
99 #[builder(default = 5)]
101 pub book_stale_check_interval_secs: u64,
102 #[builder(default = 30)]
106 pub book_stale_threshold_secs: u64,
107 #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
110 pub book_snapshot_timeout_secs: u64,
111 pub vip_level: Option<OKXVipLevel>,
114 #[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 #[must_use]
151 pub fn new() -> Self {
152 Self::default()
153 }
154
155 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 #[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 #[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 #[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 #[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 #[must_use]
224 pub fn requires_business_ws(&self) -> bool {
225 true
226 }
227}
228
229#[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 #[builder(default = AccountId::from("OKX-001"))]
247 pub account_id: AccountId,
248 pub oms_type: Option<OmsType>,
251 pub api_key: Option<SecretString>,
253 pub api_secret: Option<SecretString>,
255 pub api_passphrase: Option<SecretString>,
257 #[builder(default = vec![OKXInstrumentType::Spot])]
259 pub instrument_types: Vec<OKXInstrumentType>,
260 pub contract_types: Option<Vec<OKXContractType>>,
262 pub instrument_families: Option<Vec<String>>,
266 #[builder(default)]
268 pub environment: OKXEnvironment,
269 #[builder(default)]
271 pub region: OKXRegion,
272 pub base_url_http: Option<String>,
274 pub base_url_ws_private: Option<String>,
276 pub base_url_ws_business: Option<String>,
278 pub proxy_url: Option<SecretString>,
280 #[builder(default = 60)]
283 pub http_timeout_secs: u64,
284 #[builder(default)]
286 pub load_spreads: bool,
287 #[builder(default)]
290 pub use_mm_mass_cancel: bool,
291 #[builder(default = 3)]
293 pub max_retries: u32,
294 #[builder(default = 1_000)]
296 pub retry_delay_initial_ms: u64,
297 #[builder(default = 10_000)]
299 pub retry_delay_max_ms: u64,
300 pub margin_mode: Option<OKXMarginMode>,
302 #[builder(default)]
305 pub use_spot_margin: bool,
306 pub spot_trade_quote_ccy: Option<String>,
313 #[builder(default)]
320 pub use_spot_position_reports: bool,
321 #[builder(default = "USDT".to_string())]
326 pub spot_positions_quote_currency: String,
327 pub auth_timeout_secs: Option<u64>,
330 #[builder(default)]
332 pub transport_backend: TransportBackend,
333 pub max_reconciliation_history_pages: Option<u32>,
339 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 #[must_use]
386 pub fn new() -> Self {
387 Self::default()
388 }
389
390 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 #[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 #[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 #[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 #[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
537const 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}