1use std::{
26 fmt::Debug,
27 num::NonZeroU32,
28 sync::{
29 Arc, LazyLock,
30 atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
31 },
32 time::Duration,
33};
34
35use ahash::{AHashMap, AHashSet};
36use arc_swap::ArcSwap;
37use dashmap::DashMap;
38use futures_util::Stream;
39use nautilus_common::live::dst::time;
40use nautilus_core::{
41 AtomicMap, AtomicTime, UUID4, UnixNanos,
42 env::{get_env_var, get_or_env_var},
43 string::secret::{REDACTED, SecretString},
44 time::get_atomic_clock_realtime,
45};
46use nautilus_live::{
47 SocketControl,
48 task::{TaskGroup, TaskShutdownError},
49};
50use nautilus_model::{
51 data::BarType,
52 enums::{OrderSide, OrderType, PositionSide, TimeInForce, TriggerType},
53 identifiers::{AccountId, ClientOrderId, InstrumentId, StrategyId, TraderId, VenueOrderId},
54 instruments::{Instrument, InstrumentAny},
55 types::{Price, Quantity},
56};
57use nautilus_network::{
58 error::SendError,
59 http::create_standard_nautilus_headers,
60 mode::ConnectionMode,
61 ratelimiter::quota::Quota,
62 websocket::{
63 AUTHENTICATION_TIMEOUT_SECS, AuthTracker, SubscriptionState, TEXT_PING, TransportBackend,
64 WebSocketClient, WebSocketConfig, channel_message_handler,
65 },
66};
67use parking_lot::Mutex;
68use serde_json::Value;
69use tokio_tungstenite::tungstenite::Error;
70use tokio_util::sync::CancellationToken;
71use ustr::Ustr;
72
73use super::{
74 enums::OKXWsChannel,
75 error::OKXWsError,
76 handler::{HandlerCommand, OKXWsFeedHandler, SnapshotGate},
77 messages::{
78 OKXAuthentication, OKXAuthenticationArg, OKXSubscriptionArg, OKXWsMessage, OKXWsRequest,
79 WsAmendOrderParamsBuilder, WsAttachAlgoOrdParams, WsCancelOrderParamsBuilder,
80 WsMassCancelParams, WsPostOrderParamsBuilder,
81 },
82 subscription::{is_topic_subscribed, topic_from_subscription_arg},
83};
84use crate::common::{
85 consts::{
86 OKX_NAUTILUS_BROKER_ID, OKX_SUPPORTED_ORDER_TYPES, OKX_WS_PUBLIC_URL,
87 OKX_WS_TOPIC_DELIMITER, okx_market_target_currency, okx_reduce_only_wire_value,
88 select_book_channel, spot_trade_quote_ccy_wire_value, validate_order_time_in_force,
89 validate_regular_order_params,
90 },
91 credential::Credential,
92 enums::{
93 OKXBookChannel, OKXGreeksType, OKXInstrumentType, OKXOrderType, OKXPositionSide,
94 OKXTradeMode, OKXVipLevel,
95 },
96 parse::{
97 bar_spec_as_okx_channel, okx_instrument_type, okx_instrument_type_from_symbol,
98 parse_base_quote_from_symbol,
99 },
100};
101
102pub static OKX_WS_CONNECTION_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
106 Quota::per_second(NonZeroU32::new(3).expect("non-zero")).expect("valid constant")
107});
108
109pub static OKX_WS_SUBSCRIPTION_QUOTA: LazyLock<Quota> =
114 LazyLock::new(|| Quota::per_hour(NonZeroU32::new(480).expect("non-zero")));
115
116pub static OKX_WS_ORDER_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
118 Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant")
119});
120
121pub static OKX_WS_BATCH_ORDER_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
123 Quota::per_second(NonZeroU32::new(7).expect("non-zero")).expect("valid constant")
124});
125
126pub static OKX_WS_MASS_CANCEL_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
128 Quota::per_second(NonZeroU32::new(2).expect("non-zero")).expect("valid constant")
129});
130
131pub static OKX_WS_ALGO_ORDER_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
133 Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
134});
135
136pub static OKX_WS_ALGO_CANCEL_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
138 Quota::per_second(NonZeroU32::new(1).expect("non-zero")).expect("valid constant")
139});
140
141const OKX_WS_SUBSCRIPTION_ARGS_MAX_PER_MESSAGE: usize = 256;
143
144pub static OKX_RATE_LIMIT_KEY_SUBSCRIPTION: LazyLock<[Ustr; 1]> =
149 LazyLock::new(|| [Ustr::from("subscription")]);
150
151pub static OKX_RATE_LIMIT_KEY_ORDER: LazyLock<[Ustr; 1]> = LazyLock::new(|| [Ustr::from("order")]);
155
156pub static OKX_RATE_LIMIT_KEY_BATCH_ORDER: LazyLock<[Ustr; 1]> =
160 LazyLock::new(|| [Ustr::from("batch-order")]);
161
162pub static OKX_RATE_LIMIT_KEY_CANCEL: LazyLock<[Ustr; 1]> =
166 LazyLock::new(|| [Ustr::from("cancel")]);
167
168pub static OKX_RATE_LIMIT_KEY_BATCH_CANCEL: LazyLock<[Ustr; 1]> =
172 LazyLock::new(|| [Ustr::from("batch-cancel")]);
173
174pub static OKX_RATE_LIMIT_KEY_MASS_CANCEL: LazyLock<[Ustr; 1]> =
178 LazyLock::new(|| [Ustr::from("mass-cancel")]);
179
180pub static OKX_RATE_LIMIT_KEY_AMEND: LazyLock<[Ustr; 1]> = LazyLock::new(|| [Ustr::from("amend")]);
184
185pub static OKX_RATE_LIMIT_KEY_BATCH_AMEND: LazyLock<[Ustr; 1]> =
189 LazyLock::new(|| [Ustr::from("batch-amend")]);
190
191pub static OKX_RATE_LIMIT_KEY_ALGO_ORDER: LazyLock<[Ustr; 1]> =
195 LazyLock::new(|| [Ustr::from("algo-order")]);
196
197pub static OKX_RATE_LIMIT_KEY_ALGO_CANCEL: LazyLock<[Ustr; 1]> =
201 LazyLock::new(|| [Ustr::from("algo-cancel")]);
202
203#[derive(Debug, Clone)]
207#[allow(dead_code)]
208#[allow(
209 clippy::struct_field_names,
210 reason = "fields follow the codebase-wide trader_id/strategy_id/instrument_id naming family"
211)]
212pub(crate) struct PendingOrderInfo {
213 pub trader_id: TraderId,
214 pub strategy_id: StrategyId,
215 pub instrument_id: InstrumentId,
216}
217
218#[derive(Clone)]
226pub struct OKXWebSocketClient {
227 clock: &'static AtomicTime,
228 url: String,
229 vip_level: Arc<AtomicU8>,
230 credential: Option<Credential>,
231 heartbeat: Option<u64>,
232 auth_timeout_secs: u64,
233 auth_tracker: AuthTracker,
234 signal: Arc<AtomicBool>,
235 connection_mode: Arc<ArcSwap<AtomicU8>>,
236 cmd_tx: Arc<tokio::sync::RwLock<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>>,
237 out_rx: Option<Arc<tokio::sync::mpsc::UnboundedReceiver<OKXWsMessage>>>,
238 handler_tasks: Arc<TaskGroup>,
239 connect_lock: Arc<tokio::sync::Mutex<()>>,
240 handler_abort: Arc<Mutex<CancellationToken>>,
241 subscriptions: Arc<DashMap<String, OKXSubscriptionArg>>,
242 subscriptions_state: SubscriptionState,
243 request_id_counter: Arc<AtomicU64>,
244 instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
245 inst_id_code_cache: Arc<AtomicMap<Ustr, u64>>,
246 trade_quote_ccy_lists: Arc<AtomicMap<Ustr, Vec<Ustr>>>,
247 spot_trade_quote_ccy: Arc<Mutex<Option<Ustr>>>,
248 pub(crate) pending_orders: Arc<DashMap<String, PendingOrderInfo>>,
249 pub(crate) pending_cancels: Arc<DashMap<String, PendingOrderInfo>>,
250 pub(crate) pending_amends: Arc<DashMap<String, PendingOrderInfo>>,
251 pub(crate) pending_command_ids: Arc<DashMap<String, Vec<(ClientOrderId, UUID4)>>>,
252 option_greeks_subs: Arc<AtomicMap<InstrumentId, AHashSet<OKXGreeksType>>>,
253 index_pair_subscribers: Arc<DashMap<Ustr, usize>>,
254 index_pair_transition: Arc<tokio::sync::Mutex<()>>,
255 transport_backend: TransportBackend,
256 proxy_url: Option<SecretString>,
257 cancellation_token: CancellationToken,
258 socket_control: Option<Arc<SocketControl>>,
259}
260
261struct ConnectRollback {
262 handler_tasks: Arc<TaskGroup>,
263 signal: Arc<AtomicBool>,
264 handler_abort: CancellationToken,
265 socket_control: Option<Arc<SocketControl>>,
266 armed: bool,
267}
268
269impl ConnectRollback {
270 fn disarm(&mut self) {
271 self.armed = false;
272 }
273}
274
275impl Drop for ConnectRollback {
276 fn drop(&mut self) {
277 if !self.armed {
278 return;
279 }
280
281 self.handler_tasks.begin_shutdown();
282 self.signal.store(true, Ordering::Release);
283 self.handler_abort.cancel();
284
285 if let Some(control) = &self.socket_control {
286 control.deregister();
287 }
288 }
289}
290
291impl Default for OKXWebSocketClient {
292 fn default() -> Self {
293 Self::new(
294 None,
295 None,
296 None,
297 None,
298 None,
299 None,
300 None,
301 TransportBackend::default(),
302 None,
303 )
304 .unwrap()
305 }
306}
307
308impl Debug for OKXWebSocketClient {
309 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310 f.debug_struct(stringify!(OKXWebSocketClient))
311 .field("url", &self.url)
312 .field("credential", &self.credential.as_ref().map(|_| REDACTED))
313 .field("heartbeat", &self.heartbeat)
314 .finish_non_exhaustive()
315 }
316}
317
318impl OKXWebSocketClient {
319 #[allow(clippy::too_many_arguments)]
325 pub fn new(
326 url: Option<String>,
327 api_key: Option<String>,
328 api_secret: Option<String>,
329 api_passphrase: Option<String>,
330 _account_id: Option<AccountId>,
331 heartbeat: Option<u64>,
332 auth_timeout_secs: Option<u64>,
333 transport_backend: TransportBackend,
334 proxy_url: Option<String>,
335 ) -> anyhow::Result<Self> {
336 let url = url.unwrap_or(OKX_WS_PUBLIC_URL.to_string());
337 let credential = match (api_key, api_secret, api_passphrase) {
338 (Some(key), Some(secret), Some(passphrase)) => {
339 Some(Credential::new(key, secret, passphrase))
340 }
341 (None, None, None) => None,
342 _ => anyhow::bail!(
343 "`api_key`, `api_secret`, `api_passphrase` credentials must be provided together"
344 ),
345 };
346
347 let signal = Arc::new(AtomicBool::new(false));
348 let subscriptions = Arc::new(DashMap::new());
349 let subscriptions_state = SubscriptionState::new(OKX_WS_TOPIC_DELIMITER);
350
351 Ok(Self {
352 clock: get_atomic_clock_realtime(),
353 url,
354 vip_level: Arc::new(AtomicU8::new(0)),
355 credential,
356 heartbeat,
357 auth_timeout_secs: auth_timeout_secs.unwrap_or(AUTHENTICATION_TIMEOUT_SECS),
358 auth_tracker: AuthTracker::new(),
359 signal,
360 connection_mode: Arc::new(ArcSwap::from_pointee(AtomicU8::new(
361 ConnectionMode::Closed.as_u8(),
362 ))),
363 cmd_tx: {
364 let (tx, _) = tokio::sync::mpsc::unbounded_channel();
366 Arc::new(tokio::sync::RwLock::new(tx))
367 },
368 out_rx: None,
369 handler_tasks: Arc::new(TaskGroup::new()),
370 connect_lock: Arc::new(tokio::sync::Mutex::new(())),
371 handler_abort: Arc::new(Mutex::new(CancellationToken::new())),
372 subscriptions,
373 subscriptions_state,
374 request_id_counter: Arc::new(AtomicU64::new(1)),
375 instruments_cache: Arc::new(AtomicMap::new()),
376 inst_id_code_cache: Arc::new(AtomicMap::new()),
377 trade_quote_ccy_lists: Arc::new(AtomicMap::new()),
378 spot_trade_quote_ccy: Arc::new(Mutex::new(None)),
379 pending_orders: Arc::new(DashMap::new()),
380 pending_cancels: Arc::new(DashMap::new()),
381 pending_amends: Arc::new(DashMap::new()),
382 pending_command_ids: Arc::new(DashMap::new()),
383 option_greeks_subs: Arc::new(AtomicMap::new()),
384 index_pair_subscribers: Arc::new(DashMap::new()),
385 index_pair_transition: Arc::new(tokio::sync::Mutex::new(())),
386 transport_backend,
387 proxy_url: proxy_url.map(SecretString::from),
388 cancellation_token: CancellationToken::new(),
389 socket_control: None,
390 })
391 }
392
393 #[must_use]
395 pub fn with_socket_control(mut self, control: SocketControl) -> Self {
396 self.socket_control = Some(Arc::new(control));
397 self
398 }
399
400 #[allow(clippy::too_many_arguments)]
407 pub fn with_credentials(
408 url: Option<String>,
409 api_key: Option<String>,
410 api_secret: Option<String>,
411 api_passphrase: Option<String>,
412 account_id: Option<AccountId>,
413 heartbeat: Option<u64>,
414 auth_timeout_secs: Option<u64>,
415 transport_backend: TransportBackend,
416 proxy_url: Option<String>,
417 ) -> anyhow::Result<Self> {
418 let url = url.unwrap_or(OKX_WS_PUBLIC_URL.to_string());
419 let api_key = get_or_env_var(api_key, "OKX_API_KEY")?;
420 let api_secret = get_or_env_var(api_secret, "OKX_API_SECRET")?;
421 let api_passphrase = get_or_env_var(api_passphrase, "OKX_API_PASSPHRASE")?;
422
423 Self::new(
424 Some(url),
425 Some(api_key),
426 Some(api_secret),
427 Some(api_passphrase),
428 account_id,
429 heartbeat,
430 auth_timeout_secs,
431 transport_backend,
432 proxy_url,
433 )
434 }
435
436 pub fn from_env() -> anyhow::Result<Self> {
443 let url = get_env_var("OKX_WS_URL")?;
444 let api_key = get_env_var("OKX_API_KEY")?;
445 let api_secret = get_env_var("OKX_API_SECRET")?;
446 let api_passphrase = get_env_var("OKX_API_PASSPHRASE")?;
447
448 Self::new(
449 Some(url),
450 Some(api_key),
451 Some(api_secret),
452 Some(api_passphrase),
453 None,
454 None,
455 None,
456 TransportBackend::default(),
457 None,
458 )
459 }
460
461 pub fn cancel_all_requests(&self) {
463 self.cancellation_token.cancel();
464 }
465
466 pub fn cancellation_token(&self) -> &CancellationToken {
468 &self.cancellation_token
469 }
470
471 pub fn url(&self) -> &str {
473 self.url.as_str()
474 }
475
476 pub fn api_key(&self) -> Option<&str> {
478 self.credential.as_ref().map(Credential::api_key)
479 }
480
481 #[must_use]
483 pub fn api_key_masked(&self) -> Option<String> {
484 self.credential.as_ref().map(Credential::api_key_masked)
485 }
486
487 pub fn is_active(&self) -> bool {
489 let connection_mode_arc = self.connection_mode.load();
490 ConnectionMode::from_atomic(&connection_mode_arc).is_active()
491 && !self.signal.load(Ordering::Acquire)
492 }
493
494 pub fn is_closed(&self) -> bool {
496 let connection_mode_arc = self.connection_mode.load();
497 ConnectionMode::from_atomic(&connection_mode_arc).is_closed()
498 || self.signal.load(Ordering::Acquire)
499 }
500
501 pub(crate) fn has_task(&self) -> bool {
503 !self.handler_tasks.is_empty()
504 }
505
506 pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
510 self.instruments_cache.rcu(|m| {
511 for inst in instruments {
512 m.insert(inst.symbol().inner(), inst.clone());
513 }
514 });
515 }
516
517 pub fn cache_instrument(&self, instrument: InstrumentAny) {
521 self.instruments_cache
522 .insert(instrument.symbol().inner(), instrument);
523 }
524
525 pub fn instruments_snapshot(&self) -> AHashMap<Ustr, InstrumentAny> {
527 (**self.instruments_cache.load()).clone()
528 }
529
530 pub fn instruments_cache_arc(&self) -> Arc<AtomicMap<Ustr, InstrumentAny>> {
532 Arc::clone(&self.instruments_cache)
533 }
534
535 pub fn cache_inst_id_code(&self, inst_id: Ustr, inst_id_code: u64) {
539 self.inst_id_code_cache.insert(inst_id, inst_id_code);
540 }
541
542 pub fn cache_inst_id_codes(&self, mappings: impl IntoIterator<Item = (Ustr, u64)>) {
546 let entries: Vec<_> = mappings.into_iter().collect();
547 self.inst_id_code_cache.rcu(|m| {
548 for (inst_id, inst_id_code) in &entries {
549 m.insert(*inst_id, *inst_id_code);
550 }
551 });
552 }
553
554 #[must_use]
558 pub fn get_inst_id_code(&self, inst_id: &Ustr) -> Option<u64> {
559 self.inst_id_code_cache.load().get(inst_id).copied()
560 }
561
562 pub fn set_spot_trade_quote_ccy(&self, ccy: Option<String>) {
564 *self.spot_trade_quote_ccy.lock() = ccy.map(|value| Ustr::from(value.as_str()));
565 }
566
567 pub fn cache_trade_quote_ccy_lists(
569 &self,
570 mappings: impl IntoIterator<Item = (Ustr, Vec<Ustr>)>,
571 ) {
572 let entries: Vec<_> = mappings.into_iter().collect();
573 self.trade_quote_ccy_lists.rcu(|m| {
574 for (inst_id, list) in &entries {
575 m.insert(*inst_id, list.clone());
576 }
577 });
578 }
579
580 fn resolve_spot_trade_quote_ccy(
581 &self,
582 instrument_type: OKXInstrumentType,
583 inst_id: Ustr,
584 ) -> Result<Option<Ustr>, OKXWsError> {
585 let configured = *self.spot_trade_quote_ccy.lock();
586 let available = self
587 .trade_quote_ccy_lists
588 .load()
589 .get(&inst_id)
590 .cloned()
591 .unwrap_or_default();
592 spot_trade_quote_ccy_wire_value(
593 instrument_type,
594 configured.as_ref().map(Ustr::as_str),
595 &available,
596 )
597 .map_err(OKXWsError::ClientError)
598 }
599
600 fn inst_id_symbol_and_code_from_snapshot(
601 inst_id_codes: &AHashMap<Ustr, u64>,
602 inst_id: &InstrumentId,
603 action: &str,
604 ) -> Result<(Ustr, u64), OKXWsError> {
605 let inst_id_symbol = inst_id.symbol.inner();
606 let inst_id_code = inst_id_codes.get(&inst_id_symbol).copied().ok_or_else(|| {
607 OKXWsError::ClientError(format!(
608 "No instIdCode cached for {inst_id}, cannot {action} order"
609 ))
610 })?;
611 Ok((inst_id_symbol, inst_id_code))
612 }
613
614 pub fn set_vip_level(&self, vip_level: OKXVipLevel) {
618 self.vip_level.store(vip_level as u8, Ordering::Relaxed);
619 }
620
621 pub fn vip_level(&self) -> OKXVipLevel {
623 let level = self.vip_level.load(Ordering::Relaxed);
624 OKXVipLevel::from(level)
625 }
626
627 pub async fn connect(&mut self) -> anyhow::Result<()> {
633 let connect_lock = Arc::clone(&self.connect_lock);
634 let _connect_guard = connect_lock.lock().await;
635
636 if !self.handler_tasks.is_empty() && !self.handler_tasks.all_finished() {
637 anyhow::bail!("Cannot connect while previous WebSocket handler task is still running");
638 }
639
640 if !self.handler_tasks.is_open() || !self.handler_tasks.is_empty() {
641 self.handler_tasks.begin_shutdown();
642 self.handler_tasks
643 .finish_shutdown(Duration::from_secs(2), Duration::from_secs(2))
644 .await
645 .map_err(|e| anyhow::anyhow!("Previous WebSocket handler failed: {e}"))?;
646 self.handler_tasks.start_generation().map_err(|e| {
647 anyhow::anyhow!("Failed to start WebSocket handler task generation: {e}")
648 })?;
649 }
650 let handler_spawner = self.handler_tasks.spawner().map_err(|e| {
651 anyhow::anyhow!("Failed to acquire WebSocket handler task spawner: {e}")
652 })?;
653 let handler_abort = CancellationToken::new();
654 *self.handler_abort.lock() = handler_abort.clone();
655 let mut rollback = ConnectRollback {
656 handler_tasks: Arc::clone(&self.handler_tasks),
657 signal: Arc::clone(&self.signal),
658 handler_abort: handler_abort.clone(),
659 socket_control: self.socket_control.clone(),
660 armed: true,
661 };
662
663 self.signal.store(false, Ordering::Release);
665
666 let (message_handler, raw_rx) = channel_message_handler();
667
668 let headers = create_standard_nautilus_headers();
674
675 let config = WebSocketConfig {
676 url: self.url.clone(),
677 headers,
678 heartbeat_interval_secs: self.heartbeat,
679 heartbeat_payload: Some(TEXT_PING.to_string()),
680 connect_timeout_ms: None,
681 reconnect_delay_initial_ms: None,
682 reconnect_delay_max_ms: None,
683 reconnect_backoff_factor: None,
684 reconnect_jitter_ms: None,
685 reconnect_max_attempts: None,
686 heartbeat_timeout_secs: None,
687 idle_timeout_ms: None,
688 writer_capacity: None,
689 backend: self.transport_backend,
690 proxy_url: self
691 .proxy_url
692 .as_ref()
693 .map(|value| value.expose_secret().to_owned()),
694 max_message_size_bytes: None,
695 max_frame_size_bytes: None,
696 };
697
698 let keyed_quotas = vec![
699 (
700 OKX_RATE_LIMIT_KEY_SUBSCRIPTION[0].to_string(),
701 *OKX_WS_SUBSCRIPTION_QUOTA,
702 ),
703 (OKX_RATE_LIMIT_KEY_ORDER[0].to_string(), *OKX_WS_ORDER_QUOTA),
704 (
705 OKX_RATE_LIMIT_KEY_BATCH_ORDER[0].to_string(),
706 *OKX_WS_BATCH_ORDER_QUOTA,
707 ),
708 (
709 OKX_RATE_LIMIT_KEY_CANCEL[0].to_string(),
710 *OKX_WS_ORDER_QUOTA,
711 ),
712 (
713 OKX_RATE_LIMIT_KEY_BATCH_CANCEL[0].to_string(),
714 *OKX_WS_BATCH_ORDER_QUOTA,
715 ),
716 (
717 OKX_RATE_LIMIT_KEY_MASS_CANCEL[0].to_string(),
718 *OKX_WS_MASS_CANCEL_QUOTA,
719 ),
720 (OKX_RATE_LIMIT_KEY_AMEND[0].to_string(), *OKX_WS_ORDER_QUOTA),
721 (
722 OKX_RATE_LIMIT_KEY_BATCH_AMEND[0].to_string(),
723 *OKX_WS_BATCH_ORDER_QUOTA,
724 ),
725 (
726 OKX_RATE_LIMIT_KEY_ALGO_ORDER[0].to_string(),
727 *OKX_WS_ALGO_ORDER_QUOTA,
728 ),
729 (
730 OKX_RATE_LIMIT_KEY_ALGO_CANCEL[0].to_string(),
731 *OKX_WS_ALGO_CANCEL_QUOTA,
732 ),
733 ];
734
735 let client = WebSocketClient::builder()
736 .config(config)
737 .message_handler(message_handler)
738 .keyed_quotas(keyed_quotas)
739 .default_quota(*OKX_WS_CONNECTION_QUOTA)
740 .maybe_state_sink(self.socket_control.as_ref().map(|control| control.sink()))
741 .connect()
742 .await?;
743
744 client.set_auth_tracker(self.auth_tracker.clone(), false);
745 let ws_client = Arc::new(client);
746 let connection_epoch = ws_client.connection_epoch();
747
748 let connection_mode = ws_client.connection_mode_atomic();
749 let reconnect_handle = ws_client.reconnect_handle();
750
751 let (msg_tx, rx) = tokio::sync::mpsc::unbounded_channel::<OKXWsMessage>();
752
753 self.out_rx = Some(Arc::new(rx));
754
755 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
756
757 cmd_tx
759 .send(HandlerCommand::SetClient(Arc::clone(&ws_client)))
760 .map_err(|e| anyhow::anyhow!("Failed to send WebSocket client to handler: {e}"))?;
761
762 *self.cmd_tx.write().await = cmd_tx.clone();
763
764 self.connection_mode.store(connection_mode);
766
767 let handler_task = {
768 let auth_tracker = self.auth_tracker.clone();
769 let signal = self.signal.clone();
770 let subscriptions_state = self.subscriptions_state.clone();
771 let clock = self.clock;
772 let credential = self.credential.clone();
773 let cmd_tx_for_reconnect = cmd_tx.clone();
774 let subscriptions = self.subscriptions.clone();
775 let ws_client = Arc::clone(&ws_client);
776 let auth_timeout_secs = self.auth_timeout_secs;
777 let mut reconnect_epoch = connection_epoch;
778 let handler_spawner_for_auth = handler_spawner.clone();
779 let mut has_reconnected = false;
780
781 async move {
782 let mut handler = OKXWsFeedHandler::new(
783 signal.clone(),
784 cmd_rx,
785 raw_rx,
786 msg_tx,
787 auth_tracker.clone(),
788 credential.is_some(),
789 subscriptions_state.clone(),
790 subscriptions.clone(),
791 clock,
792 );
793
794 let resubscribe_all = || {
795 subscriptions
796 .retain(|topic, _| is_topic_subscribed(&subscriptions_state, topic));
797
798 let args = subscription_args(&subscriptions, &subscriptions_state);
799
800 for chunk in subscription_arg_batches(&args) {
801 if let Err(e) = cmd_tx_for_reconnect.send(HandlerCommand::Subscribe {
802 args: chunk.to_vec(),
803 }) {
804 log::error!("Failed to send resubscribe command: error={e}");
805 }
806 }
807 };
808
809 loop {
810 let message = tokio::select! {
811 biased;
812 () = handler_abort.cancelled() => {
813 log::debug!("Handler task aborted");
814 break;
815 }
816 message = handler.next() => message,
817 };
818
819 match message {
820 Some(OKXWsMessage::Reconnected) => {
821 let epoch = ws_client.connection_epoch();
822
823 if !advance_reconnect_epoch(
824 &mut reconnect_epoch,
825 epoch,
826 signal.load(Ordering::Acquire),
827 ws_client.is_active(),
828 ) {
829 continue;
830 }
831
832 auth_tracker.invalidate();
833 has_reconnected = true;
834
835 subscriptions_state.reset_after_reconnect();
836
837 if let Some(credential) = credential.clone() {
838 log::debug!("Re-authenticating after reconnection");
839 let signal = signal.clone();
840 let abort = handler_abort.clone();
841 let ws_client = Arc::clone(&ws_client);
842 let auth_tracker = auth_tracker.clone();
843
844 if let Err(e) = handler_spawner_for_auth.spawn(async move {
845 reauthenticate_session(
846 credential,
847 auth_tracker,
848 ws_client,
849 epoch,
850 clock,
851 auth_timeout_secs,
852 signal,
853 abort,
854 )
855 .await;
856 }) {
857 log::error!(
858 "Failed to spawn re-authentication task: error={e}"
859 );
860 }
861 }
862
863 if credential.is_none() {
866 log::debug!(
867 "No authentication required, resubscribing immediately"
868 );
869 resubscribe_all();
870 }
871
872 if handler.send(OKXWsMessage::Reconnected).is_err() {
874 log_receiver_dropped(&signal, "Reconnected");
875 break;
876 }
877 }
878 Some(OKXWsMessage::Authenticated) => {
879 if has_reconnected {
880 resubscribe_all();
881 }
882 }
883 Some(msg) => {
884 if handler.send(msg).is_err() {
885 log_receiver_dropped(&signal, "message");
886 break;
887 }
888 }
889 None => {
890 if handler.is_stopped() {
891 log::debug!("Stop signal received, ending message processing");
892 break;
893 }
894 log::debug!("WebSocket stream closed");
895 break;
896 }
897 }
898 }
899
900 log::debug!("Handler task exiting");
901 }
902 };
903
904 if let Err(e) = handler_spawner.spawn(handler_task) {
905 self.out_rx = None;
906 anyhow::bail!("Failed to register WebSocket handler task: {e}");
907 }
908
909 if let Some(control) = &self.socket_control {
910 control.register(move || reconnect_handle.request_reconnect());
911 }
912 log::debug!("Sent WebSocket client to handler");
913
914 if self.credential.is_some()
915 && let Err(e) = self.authenticate(&ws_client, connection_epoch).await
916 {
917 self.handler_tasks.begin_shutdown();
918 self.request_close().await;
919 let shutdown_result = self.close_stream_task(Duration::from_secs(2)).await;
920
921 if let Some(control) = &self.socket_control {
922 control.deregister();
923 }
924 self.out_rx = None;
925
926 match shutdown_result {
927 Ok(()) => anyhow::bail!("Authentication failed: {e}"),
928 Err(shutdown_error) => anyhow::bail!(
929 "Authentication failed: {e}; handler shutdown failed: {shutdown_error}"
930 ),
931 }
932 }
933
934 rollback.disarm();
935 Ok(())
936 }
937
938 async fn authenticate(
940 &self,
941 ws_client: &WebSocketClient,
942 connection_epoch: u64,
943 ) -> Result<(), Error> {
944 let credential = self.credential.as_ref().ok_or_else(|| {
945 Error::Io(std::io::Error::other(
946 "API credentials not available to authenticate",
947 ))
948 })?;
949
950 match authenticate_session(
951 credential,
952 &self.auth_tracker,
953 ws_client,
954 connection_epoch,
955 self.clock,
956 self.auth_timeout_secs,
957 )
958 .await
959 {
960 Ok(()) => Ok(()),
961 Err(e) if auth_attempt_superseded(&e) => {
962 if self
965 .auth_tracker
966 .wait_for_authenticated(Duration::from_secs(self.auth_timeout_secs))
967 .await
968 {
969 Ok(())
970 } else {
971 Err(e)
972 }
973 }
974 Err(e) => Err(e),
975 }
976 }
977
978 pub fn stream(&mut self) -> impl Stream<Item = OKXWsMessage> + 'static {
986 let rx = self
987 .out_rx
988 .take()
989 .expect("Data stream receiver already taken or not connected");
990 let mut rx = Arc::try_unwrap(rx).expect("Cannot take ownership - other references exist");
991 async_stream::stream! {
992 while let Some(data) = rx.recv().await {
993 yield data;
994 }
995 }
996 }
997
998 pub async fn wait_until_active(&self, timeout_secs: f64) -> Result<(), OKXWsError> {
1004 let timeout = time::Duration::from_secs_f64(timeout_secs);
1005
1006 time::timeout(timeout, async {
1007 while !self.is_active() {
1008 time::sleep(time::Duration::from_millis(10)).await;
1009 }
1010 })
1011 .await
1012 .map_err(|_| {
1013 OKXWsError::ClientError(format!(
1014 "WebSocket connection timeout after {timeout_secs} seconds"
1015 ))
1016 })?;
1017
1018 Ok(())
1019 }
1020
1021 pub(crate) fn begin_shutdown(&self) {
1022 self.handler_tasks.begin_shutdown();
1023 self.signal.store(true, Ordering::Release);
1024
1025 let handler_abort = self.handler_abort.lock().clone();
1026 handler_abort.cancel();
1027 }
1028
1029 pub(crate) async fn request_close(&self) {
1031 self.signal.store(true, Ordering::Release);
1032
1033 if let Err(e) = self.cmd_tx.read().await.send(HandlerCommand::Disconnect) {
1034 log::debug!("Handler channel closed before disconnect command was sent: {e}");
1035 } else {
1036 log::debug!("Sent disconnect command to handler");
1037 }
1038 }
1039
1040 pub async fn close(&mut self) -> Result<(), Error> {
1047 let connect_lock = Arc::clone(&self.connect_lock);
1048 let _connect_guard = connect_lock.lock().await;
1049
1050 self.close_locked().await
1051 }
1052
1053 async fn close_locked(&self) -> Result<(), Error> {
1054 log::debug!("Starting close process");
1055
1056 self.handler_tasks.begin_shutdown();
1057 self.request_close().await;
1058
1059 let task_result = self.close_stream_task(Duration::from_secs(2)).await;
1060
1061 self.index_pair_subscribers.clear();
1065
1066 if let Some(control) = &self.socket_control {
1067 control.deregister();
1068 }
1069
1070 log::debug!("Close process completed");
1071
1072 task_result
1073 }
1074
1075 async fn close_stream_task(&self, timeout: Duration) -> Result<(), Error> {
1076 match self.handler_tasks.finish_shutdown(timeout, timeout).await {
1077 Ok(()) => Ok(()),
1078 Err(error @ TaskShutdownError::Timeout { .. }) => Err(Error::Io(std::io::Error::new(
1079 std::io::ErrorKind::TimedOut,
1080 format!("Timed out joining WebSocket handler task after abort: {error}"),
1081 ))),
1082 Err(e) => Err(Error::Io(std::io::Error::other(format!(
1083 "WebSocket handler shutdown failed: {e}"
1084 )))),
1085 }
1086 }
1087
1088 pub fn get_subscriptions(&self, instrument_id: InstrumentId) -> Vec<OKXWsChannel> {
1090 let symbol = instrument_id.symbol.inner();
1091 self.subscriptions
1092 .iter()
1093 .filter(|arg| arg.inst_id == Some(symbol))
1094 .filter(|arg| is_topic_subscribed(&self.subscriptions_state, arg.key()))
1095 .map(|arg| arg.channel.clone())
1096 .collect()
1097 }
1098
1099 fn generate_unique_request_id(&self) -> String {
1100 self.request_id_counter
1101 .fetch_add(1, Ordering::SeqCst)
1102 .to_string()
1103 }
1104
1105 async fn subscribe(&self, args: Vec<OKXSubscriptionArg>) -> Result<(), OKXWsError> {
1106 self.cmd_tx
1108 .read()
1109 .await
1110 .send(HandlerCommand::Subscribe { args: args.clone() })
1111 .map_err(|e| {
1112 OKXWsError::ClientError(format!("Failed to send subscribe command: {e}"))
1113 })?;
1114
1115 self.record_subscriptions(&args);
1116 Ok(())
1117 }
1118
1119 fn record_subscriptions(&self, args: &[OKXSubscriptionArg]) {
1120 for arg in args {
1121 let topic = topic_from_subscription_arg(arg);
1122 let entry = self
1123 .subscriptions
1124 .entry(topic.clone())
1125 .or_insert_with(|| arg.clone());
1126 self.subscriptions_state.mark_subscribe(&topic);
1127 drop(entry);
1128 }
1129 }
1130
1131 async fn unsubscribe(&self, args: Vec<OKXSubscriptionArg>) -> Result<(), OKXWsError> {
1132 self.cmd_tx
1133 .read()
1134 .await
1135 .send(HandlerCommand::Unsubscribe { args: args.clone() })
1136 .map_err(|e| {
1137 OKXWsError::ClientError(format!("Failed to send unsubscribe command: {e}"))
1138 })?;
1139
1140 for arg in &args {
1141 let topic = topic_from_subscription_arg(arg);
1142 self.subscriptions_state.mark_unsubscribe(&topic);
1143 }
1144
1145 Ok(())
1146 }
1147
1148 async fn subscribe_inst_id(
1149 &self,
1150 channel: OKXWsChannel,
1151 inst_id: Ustr,
1152 ) -> Result<(), OKXWsError> {
1153 self.subscribe(vec![OKXSubscriptionArg {
1154 channel,
1155 inst_type: None,
1156 inst_family: None,
1157 inst_id: Some(inst_id),
1158 }])
1159 .await
1160 }
1161
1162 async fn unsubscribe_inst_id(
1163 &self,
1164 channel: OKXWsChannel,
1165 inst_id: Ustr,
1166 ) -> Result<(), OKXWsError> {
1167 self.unsubscribe(vec![OKXSubscriptionArg {
1168 channel,
1169 inst_type: None,
1170 inst_family: None,
1171 inst_id: Some(inst_id),
1172 }])
1173 .await
1174 }
1175
1176 pub async fn unsubscribe_all(&self) -> Result<(), OKXWsError> {
1185 let all_args = subscription_args(&self.subscriptions, &self.subscriptions_state);
1186
1187 if all_args.is_empty() {
1188 log::debug!("No active subscriptions to unsubscribe from");
1189 return Ok(());
1190 }
1191
1192 log::debug!("Batched unsubscribe from {} channels", all_args.len());
1193
1194 for chunk in subscription_arg_batches(&all_args) {
1195 self.unsubscribe(chunk.to_vec()).await?;
1196 }
1197
1198 self.index_pair_subscribers.clear();
1202
1203 Ok(())
1204 }
1205
1206 pub async fn subscribe_instruments(
1218 &self,
1219 instrument_type: OKXInstrumentType,
1220 ) -> Result<(), OKXWsError> {
1221 let arg = OKXSubscriptionArg {
1222 channel: OKXWsChannel::Instruments,
1223 inst_type: Some(instrument_type),
1224 inst_family: None,
1225 inst_id: None,
1226 };
1227 self.subscribe(vec![arg]).await
1228 }
1229
1230 pub async fn subscribe_instrument(
1244 &self,
1245 instrument_id: InstrumentId,
1246 ) -> Result<(), OKXWsError> {
1247 let inst_type = okx_instrument_type_from_symbol(instrument_id.symbol.as_str());
1248 log::debug!("Subscribing to instrument type {inst_type:?} for {instrument_id}");
1249 self.subscribe_instruments(inst_type).await
1250 }
1251
1252 pub async fn subscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1261 self.subscribe_book_with_depth(instrument_id, 0).await
1262 }
1263
1264 pub async fn subscribe_book_rpi(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1270 self.subscribe_inst_id(OKXWsChannel::BooksRpi, instrument_id.symbol.inner())
1271 .await
1272 }
1273
1274 pub(crate) async fn subscribe_book_channel(
1275 &self,
1276 instrument_id: InstrumentId,
1277 channel: OKXBookChannel,
1278 cancel: CancellationToken,
1279 gate: SnapshotGate,
1280 ) -> Result<(), OKXWsError> {
1281 let (completion, receiver) = tokio::sync::oneshot::channel();
1282 let sender = self.cmd_tx.read().await;
1283
1284 if cancel.is_cancelled() {
1285 return Ok(());
1286 }
1287
1288 let subscription = OKXSubscriptionArg {
1289 channel: ws_channel_for_book(channel),
1290 inst_type: None,
1291 inst_family: None,
1292 inst_id: Some(instrument_id.symbol.inner()),
1293 };
1294
1295 self.record_subscriptions(std::slice::from_ref(&subscription));
1296 sender
1297 .send(HandlerCommand::SubscribeBook {
1298 subscription,
1299 cancel: cancel.clone(),
1300 gate,
1301 completion,
1302 })
1303 .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?;
1304
1305 drop(sender);
1306 tokio::select! {
1307 biased;
1308 () = cancel.cancelled() => Ok(()),
1309 result = receiver => result.map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?,
1310 }
1311 }
1312
1313 pub(crate) async fn resubscribe_book_channel(
1315 &self,
1316 instrument_id: InstrumentId,
1317 channel: OKXBookChannel,
1318 cancel: CancellationToken,
1319 gate: SnapshotGate,
1320 ) -> Result<(), OKXWsError> {
1321 let (completion, receiver) = tokio::sync::oneshot::channel();
1322 let sender = self.cmd_tx.read().await;
1323
1324 if cancel.is_cancelled() {
1325 return Err(OKXWsError::ClientError("Book recovery canceled".into()));
1326 }
1327
1328 sender
1329 .send(HandlerCommand::Resubscribe {
1330 subscription: OKXSubscriptionArg {
1331 channel: ws_channel_for_book(channel),
1332 inst_type: None,
1333 inst_family: None,
1334 inst_id: Some(instrument_id.symbol.inner()),
1335 },
1336 cancel,
1337 gate,
1338 completion,
1339 })
1340 .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?;
1341
1342 drop(sender);
1343 receiver
1344 .await
1345 .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?
1346 }
1347
1348 pub async fn subscribe_book_depth5(
1360 &self,
1361 instrument_id: InstrumentId,
1362 ) -> Result<(), OKXWsError> {
1363 self.subscribe_inst_id(OKXWsChannel::Books5, instrument_id.symbol.inner())
1364 .await
1365 }
1366
1367 pub async fn subscribe_book50_l2_tbt(
1379 &self,
1380 instrument_id: InstrumentId,
1381 ) -> Result<(), OKXWsError> {
1382 self.subscribe_inst_id(OKXWsChannel::Books50Tbt, instrument_id.symbol.inner())
1383 .await
1384 }
1385
1386 pub async fn subscribe_book_l2_tbt(
1398 &self,
1399 instrument_id: InstrumentId,
1400 ) -> Result<(), OKXWsError> {
1401 self.subscribe_inst_id(OKXWsChannel::BooksTbt, instrument_id.symbol.inner())
1402 .await
1403 }
1404
1405 pub async fn subscribe_book_with_depth(
1419 &self,
1420 instrument_id: InstrumentId,
1421 depth: u16,
1422 ) -> anyhow::Result<()> {
1423 let vip = self.vip_level();
1424
1425 if !matches!(depth, 0 | 50 | 400) {
1426 anyhow::bail!("Invalid depth {depth}, must be 0, 50, or 400");
1427 }
1428
1429 if depth == 50 && vip < OKXVipLevel::Vip4 {
1430 anyhow::bail!("VIP level {vip} insufficient for 50 depth subscription (requires VIP4)");
1431 }
1432
1433 let channel = select_book_channel(depth as usize, vip);
1434 self.subscribe_inst_id(ws_channel_for_book(channel), instrument_id.symbol.inner())
1435 .await?;
1436 Ok(())
1437 }
1438
1439 pub async fn subscribe_quotes(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1452 self.subscribe_inst_id(OKXWsChannel::BboTbt, instrument_id.symbol.inner())
1453 .await
1454 }
1455
1456 pub async fn subscribe_trades(
1470 &self,
1471 instrument_id: InstrumentId,
1472 aggregated: bool,
1473 ) -> Result<(), OKXWsError> {
1474 let channel = if aggregated {
1475 OKXWsChannel::TradesAll
1476 } else {
1477 OKXWsChannel::Trades
1478 };
1479 self.subscribe_inst_id(channel, instrument_id.symbol.inner())
1480 .await
1481 }
1482
1483 pub async fn subscribe_ticker(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1495 self.subscribe_inst_id(OKXWsChannel::Tickers, instrument_id.symbol.inner())
1496 .await
1497 }
1498
1499 pub async fn subscribe_mark_prices(
1511 &self,
1512 instrument_id: InstrumentId,
1513 ) -> Result<(), OKXWsError> {
1514 self.subscribe_inst_id(OKXWsChannel::MarkPrice, instrument_id.symbol.inner())
1515 .await
1516 }
1517
1518 pub async fn subscribe_index_prices(
1530 &self,
1531 instrument_id: InstrumentId,
1532 ) -> Result<(), OKXWsError> {
1533 let symbol = instrument_id.symbol.inner();
1535 let (base, quote) = parse_base_quote_from_symbol(symbol.as_str())
1536 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1537 let base_pair = Ustr::from(&format!("{base}-{quote}"));
1538
1539 let _guard = self.index_pair_transition.lock().await;
1545
1546 let is_first = {
1551 let mut count = self.index_pair_subscribers.entry(base_pair).or_insert(0);
1552 *count += 1;
1553 *count == 1
1554 };
1555
1556 if !is_first {
1557 return Ok(());
1558 }
1559
1560 let arg = OKXSubscriptionArg {
1561 channel: OKXWsChannel::IndexTickers,
1562 inst_type: None,
1563 inst_family: None,
1564 inst_id: Some(base_pair),
1565 };
1566
1567 match self.subscribe(vec![arg]).await {
1568 Ok(()) => Ok(()),
1569 Err(e) => {
1570 self.index_pair_subscribers.remove(&base_pair);
1579 Err(e)
1580 }
1581 }
1582 }
1583
1584 pub async fn subscribe_option_summary(&self, inst_family: Ustr) -> Result<(), OKXWsError> {
1597 let arg = OKXSubscriptionArg {
1598 channel: OKXWsChannel::OptionSummary,
1599 inst_type: None,
1600 inst_family: Some(inst_family),
1601 inst_id: None,
1602 };
1603 self.subscribe(vec![arg]).await
1604 }
1605
1606 pub async fn subscribe_event_contract_markets(&self) -> Result<(), OKXWsError> {
1616 let arg = OKXSubscriptionArg {
1617 channel: OKXWsChannel::EventContractMarkets,
1618 inst_type: Some(OKXInstrumentType::Events),
1619 inst_family: None,
1620 inst_id: None,
1621 };
1622 self.subscribe(vec![arg]).await
1623 }
1624
1625 pub fn option_greeks_subs(&self) -> &Arc<AtomicMap<InstrumentId, AHashSet<OKXGreeksType>>> {
1629 &self.option_greeks_subs
1630 }
1631
1632 pub fn add_option_greeks_sub(&self, instrument_id: InstrumentId) {
1635 let both: AHashSet<OKXGreeksType> =
1636 [OKXGreeksType::Bs, OKXGreeksType::Pa].into_iter().collect();
1637 self.option_greeks_subs.insert(instrument_id, both);
1638 }
1639
1640 pub fn add_option_greeks_sub_with_conventions(
1643 &self,
1644 instrument_id: InstrumentId,
1645 conventions: AHashSet<OKXGreeksType>,
1646 ) {
1647 let set = if conventions.is_empty() {
1648 [OKXGreeksType::Bs, OKXGreeksType::Pa].into_iter().collect()
1649 } else {
1650 conventions
1651 };
1652 self.option_greeks_subs.insert(instrument_id, set);
1653 }
1654
1655 pub fn remove_option_greeks_sub(&self, instrument_id: &InstrumentId) {
1657 self.option_greeks_subs.remove(instrument_id);
1658 }
1659
1660 pub async fn subscribe_funding_rates(
1672 &self,
1673 instrument_id: InstrumentId,
1674 ) -> Result<(), OKXWsError> {
1675 self.subscribe_inst_id(OKXWsChannel::FundingRate, instrument_id.symbol.inner())
1676 .await
1677 }
1678
1679 pub async fn subscribe_bars(&self, bar_type: BarType) -> Result<(), OKXWsError> {
1691 let channel = bar_spec_as_okx_channel(bar_type.spec())
1693 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1694 self.subscribe_inst_id(channel, bar_type.instrument_id().symbol.inner())
1695 .await
1696 }
1697
1698 pub async fn unsubscribe_instruments(
1704 &self,
1705 instrument_type: OKXInstrumentType,
1706 ) -> Result<(), OKXWsError> {
1707 let arg = OKXSubscriptionArg {
1708 channel: OKXWsChannel::Instruments,
1709 inst_type: Some(instrument_type),
1710 inst_family: None,
1711 inst_id: None,
1712 };
1713 self.unsubscribe(vec![arg]).await
1714 }
1715
1716 #[allow(
1726 clippy::unused_async,
1727 clippy::unused_async_trait_impl,
1728 reason = "async signature is kept for parity with the other unsubscribe methods and callers"
1729 )]
1730 pub async fn unsubscribe_instrument(
1731 &self,
1732 instrument_id: InstrumentId,
1733 ) -> Result<(), OKXWsError> {
1734 log::debug!("Instrument unsubscribe is a no-op (shared per-type channel): {instrument_id}");
1735 Ok(())
1736 }
1737
1738 pub async fn unsubscribe_book(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1744 self.unsubscribe_inst_id(OKXWsChannel::Books, instrument_id.symbol.inner())
1745 .await
1746 }
1747
1748 pub async fn unsubscribe_book_rpi(
1754 &self,
1755 instrument_id: InstrumentId,
1756 ) -> Result<(), OKXWsError> {
1757 self.unsubscribe_inst_id(OKXWsChannel::BooksRpi, instrument_id.symbol.inner())
1758 .await
1759 }
1760
1761 pub async fn unsubscribe_book_depth5(
1767 &self,
1768 instrument_id: InstrumentId,
1769 ) -> Result<(), OKXWsError> {
1770 self.unsubscribe_inst_id(OKXWsChannel::Books5, instrument_id.symbol.inner())
1771 .await
1772 }
1773
1774 pub async fn unsubscribe_book50_l2_tbt(
1780 &self,
1781 instrument_id: InstrumentId,
1782 ) -> Result<(), OKXWsError> {
1783 self.unsubscribe_inst_id(OKXWsChannel::Books50Tbt, instrument_id.symbol.inner())
1784 .await
1785 }
1786
1787 pub async fn unsubscribe_book_l2_tbt(
1793 &self,
1794 instrument_id: InstrumentId,
1795 ) -> Result<(), OKXWsError> {
1796 self.unsubscribe_inst_id(OKXWsChannel::BooksTbt, instrument_id.symbol.inner())
1797 .await
1798 }
1799
1800 pub async fn unsubscribe_quotes(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1806 self.unsubscribe_inst_id(OKXWsChannel::BboTbt, instrument_id.symbol.inner())
1807 .await
1808 }
1809
1810 pub async fn unsubscribe_ticker(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1816 self.unsubscribe_inst_id(OKXWsChannel::Tickers, instrument_id.symbol.inner())
1817 .await
1818 }
1819
1820 pub async fn unsubscribe_mark_prices(
1826 &self,
1827 instrument_id: InstrumentId,
1828 ) -> Result<(), OKXWsError> {
1829 self.unsubscribe_inst_id(OKXWsChannel::MarkPrice, instrument_id.symbol.inner())
1830 .await
1831 }
1832
1833 pub async fn unsubscribe_index_prices(
1846 &self,
1847 instrument_id: InstrumentId,
1848 ) -> Result<(), OKXWsError> {
1849 let symbol = instrument_id.symbol.inner();
1850 let (base, quote) = parse_base_quote_from_symbol(symbol.as_str())
1851 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1852 let base_pair = Ustr::from(&format!("{base}-{quote}"));
1853
1854 let _guard = self.index_pair_transition.lock().await;
1857
1858 let is_last = {
1859 let Some(mut count) = self.index_pair_subscribers.get_mut(&base_pair) else {
1860 return Ok(());
1862 };
1863 *count = count.saturating_sub(1);
1864 *count == 0
1865 };
1866
1867 if !is_last {
1868 return Ok(());
1869 }
1870
1871 self.index_pair_subscribers
1872 .remove_if(&base_pair, |_, count| *count == 0);
1873
1874 let arg = OKXSubscriptionArg {
1875 channel: OKXWsChannel::IndexTickers,
1876 inst_type: None,
1877 inst_family: None,
1878 inst_id: Some(base_pair),
1879 };
1880 self.unsubscribe(vec![arg]).await
1881 }
1882
1883 pub async fn unsubscribe_option_summary(&self, inst_family: Ustr) -> Result<(), OKXWsError> {
1889 let arg = OKXSubscriptionArg {
1890 channel: OKXWsChannel::OptionSummary,
1891 inst_type: None,
1892 inst_family: Some(inst_family),
1893 inst_id: None,
1894 };
1895 self.unsubscribe(vec![arg]).await
1896 }
1897
1898 pub async fn unsubscribe_event_contract_markets(&self) -> Result<(), OKXWsError> {
1904 let arg = OKXSubscriptionArg {
1905 channel: OKXWsChannel::EventContractMarkets,
1906 inst_type: Some(OKXInstrumentType::Events),
1907 inst_family: None,
1908 inst_id: None,
1909 };
1910 self.unsubscribe(vec![arg]).await
1911 }
1912
1913 pub async fn unsubscribe_funding_rates(
1919 &self,
1920 instrument_id: InstrumentId,
1921 ) -> Result<(), OKXWsError> {
1922 self.unsubscribe_inst_id(OKXWsChannel::FundingRate, instrument_id.symbol.inner())
1923 .await
1924 }
1925
1926 pub async fn unsubscribe_trades(
1932 &self,
1933 instrument_id: InstrumentId,
1934 aggregated: bool,
1935 ) -> Result<(), OKXWsError> {
1936 let channel = if aggregated {
1937 OKXWsChannel::TradesAll
1938 } else {
1939 OKXWsChannel::Trades
1940 };
1941 self.unsubscribe_inst_id(channel, instrument_id.symbol.inner())
1942 .await
1943 }
1944
1945 pub async fn unsubscribe_bars(&self, bar_type: BarType) -> Result<(), OKXWsError> {
1951 let channel = bar_spec_as_okx_channel(bar_type.spec())
1952 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1953 self.unsubscribe_inst_id(channel, bar_type.instrument_id().symbol.inner())
1954 .await
1955 }
1956
1957 pub async fn subscribe_orders(
1963 &self,
1964 instrument_type: OKXInstrumentType,
1965 ) -> Result<(), OKXWsError> {
1966 let arg = OKXSubscriptionArg {
1967 channel: OKXWsChannel::Orders,
1968 inst_type: Some(instrument_type),
1969 inst_family: None,
1970 inst_id: None,
1971 };
1972 self.subscribe(vec![arg]).await
1973 }
1974
1975 pub async fn unsubscribe_orders(
1981 &self,
1982 instrument_type: OKXInstrumentType,
1983 ) -> Result<(), OKXWsError> {
1984 let arg = OKXSubscriptionArg {
1985 channel: OKXWsChannel::Orders,
1986 inst_type: Some(instrument_type),
1987 inst_family: None,
1988 inst_id: None,
1989 };
1990 self.unsubscribe(vec![arg]).await
1991 }
1992
1993 pub async fn subscribe_spread_orders(&self) -> Result<(), OKXWsError> {
1999 let arg = OKXSubscriptionArg {
2000 channel: OKXWsChannel::SprdOrders,
2001 inst_type: None,
2002 inst_family: None,
2003 inst_id: None,
2004 };
2005 self.subscribe(vec![arg]).await
2006 }
2007
2008 pub async fn unsubscribe_spread_orders(&self) -> Result<(), OKXWsError> {
2014 let arg = OKXSubscriptionArg {
2015 channel: OKXWsChannel::SprdOrders,
2016 inst_type: None,
2017 inst_family: None,
2018 inst_id: None,
2019 };
2020 self.unsubscribe(vec![arg]).await
2021 }
2022
2023 pub async fn subscribe_spread_quotes(
2029 &self,
2030 instrument_id: InstrumentId,
2031 ) -> Result<(), OKXWsError> {
2032 self.subscribe_inst_id(OKXWsChannel::SprdBboTbt, instrument_id.symbol.inner())
2033 .await
2034 }
2035
2036 pub async fn subscribe_spread_book(
2042 &self,
2043 instrument_id: InstrumentId,
2044 ) -> Result<(), OKXWsError> {
2045 self.subscribe_inst_id(OKXWsChannel::SprdBooks5, instrument_id.symbol.inner())
2046 .await
2047 }
2048
2049 pub async fn subscribe_spread_trades(
2055 &self,
2056 instrument_id: InstrumentId,
2057 ) -> Result<(), OKXWsError> {
2058 self.subscribe_inst_id(OKXWsChannel::SprdPublicTrades, instrument_id.symbol.inner())
2059 .await
2060 }
2061
2062 pub async fn unsubscribe_spread_quotes(
2068 &self,
2069 instrument_id: InstrumentId,
2070 ) -> Result<(), OKXWsError> {
2071 self.unsubscribe_inst_id(OKXWsChannel::SprdBboTbt, instrument_id.symbol.inner())
2072 .await
2073 }
2074
2075 pub async fn unsubscribe_spread_book(
2081 &self,
2082 instrument_id: InstrumentId,
2083 ) -> Result<(), OKXWsError> {
2084 self.unsubscribe_inst_id(OKXWsChannel::SprdBooks5, instrument_id.symbol.inner())
2085 .await
2086 }
2087
2088 pub async fn unsubscribe_spread_trades(
2094 &self,
2095 instrument_id: InstrumentId,
2096 ) -> Result<(), OKXWsError> {
2097 self.unsubscribe_inst_id(OKXWsChannel::SprdPublicTrades, instrument_id.symbol.inner())
2098 .await
2099 }
2100
2101 pub async fn subscribe_orders_algo(
2107 &self,
2108 instrument_type: OKXInstrumentType,
2109 ) -> Result<(), OKXWsError> {
2110 let arg = OKXSubscriptionArg {
2111 channel: OKXWsChannel::OrdersAlgo,
2112 inst_type: Some(instrument_type),
2113 inst_family: None,
2114 inst_id: None,
2115 };
2116 self.subscribe(vec![arg]).await
2117 }
2118
2119 pub async fn unsubscribe_orders_algo(
2125 &self,
2126 instrument_type: OKXInstrumentType,
2127 ) -> Result<(), OKXWsError> {
2128 let arg = OKXSubscriptionArg {
2129 channel: OKXWsChannel::OrdersAlgo,
2130 inst_type: Some(instrument_type),
2131 inst_family: None,
2132 inst_id: None,
2133 };
2134 self.unsubscribe(vec![arg]).await
2135 }
2136
2137 pub async fn subscribe_algo_advance(
2143 &self,
2144 instrument_type: OKXInstrumentType,
2145 ) -> Result<(), OKXWsError> {
2146 let arg = OKXSubscriptionArg {
2147 channel: OKXWsChannel::AlgoAdvance,
2148 inst_type: Some(instrument_type),
2149 inst_family: None,
2150 inst_id: None,
2151 };
2152 self.subscribe(vec![arg]).await
2153 }
2154
2155 pub async fn unsubscribe_algo_advance(
2161 &self,
2162 instrument_type: OKXInstrumentType,
2163 ) -> Result<(), OKXWsError> {
2164 let arg = OKXSubscriptionArg {
2165 channel: OKXWsChannel::AlgoAdvance,
2166 inst_type: Some(instrument_type),
2167 inst_family: None,
2168 inst_id: None,
2169 };
2170 self.unsubscribe(vec![arg]).await
2171 }
2172
2173 pub async fn subscribe_account(&self) -> Result<(), OKXWsError> {
2179 let arg = OKXSubscriptionArg {
2180 channel: OKXWsChannel::Account,
2181 inst_type: None,
2182 inst_family: None,
2183 inst_id: None,
2184 };
2185 self.subscribe(vec![arg]).await
2186 }
2187
2188 pub async fn unsubscribe_account(&self) -> Result<(), OKXWsError> {
2194 let arg = OKXSubscriptionArg {
2195 channel: OKXWsChannel::Account,
2196 inst_type: None,
2197 inst_family: None,
2198 inst_id: None,
2199 };
2200 self.unsubscribe(vec![arg]).await
2201 }
2202
2203 pub async fn subscribe_positions(
2213 &self,
2214 inst_type: OKXInstrumentType,
2215 ) -> Result<(), OKXWsError> {
2216 let arg = OKXSubscriptionArg {
2217 channel: OKXWsChannel::Positions,
2218 inst_type: Some(inst_type),
2219 inst_family: None,
2220 inst_id: None,
2221 };
2222 self.subscribe(vec![arg]).await
2223 }
2224
2225 pub async fn unsubscribe_positions(
2231 &self,
2232 inst_type: OKXInstrumentType,
2233 ) -> Result<(), OKXWsError> {
2234 let arg = OKXSubscriptionArg {
2235 channel: OKXWsChannel::Positions,
2236 inst_type: Some(inst_type),
2237 inst_family: None,
2238 inst_id: None,
2239 };
2240 self.unsubscribe(vec![arg]).await
2241 }
2242
2243 pub async fn subscribe_liquidation_warning(
2253 &self,
2254 instrument_type: OKXInstrumentType,
2255 ) -> Result<(), OKXWsError> {
2256 let arg = OKXSubscriptionArg {
2257 channel: OKXWsChannel::LiquidationWarning,
2258 inst_type: Some(instrument_type),
2259 inst_family: None,
2260 inst_id: None,
2261 };
2262 self.subscribe(vec![arg]).await
2263 }
2264
2265 pub async fn unsubscribe_liquidation_warning(
2271 &self,
2272 instrument_type: OKXInstrumentType,
2273 ) -> Result<(), OKXWsError> {
2274 let arg = OKXSubscriptionArg {
2275 channel: OKXWsChannel::LiquidationWarning,
2276 inst_type: Some(instrument_type),
2277 inst_family: None,
2278 inst_id: None,
2279 };
2280 self.unsubscribe(vec![arg]).await
2281 }
2282
2283 async fn ws_batch_place_orders(
2289 &self,
2290 args: Vec<Value>,
2291 client_order_ids: Vec<ClientOrderId>,
2292 ) -> Result<(), OKXWsError> {
2293 let request_id = self.generate_unique_request_id();
2294 let request = OKXWsRequest::<Value> {
2295 id: Some(request_id.clone()),
2296 op: super::enums::OKXWsOperation::BatchOrders,
2297 exp_time: None,
2298 args,
2299 };
2300
2301 let payload = serde_json::to_string(&request)
2302 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize batch orders: {e}")))?;
2303
2304 let cmd = HandlerCommand::Send {
2305 payload,
2306 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_BATCH_ORDER.to_vec()),
2307 request_id: Some(request_id),
2308 client_order_ids,
2309 op: Some(super::enums::OKXWsOperation::BatchOrders),
2310 };
2311
2312 self.send_cmd(cmd).await
2313 }
2314
2315 async fn ws_batch_cancel_orders(
2321 &self,
2322 args: Vec<Value>,
2323 client_order_ids: Vec<ClientOrderId>,
2324 causation_ids: Vec<(ClientOrderId, UUID4)>,
2325 ) -> Result<(), OKXWsError> {
2326 let request_id = self.generate_unique_request_id();
2327 let request = OKXWsRequest::<Value> {
2328 id: Some(request_id.clone()),
2329 op: super::enums::OKXWsOperation::BatchCancelOrders,
2330 exp_time: None,
2331 args,
2332 };
2333
2334 let payload = serde_json::to_string(&request)
2335 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize batch cancel: {e}")))?;
2336
2337 if !causation_ids.is_empty() {
2338 self.pending_command_ids
2339 .insert(request_id.clone(), causation_ids);
2340 }
2341
2342 let cmd = HandlerCommand::Send {
2343 payload,
2344 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_BATCH_CANCEL.to_vec()),
2345 request_id: Some(request_id.clone()),
2346 client_order_ids,
2347 op: Some(super::enums::OKXWsOperation::BatchCancelOrders),
2348 };
2349
2350 let result = self.send_cmd(cmd).await;
2351 if result.is_err() {
2352 self.pending_command_ids.remove(&request_id);
2353 }
2354
2355 result
2356 }
2357
2358 async fn ws_batch_amend_orders(
2364 &self,
2365 args: Vec<Value>,
2366 client_order_ids: Vec<ClientOrderId>,
2367 ) -> Result<(), OKXWsError> {
2368 let request_id = self.generate_unique_request_id();
2369 let request = OKXWsRequest::<Value> {
2370 id: Some(request_id.clone()),
2371 op: super::enums::OKXWsOperation::BatchAmendOrders,
2372 exp_time: None,
2373 args,
2374 };
2375
2376 let payload = serde_json::to_string(&request)
2377 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize batch amend: {e}")))?;
2378
2379 let cmd = HandlerCommand::Send {
2380 payload,
2381 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_BATCH_AMEND.to_vec()),
2382 request_id: Some(request_id),
2383 client_order_ids,
2384 op: Some(super::enums::OKXWsOperation::BatchAmendOrders),
2385 };
2386
2387 self.send_cmd(cmd).await
2388 }
2389
2390 #[expect(clippy::too_many_arguments)]
2402 pub async fn submit_order(
2403 &self,
2404 trader_id: TraderId,
2405 strategy_id: StrategyId,
2406 instrument_id: InstrumentId,
2407 td_mode: OKXTradeMode,
2408 client_order_id: ClientOrderId,
2409 order_side: OrderSide,
2410 order_type: OrderType,
2411 quantity: Quantity,
2412 time_in_force: Option<TimeInForce>,
2413 price: Option<Price>,
2414 trigger_price: Option<Price>,
2415 post_only: Option<bool>,
2416 reduce_only: Option<bool>,
2417 quote_quantity: Option<bool>,
2418 position_side: Option<PositionSide>,
2419 attach_algo_ords: Option<Vec<WsAttachAlgoOrdParams>>,
2420 px_usd: Option<String>,
2421 px_vol: Option<String>,
2422 outcome: Option<String>,
2423 slippage_pct: Option<String>,
2424 rpi: Option<bool>,
2425 rpi_taker_access: Option<bool>,
2426 rpi_px_round: Option<bool>,
2427 ) -> Result<(), OKXWsError> {
2428 let rpi = rpi.unwrap_or(false);
2429
2430 if !OKX_SUPPORTED_ORDER_TYPES.contains(&order_type) {
2431 return Err(OKXWsError::ClientError(format!(
2432 "Unsupported order type: {order_type:?}",
2433 )));
2434 }
2435
2436 validate_order_time_in_force(time_in_force).map_err(OKXWsError::ClientError)?;
2437
2438 let mut builder = WsPostOrderParamsBuilder::default();
2439
2440 let inst_id_code = self
2441 .get_inst_id_code(&instrument_id.symbol.inner())
2442 .ok_or_else(|| {
2443 OKXWsError::ClientError(format!(
2444 "No instIdCode cached for {instrument_id}, cannot submit order"
2445 ))
2446 })?;
2447 builder.inst_id_code(inst_id_code);
2448
2449 builder.td_mode(td_mode);
2450 builder.cl_ord_id(client_order_id.as_str());
2451
2452 let (instrument_type, quote_currency) = {
2453 let instruments = self.instruments_cache.load();
2454 let symbol = instrument_id.symbol.inner();
2455 let instrument = instruments.get(&symbol).ok_or_else(|| {
2456 OKXWsError::ClientError(format!("Unknown instrument {instrument_id}"))
2457 })?;
2458 let instrument_type = okx_instrument_type(instrument)
2459 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
2460 (instrument_type, instrument.quote_currency())
2461 };
2462
2463 if instrument_type == OKXInstrumentType::Option
2465 && matches!(order_type, OrderType::Market | OrderType::MarketToLimit)
2466 {
2467 return Err(OKXWsError::ClientError(
2468 "Market orders are not supported for OKX options, use Limit orders instead"
2469 .to_string(),
2470 ));
2471 }
2472
2473 match instrument_type {
2474 OKXInstrumentType::Spot | OKXInstrumentType::Margin => {
2475 builder.ccy(quote_currency.to_string());
2477 }
2478 OKXInstrumentType::Swap | OKXInstrumentType::Futures => {
2479 builder.ccy(quote_currency.to_string());
2481
2482 if position_side.is_none() {
2485 builder.pos_side(OKXPositionSide::Net);
2486 }
2487 }
2488 OKXInstrumentType::Option => {
2489 builder.ccy(quote_currency.to_string());
2490
2491 if position_side.is_none() {
2492 builder.pos_side(OKXPositionSide::Net);
2493 }
2494 }
2495 OKXInstrumentType::Events => {}
2496 _ => {
2497 builder.ccy(quote_currency.to_string());
2498
2499 if position_side.is_none() {
2500 builder.pos_side(OKXPositionSide::Net);
2501 }
2502 }
2503 }
2504
2505 if let Some(reduce_only) = okx_reduce_only_wire_value(
2506 instrument_type,
2507 td_mode,
2508 order_side,
2509 position_side,
2510 reduce_only,
2511 )
2512 .map_err(OKXWsError::ClientError)?
2513 {
2514 builder.reduce_only(reduce_only);
2515 }
2516
2517 if let Some(attach_algo_ords) = attach_algo_ords {
2518 builder.attach_algo_ords(attach_algo_ords);
2519 }
2520
2521 if let Some(tgt_ccy) =
2522 okx_market_target_currency(instrument_type, order_side, order_type, quote_quantity)
2523 .map_err(|e| OKXWsError::ClientError(e.to_string()))?
2524 {
2525 builder.tgt_ccy(tgt_ccy);
2526 }
2527
2528 builder.side(order_side);
2529
2530 if let Some(pos_side) = position_side {
2531 builder.pos_side(pos_side);
2532 }
2533
2534 validate_regular_order_params(
2538 instrument_type,
2539 order_type,
2540 time_in_force,
2541 post_only.unwrap_or(false),
2542 rpi,
2543 outcome.as_deref(),
2544 )
2545 .map_err(OKXWsError::ClientError)?;
2546
2547 let (okx_ord_type, price) = if rpi {
2548 (OKXOrderType::Rpi, price)
2549 } else if post_only.unwrap_or(false) {
2550 (OKXOrderType::PostOnly, price)
2551 } else if let Some(tif) = time_in_force {
2552 match (order_type, tif) {
2553 (OrderType::Market, TimeInForce::Ioc) => {
2554 if matches!(
2556 instrument_type,
2557 OKXInstrumentType::Spot | OKXInstrumentType::Option
2558 ) {
2559 (OKXOrderType::Market, price)
2560 } else {
2561 (OKXOrderType::OptimalLimitIoc, price)
2562 }
2563 }
2564 (OrderType::Limit, TimeInForce::Fok) => (OKXOrderType::Fok, price),
2565 (OrderType::Limit, TimeInForce::Ioc) => (OKXOrderType::Ioc, price),
2566 _ => (OKXOrderType::from(order_type), price),
2567 }
2568 } else {
2569 (OKXOrderType::from(order_type), price)
2570 };
2571
2572 log::debug!(
2573 "Order type mapping: order_type={order_type:?}, time_in_force={time_in_force:?}, post_only={post_only:?} -> okx_ord_type={okx_ord_type:?}"
2574 );
2575
2576 if let Some(outcome) = outcome {
2577 builder.outcome(outcome);
2578 }
2579
2580 if let Some(slippage) = slippage_pct {
2581 builder.slippage_pct(slippage);
2582 }
2583
2584 if let Some(rpi_taker_access) = rpi_taker_access {
2585 builder.rpi_taker_access(rpi_taker_access);
2586 }
2587
2588 if let Some(rpi_px_round) = rpi_px_round {
2589 builder.rpi_px_round(rpi_px_round);
2590 }
2591
2592 if let Some(trade_quote_ccy) =
2593 self.resolve_spot_trade_quote_ccy(instrument_type, instrument_id.symbol.inner())?
2594 {
2595 builder.trade_quote_ccy(trade_quote_ccy);
2596 }
2597
2598 builder.ord_type(okx_ord_type);
2599 builder.sz(quantity.to_string());
2600
2601 if let Some(usd) = px_usd {
2603 builder.px_usd(usd);
2604 } else if let Some(vol) = px_vol {
2605 builder.px_vol(vol);
2606 } else if let Some(tp) = trigger_price {
2607 builder.px(tp.to_string());
2608 } else if let Some(p) = price {
2609 builder.px(p.to_string());
2610 }
2611
2612 builder.tag(OKX_NAUTILUS_BROKER_ID);
2613
2614 let params = builder
2615 .build()
2616 .map_err(|e| OKXWsError::ClientError(format!("Build order params error: {e}")))?;
2617
2618 let request_id = self.generate_unique_request_id();
2619 let request = OKXWsRequest {
2620 id: Some(request_id.clone()),
2621 op: super::enums::OKXWsOperation::Order,
2622 exp_time: None,
2623 args: vec![params],
2624 };
2625
2626 let payload = serde_json::to_string(&request)
2627 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize order: {e}")))?;
2628
2629 let cl_ord_key = client_order_id.to_string();
2630 self.pending_orders.insert(
2631 cl_ord_key.clone(),
2632 PendingOrderInfo {
2633 trader_id,
2634 strategy_id,
2635 instrument_id,
2636 },
2637 );
2638
2639 let cmd = HandlerCommand::Send {
2640 payload,
2641 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_ORDER.to_vec()),
2642 request_id: Some(request_id),
2643 client_order_ids: vec![client_order_id],
2644 op: Some(super::enums::OKXWsOperation::Order),
2645 };
2646
2647 let result = self.send_cmd(cmd).await;
2648
2649 if result.is_err() {
2650 self.pending_orders.remove(&cl_ord_key);
2651 }
2652
2653 result
2654 }
2655
2656 #[expect(clippy::too_many_arguments)]
2672 pub async fn modify_order(
2673 &self,
2674 trader_id: TraderId,
2675 strategy_id: StrategyId,
2676 instrument_id: InstrumentId,
2677 client_order_id: Option<ClientOrderId>,
2678 price: Option<Price>,
2679 quantity: Option<Quantity>,
2680 venue_order_id: Option<VenueOrderId>,
2681 new_px_usd: Option<String>,
2682 new_px_vol: Option<String>,
2683 rpi_taker_access: Option<bool>,
2684 rpi_px_round: Option<bool>,
2685 ) -> Result<(), OKXWsError> {
2686 self.modify_order_with_causation(
2687 trader_id,
2688 strategy_id,
2689 instrument_id,
2690 client_order_id,
2691 price,
2692 quantity,
2693 venue_order_id,
2694 new_px_usd,
2695 new_px_vol,
2696 rpi_taker_access,
2697 rpi_px_round,
2698 None,
2699 )
2700 .await
2701 }
2702
2703 #[expect(clippy::too_many_arguments)]
2704 pub(crate) async fn modify_order_with_causation(
2705 &self,
2706 trader_id: TraderId,
2707 strategy_id: StrategyId,
2708 instrument_id: InstrumentId,
2709 client_order_id: Option<ClientOrderId>,
2710 price: Option<Price>,
2711 quantity: Option<Quantity>,
2712 venue_order_id: Option<VenueOrderId>,
2713 new_px_usd: Option<String>,
2714 new_px_vol: Option<String>,
2715 rpi_taker_access: Option<bool>,
2716 rpi_px_round: Option<bool>,
2717 causation_id: Option<UUID4>,
2718 ) -> Result<(), OKXWsError> {
2719 let mut builder = WsAmendOrderParamsBuilder::default();
2720
2721 let inst_id_code = self
2722 .get_inst_id_code(&instrument_id.symbol.inner())
2723 .ok_or_else(|| {
2724 OKXWsError::ClientError(format!(
2725 "No instIdCode cached for {instrument_id}, cannot amend order"
2726 ))
2727 })?;
2728 builder.inst_id_code(inst_id_code);
2729
2730 if let Some(venue_order_id) = venue_order_id {
2731 builder.ord_id(venue_order_id.as_str());
2732 }
2733
2734 let cl_ord_key = client_order_id.map(|id| id.to_string());
2735
2736 if let Some(client_order_id) = client_order_id {
2737 builder.cl_ord_id(client_order_id.as_str());
2738 self.pending_amends.insert(
2739 client_order_id.to_string(),
2740 PendingOrderInfo {
2741 trader_id,
2742 strategy_id,
2743 instrument_id,
2744 },
2745 );
2746 }
2747
2748 if let Some(usd) = new_px_usd {
2750 builder.new_px_usd(usd);
2751 } else if let Some(vol) = new_px_vol {
2752 builder.new_px_vol(vol);
2753 } else if let Some(price) = price {
2754 builder.new_px(price.to_string());
2755 }
2756
2757 if let Some(quantity) = quantity {
2758 builder.new_sz(quantity.to_string());
2759 }
2760
2761 if let Some(rpi_taker_access) = rpi_taker_access {
2762 builder.rpi_taker_access(rpi_taker_access);
2763 }
2764
2765 if let Some(rpi_px_round) = rpi_px_round {
2766 builder.rpi_px_round(rpi_px_round);
2767 }
2768
2769 let params = builder
2770 .build()
2771 .map_err(|e| OKXWsError::ClientError(format!("Build amend params error: {e}")))?;
2772
2773 let request_id = self.generate_unique_request_id();
2774 let request = OKXWsRequest {
2775 id: Some(request_id.clone()),
2776 op: super::enums::OKXWsOperation::AmendOrder,
2777 exp_time: None,
2778 args: vec![params],
2779 };
2780
2781 let payload = serde_json::to_string(&request)
2782 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize amend: {e}")))?;
2783
2784 if let (Some(client_order_id), Some(causation_id)) = (client_order_id, causation_id) {
2785 self.pending_command_ids
2786 .insert(request_id.clone(), vec![(client_order_id, causation_id)]);
2787 }
2788
2789 let cmd = HandlerCommand::Send {
2790 payload,
2791 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_AMEND.to_vec()),
2792 request_id: Some(request_id.clone()),
2793 client_order_ids: client_order_id.into_iter().collect(),
2794 op: Some(super::enums::OKXWsOperation::AmendOrder),
2795 };
2796
2797 let result = self.send_cmd(cmd).await;
2798
2799 if result.is_err() {
2800 self.pending_command_ids.remove(&request_id);
2801 }
2802
2803 if let (Err(_), Some(key)) = (&result, &cl_ord_key) {
2804 self.pending_amends.remove(key);
2805 }
2806
2807 result
2808 }
2809
2810 pub async fn cancel_order(
2821 &self,
2822 trader_id: TraderId,
2823 strategy_id: StrategyId,
2824 instrument_id: InstrumentId,
2825 client_order_id: Option<ClientOrderId>,
2826 venue_order_id: Option<VenueOrderId>,
2827 ) -> Result<(), OKXWsError> {
2828 self.cancel_order_with_causation(
2829 trader_id,
2830 strategy_id,
2831 instrument_id,
2832 client_order_id,
2833 venue_order_id,
2834 None,
2835 )
2836 .await
2837 }
2838
2839 pub(crate) async fn cancel_order_with_causation(
2840 &self,
2841 trader_id: TraderId,
2842 strategy_id: StrategyId,
2843 instrument_id: InstrumentId,
2844 client_order_id: Option<ClientOrderId>,
2845 venue_order_id: Option<VenueOrderId>,
2846 causation_id: Option<UUID4>,
2847 ) -> Result<(), OKXWsError> {
2848 let mut builder = WsCancelOrderParamsBuilder::default();
2849
2850 let inst_id_code = self
2851 .get_inst_id_code(&instrument_id.symbol.inner())
2852 .ok_or_else(|| {
2853 OKXWsError::ClientError(format!(
2854 "No instIdCode cached for {instrument_id}, cannot cancel order"
2855 ))
2856 })?;
2857 builder.inst_id_code(inst_id_code);
2858
2859 if let Some(venue_order_id) = venue_order_id {
2860 builder.ord_id(venue_order_id.as_str());
2861 }
2862
2863 let cl_ord_key = client_order_id.map(|id| id.to_string());
2864
2865 if let Some(client_order_id) = client_order_id {
2866 builder.cl_ord_id(client_order_id.as_str());
2867 self.pending_cancels.insert(
2868 client_order_id.to_string(),
2869 PendingOrderInfo {
2870 trader_id,
2871 strategy_id,
2872 instrument_id,
2873 },
2874 );
2875 }
2876
2877 let params = builder
2878 .build()
2879 .map_err(|e| OKXWsError::ClientError(format!("Build cancel params error: {e}")))?;
2880
2881 let request_id = self.generate_unique_request_id();
2882 let request = OKXWsRequest {
2883 id: Some(request_id.clone()),
2884 op: super::enums::OKXWsOperation::CancelOrder,
2885 exp_time: None,
2886 args: vec![params],
2887 };
2888
2889 let payload = serde_json::to_string(&request)
2890 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize cancel: {e}")))?;
2891
2892 if let (Some(client_order_id), Some(causation_id)) = (client_order_id, causation_id) {
2893 self.pending_command_ids
2894 .insert(request_id.clone(), vec![(client_order_id, causation_id)]);
2895 }
2896
2897 let cmd = HandlerCommand::Send {
2898 payload,
2899 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_CANCEL.to_vec()),
2900 request_id: Some(request_id.clone()),
2901 client_order_ids: client_order_id.into_iter().collect(),
2902 op: Some(super::enums::OKXWsOperation::CancelOrder),
2903 };
2904
2905 let result = self.send_cmd(cmd).await;
2906
2907 if result.is_err() {
2908 self.pending_command_ids.remove(&request_id);
2909 }
2910
2911 if let (Err(_), Some(key)) = (&result, &cl_ord_key) {
2912 self.pending_cancels.remove(key);
2913 }
2914
2915 result
2916 }
2917
2918 pub async fn mass_cancel_orders(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
2928 let (inst_type, inst_family) = {
2929 let instrument = self
2930 .instruments_cache
2931 .get_cloned(&instrument_id.symbol.inner())
2932 .ok_or_else(|| {
2933 OKXWsError::ClientError(format!("Unknown instrument {instrument_id}"))
2934 })?;
2935
2936 let inst_type = okx_instrument_type(&instrument)
2937 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
2938
2939 let symbol = instrument.symbol().inner();
2940 let inst_family = match &instrument {
2941 InstrumentAny::CurrencyPair(_) => symbol.as_str().to_string(),
2942 InstrumentAny::CryptoPerpetual(_) => symbol
2943 .as_str()
2944 .strip_suffix("-SWAP")
2945 .unwrap_or(symbol.as_str())
2946 .to_string(),
2947 InstrumentAny::CryptoFuture(_) => {
2948 let s = symbol.as_str();
2949 if let Some(idx) = s.rfind('-') {
2950 s[..idx].to_string()
2951 } else {
2952 s.to_string()
2953 }
2954 }
2955 _ => {
2956 return Err(OKXWsError::ClientError(
2957 "Unsupported instrument type for mass cancel".to_string(),
2958 ));
2959 }
2960 };
2961
2962 (inst_type, inst_family)
2963 };
2964
2965 let params = WsMassCancelParams {
2966 inst_type,
2967 inst_family: Ustr::from(&inst_family),
2968 };
2969
2970 let request_id = self.generate_unique_request_id();
2971 let request = OKXWsRequest {
2972 id: Some(request_id.clone()),
2973 op: super::enums::OKXWsOperation::MassCancel,
2974 exp_time: None,
2975 args: vec![
2976 serde_json::to_value(params).map_err(|e| OKXWsError::JsonError(e.to_string()))?,
2977 ],
2978 };
2979
2980 let payload = serde_json::to_string(&request)
2981 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize mass cancel: {e}")))?;
2982
2983 let cmd = HandlerCommand::Send {
2984 payload,
2985 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_MASS_CANCEL.to_vec()),
2986 request_id: Some(request_id),
2987 client_order_ids: Vec::new(),
2988 op: Some(super::enums::OKXWsOperation::MassCancel),
2989 };
2990
2991 self.send_cmd(cmd).await
2992 }
2993
2994 #[expect(clippy::type_complexity)]
3005 pub async fn batch_submit_orders(
3006 &self,
3007 orders: Vec<(
3008 OKXInstrumentType,
3009 InstrumentId,
3010 OKXTradeMode,
3011 ClientOrderId,
3012 OrderSide,
3013 Option<PositionSide>,
3014 OrderType,
3015 Quantity,
3016 Option<Price>,
3017 Option<Price>,
3018 Option<bool>,
3019 Option<bool>,
3020 Option<bool>,
3021 Option<String>,
3022 Option<bool>,
3023 Option<bool>,
3024 Option<bool>,
3025 )>,
3026 ) -> Result<(), OKXWsError> {
3027 let client_order_ids: Vec<ClientOrderId> = orders.iter().map(|o| o.3).collect();
3028 let args: Vec<Value> = {
3029 let mut args = Vec::with_capacity(orders.len());
3030 let inst_id_codes = self.inst_id_code_cache.load();
3031 let instruments = self.instruments_cache.load();
3032
3033 for (
3034 inst_type,
3035 inst_id,
3036 td_mode,
3037 cl_ord_id,
3038 ord_side,
3039 pos_side,
3040 ord_type,
3041 qty,
3042 pr,
3043 tp,
3044 post_only,
3045 reduce_only,
3046 quote_quantity,
3047 outcome,
3048 rpi,
3049 rpi_taker_access,
3050 rpi_px_round,
3051 ) in orders
3052 {
3053 let rpi = rpi.unwrap_or(false);
3054 let mut builder = WsPostOrderParamsBuilder::default();
3055
3056 let (inst_id_symbol, inst_id_code) = Self::inst_id_symbol_and_code_from_snapshot(
3057 &inst_id_codes,
3058 &inst_id,
3059 "submit",
3060 )?;
3061 builder.inst_id_code(inst_id_code);
3062
3063 builder.td_mode(td_mode);
3064 builder.cl_ord_id(cl_ord_id.as_str());
3065 builder.side(ord_side);
3066
3067 if inst_type != OKXInstrumentType::Events
3068 && let Some(instrument) = instruments.get(&inst_id_symbol)
3069 {
3070 builder.ccy(instrument.quote_currency().to_string());
3071 }
3072
3073 if let Some(ps) = pos_side {
3074 builder.pos_side(OKXPositionSide::from(ps));
3075 } else if matches!(
3076 inst_type,
3077 OKXInstrumentType::Swap
3078 | OKXInstrumentType::Futures
3079 | OKXInstrumentType::Option
3080 ) {
3081 builder.pos_side(OKXPositionSide::Net);
3082 }
3083
3084 if rpi && ord_type != OrderType::Limit {
3085 return Err(OKXWsError::ClientError(
3086 "OKX RPI batch orders require limit orders".to_string(),
3087 ));
3088 }
3089
3090 let okx_ord_type = if rpi {
3091 OKXOrderType::Rpi
3092 } else if post_only.unwrap_or(false) {
3093 OKXOrderType::PostOnly
3094 } else {
3095 match ord_type {
3096 OrderType::Market => OKXOrderType::Market,
3097 OrderType::Limit => OKXOrderType::Limit,
3098 OrderType::MarketToLimit => OKXOrderType::Ioc,
3099 _ => {
3100 return Err(OKXWsError::ClientError(format!(
3101 "Unsupported order type for batch submit: {ord_type:?}"
3102 )));
3103 }
3104 }
3105 };
3106
3107 builder.ord_type(okx_ord_type);
3108 builder.sz(qty.to_string());
3109 let tgt_ccy =
3110 okx_market_target_currency(inst_type, ord_side, ord_type, quote_quantity)
3111 .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
3112
3113 if let Some(p) = pr {
3114 builder.px(p.to_string());
3115 } else if let Some(p) = tp {
3116 builder.px(p.to_string());
3117 }
3118
3119 if let Some(reduce_only) =
3120 okx_reduce_only_wire_value(inst_type, td_mode, ord_side, pos_side, reduce_only)
3121 .map_err(OKXWsError::ClientError)?
3122 {
3123 builder.reduce_only(reduce_only);
3124 }
3125
3126 if inst_type == OKXInstrumentType::Events && outcome.is_none() {
3127 return Err(OKXWsError::ClientError(
3128 "OKX event contract orders require `outcome`".to_string(),
3129 ));
3130 }
3131
3132 if let Some(outcome) = outcome {
3133 builder.outcome(outcome);
3134 }
3135
3136 if let Some(rpi_taker_access) = rpi_taker_access {
3137 builder.rpi_taker_access(rpi_taker_access);
3138 }
3139
3140 if let Some(rpi_px_round) = rpi_px_round {
3141 builder.rpi_px_round(rpi_px_round);
3142 }
3143
3144 if let Some(trade_quote_ccy) =
3145 self.resolve_spot_trade_quote_ccy(inst_type, inst_id_symbol)?
3146 {
3147 builder.trade_quote_ccy(trade_quote_ccy);
3148 }
3149
3150 builder.tag(OKX_NAUTILUS_BROKER_ID);
3151
3152 let mut params = builder.build().map_err(|e| {
3153 OKXWsError::ClientError(format!("Build order params error: {e}"))
3154 })?;
3155
3156 params.tgt_ccy = tgt_ccy;
3157 let val = serde_json::to_value(params)
3158 .map_err(|e| OKXWsError::JsonError(e.to_string()))?;
3159 args.push(val);
3160 }
3161 args
3162 };
3163
3164 self.ws_batch_place_orders(args, client_order_ids).await
3165 }
3166
3167 #[expect(clippy::type_complexity)]
3174 pub async fn batch_modify_orders(
3175 &self,
3176 orders: Vec<(
3177 OKXInstrumentType,
3178 InstrumentId,
3179 ClientOrderId,
3180 Option<String>,
3181 Option<Price>,
3182 Option<Quantity>,
3183 Option<bool>,
3184 Option<bool>,
3185 )>,
3186 ) -> Result<(), OKXWsError> {
3187 let client_order_ids: Vec<ClientOrderId> = orders.iter().map(|o| o.2).collect();
3188 let args: Vec<Value> = {
3189 let mut args = Vec::with_capacity(orders.len());
3190 let inst_id_codes = self.inst_id_code_cache.load();
3191
3192 for (
3193 _inst_type,
3194 inst_id,
3195 cl_ord_id,
3196 request_id,
3197 pr,
3198 sz,
3199 rpi_taker_access,
3200 rpi_px_round,
3201 ) in orders
3202 {
3203 let mut builder = WsAmendOrderParamsBuilder::default();
3204
3205 let (_, inst_id_code) =
3206 Self::inst_id_symbol_and_code_from_snapshot(&inst_id_codes, &inst_id, "amend")?;
3207 builder.inst_id_code(inst_id_code);
3208
3209 builder.cl_ord_id(cl_ord_id.as_str());
3210
3211 if let Some(request_id) = request_id {
3212 builder.req_id(request_id);
3213 }
3214
3215 if let Some(p) = pr {
3216 builder.new_px(p.to_string());
3217 }
3218
3219 if let Some(q) = sz {
3220 builder.new_sz(q.to_string());
3221 }
3222
3223 if let Some(rpi_taker_access) = rpi_taker_access {
3224 builder.rpi_taker_access(rpi_taker_access);
3225 }
3226
3227 if let Some(rpi_px_round) = rpi_px_round {
3228 builder.rpi_px_round(rpi_px_round);
3229 }
3230
3231 let params = builder.build().map_err(|e| {
3232 OKXWsError::ClientError(format!("Build amend batch params error: {e}"))
3233 })?;
3234 let val = serde_json::to_value(params)
3235 .map_err(|e| OKXWsError::JsonError(e.to_string()))?;
3236 args.push(val);
3237 }
3238 args
3239 };
3240
3241 self.ws_batch_amend_orders(args, client_order_ids).await
3242 }
3243
3244 pub async fn batch_cancel_orders(
3257 &self,
3258 orders: Vec<(InstrumentId, Option<ClientOrderId>, Option<VenueOrderId>)>,
3259 ) -> Result<(), OKXWsError> {
3260 self.batch_cancel_orders_with_causation(orders, Vec::new())
3261 .await
3262 }
3263
3264 pub(crate) async fn batch_cancel_orders_with_causation(
3265 &self,
3266 orders: Vec<(InstrumentId, Option<ClientOrderId>, Option<VenueOrderId>)>,
3267 causation_ids: Vec<(ClientOrderId, UUID4)>,
3268 ) -> Result<(), OKXWsError> {
3269 let client_order_ids: Vec<ClientOrderId> = orders
3270 .iter()
3271 .filter_map(|(_, cl_ord_id, _)| *cl_ord_id)
3272 .collect();
3273 let args: Vec<Value> = {
3274 let mut args = Vec::with_capacity(orders.len());
3275 let inst_id_codes = self.inst_id_code_cache.load();
3276
3277 for (inst_id, cl_ord_id, ord_id) in orders {
3278 let mut builder = WsCancelOrderParamsBuilder::default();
3279
3280 let (_, inst_id_code) = Self::inst_id_symbol_and_code_from_snapshot(
3281 &inst_id_codes,
3282 &inst_id,
3283 "cancel",
3284 )?;
3285 builder.inst_id_code(inst_id_code);
3286
3287 if let Some(c) = cl_ord_id {
3288 builder.cl_ord_id(c.as_str());
3289 }
3290
3291 if let Some(o) = ord_id {
3292 builder.ord_id(o.as_str());
3293 }
3294
3295 let params = builder.build().map_err(|e| {
3296 OKXWsError::ClientError(format!("Build cancel batch params error: {e}"))
3297 })?;
3298 let val = serde_json::to_value(params)
3299 .map_err(|e| OKXWsError::JsonError(e.to_string()))?;
3300 args.push(val);
3301 }
3302 args
3303 };
3304
3305 self.ws_batch_cancel_orders(args, client_order_ids, causation_ids)
3306 .await
3307 }
3308
3309 #[expect(clippy::too_many_arguments)]
3315 #[expect(
3316 clippy::unused_async,
3317 clippy::unused_async_trait_impl,
3318 reason = "Preserves the published async API while rejecting an unsupported operation"
3319 )]
3320 pub async fn submit_algo_order(
3321 &self,
3322 _trader_id: TraderId,
3323 _strategy_id: StrategyId,
3324 _instrument_id: InstrumentId,
3325 _td_mode: OKXTradeMode,
3326 _client_order_id: ClientOrderId,
3327 _order_side: OrderSide,
3328 _order_type: OrderType,
3329 _quantity: Quantity,
3330 _trigger_price: Option<Price>,
3331 _trigger_type: Option<TriggerType>,
3332 _limit_price: Option<Price>,
3333 _reduce_only: Option<bool>,
3334 _callback_ratio: Option<String>,
3335 _callback_spread: Option<String>,
3336 _activation_price: Option<Price>,
3337 ) -> Result<(), OKXWsError> {
3338 Err(OKXWsError::ClientError(
3339 "OKX algo placement requires HTTP; use OKXHttpClient::place_algo_order_with_domain_types"
3340 .to_string(),
3341 ))
3342 }
3343
3344 pub async fn cancel_algo_order(
3355 &self,
3356 _trader_id: TraderId,
3357 _strategy_id: StrategyId,
3358 instrument_id: InstrumentId,
3359 client_order_id: Option<ClientOrderId>,
3360 algo_order_id: Option<String>,
3361 ) -> Result<(), OKXWsError> {
3362 let mut builder = super::messages::WsCancelAlgoOrderParamsBuilder::default();
3363
3364 let inst_id_code = self
3365 .get_inst_id_code(&instrument_id.symbol.inner())
3366 .ok_or_else(|| {
3367 OKXWsError::ClientError(format!(
3368 "No instIdCode cached for {instrument_id}, cannot cancel algo order"
3369 ))
3370 })?;
3371 builder.inst_id_code(inst_id_code);
3372
3373 if let Some(algo_id) = algo_order_id {
3374 builder.algo_id(algo_id);
3375 }
3376
3377 if let Some(cl_ord_id) = client_order_id {
3378 builder.algo_cl_ord_id(cl_ord_id.to_string());
3379 }
3380
3381 let params = builder
3382 .build()
3383 .map_err(|e| OKXWsError::ClientError(format!("Build cancel algo params error: {e}")))?;
3384
3385 let request_id = self.generate_unique_request_id();
3386 let request = OKXWsRequest {
3387 id: Some(request_id.clone()),
3388 op: super::enums::OKXWsOperation::CancelAlgos,
3389 exp_time: None,
3390 args: vec![params],
3391 };
3392
3393 let payload = serde_json::to_string(&request)
3394 .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize cancel algo: {e}")))?;
3395
3396 let cmd = HandlerCommand::Send {
3397 payload,
3398 rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_ALGO_CANCEL.to_vec()),
3399 request_id: Some(request_id),
3400 client_order_ids: client_order_id.into_iter().collect(),
3401 op: Some(super::enums::OKXWsOperation::CancelAlgos),
3402 };
3403
3404 self.send_cmd(cmd).await
3405 }
3406
3407 async fn send_cmd(&self, cmd: HandlerCommand) -> Result<(), OKXWsError> {
3409 self.cmd_tx
3410 .read()
3411 .await
3412 .send(cmd)
3413 .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))
3414 }
3415}
3416
3417fn authentication_timestamp(now: UnixNanos) -> String {
3418 now.as_seconds().to_string()
3419}
3420
3421fn subscription_args(
3422 subscriptions: &DashMap<String, OKXSubscriptionArg>,
3423 subscriptions_state: &SubscriptionState,
3424) -> Vec<OKXSubscriptionArg> {
3425 let mut args: Vec<_> = subscriptions_state
3426 .all_topics()
3427 .iter()
3428 .filter_map(|topic| subscriptions.get(topic).map(|arg| arg.value().clone()))
3429 .collect();
3430 args.sort_unstable_by_key(topic_from_subscription_arg);
3431 args
3432}
3433
3434fn subscription_arg_batches(
3435 args: &[OKXSubscriptionArg],
3436) -> impl Iterator<Item = &[OKXSubscriptionArg]> {
3437 args.chunks(OKX_WS_SUBSCRIPTION_ARGS_MAX_PER_MESSAGE)
3438}
3439
3440fn advance_reconnect_epoch(
3441 reconnect_epoch: &mut u64,
3442 epoch: u64,
3443 stopping: bool,
3444 active: bool,
3445) -> bool {
3446 if stopping || !active || epoch == *reconnect_epoch {
3447 return false;
3448 }
3449
3450 *reconnect_epoch = epoch;
3451 true
3452}
3453
3454fn auth_attempt_superseded(error: &Error) -> bool {
3455 error.to_string().contains("superseded")
3456 || matches!(error, Error::Io(e) if matches!(
3457 e.get_ref().and_then(|e| e.downcast_ref::<SendError>()),
3458 Some(SendError::ConnectionChanged),
3459 ))
3460}
3461
3462async fn authenticate_session(
3463 credential: &Credential,
3464 auth_tracker: &AuthTracker,
3465 ws_client: &WebSocketClient,
3466 connection_epoch: u64,
3467 clock: &'static AtomicTime,
3468 auth_timeout_secs: u64,
3469) -> Result<(), Error> {
3470 if !ws_client.is_active() || ws_client.connection_epoch() != connection_epoch {
3471 return Err(Error::Io(std::io::Error::other(
3472 SendError::ConnectionChanged,
3473 )));
3474 }
3475
3476 let rx = auth_tracker.begin();
3477 let timestamp = authentication_timestamp(clock.get_time_ns());
3478 let signature = credential.sign(×tamp, "GET", "/users/self/verify", "");
3479
3480 let auth_message = OKXAuthentication {
3481 op: "login",
3482 args: vec![OKXAuthenticationArg {
3483 api_key: SecretString::from(credential.api_key()),
3484 passphrase: SecretString::from(credential.api_passphrase()),
3485 timestamp,
3486 sign: SecretString::from(signature),
3487 }],
3488 };
3489
3490 let payload = serde_json::to_string(&auth_message)
3491 .map(SecretString::from)
3492 .map_err(|e| {
3493 Error::Io(std::io::Error::other(format!(
3494 "Failed to serialize auth message: {e}"
3495 )))
3496 })?;
3497
3498 ws_client
3499 .send_text_on_connection(
3500 payload.expose_secret().to_owned(),
3501 Some(OKX_RATE_LIMIT_KEY_SUBSCRIPTION.as_slice()),
3502 connection_epoch,
3503 )
3504 .await
3505 .map_err(|e| Error::Io(std::io::Error::other(e)))?;
3506
3507 match auth_tracker
3508 .wait_for_result::<OKXWsError>(Duration::from_secs(auth_timeout_secs), rx)
3509 .await
3510 {
3511 Ok(()) => {
3512 log::debug!("WebSocket authenticated");
3513 Ok(())
3514 }
3515 Err(e) => {
3516 let auth_error = Error::Io(std::io::Error::other(e.to_string()));
3517 if !auth_attempt_superseded(&auth_error) {
3518 log::warn!("WebSocket authentication failed: error={e}");
3519 }
3520
3521 Err(auth_error)
3522 }
3523 }
3524}
3525
3526#[allow(
3527 clippy::too_many_arguments,
3528 reason = "reconnect authentication uses the existing session and shutdown state"
3529)]
3530async fn reauthenticate_session(
3531 credential: Credential,
3532 auth_tracker: AuthTracker,
3533 ws_client: Arc<WebSocketClient>,
3534 connection_epoch: u64,
3535 clock: &'static AtomicTime,
3536 auth_timeout_secs: u64,
3537 signal: Arc<AtomicBool>,
3538 abort: CancellationToken,
3539) {
3540 if signal.load(Ordering::Acquire) || abort.is_cancelled() {
3541 return;
3542 }
3543
3544 if ws_client.connection_epoch() != connection_epoch || !ws_client.is_active() {
3545 return;
3546 }
3547
3548 let result = tokio::select! {
3549 biased;
3550 () = abort.cancelled() => return,
3551 result = authenticate_session(
3552 &credential,
3553 &auth_tracker,
3554 &ws_client,
3555 connection_epoch,
3556 clock,
3557 auth_timeout_secs,
3558 ) => result,
3559 };
3560
3561 match result {
3562 Ok(()) => log::debug!("Re-authenticated after reconnection"),
3563 Err(e) => {
3564 if signal.load(Ordering::Acquire)
3565 || abort.is_cancelled()
3566 || ws_client.connection_epoch() != connection_epoch
3567 || auth_tracker.is_authenticated()
3568 {
3569 return;
3570 }
3571
3572 log::warn!("Re-authentication failed, reconnecting: {e}");
3573 let _ = ws_client.reconnect_handle().request_reconnect();
3574 }
3575 }
3576}
3577
3578pub(crate) fn ws_channel_for_book(channel: OKXBookChannel) -> OKXWsChannel {
3579 match channel {
3580 OKXBookChannel::Book => OKXWsChannel::Books,
3581 OKXBookChannel::BookL2Tbt => OKXWsChannel::BooksTbt,
3582 OKXBookChannel::Books50L2Tbt => OKXWsChannel::Books50Tbt,
3583 OKXBookChannel::BooksRpi => OKXWsChannel::BooksRpi,
3584 OKXBookChannel::SprdBooks5 => OKXWsChannel::SprdBooks5,
3585 }
3586}
3587
3588fn log_receiver_dropped(signal: &AtomicBool, item: &str) {
3589 if signal.load(Ordering::Acquire) {
3590 log::debug!("Receiver dropped after stop signal while forwarding {item}");
3591 } else {
3592 log::error!("Failed to send {item} through channel: receiver dropped");
3593 }
3594}
3595
3596#[cfg(test)]
3597mod tests {
3598 use futures_util::StreamExt;
3599 use nautilus_core::time::get_atomic_clock_realtime;
3600 use nautilus_live::{SocketReconnectRegistry, SocketReconnectRequestOutcome};
3601 use nautilus_model::identifiers::ClientId;
3602 use nautilus_network::RECONNECTED;
3603 use rstest::rstest;
3604 use tokio_tungstenite::tungstenite::Message;
3605
3606 use super::*;
3607 use crate::{
3608 common::{
3609 consts::{OKX_POST_ONLY_CANCEL_SOURCE, OKX_VENUE},
3610 enums::{
3611 OKXExecType, OKXOrderCategory, OKXOrderStatus, OKXPriceType, OKXQuickMarginType,
3612 OKXSelfTradePreventionMode, OKXSide,
3613 },
3614 },
3615 websocket::{
3616 handler::is_post_only_auto_cancel,
3617 messages::{OKXOrderMsg, OKXWsFrame},
3618 },
3619 };
3620
3621 struct DropSignal(Option<tokio::sync::oneshot::Sender<()>>);
3622
3623 impl Drop for DropSignal {
3624 fn drop(&mut self) {
3625 if let Some(sender) = self.0.take() {
3626 let _ = sender.send(());
3627 }
3628 }
3629 }
3630
3631 struct BlockingDrop(Arc<(parking_lot::Mutex<bool>, parking_lot::Condvar)>);
3632
3633 impl Drop for BlockingDrop {
3634 fn drop(&mut self) {
3635 let (lock, condvar) = &*self.0;
3636 let mut released = lock.lock();
3637 condvar.wait_while(&mut released, |released| !*released);
3638 }
3639 }
3640
3641 #[rstest]
3642 #[case(OKXBookChannel::Book, OKXWsChannel::Books)]
3643 #[case(OKXBookChannel::BookL2Tbt, OKXWsChannel::BooksTbt)]
3644 #[case(OKXBookChannel::Books50L2Tbt, OKXWsChannel::Books50Tbt)]
3645 #[case(OKXBookChannel::BooksRpi, OKXWsChannel::BooksRpi)]
3646 #[case(OKXBookChannel::SprdBooks5, OKXWsChannel::SprdBooks5)]
3647 fn test_ws_channel_for_book(#[case] channel: OKXBookChannel, #[case] expected: OKXWsChannel) {
3648 assert_eq!(ws_channel_for_book(channel), expected);
3649 }
3650
3651 #[rstest]
3652 fn test_timestamp_format_for_websocket_auth() {
3653 let now = UnixNanos::new(1_700_000_000_999_999_999);
3654
3655 assert_eq!(authentication_timestamp(now), "1700000000");
3656 }
3657
3658 #[rstest]
3659 fn test_subscription_args_are_sorted_by_topic() {
3660 let client = OKXWebSocketClient::default();
3661
3662 let args = [
3663 OKXSubscriptionArg {
3664 channel: OKXWsChannel::Instruments,
3665 inst_type: Some(OKXInstrumentType::Swap),
3666 inst_family: None,
3667 inst_id: None,
3668 },
3669 OKXSubscriptionArg {
3670 channel: OKXWsChannel::Instruments,
3671 inst_type: Some(OKXInstrumentType::Spot),
3672 inst_family: None,
3673 inst_id: None,
3674 },
3675 OKXSubscriptionArg {
3676 channel: OKXWsChannel::OpenInterest,
3677 inst_type: None,
3678 inst_family: Some(Ustr::from("BTC-USD")),
3679 inst_id: None,
3680 },
3681 OKXSubscriptionArg {
3682 channel: OKXWsChannel::Tickers,
3683 inst_type: None,
3684 inst_family: None,
3685 inst_id: Some(Ustr::from("ETH-USDT")),
3686 },
3687 OKXSubscriptionArg {
3688 channel: OKXWsChannel::Tickers,
3689 inst_type: None,
3690 inst_family: None,
3691 inst_id: Some(Ustr::from("BTC-USDT")),
3692 },
3693 OKXSubscriptionArg {
3694 channel: OKXWsChannel::Status,
3695 inst_type: None,
3696 inst_family: None,
3697 inst_id: None,
3698 },
3699 ];
3700
3701 client.record_subscriptions(&args);
3702
3703 let topics = subscription_args(&client.subscriptions, &client.subscriptions_state)
3704 .iter()
3705 .map(topic_from_subscription_arg)
3706 .collect::<Vec<_>>();
3707
3708 assert_eq!(
3709 topics,
3710 [
3711 "Instruments:Spot",
3712 "Instruments:Swap",
3713 "OpenInterest:BTC-USD",
3714 "Status",
3715 "Tickers:BTC-USDT",
3716 "Tickers:ETH-USDT",
3717 ]
3718 );
3719 }
3720
3721 #[rstest]
3722 #[case::channel_unknown(false, true)]
3723 #[case::symbol_unknown(true, false)]
3724 #[case::both_unknown(false, false)]
3725 fn subscription_lookup_does_not_intern_unknown_values(
3726 #[case] channel_known: bool,
3727 #[case] symbol_known: bool,
3728 ) {
3729 let state = SubscriptionState::new(OKX_WS_TOPIC_DELIMITER);
3730 state.mark_subscribe("Trades:BTC-USDT");
3731
3732 let channel = if channel_known {
3733 "Trades".to_string()
3734 } else {
3735 format!("unknown_okx_channel_{}", UUID4::new())
3736 };
3737
3738 let symbol = if symbol_known {
3739 "BTC-USDT".to_string()
3740 } else {
3741 format!("unknown_okx_symbol_{}", UUID4::new())
3742 };
3743
3744 let topic = format!("{channel}:{symbol}");
3745 let channel_before = Ustr::from_existing(&channel);
3746 let symbol_before = Ustr::from_existing(&symbol);
3747
3748 let subscribed = is_topic_subscribed(&state, &topic);
3749
3750 assert!(is_topic_subscribed(&state, "Trades:BTC-USDT"));
3751 assert!(!subscribed);
3752 assert_eq!(channel_before.is_some(), channel_known);
3753 assert_eq!(symbol_before.is_some(), symbol_known);
3754 assert_eq!(Ustr::from_existing(&channel), channel_before);
3755 assert_eq!(Ustr::from_existing(&symbol), symbol_before);
3756 assert_eq!(state.all_topics(), vec!["Trades:BTC-USDT".to_string()]);
3757 }
3758
3759 #[rstest]
3760 fn pending_unsubscribe_is_excluded_from_replay_arguments() {
3761 let client = OKXWebSocketClient::default();
3762
3763 let canceled = OKXSubscriptionArg {
3764 channel: OKXWsChannel::Trades,
3765 inst_type: None,
3766 inst_family: None,
3767 inst_id: Some(Ustr::from("BTC-USDT")),
3768 };
3769
3770 let retained = OKXSubscriptionArg {
3771 inst_id: Some(Ustr::from("ETH-USDT")),
3772 ..canceled.clone()
3773 };
3774
3775 client.record_subscriptions(&[canceled.clone(), retained.clone()]);
3776 let topic = topic_from_subscription_arg(&canceled);
3777 client.subscriptions_state.mark_unsubscribe(&topic);
3778
3779 client.subscriptions_state.reset_after_reconnect();
3780 let args = subscription_args(&client.subscriptions, &client.subscriptions_state);
3781
3782 assert!(client.subscriptions.contains_key(&topic));
3783 assert_eq!(args.len(), 1);
3784 assert_eq!(args[0].channel, retained.channel);
3785 assert_eq!(args[0].inst_id, retained.inst_id);
3786 assert_eq!(args[0].inst_type, None);
3787 assert_eq!(args[0].inst_family, None);
3788 }
3789
3790 #[tokio::test]
3791 async fn subscribe_during_connect_reaches_initialized_handler() {
3792 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3793 let addr = listener.local_addr().unwrap();
3794 let (received_tx, received_rx) = tokio::sync::oneshot::channel();
3795
3796 let server = tokio::spawn(async move {
3797 let (socket, _) = listener.accept().await.unwrap();
3798 let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
3799 if let Some(Ok(message)) = socket.next().await {
3800 let _ = received_tx.send(message);
3801
3802 while matches!(socket.next().await, Some(Ok(_))) {}
3803 }
3804 });
3805
3806 let mut ws_client = OKXWebSocketClient::new(
3807 Some(format!("ws://{addr}")),
3808 None,
3809 None,
3810 None,
3811 None,
3812 None,
3813 None,
3814 TransportBackend::default(),
3815 None,
3816 )
3817 .unwrap();
3818 let observer = ws_client.clone();
3819 let sender = Arc::clone(&ws_client.cmd_tx);
3820 let publication = sender.read().await;
3821 let mut connect = Box::pin(ws_client.connect());
3822
3823 tokio::time::timeout(Duration::from_secs(5), async {
3824 loop {
3825 assert!(futures_util::poll!(connect.as_mut()).is_pending());
3826
3827 if sender.try_read().is_err() {
3828 break;
3829 }
3830
3831 tokio::task::yield_now().await;
3832 }
3833 })
3834 .await
3835 .expect("connect must wait to publish its sender");
3836
3837 let active_before_publication = observer.is_active();
3838 let mut subscribe =
3839 Box::pin(observer.subscribe_inst_id(OKXWsChannel::Trades, Ustr::from("BTC-USDT")));
3840 assert!(futures_util::poll!(subscribe.as_mut()).is_pending());
3841
3842 let mut barrier = Box::pin(sender.write());
3844 assert!(futures_util::poll!(barrier.as_mut()).is_pending());
3845 drop(publication);
3846 let connect_result = futures_util::poll!(connect.as_mut());
3847 subscribe.await.expect("concurrent subscribe command");
3848 let barrier = barrier.await;
3849 let received = tokio::time::timeout(Duration::from_secs(2), received_rx).await;
3850 drop(barrier);
3851
3852 if let std::task::Poll::Ready(result) = connect_result {
3853 result.expect("connect failed");
3854 } else {
3855 connect.as_mut().await.expect("connect failed");
3856 }
3857
3858 drop(connect);
3859 ws_client.close().await.expect("close failed");
3860 server.await.expect("server task failed");
3861
3862 assert!(
3863 !active_before_publication,
3864 "active before sender publication"
3865 );
3866 let message = received.expect("subscription must reach server").unwrap();
3867
3868 let Message::Text(text) = message else {
3869 panic!("expected text subscription")
3870 };
3871
3872 let payload: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
3873 assert_eq!(
3874 payload,
3875 serde_json::json!({
3876 "op": "subscribe",
3877 "args": [{ "channel": "trades", "instId": "BTC-USDT" }],
3878 })
3879 );
3880 }
3881
3882 #[rstest]
3883 #[tokio::test]
3884 async fn begin_shutdown_stops_handler_before_bounded_close() {
3885 let client_id = ClientId::from("OKX-TEST");
3886 let endpoint = Ustr::from("okx-test-stream");
3887 let registry = SocketReconnectRegistry::default();
3888 let control =
3889 SocketControl::with_registry(client_id, Some(*OKX_VENUE), endpoint, ®istry);
3890 let _sink = control.sink();
3891 control.register(|| SocketReconnectRequestOutcome::Accepted);
3892 let mut client = OKXWebSocketClient::default().with_socket_control(control);
3893 client
3894 .connection_mode
3895 .load()
3896 .store(ConnectionMode::Active.as_u8(), Ordering::SeqCst);
3897 let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();
3898 let signal = DropSignal(Some(drop_tx));
3899 let handler_abort = CancellationToken::new();
3900 *client.handler_abort.lock() = handler_abort.clone();
3901 client
3902 .handler_tasks
3903 .spawn(async move {
3904 let _signal = signal;
3905 handler_abort.cancelled().await;
3906 })
3907 .expect("handler task should register");
3908
3909 assert!(registry.handle(client_id, endpoint).is_some());
3910 client.begin_shutdown();
3911
3912 tokio::time::timeout(Duration::from_secs(1), drop_rx)
3913 .await
3914 .expect("begin shutdown must drop the handler task")
3915 .expect("drop signal");
3916 assert!(client.is_closed());
3917 assert!(!client.handler_tasks.is_open());
3918 assert!(registry.handle(client_id, endpoint).is_some());
3919
3920 client.close().await.expect("bounded close");
3921 assert!(!client.has_task());
3922 assert!(registry.handle(client_id, endpoint).is_none());
3923 }
3924
3925 #[rstest]
3926 #[tokio::test]
3927 async fn connect_rollback_closes_handler_admission_and_deregisters_socket() {
3928 let client_id = ClientId::from("OKX-CONNECT-ROLLBACK");
3929 let endpoint = Ustr::from("okx-connect-rollback");
3930 let registry = SocketReconnectRegistry::default();
3931 let control =
3932 SocketControl::with_registry(client_id, Some(*OKX_VENUE), endpoint, ®istry);
3933 control.register(|| SocketReconnectRequestOutcome::Accepted);
3934 let handler_tasks = Arc::new(TaskGroup::new());
3935 let signal = Arc::new(AtomicBool::new(false));
3936 let handler_abort = CancellationToken::new();
3937
3938 let rollback = ConnectRollback {
3939 handler_tasks: Arc::clone(&handler_tasks),
3940 signal: Arc::clone(&signal),
3941 handler_abort: handler_abort.clone(),
3942 socket_control: Some(Arc::new(control)),
3943 armed: true,
3944 };
3945
3946 drop(rollback);
3947
3948 assert!(!handler_tasks.is_open());
3949 assert!(signal.load(Ordering::Acquire));
3950 assert!(handler_abort.is_cancelled());
3951 assert!(registry.handle(client_id, endpoint).is_none());
3952 handler_tasks
3953 .finish_shutdown(Duration::ZERO, Duration::from_secs(1))
3954 .await
3955 .expect("empty handler scope should drain");
3956 }
3957
3958 #[rstest]
3959 #[tokio::test]
3960 async fn request_close_signals_before_handler_shutdown() {
3961 let mut client = OKXWebSocketClient::default();
3962 let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3963 client.cmd_tx = Arc::new(tokio::sync::RwLock::new(cmd_tx));
3964 client.signal.store(false, Ordering::Release);
3965
3966 client.request_close().await;
3967
3968 assert!(client.signal.load(Ordering::Acquire));
3969 assert!(matches!(cmd_rx.try_recv(), Ok(HandlerCommand::Disconnect)));
3970 }
3971
3972 #[rstest]
3973 #[tokio::test]
3974 async fn close_joins_handler_shared_with_clone() {
3975 let mut client = OKXWebSocketClient::default();
3976 let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();
3977 let signal = DropSignal(Some(drop_tx));
3978 client
3979 .handler_tasks
3980 .spawn(async move {
3981 let _signal = signal;
3982 std::future::pending::<()>().await;
3983 })
3984 .expect("handler task should register");
3985 let retained = client.clone();
3986
3987 client.close().await.expect("close with retained clone");
3988
3989 tokio::time::timeout(Duration::from_secs(1), drop_rx)
3990 .await
3991 .expect("close must drop the handler task")
3992 .expect("drop signal");
3993 assert!(!client.has_task());
3994 assert!(!retained.has_task());
3995 }
3996
3997 #[rstest]
3998 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3999 async fn timeout_retains_unfinished_handler_task() {
4000 let mut client = OKXWebSocketClient::default();
4001 let release = Arc::new((parking_lot::Mutex::new(false), parking_lot::Condvar::new()));
4002 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4003 let blocking_drop = BlockingDrop(Arc::clone(&release));
4004 client
4005 .handler_tasks
4006 .spawn(async move {
4007 let _blocking_drop = blocking_drop;
4008 started_tx.send(()).expect("started receiver");
4009 std::future::pending::<()>().await;
4010 })
4011 .expect("handler task should register");
4012 started_rx.await.expect("blocking task started");
4013 client.begin_shutdown();
4014
4015 let result = client.close_stream_task(Duration::from_millis(10)).await;
4016 let retained = client.has_task();
4017 let reconnect_result = client.connect().await;
4018
4019 let (lock, condvar) = &*release;
4020 *lock.lock() = true;
4021 condvar.notify_all();
4022
4023 client
4024 .close_stream_task(Duration::from_secs(1))
4025 .await
4026 .expect("blocking handler task terminated");
4027
4028 assert!(result.is_err());
4029 assert!(retained);
4030 assert_eq!(
4031 reconnect_result
4032 .expect_err("reconnect with unfinished handler")
4033 .to_string(),
4034 "Cannot connect while previous WebSocket handler task is still running"
4035 );
4036 assert!(!client.has_task());
4037 }
4038
4039 #[rstest]
4040 fn test_feed_handler_reconnection_detection() {
4041 let msg = Message::Text(RECONNECTED.to_string().into());
4042 let result = OKXWsFeedHandler::parse_raw_message(msg);
4043 assert!(matches!(result, Some(OKXWsFrame::Reconnected)));
4044 }
4045
4046 #[rstest]
4047 fn test_feed_handler_normal_message_processing() {
4048 let ping_msg = Message::Text(TEXT_PING.to_string().into());
4049 let result = OKXWsFeedHandler::parse_raw_message(ping_msg);
4050 assert!(matches!(result, Some(OKXWsFrame::Ping)));
4051
4052 let sub_msg = r#"{
4053 "event": "subscribe",
4054 "arg": {
4055 "channel": "tickers",
4056 "instType": "SPOT"
4057 },
4058 "connId": "a4d3ae55"
4059 }"#;
4060
4061 let sub_result =
4062 OKXWsFeedHandler::parse_raw_message(Message::Text(sub_msg.to_string().into()));
4063 assert!(matches!(sub_result, Some(OKXWsFrame::Subscription { .. })));
4064 }
4065
4066 #[rstest]
4067 fn test_feed_handler_close_message() {
4068 let result = OKXWsFeedHandler::parse_raw_message(Message::Close(None));
4069 assert!(result.is_none());
4070 }
4071
4072 #[rstest]
4073 fn test_reconnection_message_constant() {
4074 assert_eq!(RECONNECTED, "__RECONNECTED__");
4075 }
4076
4077 #[rstest]
4078 fn resubscribe_batches_subscription_args_into_venue_message_size() {
4079 let args: Vec<_> = (0..300)
4080 .map(|i| OKXSubscriptionArg {
4081 channel: OKXWsChannel::Tickers,
4082 inst_type: None,
4083 inst_family: None,
4084 inst_id: Some(Ustr::from(&format!("INST-{i}"))),
4085 })
4086 .collect();
4087
4088 let batches: Vec<_> = subscription_arg_batches(&args).collect();
4089
4090 assert_eq!(OKX_WS_SUBSCRIPTION_ARGS_MAX_PER_MESSAGE, 256);
4091 assert_eq!(batches.len(), 2);
4092 assert_eq!(batches[0].len(), 256);
4093 assert_eq!(batches[1].len(), 44);
4094 }
4095
4096 #[rstest]
4097 #[case::buffered_notifications(false)]
4098 #[case::notification_during_install(true)]
4099 fn buffered_reconnects_advance_only_the_active_epoch(#[case] install_window: bool) {
4100 let mut reconnect_epoch = 0;
4101 if install_window {
4102 let advanced = advance_reconnect_epoch(&mut reconnect_epoch, 2, false, false);
4103 assert!(!advanced);
4104 assert_eq!(reconnect_epoch, 0);
4105 }
4106
4107 let first = advance_reconnect_epoch(&mut reconnect_epoch, 2, false, true);
4108 let duplicate = advance_reconnect_epoch(&mut reconnect_epoch, 2, false, true);
4109 let next = advance_reconnect_epoch(&mut reconnect_epoch, 3, false, true);
4110
4111 assert!(first);
4112 assert!(!duplicate);
4113 assert!(next);
4114 assert_eq!(reconnect_epoch, 3);
4115 }
4116
4117 #[rstest]
4118 fn stopped_reconnect_does_not_advance_the_epoch() {
4119 let mut reconnect_epoch = 1;
4120 let advanced = advance_reconnect_epoch(&mut reconnect_epoch, 2, true, true);
4121
4122 assert!(!advanced);
4123 assert_eq!(reconnect_epoch, 1);
4124 }
4125
4126 #[rstest]
4127 #[tokio::test]
4128 async fn authenticate_session_sends_login_and_completes_on_success() {
4129 let (ws_client, mut received, server) = connect_auth_socket().await;
4130 let auth_tracker = AuthTracker::new();
4131 let credential = Credential::new("key".into(), "secret".into(), "pass".into());
4132 let clock = Box::leak(Box::new(AtomicTime::new(
4133 false,
4134 UnixNanos::new(1_700_000_000_999_999_999),
4135 )));
4136 let timestamp = authentication_timestamp(clock.get_time_ns());
4137 let signature = credential.sign(×tamp, "GET", "/users/self/verify", "");
4138 let tracker = auth_tracker.clone();
4139
4140 let task = {
4141 let ws_client = Arc::clone(&ws_client);
4142
4143 tokio::spawn(async move {
4144 authenticate_session(
4145 &credential,
4146 &auth_tracker,
4147 &ws_client,
4148 ws_client.connection_epoch(),
4149 clock,
4150 5,
4151 )
4152 .await
4153 })
4154 };
4155
4156 let frame = tokio::time::timeout(Duration::from_secs(5), received.recv())
4157 .await
4158 .unwrap()
4159 .unwrap();
4160 let payload: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap();
4161 tracker.succeed();
4162 task.await.unwrap().unwrap();
4163 ws_client.disconnect().await;
4164 server.abort();
4165
4166 assert_eq!(payload.as_object().unwrap().len(), 2);
4167 assert_eq!(payload["op"], "login");
4168 assert_eq!(payload["args"].as_array().unwrap().len(), 1);
4169 assert_eq!(payload["args"][0].as_object().unwrap().len(), 4);
4170 assert_eq!(payload["args"][0]["apiKey"], "key");
4171 assert_eq!(payload["args"][0]["passphrase"], "pass");
4172 assert_eq!(payload["args"][0]["timestamp"], timestamp);
4173 assert_eq!(payload["args"][0]["sign"], signature);
4174 }
4175
4176 #[rstest]
4177 #[tokio::test]
4178 async fn authenticate_session_rejects_mismatched_epoch_without_resetting_tracker() {
4179 let (ws_client, mut received, server) = connect_auth_socket().await;
4180 let auth_tracker = AuthTracker::new();
4181 auth_tracker.succeed();
4182 let credential = Credential::new("key".into(), "secret".into(), "pass".into());
4183
4184 let error = authenticate_session(
4185 &credential,
4186 &auth_tracker,
4187 &ws_client,
4188 ws_client.connection_epoch() + 1,
4189 get_atomic_clock_realtime(),
4190 5,
4191 )
4192 .await
4193 .unwrap_err();
4194 let authenticated = auth_tracker.is_authenticated();
4195 let frame = received.try_recv();
4196 ws_client.disconnect().await;
4197 server.abort();
4198
4199 assert!(matches!(error, Error::Io(e) if matches!(
4200 e.get_ref().and_then(|e| e.downcast_ref::<SendError>()),
4201 Some(SendError::ConnectionChanged),
4202 )));
4203 assert!(authenticated);
4204 assert!(matches!(
4205 frame,
4206 Err(tokio::sync::mpsc::error::TryRecvError::Empty)
4207 ));
4208 }
4209
4210 #[rstest]
4211 fn auth_attempt_superseded_matches_tracker_message() {
4212 let error = Error::Io(std::io::Error::other("Authentication attempt superseded"));
4213 assert!(auth_attempt_superseded(&error));
4214 let changed = Error::Io(std::io::Error::other(SendError::ConnectionChanged));
4215 assert!(auth_attempt_superseded(&changed));
4216 let other = Error::Io(std::io::Error::other("Authentication timed out"));
4217 assert!(!auth_attempt_superseded(&other));
4218 }
4219
4220 #[rstest]
4221 #[tokio::test]
4222 async fn reauthenticate_session_starts_fresh_attempt_when_tracker_is_authenticated() {
4223 let (ws_client, mut rx, server) = connect_auth_socket().await;
4224 let auth_tracker = AuthTracker::new();
4225 auth_tracker.succeed();
4226 let tracker = auth_tracker.clone();
4227
4228 let task = {
4229 let ws_client = Arc::clone(&ws_client);
4230
4231 tokio::spawn(reauthenticate_session(
4232 Credential::new("key".into(), "secret".into(), "pass".into()),
4233 auth_tracker,
4234 Arc::clone(&ws_client),
4235 ws_client.connection_epoch(),
4236 get_atomic_clock_realtime(),
4237 5,
4238 Arc::new(AtomicBool::new(false)),
4239 CancellationToken::new(),
4240 ))
4241 };
4242
4243 let received = tokio::time::timeout(Duration::from_secs(1), rx.recv())
4244 .await
4245 .unwrap()
4246 .unwrap();
4247 let authenticated_before_ack = tracker.is_authenticated();
4248 tracker.succeed();
4249 task.await.unwrap();
4250 ws_client.disconnect().await;
4251 server.abort();
4252
4253 let payload: Value = serde_json::from_str(received.to_text().unwrap()).unwrap();
4254 assert_eq!(payload["op"], "login");
4255 assert!(!authenticated_before_ack);
4256 assert!(tracker.is_authenticated());
4257 }
4258
4259 #[rstest]
4260 #[tokio::test]
4261 async fn reauthenticate_session_stops_when_aborted() {
4262 let (ws_client, mut rx, server) = connect_auth_socket().await;
4263 let abort = CancellationToken::new();
4264 abort.cancel();
4265
4266 tokio::time::timeout(
4267 Duration::from_millis(200),
4268 reauthenticate_session(
4269 Credential::new("key".into(), "secret".into(), "pass".into()),
4270 AuthTracker::new(),
4271 Arc::clone(&ws_client),
4272 ws_client.connection_epoch(),
4273 get_atomic_clock_realtime(),
4274 5,
4275 Arc::new(AtomicBool::new(false)),
4276 abort,
4277 ),
4278 )
4279 .await
4280 .expect("aborted authentication must return without waiting");
4281 let received = rx.try_recv();
4282 ws_client.disconnect().await;
4283 server.abort();
4284 assert!(matches!(
4285 received,
4286 Err(tokio::sync::mpsc::error::TryRecvError::Empty)
4287 ));
4288 }
4289
4290 async fn connect_auth_socket() -> (
4291 Arc<WebSocketClient>,
4292 tokio::sync::mpsc::UnboundedReceiver<Message>,
4293 tokio::task::JoinHandle<()>,
4294 ) {
4295 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4296 let addr = listener.local_addr().unwrap();
4297 let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
4298
4299 let server = tokio::spawn(async move {
4300 let (socket, _) = listener.accept().await.unwrap();
4301 let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
4302 while let Some(Ok(frame)) = socket.next().await {
4303 if tx.send(frame).is_err() {
4304 break;
4305 }
4306 }
4307 });
4308
4309 let config = WebSocketConfig::builder()
4310 .url(format!("ws://{addr}"))
4311 .build()
4312 .unwrap();
4313 let ws_client = WebSocketClient::builder()
4314 .config(config)
4315 .message_handler(Arc::new(|_| {}))
4316 .connect()
4317 .await
4318 .unwrap();
4319 (Arc::new(ws_client), rx, server)
4320 }
4321
4322 #[rstest]
4323 fn test_multiple_reconnection_signals() {
4324 for _ in 0..3 {
4325 let msg = Message::Text(RECONNECTED.to_string().into());
4326 let result = OKXWsFeedHandler::parse_raw_message(msg);
4327 assert!(matches!(result, Some(OKXWsFrame::Reconnected)));
4328 }
4329 }
4330
4331 fn sample_canceled_order_msg() -> OKXOrderMsg {
4332 OKXOrderMsg {
4333 acc_fill_sz: Some("0".to_string()),
4334 avg_px: "0".to_string(),
4335 c_time: 0,
4336 cancel_source: None,
4337 cancel_source_reason: None,
4338 category: OKXOrderCategory::Normal,
4339 ccy: Ustr::from("USDT"),
4340 cl_ord_id: "order-1".to_string(),
4341 algo_cl_ord_id: None,
4342 attach_algo_cl_ord_id: None,
4343 attach_algo_ords: Vec::new(),
4344 outcome: None,
4345 fee: None,
4346 fee_ccy: Ustr::from("USDT"),
4347 fill_px: "0".to_string(),
4348 fill_sz: "0".to_string(),
4349 fill_time: 0,
4350 inst_id: Ustr::from("ETH-USDT-SWAP"),
4351 inst_type: OKXInstrumentType::Swap,
4352 lever: "1".to_string(),
4353 ord_id: Ustr::from("123456"),
4354 ord_type: OKXOrderType::Limit,
4355 pnl: "0".to_string(),
4356 pos_side: OKXPositionSide::Net,
4357 px: "0".to_string(),
4358 reduce_only: "false".to_string(),
4359 side: OKXSide::Buy,
4360 state: OKXOrderStatus::Canceled,
4361 exec_type: OKXExecType::None,
4362 sz: "1".to_string(),
4363 td_mode: OKXTradeMode::Cross,
4364 tgt_ccy: None,
4365 trade_id: String::new(),
4366 algo_id: None,
4367 fill_fee: None,
4368 fill_fee_ccy: None,
4369 fill_mark_px: None,
4370 fill_mark_vol: None,
4371 fill_px_vol: None,
4372 fill_px_usd: None,
4373 fill_fwd_px: None,
4374 fill_notional_usd: None,
4375 fill_pnl: None,
4376 is_tp_limit: None,
4377 linked_algo_ord: None,
4378 notional_usd: None,
4379 px_type: OKXPriceType::None,
4380 px_usd: None,
4381 px_vol: None,
4382 quick_mgn_type: OKXQuickMarginType::None,
4383 rebate: None,
4384 rebate_ccy: None,
4385 sl_ord_px: None,
4386 sl_trigger_px: None,
4387 sl_trigger_px_type: None,
4388 source: None,
4389 stp_id: None,
4390 stp_mode: OKXSelfTradePreventionMode::None,
4391 tag: None,
4392 tp_ord_px: None,
4393 tp_trigger_px: None,
4394 tp_trigger_px_type: None,
4395 amend_result: None,
4396 req_id: None,
4397 code: None,
4398 msg: None,
4399 u_time: 0,
4400 }
4401 }
4402
4403 #[rstest]
4404 fn test_is_post_only_auto_cancel_detects_cancel_source() {
4405 let mut msg = sample_canceled_order_msg();
4406 msg.cancel_source = Some(OKX_POST_ONLY_CANCEL_SOURCE.to_string());
4407
4408 assert!(is_post_only_auto_cancel(&msg));
4409 }
4410
4411 #[rstest]
4412 fn test_is_post_only_auto_cancel_detects_reason() {
4413 let mut msg = sample_canceled_order_msg();
4414 msg.cancel_source_reason = Some("POST_ONLY would take liquidity".to_string());
4415
4416 assert!(is_post_only_auto_cancel(&msg));
4417 }
4418
4419 #[rstest]
4420 fn test_is_post_only_auto_cancel_false_without_markers() {
4421 let msg = sample_canceled_order_msg();
4422
4423 assert!(!is_post_only_auto_cancel(&msg));
4424 }
4425
4426 #[rstest]
4427 fn test_is_post_only_auto_cancel_false_for_order_type_only() {
4428 let mut msg = sample_canceled_order_msg();
4429 msg.ord_type = OKXOrderType::PostOnly;
4430
4431 assert!(!is_post_only_auto_cancel(&msg));
4432 }
4433}