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#[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 #[builder(default = AccountId::from("OKX-001"))]
243 pub account_id: AccountId,
244 pub oms_type: Option<OmsType>,
247 pub api_key: Option<SecretString>,
249 pub api_secret: Option<SecretString>,
251 pub api_passphrase: Option<SecretString>,
253 #[builder(default = vec![OKXInstrumentType::Spot])]
255 pub instrument_types: Vec<OKXInstrumentType>,
256 pub contract_types: Option<Vec<OKXContractType>>,
258 pub instrument_families: Option<Vec<String>>,
262 #[builder(default)]
264 pub environment: OKXEnvironment,
265 #[builder(default)]
267 pub region: OKXRegion,
268 pub base_url_http: Option<String>,
270 pub base_url_ws_private: Option<String>,
272 pub base_url_ws_business: Option<String>,
274 pub proxy_url: Option<SecretString>,
276 #[builder(default = 60)]
279 pub http_timeout_secs: u64,
280 #[builder(default)]
282 pub load_spreads: bool,
283 #[builder(default)]
286 pub use_mm_mass_cancel: bool,
287 #[builder(default = 3)]
289 pub max_retries: u32,
290 #[builder(default = 1_000)]
292 pub retry_delay_initial_ms: u64,
293 #[builder(default = 10_000)]
295 pub retry_delay_max_ms: u64,
296 pub margin_mode: Option<OKXMarginMode>,
298 #[builder(default)]
301 pub use_spot_margin: bool,
302 pub spot_trade_quote_ccy: Option<String>,
309 pub auth_timeout_secs: Option<u64>,
312 #[builder(default)]
314 pub transport_backend: TransportBackend,
315 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 #[must_use]
357 pub fn new() -> Self {
358 Self::default()
359 }
360
361 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 #[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 #[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 #[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 #[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}