Skip to main content

nautilus_okx/websocket/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides the WebSocket client integration for the [OKX](https://okx.com) WebSocket API.
17//!
18//! The [`OKXWebSocketClient`] ties together several recurring patterns:
19//! - Heartbeats use text `ping`/`pong`, responding to both text and control-frame pings.
20//! - Authentication re-runs on reconnect before resubscribing and skips private channels when
21//!   credentials are unavailable.
22//! - Subscriptions retain channel arguments so reconnects rebuild the same set of channels while
23//!   respecting the authentication guard described above.
24
25use 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
102/// Default OKX WebSocket connection rate limit: 3 requests per second.
103///
104/// This applies to establishing WebSocket connections, not to subscribe/unsubscribe operations.
105pub static OKX_WS_CONNECTION_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
106    Quota::per_second(NonZeroU32::new(3).expect("non-zero")).expect("valid constant")
107});
108
109/// OKX WebSocket subscription rate limit: 480 requests per hour per connection.
110///
111/// This applies to subscribe/unsubscribe/login operations.
112/// 480 per hour = 8 per minute, but we use per-hour for accurate limiting.
113pub static OKX_WS_SUBSCRIPTION_QUOTA: LazyLock<Quota> =
114    LazyLock::new(|| Quota::per_hour(NonZeroU32::new(480).expect("non-zero")));
115
116/// Rate limit for single order, cancel, and amend WebSocket operations: 30 requests per second.
117pub static OKX_WS_ORDER_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
118    Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant")
119});
120
121/// Rate limit for batch order, cancel, and amend WebSocket operations: 7 requests per second.
122pub 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
126/// Rate limit for mass cancel WebSocket operations: 2 requests per second.
127pub 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
131/// Rate limit for algo order WebSocket operations: 10 requests per second.
132pub 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
136/// Rate limit for algo cancel WebSocket operations: 1 request per second.
137pub 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
141/// Maximum subscription args per subscribe/unsubscribe websocket message.
142const OKX_WS_SUBSCRIPTION_ARGS_MAX_PER_MESSAGE: usize = 256;
143
144/// Pre-interned rate limit key for subscription operations (subscribe/unsubscribe/login).
145///
146/// See: <https://www.okx.com/docs-v5/en/#websocket-api-login>
147/// See: <https://www.okx.com/docs-v5/en/#websocket-api-subscribe>
148pub static OKX_RATE_LIMIT_KEY_SUBSCRIPTION: LazyLock<[Ustr; 1]> =
149    LazyLock::new(|| [Ustr::from("subscription")]);
150
151/// Pre-interned rate limit key for single regular order operations.
152///
153/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-place-order>
154pub static OKX_RATE_LIMIT_KEY_ORDER: LazyLock<[Ustr; 1]> = LazyLock::new(|| [Ustr::from("order")]);
155
156/// Pre-interned rate limit key for batch order operations.
157///
158/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-place-multiple-orders>
159pub static OKX_RATE_LIMIT_KEY_BATCH_ORDER: LazyLock<[Ustr; 1]> =
160    LazyLock::new(|| [Ustr::from("batch-order")]);
161
162/// Pre-interned rate limit key for single regular cancel operations.
163///
164/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-cancel-order>
165pub static OKX_RATE_LIMIT_KEY_CANCEL: LazyLock<[Ustr; 1]> =
166    LazyLock::new(|| [Ustr::from("cancel")]);
167
168/// Pre-interned rate limit key for batch cancel operations.
169///
170/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-cancel-multiple-orders>
171pub static OKX_RATE_LIMIT_KEY_BATCH_CANCEL: LazyLock<[Ustr; 1]> =
172    LazyLock::new(|| [Ustr::from("batch-cancel")]);
173
174/// Pre-interned rate limit key for mass cancel operations.
175///
176/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-mass-cancel-order>
177pub static OKX_RATE_LIMIT_KEY_MASS_CANCEL: LazyLock<[Ustr; 1]> =
178    LazyLock::new(|| [Ustr::from("mass-cancel")]);
179
180/// Pre-interned rate limit key for amend operations (amend orders).
181///
182/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-amend-order>
183pub static OKX_RATE_LIMIT_KEY_AMEND: LazyLock<[Ustr; 1]> = LazyLock::new(|| [Ustr::from("amend")]);
184
185/// Pre-interned rate limit key for batch amend operations.
186///
187/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-amend-multiple-orders>
188pub static OKX_RATE_LIMIT_KEY_BATCH_AMEND: LazyLock<[Ustr; 1]> =
189    LazyLock::new(|| [Ustr::from("batch-amend")]);
190
191/// Pre-interned rate limit key for algo order operations.
192///
193/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-ws-place-algo-order>
194pub static OKX_RATE_LIMIT_KEY_ALGO_ORDER: LazyLock<[Ustr; 1]> =
195    LazyLock::new(|| [Ustr::from("algo-order")]);
196
197/// Pre-interned rate limit key for algo cancel operations.
198///
199/// See: <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-ws-cancel-algo-order>
200pub static OKX_RATE_LIMIT_KEY_ALGO_CANCEL: LazyLock<[Ustr; 1]> =
201    LazyLock::new(|| [Ustr::from("algo-cancel")]);
202
203/// Context stored at order submission time for correlating venue responses.
204///
205/// Fields are read in `python/websocket.rs` (behind the `python` feature gate).
206#[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/// Provides a WebSocket client for connecting to [OKX](https://okx.com).
219///
220/// Instruments with the same base pair share one `index-tickers` subscription.
221/// Only the first subscriber triggers a venue subscribe, and only the last triggers
222/// a venue unsubscribe. Reference count updates and venue sends are serialized so
223/// concurrent subscription changes cannot leave the venue unsubscribed while local
224/// subscribers remain.
225#[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    order_request_ttl_ms: Option<u64>,
249    pub(crate) pending_orders: Arc<DashMap<String, PendingOrderInfo>>,
250    pub(crate) pending_cancels: Arc<DashMap<String, PendingOrderInfo>>,
251    pub(crate) pending_amends: Arc<DashMap<String, PendingOrderInfo>>,
252    pub(crate) pending_command_ids: Arc<DashMap<String, Vec<(ClientOrderId, UUID4)>>>,
253    option_greeks_subs: Arc<AtomicMap<InstrumentId, AHashSet<OKXGreeksType>>>,
254    index_pair_subscribers: Arc<DashMap<Ustr, usize>>,
255    index_pair_transition: Arc<tokio::sync::Mutex<()>>,
256    transport_backend: TransportBackend,
257    proxy_url: Option<SecretString>,
258    cancellation_token: CancellationToken,
259    socket_control: Option<Arc<SocketControl>>,
260}
261
262struct ConnectRollback {
263    handler_tasks: Arc<TaskGroup>,
264    signal: Arc<AtomicBool>,
265    handler_abort: CancellationToken,
266    socket_control: Option<Arc<SocketControl>>,
267    armed: bool,
268}
269
270impl ConnectRollback {
271    fn disarm(&mut self) {
272        self.armed = false;
273    }
274}
275
276impl Drop for ConnectRollback {
277    fn drop(&mut self) {
278        if !self.armed {
279            return;
280        }
281
282        self.handler_tasks.begin_shutdown();
283        self.signal.store(true, Ordering::Release);
284        self.handler_abort.cancel();
285
286        if let Some(control) = &self.socket_control {
287            control.deregister();
288        }
289    }
290}
291
292impl Default for OKXWebSocketClient {
293    fn default() -> Self {
294        Self::new(
295            None,
296            None,
297            None,
298            None,
299            None,
300            None,
301            None,
302            TransportBackend::default(),
303            None,
304        )
305        .unwrap()
306    }
307}
308
309impl Debug for OKXWebSocketClient {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        f.debug_struct(stringify!(OKXWebSocketClient))
312            .field("url", &self.url)
313            .field("credential", &self.credential.as_ref().map(|_| REDACTED))
314            .field("heartbeat", &self.heartbeat)
315            .finish_non_exhaustive()
316    }
317}
318
319impl OKXWebSocketClient {
320    /// Creates a new [`OKXWebSocketClient`] instance.
321    ///
322    /// # Errors
323    ///
324    /// Returns an error if the request fails.
325    #[allow(clippy::too_many_arguments)]
326    pub fn new(
327        url: Option<String>,
328        api_key: Option<String>,
329        api_secret: Option<String>,
330        api_passphrase: Option<String>,
331        _account_id: Option<AccountId>,
332        heartbeat: Option<u64>,
333        auth_timeout_secs: Option<u64>,
334        transport_backend: TransportBackend,
335        proxy_url: Option<String>,
336    ) -> anyhow::Result<Self> {
337        let url = url.unwrap_or(OKX_WS_PUBLIC_URL.to_string());
338        let credential = match (api_key, api_secret, api_passphrase) {
339            (Some(key), Some(secret), Some(passphrase)) => {
340                Some(Credential::new(key, secret, passphrase))
341            }
342            (None, None, None) => None,
343            _ => anyhow::bail!(
344                "`api_key`, `api_secret`, `api_passphrase` credentials must be provided together"
345            ),
346        };
347
348        let signal = Arc::new(AtomicBool::new(false));
349        let subscriptions = Arc::new(DashMap::new());
350        let subscriptions_state = SubscriptionState::new(OKX_WS_TOPIC_DELIMITER);
351
352        Ok(Self {
353            clock: get_atomic_clock_realtime(),
354            url,
355            vip_level: Arc::new(AtomicU8::new(0)),
356            credential,
357            heartbeat,
358            auth_timeout_secs: auth_timeout_secs.unwrap_or(AUTHENTICATION_TIMEOUT_SECS),
359            auth_tracker: AuthTracker::new(),
360            signal,
361            connection_mode: Arc::new(ArcSwap::from_pointee(AtomicU8::new(
362                ConnectionMode::Closed.as_u8(),
363            ))),
364            cmd_tx: {
365                // Placeholder channel until connect() creates the real handler and replays queued instruments
366                let (tx, _) = tokio::sync::mpsc::unbounded_channel();
367                Arc::new(tokio::sync::RwLock::new(tx))
368            },
369            out_rx: None,
370            handler_tasks: Arc::new(TaskGroup::new()),
371            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
372            handler_abort: Arc::new(Mutex::new(CancellationToken::new())),
373            subscriptions,
374            subscriptions_state,
375            request_id_counter: Arc::new(AtomicU64::new(1)),
376            instruments_cache: Arc::new(AtomicMap::new()),
377            inst_id_code_cache: Arc::new(AtomicMap::new()),
378            trade_quote_ccy_lists: Arc::new(AtomicMap::new()),
379            spot_trade_quote_ccy: Arc::new(Mutex::new(None)),
380            order_request_ttl_ms: None,
381            pending_orders: Arc::new(DashMap::new()),
382            pending_cancels: Arc::new(DashMap::new()),
383            pending_amends: Arc::new(DashMap::new()),
384            pending_command_ids: Arc::new(DashMap::new()),
385            option_greeks_subs: Arc::new(AtomicMap::new()),
386            index_pair_subscribers: Arc::new(DashMap::new()),
387            index_pair_transition: Arc::new(tokio::sync::Mutex::new(())),
388            transport_backend,
389            proxy_url: proxy_url.map(SecretString::from),
390            cancellation_token: CancellationToken::new(),
391            socket_control: None,
392        })
393    }
394
395    /// Configures socket state reporting and reconnect control.
396    #[must_use]
397    pub fn with_socket_control(mut self, control: SocketControl) -> Self {
398        self.socket_control = Some(Arc::new(control));
399        self
400    }
401
402    /// Sets the TTL used to derive `expTime` on place and amend requests.
403    ///
404    /// Each request carries `expTime = now + ttl_ms`, computed when the request is built.
405    /// OKX does not process the request if its server time is past `expTime`. `None` omits
406    /// `expTime`.
407    #[must_use]
408    pub fn with_order_request_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
409        self.order_request_ttl_ms = ttl_ms;
410        self
411    }
412
413    fn order_request_exp_time(&self) -> Option<String> {
414        self.order_request_ttl_ms
415            .map(|ttl_ms| self.clock.get_time_ms().saturating_add(ttl_ms).to_string())
416    }
417
418    /// Creates a new [`OKXWebSocketClient`] instance.
419    ///
420    /// # Errors
421    ///
422    /// Returns an error if credential values cannot be loaded or if the
423    /// client fails to initialize.
424    #[allow(clippy::too_many_arguments)]
425    pub fn with_credentials(
426        url: Option<String>,
427        api_key: Option<String>,
428        api_secret: Option<String>,
429        api_passphrase: Option<String>,
430        account_id: Option<AccountId>,
431        heartbeat: Option<u64>,
432        auth_timeout_secs: Option<u64>,
433        transport_backend: TransportBackend,
434        proxy_url: Option<String>,
435    ) -> anyhow::Result<Self> {
436        let url = url.unwrap_or(OKX_WS_PUBLIC_URL.to_string());
437        let api_key = get_or_env_var(api_key, "OKX_API_KEY")?;
438        let api_secret = get_or_env_var(api_secret, "OKX_API_SECRET")?;
439        let api_passphrase = get_or_env_var(api_passphrase, "OKX_API_PASSPHRASE")?;
440
441        Self::new(
442            Some(url),
443            Some(api_key),
444            Some(api_secret),
445            Some(api_passphrase),
446            account_id,
447            heartbeat,
448            auth_timeout_secs,
449            transport_backend,
450            proxy_url,
451        )
452    }
453
454    /// Creates a new authenticated [`OKXWebSocketClient`] using environment variables.
455    ///
456    /// # Errors
457    ///
458    /// Returns an error if required environment variables are missing or if
459    /// the client fails to initialize.
460    pub fn from_env() -> anyhow::Result<Self> {
461        let url = get_env_var("OKX_WS_URL")?;
462        let api_key = get_env_var("OKX_API_KEY")?;
463        let api_secret = get_env_var("OKX_API_SECRET")?;
464        let api_passphrase = get_env_var("OKX_API_PASSPHRASE")?;
465
466        Self::new(
467            Some(url),
468            Some(api_key),
469            Some(api_secret),
470            Some(api_passphrase),
471            None,
472            None,
473            None,
474            TransportBackend::default(),
475            None,
476        )
477    }
478
479    /// Cancel all pending WebSocket requests.
480    pub fn cancel_all_requests(&self) {
481        self.cancellation_token.cancel();
482    }
483
484    /// Get the cancellation token for this client.
485    pub fn cancellation_token(&self) -> &CancellationToken {
486        &self.cancellation_token
487    }
488
489    /// Returns the websocket url being used by the client.
490    pub fn url(&self) -> &str {
491        self.url.as_str()
492    }
493
494    /// Returns the public API key being used by the client.
495    pub fn api_key(&self) -> Option<&str> {
496        self.credential.as_ref().map(Credential::api_key)
497    }
498
499    /// Returns a masked version of the API key for logging purposes.
500    #[must_use]
501    pub fn api_key_masked(&self) -> Option<String> {
502        self.credential.as_ref().map(Credential::api_key_masked)
503    }
504
505    /// Returns a value indicating whether the client is active.
506    pub fn is_active(&self) -> bool {
507        let connection_mode_arc = self.connection_mode.load();
508        ConnectionMode::from_atomic(&connection_mode_arc).is_active()
509            && !self.signal.load(Ordering::Acquire)
510    }
511
512    /// Returns a value indicating whether the client is closed.
513    pub fn is_closed(&self) -> bool {
514        let connection_mode_arc = self.connection_mode.load();
515        ConnectionMode::from_atomic(&connection_mode_arc).is_closed()
516            || self.signal.load(Ordering::Acquire)
517    }
518
519    /// Returns whether this client retains ownership of a handler task.
520    pub(crate) fn has_task(&self) -> bool {
521        !self.handler_tasks.is_empty()
522    }
523
524    /// Caches multiple instruments.
525    ///
526    /// Any existing instruments with the same symbols will be replaced.
527    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
528        self.instruments_cache.rcu(|m| {
529            for inst in instruments {
530                m.insert(inst.symbol().inner(), inst.clone());
531            }
532        });
533    }
534
535    /// Caches a single instrument.
536    ///
537    /// Any existing instrument with the same symbol will be replaced.
538    pub fn cache_instrument(&self, instrument: InstrumentAny) {
539        self.instruments_cache
540            .insert(instrument.symbol().inner(), instrument);
541    }
542
543    /// Returns a snapshot of the instruments cache as an `AHashMap`.
544    pub fn instruments_snapshot(&self) -> AHashMap<Ustr, InstrumentAny> {
545        (**self.instruments_cache.load()).clone()
546    }
547
548    /// Returns a shared handle to the live instruments cache.
549    pub fn instruments_cache_arc(&self) -> Arc<AtomicMap<Ustr, InstrumentAny>> {
550        Arc::clone(&self.instruments_cache)
551    }
552
553    /// Caches the instIdCode mapping for an instrument.
554    ///
555    /// The instIdCode is required for WebSocket order operations per OKX API deprecation.
556    pub fn cache_inst_id_code(&self, inst_id: Ustr, inst_id_code: u64) {
557        self.inst_id_code_cache.insert(inst_id, inst_id_code);
558    }
559
560    /// Caches multiple instIdCode mappings for instruments.
561    ///
562    /// This is typically called after loading instruments from the HTTP API.
563    pub fn cache_inst_id_codes(&self, mappings: impl IntoIterator<Item = (Ustr, u64)>) {
564        let entries: Vec<_> = mappings.into_iter().collect();
565        self.inst_id_code_cache.rcu(|m| {
566            for (inst_id, inst_id_code) in &entries {
567                m.insert(*inst_id, *inst_id_code);
568            }
569        });
570    }
571
572    /// Gets the instIdCode for an instrument.
573    ///
574    /// Returns `None` if the instrument is not in the cache.
575    #[must_use]
576    pub fn get_inst_id_code(&self, inst_id: &Ustr) -> Option<u64> {
577        self.inst_id_code_cache.load().get(inst_id).copied()
578    }
579
580    /// Sets the optional SPOT `tradeQuoteCcy` override for subsequent order placement.
581    pub fn set_spot_trade_quote_ccy(&self, ccy: Option<String>) {
582        *self.spot_trade_quote_ccy.lock() = ccy.map(|value| Ustr::from(value.as_str()));
583    }
584
585    /// Caches `tradeQuoteCcyList` values keyed by instrument ID.
586    pub fn cache_trade_quote_ccy_lists(
587        &self,
588        mappings: impl IntoIterator<Item = (Ustr, Vec<Ustr>)>,
589    ) {
590        let entries: Vec<_> = mappings.into_iter().collect();
591        self.trade_quote_ccy_lists.rcu(|m| {
592            for (inst_id, list) in &entries {
593                m.insert(*inst_id, list.clone());
594            }
595        });
596    }
597
598    fn resolve_spot_trade_quote_ccy(
599        &self,
600        instrument_type: OKXInstrumentType,
601        inst_id: Ustr,
602    ) -> Result<Option<Ustr>, OKXWsError> {
603        let configured = *self.spot_trade_quote_ccy.lock();
604        let available = self
605            .trade_quote_ccy_lists
606            .load()
607            .get(&inst_id)
608            .cloned()
609            .unwrap_or_default();
610        spot_trade_quote_ccy_wire_value(
611            instrument_type,
612            configured.as_ref().map(Ustr::as_str),
613            &available,
614        )
615        .map_err(OKXWsError::ClientError)
616    }
617
618    fn inst_id_symbol_and_code_from_snapshot(
619        inst_id_codes: &AHashMap<Ustr, u64>,
620        inst_id: &InstrumentId,
621        action: &str,
622    ) -> Result<(Ustr, u64), OKXWsError> {
623        let inst_id_symbol = inst_id.symbol.inner();
624        let inst_id_code = inst_id_codes.get(&inst_id_symbol).copied().ok_or_else(|| {
625            OKXWsError::ClientError(format!(
626                "No instIdCode cached for {inst_id}, cannot {action} order"
627            ))
628        })?;
629        Ok((inst_id_symbol, inst_id_code))
630    }
631
632    /// Sets the VIP level for this client.
633    ///
634    /// The VIP level determines which WebSocket channels are available.
635    pub fn set_vip_level(&self, vip_level: OKXVipLevel) {
636        self.vip_level.store(vip_level as u8, Ordering::Relaxed);
637    }
638
639    /// Gets the current VIP level.
640    pub fn vip_level(&self) -> OKXVipLevel {
641        let level = self.vip_level.load(Ordering::Relaxed);
642        OKXVipLevel::from(level)
643    }
644
645    /// Connect to the OKX WebSocket server.
646    ///
647    /// # Errors
648    ///
649    /// Returns an error if the connection process fails.
650    pub async fn connect(&mut self) -> anyhow::Result<()> {
651        let connect_lock = Arc::clone(&self.connect_lock);
652        let _connect_guard = connect_lock.lock().await;
653
654        if !self.handler_tasks.is_empty() && !self.handler_tasks.all_finished() {
655            anyhow::bail!("Cannot connect while previous WebSocket handler task is still running");
656        }
657
658        if !self.handler_tasks.is_open() || !self.handler_tasks.is_empty() {
659            self.handler_tasks.begin_shutdown();
660            self.handler_tasks
661                .finish_shutdown(Duration::from_secs(2), Duration::from_secs(2))
662                .await
663                .map_err(|e| anyhow::anyhow!("Previous WebSocket handler failed: {e}"))?;
664            self.handler_tasks.start_generation().map_err(|e| {
665                anyhow::anyhow!("Failed to start WebSocket handler task generation: {e}")
666            })?;
667        }
668        let handler_spawner = self.handler_tasks.spawner().map_err(|e| {
669            anyhow::anyhow!("Failed to acquire WebSocket handler task spawner: {e}")
670        })?;
671        let handler_abort = CancellationToken::new();
672        *self.handler_abort.lock() = handler_abort.clone();
673        let mut rollback = ConnectRollback {
674            handler_tasks: Arc::clone(&self.handler_tasks),
675            signal: Arc::clone(&self.signal),
676            handler_abort: handler_abort.clone(),
677            socket_control: self.socket_control.clone(),
678            armed: true,
679        };
680
681        // Reset signal so is_active()/is_closed() work after a previous close()
682        self.signal.store(false, Ordering::Release);
683
684        let (message_handler, raw_rx) = channel_message_handler();
685
686        // No-op ping handler: handler owns the WebSocketClient and responds to pings directly
687        // in the message loop for minimal latency (see handler.rs TEXT_PONG response)
688        // Inbound Ping frames are answered by the transport, so no ping handler is needed;
689        // the reader routes them away from the message channel and the handler never sees them.
690
691        let headers = create_standard_nautilus_headers();
692
693        let config = WebSocketConfig {
694            url: self.url.clone(),
695            headers,
696            heartbeat_interval_secs: self.heartbeat,
697            heartbeat_payload: Some(TEXT_PING.to_string()),
698            connect_timeout_ms: None,
699            reconnect_delay_initial_ms: None,
700            reconnect_delay_max_ms: None,
701            reconnect_backoff_factor: None,
702            reconnect_jitter_ms: None,
703            reconnect_max_attempts: None,
704            heartbeat_timeout_secs: None,
705            idle_timeout_ms: None,
706            writer_capacity: None,
707            backend: self.transport_backend,
708            proxy_url: self
709                .proxy_url
710                .as_ref()
711                .map(|value| value.expose_secret().to_owned()),
712            max_message_size_bytes: None,
713            max_frame_size_bytes: None,
714        };
715
716        let keyed_quotas = vec![
717            (
718                OKX_RATE_LIMIT_KEY_SUBSCRIPTION[0].to_string(),
719                *OKX_WS_SUBSCRIPTION_QUOTA,
720            ),
721            (OKX_RATE_LIMIT_KEY_ORDER[0].to_string(), *OKX_WS_ORDER_QUOTA),
722            (
723                OKX_RATE_LIMIT_KEY_BATCH_ORDER[0].to_string(),
724                *OKX_WS_BATCH_ORDER_QUOTA,
725            ),
726            (
727                OKX_RATE_LIMIT_KEY_CANCEL[0].to_string(),
728                *OKX_WS_ORDER_QUOTA,
729            ),
730            (
731                OKX_RATE_LIMIT_KEY_BATCH_CANCEL[0].to_string(),
732                *OKX_WS_BATCH_ORDER_QUOTA,
733            ),
734            (
735                OKX_RATE_LIMIT_KEY_MASS_CANCEL[0].to_string(),
736                *OKX_WS_MASS_CANCEL_QUOTA,
737            ),
738            (OKX_RATE_LIMIT_KEY_AMEND[0].to_string(), *OKX_WS_ORDER_QUOTA),
739            (
740                OKX_RATE_LIMIT_KEY_BATCH_AMEND[0].to_string(),
741                *OKX_WS_BATCH_ORDER_QUOTA,
742            ),
743            (
744                OKX_RATE_LIMIT_KEY_ALGO_ORDER[0].to_string(),
745                *OKX_WS_ALGO_ORDER_QUOTA,
746            ),
747            (
748                OKX_RATE_LIMIT_KEY_ALGO_CANCEL[0].to_string(),
749                *OKX_WS_ALGO_CANCEL_QUOTA,
750            ),
751        ];
752
753        let client = WebSocketClient::builder()
754            .config(config)
755            .message_handler(message_handler)
756            .keyed_quotas(keyed_quotas)
757            .default_quota(*OKX_WS_CONNECTION_QUOTA)
758            .maybe_state_sink(self.socket_control.as_ref().map(|control| control.sink()))
759            .connect()
760            .await?;
761
762        client.set_auth_tracker(self.auth_tracker.clone(), false);
763        let ws_client = Arc::new(client);
764        let connection_epoch = ws_client.connection_epoch();
765
766        let connection_mode = ws_client.connection_mode_atomic();
767        let reconnect_handle = ws_client.reconnect_handle();
768
769        let (msg_tx, rx) = tokio::sync::mpsc::unbounded_channel::<OKXWsMessage>();
770
771        self.out_rx = Some(Arc::new(rx));
772
773        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
774
775        // Queue initialization before clones can subscribe through the new sender
776        cmd_tx
777            .send(HandlerCommand::SetClient(Arc::clone(&ws_client)))
778            .map_err(|e| anyhow::anyhow!("Failed to send WebSocket client to handler: {e}"))?;
779
780        *self.cmd_tx.write().await = cmd_tx.clone();
781
782        // Clones observing active must already see the initialized sender
783        self.connection_mode.store(connection_mode);
784
785        let handler_task = {
786            let auth_tracker = self.auth_tracker.clone();
787            let signal = self.signal.clone();
788            let subscriptions_state = self.subscriptions_state.clone();
789            let clock = self.clock;
790            let credential = self.credential.clone();
791            let cmd_tx_for_reconnect = cmd_tx.clone();
792            let subscriptions = self.subscriptions.clone();
793            let ws_client = Arc::clone(&ws_client);
794            let auth_timeout_secs = self.auth_timeout_secs;
795            let mut reconnect_epoch = connection_epoch;
796            let handler_spawner_for_auth = handler_spawner.clone();
797            let mut has_reconnected = false;
798
799            async move {
800                let mut handler = OKXWsFeedHandler::new(
801                    signal.clone(),
802                    cmd_rx,
803                    raw_rx,
804                    msg_tx,
805                    auth_tracker.clone(),
806                    credential.is_some(),
807                    subscriptions_state.clone(),
808                    subscriptions.clone(),
809                    clock,
810                );
811
812                let resubscribe_all = || {
813                    subscriptions
814                        .retain(|topic, _| is_topic_subscribed(&subscriptions_state, topic));
815
816                    let args = subscription_args(&subscriptions, &subscriptions_state);
817
818                    for chunk in subscription_arg_batches(&args) {
819                        if let Err(e) = cmd_tx_for_reconnect.send(HandlerCommand::Subscribe {
820                            args: chunk.to_vec(),
821                        }) {
822                            log::error!("Failed to send resubscribe command: error={e}");
823                        }
824                    }
825                };
826
827                loop {
828                    let message = tokio::select! {
829                        biased;
830                        () = handler_abort.cancelled() => {
831                            log::debug!("Handler task aborted");
832                            break;
833                        }
834                        message = handler.next() => message,
835                    };
836
837                    match message {
838                        Some(OKXWsMessage::Reconnected) => {
839                            let epoch = ws_client.connection_epoch();
840
841                            if !advance_reconnect_epoch(
842                                &mut reconnect_epoch,
843                                epoch,
844                                signal.load(Ordering::Acquire),
845                                ws_client.is_active(),
846                            ) {
847                                continue;
848                            }
849
850                            auth_tracker.invalidate();
851                            has_reconnected = true;
852
853                            subscriptions_state.reset_after_reconnect();
854
855                            if let Some(credential) = credential.clone() {
856                                log::debug!("Re-authenticating after reconnection");
857                                let signal = signal.clone();
858                                let abort = handler_abort.clone();
859                                let ws_client = Arc::clone(&ws_client);
860                                let auth_tracker = auth_tracker.clone();
861
862                                if let Err(e) = handler_spawner_for_auth.spawn(async move {
863                                    reauthenticate_session(
864                                        credential,
865                                        auth_tracker,
866                                        ws_client,
867                                        epoch,
868                                        clock,
869                                        auth_timeout_secs,
870                                        signal,
871                                        abort,
872                                    )
873                                    .await;
874                                }) {
875                                    log::error!(
876                                        "Failed to spawn re-authentication task: error={e}"
877                                    );
878                                }
879                            }
880
881                            // Unauthenticated sessions resubscribe immediately after reconnection,
882                            // authenticated sessions wait for Authenticated message
883                            if credential.is_none() {
884                                log::debug!(
885                                    "No authentication required, resubscribing immediately"
886                                );
887                                resubscribe_all();
888                            }
889
890                            // Forward Reconnected to consumers so they can reset state
891                            if handler.send(OKXWsMessage::Reconnected).is_err() {
892                                log_receiver_dropped(&signal, "Reconnected");
893                                break;
894                            }
895                        }
896                        Some(OKXWsMessage::Authenticated) => {
897                            if has_reconnected {
898                                resubscribe_all();
899                            }
900                        }
901                        Some(msg) => {
902                            if handler.send(msg).is_err() {
903                                log_receiver_dropped(&signal, "message");
904                                break;
905                            }
906                        }
907                        None => {
908                            if handler.is_stopped() {
909                                log::debug!("Stop signal received, ending message processing");
910                                break;
911                            }
912                            log::debug!("WebSocket stream closed");
913                            break;
914                        }
915                    }
916                }
917
918                log::debug!("Handler task exiting");
919            }
920        };
921
922        if let Err(e) = handler_spawner.spawn(handler_task) {
923            self.out_rx = None;
924            anyhow::bail!("Failed to register WebSocket handler task: {e}");
925        }
926
927        if let Some(control) = &self.socket_control {
928            control.register(move || reconnect_handle.request_reconnect());
929        }
930        log::debug!("Sent WebSocket client to handler");
931
932        if self.credential.is_some()
933            && let Err(e) = self.authenticate(&ws_client, connection_epoch).await
934        {
935            self.handler_tasks.begin_shutdown();
936            self.request_close().await;
937            let shutdown_result = self.close_stream_task(Duration::from_secs(2)).await;
938
939            if let Some(control) = &self.socket_control {
940                control.deregister();
941            }
942            self.out_rx = None;
943
944            match shutdown_result {
945                Ok(()) => anyhow::bail!("Authentication failed: {e}"),
946                Err(shutdown_error) => anyhow::bail!(
947                    "Authentication failed: {e}; handler shutdown failed: {shutdown_error}"
948                ),
949            }
950        }
951
952        rollback.disarm();
953        Ok(())
954    }
955
956    /// Authenticates the WebSocket session with OKX.
957    async fn authenticate(
958        &self,
959        ws_client: &WebSocketClient,
960        connection_epoch: u64,
961    ) -> Result<(), Error> {
962        let credential = self.credential.as_ref().ok_or_else(|| {
963            Error::Io(std::io::Error::other(
964                "API credentials not available to authenticate",
965            ))
966        })?;
967
968        match authenticate_session(
969            credential,
970            &self.auth_tracker,
971            ws_client,
972            connection_epoch,
973            self.clock,
974            self.auth_timeout_secs,
975        )
976        .await
977        {
978            Ok(()) => Ok(()),
979            Err(e) if auth_attempt_superseded(&e) => {
980                // A reconnect retry may have taken over this attempt. Wait for
981                // that login instead of tearing down a live authenticated socket.
982                if self
983                    .auth_tracker
984                    .wait_for_authenticated(Duration::from_secs(self.auth_timeout_secs))
985                    .await
986                {
987                    Ok(())
988                } else {
989                    Err(e)
990                }
991            }
992            Err(e) => Err(e),
993        }
994    }
995
996    /// Provides the internal data stream as a channel-based stream.
997    ///
998    /// # Panics
999    ///
1000    /// Panics if:
1001    /// - The websocket is not connected.
1002    /// - `stream_data` has already been called somewhere else (stream receiver is then taken).
1003    pub fn stream(&mut self) -> impl Stream<Item = OKXWsMessage> + 'static {
1004        let rx = self
1005            .out_rx
1006            .take()
1007            .expect("Data stream receiver already taken or not connected");
1008        let mut rx = Arc::try_unwrap(rx).expect("Cannot take ownership - other references exist");
1009        async_stream::stream! {
1010            while let Some(data) = rx.recv().await {
1011                yield data;
1012            }
1013        }
1014    }
1015
1016    /// Wait until the WebSocket connection is active.
1017    ///
1018    /// # Errors
1019    ///
1020    /// Returns an error if the connection times out.
1021    pub async fn wait_until_active(&self, timeout_secs: f64) -> Result<(), OKXWsError> {
1022        let timeout = time::Duration::from_secs_f64(timeout_secs);
1023
1024        time::timeout(timeout, async {
1025            while !self.is_active() {
1026                time::sleep(time::Duration::from_millis(10)).await;
1027            }
1028        })
1029        .await
1030        .map_err(|_| {
1031            OKXWsError::ClientError(format!(
1032                "WebSocket connection timeout after {timeout_secs} seconds"
1033            ))
1034        })?;
1035
1036        Ok(())
1037    }
1038
1039    pub(crate) fn begin_shutdown(&self) {
1040        self.handler_tasks.begin_shutdown();
1041        self.signal.store(true, Ordering::Release);
1042
1043        let handler_abort = self.handler_abort.lock().clone();
1044        handler_abort.cancel();
1045    }
1046
1047    /// Signals the handler to close without joining its task.
1048    pub(crate) async fn request_close(&self) {
1049        self.signal.store(true, Ordering::Release);
1050
1051        if let Err(e) = self.cmd_tx.read().await.send(HandlerCommand::Disconnect) {
1052            log::debug!("Handler channel closed before disconnect command was sent: {e}");
1053        } else {
1054            log::debug!("Sent disconnect command to handler");
1055        }
1056    }
1057
1058    /// Closes the client.
1059    ///
1060    /// # Errors
1061    ///
1062    /// Returns an error if disconnecting the websocket or cleaning up the
1063    /// client fails.
1064    pub async fn close(&mut self) -> Result<(), Error> {
1065        let connect_lock = Arc::clone(&self.connect_lock);
1066        let _connect_guard = connect_lock.lock().await;
1067
1068        self.close_locked().await
1069    }
1070
1071    async fn close_locked(&self) -> Result<(), Error> {
1072        log::debug!("Starting close process");
1073
1074        self.handler_tasks.begin_shutdown();
1075        self.request_close().await;
1076
1077        let task_result = self.close_stream_task(Duration::from_secs(2)).await;
1078
1079        // Wipe per-base-pair refcounts so a subsequent reconnect can re-arm
1080        // the index-tickers channel. Otherwise the stale count short-circuits
1081        // every future `subscribe_index_prices` call and the feed stays dark.
1082        self.index_pair_subscribers.clear();
1083
1084        if let Some(control) = &self.socket_control {
1085            control.deregister();
1086        }
1087
1088        log::debug!("Close process completed");
1089
1090        task_result
1091    }
1092
1093    async fn close_stream_task(&self, timeout: Duration) -> Result<(), Error> {
1094        match self.handler_tasks.finish_shutdown(timeout, timeout).await {
1095            Ok(()) => Ok(()),
1096            Err(error @ TaskShutdownError::Timeout { .. }) => Err(Error::Io(std::io::Error::new(
1097                std::io::ErrorKind::TimedOut,
1098                format!("Timed out joining WebSocket handler task after abort: {error}"),
1099            ))),
1100            Err(e) => Err(Error::Io(std::io::Error::other(format!(
1101                "WebSocket handler shutdown failed: {e}"
1102            )))),
1103        }
1104    }
1105
1106    /// Returns active subscription channels for an instrument.
1107    pub fn get_subscriptions(&self, instrument_id: InstrumentId) -> Vec<OKXWsChannel> {
1108        let symbol = instrument_id.symbol.inner();
1109        self.subscriptions
1110            .iter()
1111            .filter(|arg| arg.inst_id == Some(symbol))
1112            .filter(|arg| is_topic_subscribed(&self.subscriptions_state, arg.key()))
1113            .map(|arg| arg.channel.clone())
1114            .collect()
1115    }
1116
1117    fn generate_unique_request_id(&self) -> String {
1118        self.request_id_counter
1119            .fetch_add(1, Ordering::SeqCst)
1120            .to_string()
1121    }
1122
1123    async fn subscribe(&self, args: Vec<OKXSubscriptionArg>) -> Result<(), OKXWsError> {
1124        // Send the command first; only update local state on success
1125        self.cmd_tx
1126            .read()
1127            .await
1128            .send(HandlerCommand::Subscribe { args: args.clone() })
1129            .map_err(|e| {
1130                OKXWsError::ClientError(format!("Failed to send subscribe command: {e}"))
1131            })?;
1132
1133        self.record_subscriptions(&args);
1134        Ok(())
1135    }
1136
1137    fn record_subscriptions(&self, args: &[OKXSubscriptionArg]) {
1138        for arg in args {
1139            let topic = topic_from_subscription_arg(arg);
1140            let entry = self
1141                .subscriptions
1142                .entry(topic.clone())
1143                .or_insert_with(|| arg.clone());
1144            self.subscriptions_state.mark_subscribe(&topic);
1145            drop(entry);
1146        }
1147    }
1148
1149    async fn unsubscribe(&self, args: Vec<OKXSubscriptionArg>) -> Result<(), OKXWsError> {
1150        self.cmd_tx
1151            .read()
1152            .await
1153            .send(HandlerCommand::Unsubscribe { args: args.clone() })
1154            .map_err(|e| {
1155                OKXWsError::ClientError(format!("Failed to send unsubscribe command: {e}"))
1156            })?;
1157
1158        for arg in &args {
1159            let topic = topic_from_subscription_arg(arg);
1160            self.subscriptions_state.mark_unsubscribe(&topic);
1161        }
1162
1163        Ok(())
1164    }
1165
1166    async fn subscribe_inst_id(
1167        &self,
1168        channel: OKXWsChannel,
1169        inst_id: Ustr,
1170    ) -> Result<(), OKXWsError> {
1171        self.subscribe(vec![OKXSubscriptionArg {
1172            channel,
1173            inst_type: None,
1174            inst_family: None,
1175            inst_id: Some(inst_id),
1176        }])
1177        .await
1178    }
1179
1180    async fn unsubscribe_inst_id(
1181        &self,
1182        channel: OKXWsChannel,
1183        inst_id: Ustr,
1184    ) -> Result<(), OKXWsError> {
1185        self.unsubscribe(vec![OKXSubscriptionArg {
1186            channel,
1187            inst_type: None,
1188            inst_family: None,
1189            inst_id: Some(inst_id),
1190        }])
1191        .await
1192    }
1193
1194    /// Unsubscribes from all active subscriptions in batched messages.
1195    ///
1196    /// Collects all confirmed subscriptions and sends unsubscribe requests in batches,
1197    /// which is significantly more efficient than individual unsubscribes during disconnect.
1198    ///
1199    /// # Errors
1200    ///
1201    /// Returns an error if the unsubscribe request fails to send.
1202    pub async fn unsubscribe_all(&self) -> Result<(), OKXWsError> {
1203        let all_args = subscription_args(&self.subscriptions, &self.subscriptions_state);
1204
1205        if all_args.is_empty() {
1206            log::debug!("No active subscriptions to unsubscribe from");
1207            return Ok(());
1208        }
1209
1210        log::debug!("Batched unsubscribe from {} channels", all_args.len());
1211
1212        for chunk in subscription_arg_batches(&all_args) {
1213            self.unsubscribe(chunk.to_vec()).await?;
1214        }
1215
1216        // The index-pair refcount mirrors live subscriptions; after a bulk
1217        // unsubscribe the venue knows nothing, so any retained count would
1218        // wedge the next `subscribe_index_prices`.
1219        self.index_pair_subscribers.clear();
1220
1221        Ok(())
1222    }
1223
1224    /// Subscribes to instrument updates for a specific instrument type.
1225    ///
1226    /// Provides updates when instrument specifications change.
1227    ///
1228    /// # Errors
1229    ///
1230    /// Returns an error if the subscription request fails.
1231    ///
1232    /// # References
1233    ///
1234    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-instruments-channel>.
1235    pub async fn subscribe_instruments(
1236        &self,
1237        instrument_type: OKXInstrumentType,
1238    ) -> Result<(), OKXWsError> {
1239        let arg = OKXSubscriptionArg {
1240            channel: OKXWsChannel::Instruments,
1241            inst_type: Some(instrument_type),
1242            inst_family: None,
1243            inst_id: None,
1244        };
1245        self.subscribe(vec![arg]).await
1246    }
1247
1248    /// Subscribes to instrument updates for a specific instrument.
1249    ///
1250    /// Since OKX doesn't support subscribing to individual instruments via `instId`,
1251    /// this method subscribes to the entire instrument type. OKX handles duplicate
1252    /// subscriptions gracefully and pushes a fresh snapshot on each subscribe.
1253    ///
1254    /// # Errors
1255    ///
1256    /// Returns an error if the subscription request fails.
1257    ///
1258    /// # References
1259    ///
1260    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-instruments-channel>.
1261    pub async fn subscribe_instrument(
1262        &self,
1263        instrument_id: InstrumentId,
1264    ) -> Result<(), OKXWsError> {
1265        let inst_type = okx_instrument_type_from_symbol(instrument_id.symbol.as_str());
1266        log::debug!("Subscribing to instrument type {inst_type:?} for {instrument_id}");
1267        self.subscribe_instruments(inst_type).await
1268    }
1269
1270    /// Subscribes to order book data for an instrument.
1271    ///
1272    /// This is a convenience method that calls [`Self::subscribe_book_with_depth`] with depth 0,
1273    /// which automatically selects the appropriate channel based on VIP level.
1274    ///
1275    /// # Errors
1276    ///
1277    /// Returns an error if the subscription request fails.
1278    pub async fn subscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1279        self.subscribe_book_with_depth(instrument_id, 0).await
1280    }
1281
1282    /// Subscribes to the Retail Price Improvement order book channel.
1283    ///
1284    /// # Errors
1285    ///
1286    /// Returns an error if the subscription request fails.
1287    pub async fn subscribe_book_rpi(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1288        self.subscribe_inst_id(OKXWsChannel::BooksRpi, instrument_id.symbol.inner())
1289            .await
1290    }
1291
1292    pub(crate) async fn subscribe_book_channel(
1293        &self,
1294        instrument_id: InstrumentId,
1295        channel: OKXBookChannel,
1296        cancel: CancellationToken,
1297        gate: SnapshotGate,
1298    ) -> Result<(), OKXWsError> {
1299        let (completion, receiver) = tokio::sync::oneshot::channel();
1300        let sender = self.cmd_tx.read().await;
1301
1302        if cancel.is_cancelled() {
1303            return Ok(());
1304        }
1305
1306        let subscription = OKXSubscriptionArg {
1307            channel: ws_channel_for_book(channel),
1308            inst_type: None,
1309            inst_family: None,
1310            inst_id: Some(instrument_id.symbol.inner()),
1311        };
1312
1313        self.record_subscriptions(std::slice::from_ref(&subscription));
1314        sender
1315            .send(HandlerCommand::SubscribeBook {
1316                subscription,
1317                cancel: cancel.clone(),
1318                gate,
1319                completion,
1320            })
1321            .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?;
1322
1323        drop(sender);
1324        tokio::select! {
1325            biased;
1326            () = cancel.cancelled() => Ok(()),
1327            result = receiver => result.map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?,
1328        }
1329    }
1330
1331    /// Requests a fresh snapshot by replacing the current incremental book subscription.
1332    pub(crate) async fn resubscribe_book_channel(
1333        &self,
1334        instrument_id: InstrumentId,
1335        channel: OKXBookChannel,
1336        cancel: CancellationToken,
1337        gate: SnapshotGate,
1338    ) -> Result<(), OKXWsError> {
1339        let (completion, receiver) = tokio::sync::oneshot::channel();
1340        let sender = self.cmd_tx.read().await;
1341
1342        if cancel.is_cancelled() {
1343            return Err(OKXWsError::ClientError("Book recovery canceled".into()));
1344        }
1345
1346        sender
1347            .send(HandlerCommand::Resubscribe {
1348                subscription: OKXSubscriptionArg {
1349                    channel: ws_channel_for_book(channel),
1350                    inst_type: None,
1351                    inst_family: None,
1352                    inst_id: Some(instrument_id.symbol.inner()),
1353                },
1354                cancel,
1355                gate,
1356                completion,
1357            })
1358            .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?;
1359
1360        drop(sender);
1361        receiver
1362            .await
1363            .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))?
1364    }
1365
1366    /// Subscribes to 5-level order book snapshot data for an instrument.
1367    ///
1368    /// Updates every 100ms when there are changes.
1369    ///
1370    /// # Errors
1371    ///
1372    /// Returns an error if the subscription request fails.
1373    ///
1374    /// # References
1375    ///
1376    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-5-depth-channel>.
1377    pub async fn subscribe_book_depth5(
1378        &self,
1379        instrument_id: InstrumentId,
1380    ) -> Result<(), OKXWsError> {
1381        self.subscribe_inst_id(OKXWsChannel::Books5, instrument_id.symbol.inner())
1382            .await
1383    }
1384
1385    /// Subscribes to 50-level tick-by-tick order book data for an instrument.
1386    ///
1387    /// Provides real-time updates whenever order book changes.
1388    ///
1389    /// # Errors
1390    ///
1391    /// Returns an error if the subscription request fails.
1392    ///
1393    /// # References
1394    ///
1395    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-50-depth-tbt-channel>.
1396    pub async fn subscribe_book50_l2_tbt(
1397        &self,
1398        instrument_id: InstrumentId,
1399    ) -> Result<(), OKXWsError> {
1400        self.subscribe_inst_id(OKXWsChannel::Books50Tbt, instrument_id.symbol.inner())
1401            .await
1402    }
1403
1404    /// Subscribes to tick-by-tick full depth (400 levels) order book data for an instrument.
1405    ///
1406    /// Provides real-time updates with all depth levels whenever order book changes.
1407    ///
1408    /// # Errors
1409    ///
1410    /// Returns an error if the subscription request fails.
1411    ///
1412    /// # References
1413    ///
1414    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-400-depth-tbt-channel>.
1415    pub async fn subscribe_book_l2_tbt(
1416        &self,
1417        instrument_id: InstrumentId,
1418    ) -> Result<(), OKXWsError> {
1419        self.subscribe_inst_id(OKXWsChannel::BooksTbt, instrument_id.symbol.inner())
1420            .await
1421    }
1422
1423    /// Subscribes to order book data with automatic channel selection based on VIP level and depth.
1424    ///
1425    /// Selects the optimal channel based on user's VIP tier and requested depth:
1426    /// - depth 50: Requires VIP4+, subscribes to `books50-l2-tbt`
1427    /// - depth 0 or 400:
1428    ///   - VIP4+: subscribes to `books-l2-tbt` (400 depth, fastest)
1429    ///   - Below VIP4: subscribes to `books` (standard depth)
1430    ///
1431    /// # Errors
1432    ///
1433    /// Returns an error if:
1434    /// - Subscription request fails.
1435    /// - Depth is 50 but VIP level is below 4.
1436    pub async fn subscribe_book_with_depth(
1437        &self,
1438        instrument_id: InstrumentId,
1439        depth: u16,
1440    ) -> anyhow::Result<()> {
1441        let vip = self.vip_level();
1442
1443        if !matches!(depth, 0 | 50 | 400) {
1444            anyhow::bail!("Invalid depth {depth}, must be 0, 50, or 400");
1445        }
1446
1447        if depth == 50 && vip < OKXVipLevel::Vip4 {
1448            anyhow::bail!("VIP level {vip} insufficient for 50 depth subscription (requires VIP4)");
1449        }
1450
1451        let channel = select_book_channel(depth as usize, vip);
1452        self.subscribe_inst_id(ws_channel_for_book(channel), instrument_id.symbol.inner())
1453            .await?;
1454        Ok(())
1455    }
1456
1457    /// Subscribes to best bid/ask quote data for an instrument.
1458    ///
1459    /// Provides tick-by-tick updates of the best bid and ask prices using the bbo-tbt channel.
1460    /// Supports all instrument types: SPOT, MARGIN, SWAP, FUTURES, OPTION.
1461    ///
1462    /// # Errors
1463    ///
1464    /// Returns an error if the subscription request fails.
1465    ///
1466    /// # References
1467    ///
1468    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-best-bid-offer-channel>.
1469    pub async fn subscribe_quotes(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1470        self.subscribe_inst_id(OKXWsChannel::BboTbt, instrument_id.symbol.inner())
1471            .await
1472    }
1473
1474    /// Subscribes to trade data for an instrument.
1475    ///
1476    /// When `aggregated` is `false`, subscribes to the `trades` channel, where one update can
1477    /// aggregate several trades. When `aggregated` is `true`, subscribes to the `trades-all`
1478    /// channel, where each update carries one trade.
1479    ///
1480    /// # Errors
1481    ///
1482    /// Returns an error if the subscription request fails.
1483    ///
1484    /// # References
1485    ///
1486    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-trades-channel>.
1487    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-all-trades-channel>.
1488    pub async fn subscribe_trades(
1489        &self,
1490        instrument_id: InstrumentId,
1491        aggregated: bool,
1492    ) -> Result<(), OKXWsError> {
1493        let channel = if aggregated {
1494            OKXWsChannel::TradesAll
1495        } else {
1496            OKXWsChannel::Trades
1497        };
1498        self.subscribe_inst_id(channel, instrument_id.symbol.inner())
1499            .await
1500    }
1501
1502    /// Subscribes to 24hr rolling ticker data for an instrument.
1503    ///
1504    /// Updates every 100ms with trading statistics.
1505    ///
1506    /// # Errors
1507    ///
1508    /// Returns an error if the subscription request fails.
1509    ///
1510    /// # References
1511    ///
1512    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel>.
1513    pub async fn subscribe_ticker(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1514        self.subscribe_inst_id(OKXWsChannel::Tickers, instrument_id.symbol.inner())
1515            .await
1516    }
1517
1518    /// Subscribes to mark price data for derivatives instruments.
1519    ///
1520    /// Updates every 200ms for perpetual swaps, or at settlement for futures.
1521    ///
1522    /// # Errors
1523    ///
1524    /// Returns an error if the subscription request fails.
1525    ///
1526    /// # References
1527    ///
1528    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-mark-price-channel>.
1529    pub async fn subscribe_mark_prices(
1530        &self,
1531        instrument_id: InstrumentId,
1532    ) -> Result<(), OKXWsError> {
1533        self.subscribe_inst_id(OKXWsChannel::MarkPrice, instrument_id.symbol.inner())
1534            .await
1535    }
1536
1537    /// Subscribes to index price data for an instrument.
1538    ///
1539    /// Updates every second with the underlying index price.
1540    ///
1541    /// # Errors
1542    ///
1543    /// Returns an error if the subscription request fails.
1544    ///
1545    /// # References
1546    ///
1547    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-index-tickers-channel>.
1548    pub async fn subscribe_index_prices(
1549        &self,
1550        instrument_id: InstrumentId,
1551    ) -> Result<(), OKXWsError> {
1552        // Index-tickers channel requires base pair format (e.g., BTC-USDT)
1553        let symbol = instrument_id.symbol.inner();
1554        let (base, quote) = parse_base_quote_from_symbol(symbol.as_str())
1555            .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1556        let base_pair = Ustr::from(&format!("{base}-{quote}"));
1557
1558        // Hold the transition lock across both the refcount update and the
1559        // venue send so a concurrent `unsubscribe_index_prices` cannot
1560        // observe a transient 0 state between our decrement and the venue
1561        // unsubscribe, or vice versa. Without this, contract rolls can
1562        // leave the venue unsubscribed while the local count says active.
1563        let _guard = self.index_pair_transition.lock().await;
1564
1565        // Bump the per-base-pair refcount so a later unsubscribe can decide
1566        // whether it is the last subscriber. Only the 0→1 transition fires
1567        // a venue subscribe; subsequent callers piggy-back on the existing
1568        // channel.
1569        let is_first = {
1570            let mut count = self.index_pair_subscribers.entry(base_pair).or_insert(0);
1571            *count += 1;
1572            *count == 1
1573        };
1574
1575        if !is_first {
1576            return Ok(());
1577        }
1578
1579        let arg = OKXSubscriptionArg {
1580            channel: OKXWsChannel::IndexTickers,
1581            inst_type: None,
1582            inst_family: None,
1583            inst_id: Some(base_pair),
1584        };
1585
1586        match self.subscribe(vec![arg]).await {
1587            Ok(()) => Ok(()),
1588            Err(e) => {
1589                // When the venue subscribe fails there is no live channel,
1590                // even though other local callers may have piggy-backed on
1591                // the in-flight attempt (they saw `!is_first` and returned
1592                // `Ok`). Removing the entry entirely ensures the next
1593                // caller re-enters the 0→1 branch and re-arms the venue
1594                // subscription; a mere decrement would leave the map at 1+
1595                // without a matching feed and every later subscribe would
1596                // short-circuit into a silent no-op.
1597                self.index_pair_subscribers.remove(&base_pair);
1598                Err(e)
1599            }
1600        }
1601    }
1602
1603    /// Subscribes to option summary data for an instrument family.
1604    ///
1605    /// Streams greeks (delta, gamma, vega, theta), implied volatility, and other
1606    /// option metrics for all instruments in the specified family.
1607    ///
1608    /// # Errors
1609    ///
1610    /// Returns an error if the subscription request fails.
1611    ///
1612    /// # References
1613    ///
1614    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-option-summary-channel>.
1615    pub async fn subscribe_option_summary(&self, inst_family: Ustr) -> Result<(), OKXWsError> {
1616        let arg = OKXSubscriptionArg {
1617            channel: OKXWsChannel::OptionSummary,
1618            inst_type: None,
1619            inst_family: Some(inst_family),
1620            inst_id: None,
1621        };
1622        self.subscribe(vec![arg]).await
1623    }
1624
1625    /// Subscribes to event contract market updates.
1626    ///
1627    /// # Errors
1628    ///
1629    /// Returns an error if the subscription request fails.
1630    ///
1631    /// # References
1632    ///
1633    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-event-contract-markets-channel>.
1634    pub async fn subscribe_event_contract_markets(&self) -> Result<(), OKXWsError> {
1635        let arg = OKXSubscriptionArg {
1636            channel: OKXWsChannel::EventContractMarkets,
1637            inst_type: Some(OKXInstrumentType::Events),
1638            inst_family: None,
1639            inst_id: None,
1640        };
1641        self.subscribe(vec![arg]).await
1642    }
1643
1644    /// Returns a reference to the option greeks subscription map.
1645    ///
1646    /// The map stores the set of greeks conventions to emit for each subscribed instrument.
1647    pub fn option_greeks_subs(&self) -> &Arc<AtomicMap<InstrumentId, AHashSet<OKXGreeksType>>> {
1648        &self.option_greeks_subs
1649    }
1650
1651    /// Adds an instrument to the option greeks subscription filter, emitting both
1652    /// Black-Scholes and price-adjusted greeks.
1653    pub fn add_option_greeks_sub(&self, instrument_id: InstrumentId) {
1654        let both: AHashSet<OKXGreeksType> =
1655            [OKXGreeksType::Bs, OKXGreeksType::Pa].into_iter().collect();
1656        self.option_greeks_subs.insert(instrument_id, both);
1657    }
1658
1659    /// Adds an instrument to the option greeks subscription filter with an explicit
1660    /// set of greeks conventions to emit. An empty set is treated as "emit both".
1661    pub fn add_option_greeks_sub_with_conventions(
1662        &self,
1663        instrument_id: InstrumentId,
1664        conventions: AHashSet<OKXGreeksType>,
1665    ) {
1666        let set = if conventions.is_empty() {
1667            [OKXGreeksType::Bs, OKXGreeksType::Pa].into_iter().collect()
1668        } else {
1669            conventions
1670        };
1671        self.option_greeks_subs.insert(instrument_id, set);
1672    }
1673
1674    /// Removes an instrument from the option greeks subscription filter.
1675    pub fn remove_option_greeks_sub(&self, instrument_id: &InstrumentId) {
1676        self.option_greeks_subs.remove(instrument_id);
1677    }
1678
1679    /// Subscribes to funding rate data for perpetual swap instruments.
1680    ///
1681    /// Updates when funding rate changes or at funding intervals.
1682    ///
1683    /// # Errors
1684    ///
1685    /// Returns an error if the subscription request fails.
1686    ///
1687    /// # References
1688    ///
1689    /// <https://www.okx.com/docs-v5/en/#public-data-websocket-funding-rate-channel>.
1690    pub async fn subscribe_funding_rates(
1691        &self,
1692        instrument_id: InstrumentId,
1693    ) -> Result<(), OKXWsError> {
1694        self.subscribe_inst_id(OKXWsChannel::FundingRate, instrument_id.symbol.inner())
1695            .await
1696    }
1697
1698    /// Subscribes to candlestick/bar data for an instrument.
1699    ///
1700    /// Supports various time intervals from 1s to 3M.
1701    ///
1702    /// # Errors
1703    ///
1704    /// Returns an error if the subscription request fails.
1705    ///
1706    /// # References
1707    ///
1708    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-candlesticks-channel>.
1709    pub async fn subscribe_bars(&self, bar_type: BarType) -> Result<(), OKXWsError> {
1710        // Use regular trade-price candlesticks which work for all instrument types
1711        let channel = bar_spec_as_okx_channel(bar_type.spec())
1712            .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1713        self.subscribe_inst_id(channel, bar_type.instrument_id().symbol.inner())
1714            .await
1715    }
1716
1717    /// Unsubscribes from instrument updates for a specific instrument type.
1718    ///
1719    /// # Errors
1720    ///
1721    /// Returns an error if the subscription request fails.
1722    pub async fn unsubscribe_instruments(
1723        &self,
1724        instrument_type: OKXInstrumentType,
1725    ) -> Result<(), OKXWsError> {
1726        let arg = OKXSubscriptionArg {
1727            channel: OKXWsChannel::Instruments,
1728            inst_type: Some(instrument_type),
1729            inst_family: None,
1730            inst_id: None,
1731        };
1732        self.unsubscribe(vec![arg]).await
1733    }
1734
1735    /// Unsubscribe from instrument updates for a specific instrument.
1736    ///
1737    /// No-op: the instruments channel is per-type (SWAP, FUTURES, etc.) and
1738    /// other instruments of the same type may still need it. The channel
1739    /// stays subscribed; overhead is negligible.
1740    ///
1741    /// # Errors
1742    ///
1743    /// Returns an error if the unsubscription request fails.
1744    #[allow(
1745        clippy::unused_async,
1746        clippy::unused_async_trait_impl,
1747        reason = "async signature is kept for parity with the other unsubscribe methods and callers"
1748    )]
1749    pub async fn unsubscribe_instrument(
1750        &self,
1751        instrument_id: InstrumentId,
1752    ) -> Result<(), OKXWsError> {
1753        log::debug!("Instrument unsubscribe is a no-op (shared per-type channel): {instrument_id}");
1754        Ok(())
1755    }
1756
1757    /// Unsubscribe from full order book data for an instrument.
1758    ///
1759    /// # Errors
1760    ///
1761    /// Returns an error if the subscription request fails.
1762    pub async fn unsubscribe_book(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1763        self.unsubscribe_inst_id(OKXWsChannel::Books, instrument_id.symbol.inner())
1764            .await
1765    }
1766
1767    /// Unsubscribe from Retail Price Improvement order book data for an instrument.
1768    ///
1769    /// # Errors
1770    ///
1771    /// Returns an error if the unsubscription request fails.
1772    pub async fn unsubscribe_book_rpi(
1773        &self,
1774        instrument_id: InstrumentId,
1775    ) -> Result<(), OKXWsError> {
1776        self.unsubscribe_inst_id(OKXWsChannel::BooksRpi, instrument_id.symbol.inner())
1777            .await
1778    }
1779
1780    /// Unsubscribe from 5-level order book snapshot data for an instrument.
1781    ///
1782    /// # Errors
1783    ///
1784    /// Returns an error if the subscription request fails.
1785    pub async fn unsubscribe_book_depth5(
1786        &self,
1787        instrument_id: InstrumentId,
1788    ) -> Result<(), OKXWsError> {
1789        self.unsubscribe_inst_id(OKXWsChannel::Books5, instrument_id.symbol.inner())
1790            .await
1791    }
1792
1793    /// Unsubscribe from 50-level tick-by-tick order book data for an instrument.
1794    ///
1795    /// # Errors
1796    ///
1797    /// Returns an error if the subscription request fails.
1798    pub async fn unsubscribe_book50_l2_tbt(
1799        &self,
1800        instrument_id: InstrumentId,
1801    ) -> Result<(), OKXWsError> {
1802        self.unsubscribe_inst_id(OKXWsChannel::Books50Tbt, instrument_id.symbol.inner())
1803            .await
1804    }
1805
1806    /// Unsubscribe from tick-by-tick full depth order book data for an instrument.
1807    ///
1808    /// # Errors
1809    ///
1810    /// Returns an error if the subscription request fails.
1811    pub async fn unsubscribe_book_l2_tbt(
1812        &self,
1813        instrument_id: InstrumentId,
1814    ) -> Result<(), OKXWsError> {
1815        self.unsubscribe_inst_id(OKXWsChannel::BooksTbt, instrument_id.symbol.inner())
1816            .await
1817    }
1818
1819    /// Unsubscribe from best bid/ask quote data for an instrument.
1820    ///
1821    /// # Errors
1822    ///
1823    /// Returns an error if the subscription request fails.
1824    pub async fn unsubscribe_quotes(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1825        self.unsubscribe_inst_id(OKXWsChannel::BboTbt, instrument_id.symbol.inner())
1826            .await
1827    }
1828
1829    /// Unsubscribe from 24hr rolling ticker data for an instrument.
1830    ///
1831    /// # Errors
1832    ///
1833    /// Returns an error if the subscription request fails.
1834    pub async fn unsubscribe_ticker(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
1835        self.unsubscribe_inst_id(OKXWsChannel::Tickers, instrument_id.symbol.inner())
1836            .await
1837    }
1838
1839    /// Unsubscribe from mark price data for a derivatives instrument.
1840    ///
1841    /// # Errors
1842    ///
1843    /// Returns an error if the subscription request fails.
1844    pub async fn unsubscribe_mark_prices(
1845        &self,
1846        instrument_id: InstrumentId,
1847    ) -> Result<(), OKXWsError> {
1848        self.unsubscribe_inst_id(OKXWsChannel::MarkPrice, instrument_id.symbol.inner())
1849            .await
1850    }
1851
1852    /// Unsubscribe from index price data for the base pair derived from
1853    /// `instrument_id`.
1854    ///
1855    /// Refcounting is handled internally so any caller (Rust data client,
1856    /// Python wrapper, etc.) can pair every `subscribe_index_prices` with
1857    /// exactly one `unsubscribe_index_prices`. The OKX `index-tickers`
1858    /// channel is keyed by base pair (e.g. `BTC-USDT`), so the venue
1859    /// unsubscribe only fires when the last subscriber for that pair drops.
1860    ///
1861    /// # Errors
1862    ///
1863    /// Returns an error if the unsubscription request fails.
1864    pub async fn unsubscribe_index_prices(
1865        &self,
1866        instrument_id: InstrumentId,
1867    ) -> Result<(), OKXWsError> {
1868        let symbol = instrument_id.symbol.inner();
1869        let (base, quote) = parse_base_quote_from_symbol(symbol.as_str())
1870            .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1871        let base_pair = Ustr::from(&format!("{base}-{quote}"));
1872
1873        // Serialize with any concurrent `subscribe_index_prices` on the same
1874        // base pair. See the subscribe path for the race this prevents.
1875        let _guard = self.index_pair_transition.lock().await;
1876
1877        let is_last = {
1878            let Some(mut count) = self.index_pair_subscribers.get_mut(&base_pair) else {
1879                // No matching subscriber recorded; nothing to do.
1880                return Ok(());
1881            };
1882            *count = count.saturating_sub(1);
1883            *count == 0
1884        };
1885
1886        if !is_last {
1887            return Ok(());
1888        }
1889
1890        self.index_pair_subscribers
1891            .remove_if(&base_pair, |_, count| *count == 0);
1892
1893        let arg = OKXSubscriptionArg {
1894            channel: OKXWsChannel::IndexTickers,
1895            inst_type: None,
1896            inst_family: None,
1897            inst_id: Some(base_pair),
1898        };
1899        self.unsubscribe(vec![arg]).await
1900    }
1901
1902    /// Unsubscribe from option summary data for an instrument family.
1903    ///
1904    /// # Errors
1905    ///
1906    /// Returns an error if the unsubscription request fails.
1907    pub async fn unsubscribe_option_summary(&self, inst_family: Ustr) -> Result<(), OKXWsError> {
1908        let arg = OKXSubscriptionArg {
1909            channel: OKXWsChannel::OptionSummary,
1910            inst_type: None,
1911            inst_family: Some(inst_family),
1912            inst_id: None,
1913        };
1914        self.unsubscribe(vec![arg]).await
1915    }
1916
1917    /// Unsubscribes from event contract market updates.
1918    ///
1919    /// # Errors
1920    ///
1921    /// Returns an error if the unsubscription request fails.
1922    pub async fn unsubscribe_event_contract_markets(&self) -> Result<(), OKXWsError> {
1923        let arg = OKXSubscriptionArg {
1924            channel: OKXWsChannel::EventContractMarkets,
1925            inst_type: Some(OKXInstrumentType::Events),
1926            inst_family: None,
1927            inst_id: None,
1928        };
1929        self.unsubscribe(vec![arg]).await
1930    }
1931
1932    /// Unsubscribe from funding rate data for a perpetual swap instrument.
1933    ///
1934    /// # Errors
1935    ///
1936    /// Returns an error if the subscription request fails.
1937    pub async fn unsubscribe_funding_rates(
1938        &self,
1939        instrument_id: InstrumentId,
1940    ) -> Result<(), OKXWsError> {
1941        self.unsubscribe_inst_id(OKXWsChannel::FundingRate, instrument_id.symbol.inner())
1942            .await
1943    }
1944
1945    /// Unsubscribe from trade data for an instrument.
1946    ///
1947    /// # Errors
1948    ///
1949    /// Returns an error if the subscription request fails.
1950    pub async fn unsubscribe_trades(
1951        &self,
1952        instrument_id: InstrumentId,
1953        aggregated: bool,
1954    ) -> Result<(), OKXWsError> {
1955        let channel = if aggregated {
1956            OKXWsChannel::TradesAll
1957        } else {
1958            OKXWsChannel::Trades
1959        };
1960        self.unsubscribe_inst_id(channel, instrument_id.symbol.inner())
1961            .await
1962    }
1963
1964    /// Unsubscribe from candlestick/bar data for an instrument.
1965    ///
1966    /// # Errors
1967    ///
1968    /// Returns an error if the subscription request fails.
1969    pub async fn unsubscribe_bars(&self, bar_type: BarType) -> Result<(), OKXWsError> {
1970        let channel = bar_spec_as_okx_channel(bar_type.spec())
1971            .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
1972        self.unsubscribe_inst_id(channel, bar_type.instrument_id().symbol.inner())
1973            .await
1974    }
1975
1976    /// Subscribes to order updates for the given instrument type.
1977    ///
1978    /// # Errors
1979    ///
1980    /// Returns an error if the subscription request fails.
1981    pub async fn subscribe_orders(
1982        &self,
1983        instrument_type: OKXInstrumentType,
1984    ) -> Result<(), OKXWsError> {
1985        let arg = OKXSubscriptionArg {
1986            channel: OKXWsChannel::Orders,
1987            inst_type: Some(instrument_type),
1988            inst_family: None,
1989            inst_id: None,
1990        };
1991        self.subscribe(vec![arg]).await
1992    }
1993
1994    /// Unsubscribes from order updates for the given instrument type.
1995    ///
1996    /// # Errors
1997    ///
1998    /// Returns an error if the subscription request fails.
1999    pub async fn unsubscribe_orders(
2000        &self,
2001        instrument_type: OKXInstrumentType,
2002    ) -> Result<(), OKXWsError> {
2003        let arg = OKXSubscriptionArg {
2004            channel: OKXWsChannel::Orders,
2005            inst_type: Some(instrument_type),
2006            inst_family: None,
2007            inst_id: None,
2008        };
2009        self.unsubscribe(vec![arg]).await
2010    }
2011
2012    /// Subscribes to Nitro spread order updates.
2013    ///
2014    /// # Errors
2015    ///
2016    /// Returns an error if the subscription request fails.
2017    pub async fn subscribe_spread_orders(&self) -> Result<(), OKXWsError> {
2018        let arg = OKXSubscriptionArg {
2019            channel: OKXWsChannel::SprdOrders,
2020            inst_type: None,
2021            inst_family: None,
2022            inst_id: None,
2023        };
2024        self.subscribe(vec![arg]).await
2025    }
2026
2027    /// Unsubscribes from Nitro spread order updates.
2028    ///
2029    /// # Errors
2030    ///
2031    /// Returns an error if the subscription request fails.
2032    pub async fn unsubscribe_spread_orders(&self) -> Result<(), OKXWsError> {
2033        let arg = OKXSubscriptionArg {
2034            channel: OKXWsChannel::SprdOrders,
2035            inst_type: None,
2036            inst_family: None,
2037            inst_id: None,
2038        };
2039        self.unsubscribe(vec![arg]).await
2040    }
2041
2042    /// Subscribes to best bid/offer quotes for a spread instrument (`sprd-bbo-tbt`).
2043    ///
2044    /// # Errors
2045    ///
2046    /// Returns an error if the subscription request fails.
2047    pub async fn subscribe_spread_quotes(
2048        &self,
2049        instrument_id: InstrumentId,
2050    ) -> Result<(), OKXWsError> {
2051        self.subscribe_inst_id(OKXWsChannel::SprdBboTbt, instrument_id.symbol.inner())
2052            .await
2053    }
2054
2055    /// Subscribes to 5-level book snapshots for a spread instrument (`sprd-books5`).
2056    ///
2057    /// # Errors
2058    ///
2059    /// Returns an error if the subscription request fails.
2060    pub async fn subscribe_spread_book(
2061        &self,
2062        instrument_id: InstrumentId,
2063    ) -> Result<(), OKXWsError> {
2064        self.subscribe_inst_id(OKXWsChannel::SprdBooks5, instrument_id.symbol.inner())
2065            .await
2066    }
2067
2068    /// Subscribes to public trades for a spread instrument (`sprd-public-trades`).
2069    ///
2070    /// # Errors
2071    ///
2072    /// Returns an error if the subscription request fails.
2073    pub async fn subscribe_spread_trades(
2074        &self,
2075        instrument_id: InstrumentId,
2076    ) -> Result<(), OKXWsError> {
2077        self.subscribe_inst_id(OKXWsChannel::SprdPublicTrades, instrument_id.symbol.inner())
2078            .await
2079    }
2080
2081    /// Unsubscribes from spread quotes (`sprd-bbo-tbt`).
2082    ///
2083    /// # Errors
2084    ///
2085    /// Returns an error if the unsubscribe request fails.
2086    pub async fn unsubscribe_spread_quotes(
2087        &self,
2088        instrument_id: InstrumentId,
2089    ) -> Result<(), OKXWsError> {
2090        self.unsubscribe_inst_id(OKXWsChannel::SprdBboTbt, instrument_id.symbol.inner())
2091            .await
2092    }
2093
2094    /// Unsubscribes from spread book snapshots (`sprd-books5`).
2095    ///
2096    /// # Errors
2097    ///
2098    /// Returns an error if the unsubscribe request fails.
2099    pub async fn unsubscribe_spread_book(
2100        &self,
2101        instrument_id: InstrumentId,
2102    ) -> Result<(), OKXWsError> {
2103        self.unsubscribe_inst_id(OKXWsChannel::SprdBooks5, instrument_id.symbol.inner())
2104            .await
2105    }
2106
2107    /// Unsubscribes from spread public trades (`sprd-public-trades`).
2108    ///
2109    /// # Errors
2110    ///
2111    /// Returns an error if the unsubscribe request fails.
2112    pub async fn unsubscribe_spread_trades(
2113        &self,
2114        instrument_id: InstrumentId,
2115    ) -> Result<(), OKXWsError> {
2116        self.unsubscribe_inst_id(OKXWsChannel::SprdPublicTrades, instrument_id.symbol.inner())
2117            .await
2118    }
2119
2120    /// Subscribes to algo order updates for the given instrument type.
2121    ///
2122    /// # Errors
2123    ///
2124    /// Returns an error if the subscription request fails.
2125    pub async fn subscribe_orders_algo(
2126        &self,
2127        instrument_type: OKXInstrumentType,
2128    ) -> Result<(), OKXWsError> {
2129        let arg = OKXSubscriptionArg {
2130            channel: OKXWsChannel::OrdersAlgo,
2131            inst_type: Some(instrument_type),
2132            inst_family: None,
2133            inst_id: None,
2134        };
2135        self.subscribe(vec![arg]).await
2136    }
2137
2138    /// Unsubscribes from algo order updates for the given instrument type.
2139    ///
2140    /// # Errors
2141    ///
2142    /// Returns an error if the subscription request fails.
2143    pub async fn unsubscribe_orders_algo(
2144        &self,
2145        instrument_type: OKXInstrumentType,
2146    ) -> Result<(), OKXWsError> {
2147        let arg = OKXSubscriptionArg {
2148            channel: OKXWsChannel::OrdersAlgo,
2149            inst_type: Some(instrument_type),
2150            inst_family: None,
2151            inst_id: None,
2152        };
2153        self.unsubscribe(vec![arg]).await
2154    }
2155
2156    /// Subscribes to advance algo order updates (trailing stops, iceberg, twap).
2157    ///
2158    /// # Errors
2159    ///
2160    /// Returns an error if the subscription request fails.
2161    pub async fn subscribe_algo_advance(
2162        &self,
2163        instrument_type: OKXInstrumentType,
2164    ) -> Result<(), OKXWsError> {
2165        let arg = OKXSubscriptionArg {
2166            channel: OKXWsChannel::AlgoAdvance,
2167            inst_type: Some(instrument_type),
2168            inst_family: None,
2169            inst_id: None,
2170        };
2171        self.subscribe(vec![arg]).await
2172    }
2173
2174    /// Unsubscribes from advance algo order updates.
2175    ///
2176    /// # Errors
2177    ///
2178    /// Returns an error if the subscription request fails.
2179    pub async fn unsubscribe_algo_advance(
2180        &self,
2181        instrument_type: OKXInstrumentType,
2182    ) -> Result<(), OKXWsError> {
2183        let arg = OKXSubscriptionArg {
2184            channel: OKXWsChannel::AlgoAdvance,
2185            inst_type: Some(instrument_type),
2186            inst_family: None,
2187            inst_id: None,
2188        };
2189        self.unsubscribe(vec![arg]).await
2190    }
2191
2192    /// Subscribes to account balance updates.
2193    ///
2194    /// # Errors
2195    ///
2196    /// Returns an error if the subscription request fails.
2197    pub async fn subscribe_account(&self) -> Result<(), OKXWsError> {
2198        let arg = OKXSubscriptionArg {
2199            channel: OKXWsChannel::Account,
2200            inst_type: None,
2201            inst_family: None,
2202            inst_id: None,
2203        };
2204        self.subscribe(vec![arg]).await
2205    }
2206
2207    /// Unsubscribes from account balance updates.
2208    ///
2209    /// # Errors
2210    ///
2211    /// Returns an error if the subscription request fails.
2212    pub async fn unsubscribe_account(&self) -> Result<(), OKXWsError> {
2213        let arg = OKXSubscriptionArg {
2214            channel: OKXWsChannel::Account,
2215            inst_type: None,
2216            inst_family: None,
2217            inst_id: None,
2218        };
2219        self.unsubscribe(vec![arg]).await
2220    }
2221
2222    /// Subscribes to position updates for a specific instrument type.
2223    ///
2224    /// # Errors
2225    ///
2226    /// Returns an error if the subscription request fails.
2227    ///
2228    /// # References
2229    ///
2230    /// <https://www.okx.com/docs-v5/en/#websocket-api-private-channel-positions-channel>
2231    pub async fn subscribe_positions(
2232        &self,
2233        inst_type: OKXInstrumentType,
2234    ) -> Result<(), OKXWsError> {
2235        let arg = OKXSubscriptionArg {
2236            channel: OKXWsChannel::Positions,
2237            inst_type: Some(inst_type),
2238            inst_family: None,
2239            inst_id: None,
2240        };
2241        self.subscribe(vec![arg]).await
2242    }
2243
2244    /// Unsubscribes from position updates for a specific instrument type.
2245    ///
2246    /// # Errors
2247    ///
2248    /// Returns an error if the subscription request fails.
2249    pub async fn unsubscribe_positions(
2250        &self,
2251        inst_type: OKXInstrumentType,
2252    ) -> Result<(), OKXWsError> {
2253        let arg = OKXSubscriptionArg {
2254            channel: OKXWsChannel::Positions,
2255            inst_type: Some(inst_type),
2256            inst_family: None,
2257            inst_id: None,
2258        };
2259        self.unsubscribe(vec![arg]).await
2260    }
2261
2262    /// Subscribes to liquidation risk warnings for the given instrument type.
2263    ///
2264    /// # Errors
2265    ///
2266    /// Returns an error if the subscription request fails.
2267    ///
2268    /// # References
2269    ///
2270    /// <https://www.okx.com/docs-v5/en/#trading-account-websocket-liquidation-warning-channel>
2271    pub async fn subscribe_liquidation_warning(
2272        &self,
2273        instrument_type: OKXInstrumentType,
2274    ) -> Result<(), OKXWsError> {
2275        let arg = OKXSubscriptionArg {
2276            channel: OKXWsChannel::LiquidationWarning,
2277            inst_type: Some(instrument_type),
2278            inst_family: None,
2279            inst_id: None,
2280        };
2281        self.subscribe(vec![arg]).await
2282    }
2283
2284    /// Unsubscribes from liquidation risk warnings for the given instrument type.
2285    ///
2286    /// # Errors
2287    ///
2288    /// Returns an error if the unsubscription request fails.
2289    pub async fn unsubscribe_liquidation_warning(
2290        &self,
2291        instrument_type: OKXInstrumentType,
2292    ) -> Result<(), OKXWsError> {
2293        let arg = OKXSubscriptionArg {
2294            channel: OKXWsChannel::LiquidationWarning,
2295            inst_type: Some(instrument_type),
2296            inst_family: None,
2297            inst_id: None,
2298        };
2299        self.unsubscribe(vec![arg]).await
2300    }
2301
2302    /// Place multiple orders in a single batch via WebSocket.
2303    ///
2304    /// # References
2305    ///
2306    /// <https://www.okx.com/docs-v5/en/#order-book-trading-websocket-batch-orders>
2307    async fn ws_batch_place_orders(
2308        &self,
2309        args: Vec<Value>,
2310        client_order_ids: Vec<ClientOrderId>,
2311    ) -> Result<(), OKXWsError> {
2312        let request_id = self.generate_unique_request_id();
2313        let request = OKXWsRequest::<Value> {
2314            id: Some(request_id.clone()),
2315            op: super::enums::OKXWsOperation::BatchOrders,
2316            exp_time: self.order_request_exp_time(),
2317            args,
2318        };
2319
2320        let payload = serde_json::to_string(&request)
2321            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize batch orders: {e}")))?;
2322
2323        let cmd = HandlerCommand::Send {
2324            payload,
2325            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_BATCH_ORDER.to_vec()),
2326            request_id: Some(request_id),
2327            client_order_ids,
2328            op: Some(super::enums::OKXWsOperation::BatchOrders),
2329        };
2330
2331        self.send_cmd(cmd).await
2332    }
2333
2334    /// Cancel multiple orders in a single batch via WebSocket.
2335    ///
2336    /// # References
2337    ///
2338    /// <https://www.okx.com/docs-v5/en/#order-book-trading-websocket-batch-cancel-orders>
2339    async fn ws_batch_cancel_orders(
2340        &self,
2341        args: Vec<Value>,
2342        client_order_ids: Vec<ClientOrderId>,
2343        causation_ids: Vec<(ClientOrderId, UUID4)>,
2344    ) -> Result<(), OKXWsError> {
2345        let request_id = self.generate_unique_request_id();
2346        let request = OKXWsRequest::<Value> {
2347            id: Some(request_id.clone()),
2348            op: super::enums::OKXWsOperation::BatchCancelOrders,
2349            exp_time: None,
2350            args,
2351        };
2352
2353        let payload = serde_json::to_string(&request)
2354            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize batch cancel: {e}")))?;
2355
2356        if !causation_ids.is_empty() {
2357            self.pending_command_ids
2358                .insert(request_id.clone(), causation_ids);
2359        }
2360
2361        let cmd = HandlerCommand::Send {
2362            payload,
2363            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_BATCH_CANCEL.to_vec()),
2364            request_id: Some(request_id.clone()),
2365            client_order_ids,
2366            op: Some(super::enums::OKXWsOperation::BatchCancelOrders),
2367        };
2368
2369        let result = self.send_cmd(cmd).await;
2370        if result.is_err() {
2371            self.pending_command_ids.remove(&request_id);
2372        }
2373
2374        result
2375    }
2376
2377    /// Amend multiple orders in a single batch via WebSocket.
2378    ///
2379    /// # References
2380    ///
2381    /// <https://www.okx.com/docs-v5/en/#order-book-trading-websocket-batch-amend-orders>
2382    async fn ws_batch_amend_orders(
2383        &self,
2384        args: Vec<Value>,
2385        client_order_ids: Vec<ClientOrderId>,
2386    ) -> Result<(), OKXWsError> {
2387        let request_id = self.generate_unique_request_id();
2388        let request = OKXWsRequest::<Value> {
2389            id: Some(request_id.clone()),
2390            op: super::enums::OKXWsOperation::BatchAmendOrders,
2391            exp_time: self.order_request_exp_time(),
2392            args,
2393        };
2394
2395        let payload = serde_json::to_string(&request)
2396            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize batch amend: {e}")))?;
2397
2398        let cmd = HandlerCommand::Send {
2399            payload,
2400            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_BATCH_AMEND.to_vec()),
2401            request_id: Some(request_id),
2402            client_order_ids,
2403            op: Some(super::enums::OKXWsOperation::BatchAmendOrders),
2404        };
2405
2406        self.send_cmd(cmd).await
2407    }
2408
2409    /// Submits an order, automatically routing conditional orders to the algo endpoint.
2410    ///
2411    /// # Errors
2412    ///
2413    /// Returns an error if the order parameters are invalid or if the request
2414    /// cannot be sent to the websocket client.
2415    ///
2416    /// # References
2417    ///
2418    /// - Regular orders: <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-place-order>
2419    /// - Algo orders: <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order>
2420    #[expect(clippy::too_many_arguments)]
2421    pub async fn submit_order(
2422        &self,
2423        trader_id: TraderId,
2424        strategy_id: StrategyId,
2425        instrument_id: InstrumentId,
2426        td_mode: OKXTradeMode,
2427        client_order_id: ClientOrderId,
2428        order_side: OrderSide,
2429        order_type: OrderType,
2430        quantity: Quantity,
2431        time_in_force: Option<TimeInForce>,
2432        price: Option<Price>,
2433        trigger_price: Option<Price>,
2434        post_only: Option<bool>,
2435        reduce_only: Option<bool>,
2436        quote_quantity: Option<bool>,
2437        position_side: Option<PositionSide>,
2438        attach_algo_ords: Option<Vec<WsAttachAlgoOrdParams>>,
2439        px_usd: Option<String>,
2440        px_vol: Option<String>,
2441        outcome: Option<String>,
2442        slippage_pct: Option<String>,
2443        rpi: Option<bool>,
2444        rpi_taker_access: Option<bool>,
2445        rpi_px_round: Option<bool>,
2446    ) -> Result<(), OKXWsError> {
2447        let rpi = rpi.unwrap_or(false);
2448
2449        if !OKX_SUPPORTED_ORDER_TYPES.contains(&order_type) {
2450            return Err(OKXWsError::ClientError(format!(
2451                "Unsupported order type: {order_type:?}",
2452            )));
2453        }
2454
2455        validate_order_time_in_force(time_in_force).map_err(OKXWsError::ClientError)?;
2456
2457        let mut builder = WsPostOrderParamsBuilder::default();
2458
2459        let inst_id_code = self
2460            .get_inst_id_code(&instrument_id.symbol.inner())
2461            .ok_or_else(|| {
2462                OKXWsError::ClientError(format!(
2463                    "No instIdCode cached for {instrument_id}, cannot submit order"
2464                ))
2465            })?;
2466        builder.inst_id_code(inst_id_code);
2467
2468        builder.td_mode(td_mode);
2469        builder.cl_ord_id(client_order_id.as_str());
2470
2471        let (instrument_type, quote_currency) = {
2472            let instruments = self.instruments_cache.load();
2473            let symbol = instrument_id.symbol.inner();
2474            let instrument = instruments.get(&symbol).ok_or_else(|| {
2475                OKXWsError::ClientError(format!("Unknown instrument {instrument_id}"))
2476            })?;
2477            let instrument_type = okx_instrument_type(instrument)
2478                .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
2479            (instrument_type, instrument.quote_currency())
2480        };
2481
2482        // OKX options only support limit-style orders
2483        if instrument_type == OKXInstrumentType::Option
2484            && matches!(order_type, OrderType::Market | OrderType::MarketToLimit)
2485        {
2486            return Err(OKXWsError::ClientError(
2487                "Market orders are not supported for OKX options, use Limit orders instead"
2488                    .to_string(),
2489            ));
2490        }
2491
2492        match instrument_type {
2493            OKXInstrumentType::Spot | OKXInstrumentType::Margin => {
2494                // SPOT: ccy parameter is required by OKX for spot trading
2495                builder.ccy(quote_currency.to_string());
2496            }
2497            OKXInstrumentType::Swap | OKXInstrumentType::Futures => {
2498                // SWAP/FUTURES: use quote currency for margin (required by OKX)
2499                builder.ccy(quote_currency.to_string());
2500
2501                // For derivatives, posSide is required by OKX
2502                // Use Net for one-way mode (default for NETTING OMS)
2503                if position_side.is_none() {
2504                    builder.pos_side(OKXPositionSide::Net);
2505                }
2506            }
2507            OKXInstrumentType::Option => {
2508                builder.ccy(quote_currency.to_string());
2509
2510                if position_side.is_none() {
2511                    builder.pos_side(OKXPositionSide::Net);
2512                }
2513            }
2514            OKXInstrumentType::Events => {}
2515            _ => {
2516                builder.ccy(quote_currency.to_string());
2517
2518                if position_side.is_none() {
2519                    builder.pos_side(OKXPositionSide::Net);
2520                }
2521            }
2522        }
2523
2524        if let Some(reduce_only) = okx_reduce_only_wire_value(
2525            instrument_type,
2526            td_mode,
2527            order_side,
2528            position_side,
2529            reduce_only,
2530        )
2531        .map_err(OKXWsError::ClientError)?
2532        {
2533            builder.reduce_only(reduce_only);
2534        }
2535
2536        if let Some(attach_algo_ords) = attach_algo_ords {
2537            builder.attach_algo_ords(attach_algo_ords);
2538        }
2539
2540        if let Some(tgt_ccy) =
2541            okx_market_target_currency(instrument_type, order_side, order_type, quote_quantity)
2542                .map_err(|e| OKXWsError::ClientError(e.to_string()))?
2543        {
2544            builder.tgt_ccy(tgt_ccy);
2545        }
2546
2547        builder.side(order_side);
2548
2549        if let Some(pos_side) = position_side {
2550            builder.pos_side(pos_side);
2551        }
2552
2553        // OKX implements FOK/IOC as order types rather than separate time-in-force
2554        // Market + FOK is unsupported (FOK requires a limit price)
2555        // optimal_limit_ioc is only supported for SWAP/FUTURES, not SPOT or OPTION
2556        validate_regular_order_params(
2557            instrument_type,
2558            order_type,
2559            time_in_force,
2560            post_only.unwrap_or(false),
2561            rpi,
2562            outcome.as_deref(),
2563        )
2564        .map_err(OKXWsError::ClientError)?;
2565
2566        let (okx_ord_type, price) = if rpi {
2567            (OKXOrderType::Rpi, price)
2568        } else if post_only.unwrap_or(false) {
2569            (OKXOrderType::PostOnly, price)
2570        } else if let Some(tif) = time_in_force {
2571            match (order_type, tif) {
2572                (OrderType::Market, TimeInForce::Ioc) => {
2573                    // optimal_limit_ioc only works for SWAP/FUTURES
2574                    if matches!(
2575                        instrument_type,
2576                        OKXInstrumentType::Spot | OKXInstrumentType::Option
2577                    ) {
2578                        (OKXOrderType::Market, price)
2579                    } else {
2580                        (OKXOrderType::OptimalLimitIoc, price)
2581                    }
2582                }
2583                (OrderType::Limit, TimeInForce::Fok) => (OKXOrderType::Fok, price),
2584                (OrderType::Limit, TimeInForce::Ioc) => (OKXOrderType::Ioc, price),
2585                _ => (OKXOrderType::from(order_type), price),
2586            }
2587        } else {
2588            (OKXOrderType::from(order_type), price)
2589        };
2590
2591        log::debug!(
2592            "Order type mapping: order_type={order_type:?}, time_in_force={time_in_force:?}, post_only={post_only:?} -> okx_ord_type={okx_ord_type:?}"
2593        );
2594
2595        if let Some(outcome) = outcome {
2596            builder.outcome(outcome);
2597        }
2598
2599        if let Some(slippage) = slippage_pct {
2600            builder.slippage_pct(slippage);
2601        }
2602
2603        if let Some(rpi_taker_access) = rpi_taker_access {
2604            builder.rpi_taker_access(rpi_taker_access);
2605        }
2606
2607        if let Some(rpi_px_round) = rpi_px_round {
2608            builder.rpi_px_round(rpi_px_round);
2609        }
2610
2611        if let Some(trade_quote_ccy) =
2612            self.resolve_spot_trade_quote_ccy(instrument_type, instrument_id.symbol.inner())?
2613        {
2614            builder.trade_quote_ccy(trade_quote_ccy);
2615        }
2616
2617        builder.ord_type(okx_ord_type);
2618        builder.sz(quantity.to_string());
2619
2620        // For options: pxUsd/pxVol are mutually exclusive with px
2621        if let Some(usd) = px_usd {
2622            builder.px_usd(usd);
2623        } else if let Some(vol) = px_vol {
2624            builder.px_vol(vol);
2625        } else if let Some(tp) = trigger_price {
2626            builder.px(tp.to_string());
2627        } else if let Some(p) = price {
2628            builder.px(p.to_string());
2629        }
2630
2631        builder.tag(OKX_NAUTILUS_BROKER_ID);
2632
2633        let params = builder
2634            .build()
2635            .map_err(|e| OKXWsError::ClientError(format!("Build order params error: {e}")))?;
2636
2637        let request_id = self.generate_unique_request_id();
2638        let request = OKXWsRequest {
2639            id: Some(request_id.clone()),
2640            op: super::enums::OKXWsOperation::Order,
2641            exp_time: self.order_request_exp_time(),
2642            args: vec![params],
2643        };
2644
2645        let payload = serde_json::to_string(&request)
2646            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize order: {e}")))?;
2647
2648        let cl_ord_key = client_order_id.to_string();
2649        self.pending_orders.insert(
2650            cl_ord_key.clone(),
2651            PendingOrderInfo {
2652                trader_id,
2653                strategy_id,
2654                instrument_id,
2655            },
2656        );
2657
2658        let cmd = HandlerCommand::Send {
2659            payload,
2660            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_ORDER.to_vec()),
2661            request_id: Some(request_id),
2662            client_order_ids: vec![client_order_id],
2663            op: Some(super::enums::OKXWsOperation::Order),
2664        };
2665
2666        let result = self.send_cmd(cmd).await;
2667
2668        if result.is_err() {
2669            self.pending_orders.remove(&cl_ord_key);
2670        }
2671
2672        result
2673    }
2674
2675    /// Place a new order via WebSocket.
2676    ///
2677    /// # References
2678    ///
2679    /// <https://www.okx.com/docs-v5/en/#order-book-trading-websocket-place-order>
2680    /// Modifies an existing order.
2681    ///
2682    /// # Errors
2683    ///
2684    /// Returns an error if the amend parameters are invalid or if the
2685    /// websocket request fails to send.
2686    ///
2687    /// # References
2688    ///
2689    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-amend-order>.
2690    #[expect(clippy::too_many_arguments)]
2691    pub async fn modify_order(
2692        &self,
2693        trader_id: TraderId,
2694        strategy_id: StrategyId,
2695        instrument_id: InstrumentId,
2696        client_order_id: Option<ClientOrderId>,
2697        price: Option<Price>,
2698        quantity: Option<Quantity>,
2699        venue_order_id: Option<VenueOrderId>,
2700        new_px_usd: Option<String>,
2701        new_px_vol: Option<String>,
2702        rpi_taker_access: Option<bool>,
2703        rpi_px_round: Option<bool>,
2704    ) -> Result<(), OKXWsError> {
2705        self.modify_order_with_causation(
2706            trader_id,
2707            strategy_id,
2708            instrument_id,
2709            client_order_id,
2710            price,
2711            quantity,
2712            venue_order_id,
2713            new_px_usd,
2714            new_px_vol,
2715            rpi_taker_access,
2716            rpi_px_round,
2717            None,
2718        )
2719        .await
2720    }
2721
2722    #[expect(clippy::too_many_arguments)]
2723    pub(crate) async fn modify_order_with_causation(
2724        &self,
2725        trader_id: TraderId,
2726        strategy_id: StrategyId,
2727        instrument_id: InstrumentId,
2728        client_order_id: Option<ClientOrderId>,
2729        price: Option<Price>,
2730        quantity: Option<Quantity>,
2731        venue_order_id: Option<VenueOrderId>,
2732        new_px_usd: Option<String>,
2733        new_px_vol: Option<String>,
2734        rpi_taker_access: Option<bool>,
2735        rpi_px_round: Option<bool>,
2736        causation_id: Option<UUID4>,
2737    ) -> Result<(), OKXWsError> {
2738        let mut builder = WsAmendOrderParamsBuilder::default();
2739
2740        let inst_id_code = self
2741            .get_inst_id_code(&instrument_id.symbol.inner())
2742            .ok_or_else(|| {
2743                OKXWsError::ClientError(format!(
2744                    "No instIdCode cached for {instrument_id}, cannot amend order"
2745                ))
2746            })?;
2747        builder.inst_id_code(inst_id_code);
2748
2749        if let Some(venue_order_id) = venue_order_id {
2750            builder.ord_id(venue_order_id.as_str());
2751        }
2752
2753        let cl_ord_key = client_order_id.map(|id| id.to_string());
2754
2755        if let Some(client_order_id) = client_order_id {
2756            builder.cl_ord_id(client_order_id.as_str());
2757            self.pending_amends.insert(
2758                client_order_id.to_string(),
2759                PendingOrderInfo {
2760                    trader_id,
2761                    strategy_id,
2762                    instrument_id,
2763                },
2764            );
2765        }
2766
2767        // For options: newPxUsd/newPxVol are mutually exclusive with newPx
2768        if let Some(usd) = new_px_usd {
2769            builder.new_px_usd(usd);
2770        } else if let Some(vol) = new_px_vol {
2771            builder.new_px_vol(vol);
2772        } else if let Some(price) = price {
2773            builder.new_px(price.to_string());
2774        }
2775
2776        if let Some(quantity) = quantity {
2777            builder.new_sz(quantity.to_string());
2778        }
2779
2780        if let Some(rpi_taker_access) = rpi_taker_access {
2781            builder.rpi_taker_access(rpi_taker_access);
2782        }
2783
2784        if let Some(rpi_px_round) = rpi_px_round {
2785            builder.rpi_px_round(rpi_px_round);
2786        }
2787
2788        let params = builder
2789            .build()
2790            .map_err(|e| OKXWsError::ClientError(format!("Build amend params error: {e}")))?;
2791
2792        let request_id = self.generate_unique_request_id();
2793        let request = OKXWsRequest {
2794            id: Some(request_id.clone()),
2795            op: super::enums::OKXWsOperation::AmendOrder,
2796            exp_time: self.order_request_exp_time(),
2797            args: vec![params],
2798        };
2799
2800        let payload = serde_json::to_string(&request)
2801            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize amend: {e}")))?;
2802
2803        if let (Some(client_order_id), Some(causation_id)) = (client_order_id, causation_id) {
2804            self.pending_command_ids
2805                .insert(request_id.clone(), vec![(client_order_id, causation_id)]);
2806        }
2807
2808        let cmd = HandlerCommand::Send {
2809            payload,
2810            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_AMEND.to_vec()),
2811            request_id: Some(request_id.clone()),
2812            client_order_ids: client_order_id.into_iter().collect(),
2813            op: Some(super::enums::OKXWsOperation::AmendOrder),
2814        };
2815
2816        let result = self.send_cmd(cmd).await;
2817
2818        if result.is_err() {
2819            self.pending_command_ids.remove(&request_id);
2820        }
2821
2822        if let (Err(_), Some(key)) = (&result, &cl_ord_key) {
2823            self.pending_amends.remove(key);
2824        }
2825
2826        result
2827    }
2828
2829    /// Cancels an existing order.
2830    ///
2831    /// # Errors
2832    ///
2833    /// Returns an error if the cancel parameters are invalid or if the
2834    /// cancellation request fails to send.
2835    ///
2836    /// # References
2837    ///
2838    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-cancel-order>.
2839    pub async fn cancel_order(
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    ) -> Result<(), OKXWsError> {
2847        self.cancel_order_with_causation(
2848            trader_id,
2849            strategy_id,
2850            instrument_id,
2851            client_order_id,
2852            venue_order_id,
2853            None,
2854        )
2855        .await
2856    }
2857
2858    pub(crate) async fn cancel_order_with_causation(
2859        &self,
2860        trader_id: TraderId,
2861        strategy_id: StrategyId,
2862        instrument_id: InstrumentId,
2863        client_order_id: Option<ClientOrderId>,
2864        venue_order_id: Option<VenueOrderId>,
2865        causation_id: Option<UUID4>,
2866    ) -> Result<(), OKXWsError> {
2867        let mut builder = WsCancelOrderParamsBuilder::default();
2868
2869        let inst_id_code = self
2870            .get_inst_id_code(&instrument_id.symbol.inner())
2871            .ok_or_else(|| {
2872                OKXWsError::ClientError(format!(
2873                    "No instIdCode cached for {instrument_id}, cannot cancel order"
2874                ))
2875            })?;
2876        builder.inst_id_code(inst_id_code);
2877
2878        if let Some(venue_order_id) = venue_order_id {
2879            builder.ord_id(venue_order_id.as_str());
2880        }
2881
2882        let cl_ord_key = client_order_id.map(|id| id.to_string());
2883
2884        if let Some(client_order_id) = client_order_id {
2885            builder.cl_ord_id(client_order_id.as_str());
2886            self.pending_cancels.insert(
2887                client_order_id.to_string(),
2888                PendingOrderInfo {
2889                    trader_id,
2890                    strategy_id,
2891                    instrument_id,
2892                },
2893            );
2894        }
2895
2896        let params = builder
2897            .build()
2898            .map_err(|e| OKXWsError::ClientError(format!("Build cancel params error: {e}")))?;
2899
2900        let request_id = self.generate_unique_request_id();
2901        let request = OKXWsRequest {
2902            id: Some(request_id.clone()),
2903            op: super::enums::OKXWsOperation::CancelOrder,
2904            exp_time: None,
2905            args: vec![params],
2906        };
2907
2908        let payload = serde_json::to_string(&request)
2909            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize cancel: {e}")))?;
2910
2911        if let (Some(client_order_id), Some(causation_id)) = (client_order_id, causation_id) {
2912            self.pending_command_ids
2913                .insert(request_id.clone(), vec![(client_order_id, causation_id)]);
2914        }
2915
2916        let cmd = HandlerCommand::Send {
2917            payload,
2918            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_CANCEL.to_vec()),
2919            request_id: Some(request_id.clone()),
2920            client_order_ids: client_order_id.into_iter().collect(),
2921            op: Some(super::enums::OKXWsOperation::CancelOrder),
2922        };
2923
2924        let result = self.send_cmd(cmd).await;
2925
2926        if result.is_err() {
2927            self.pending_command_ids.remove(&request_id);
2928        }
2929
2930        if let (Err(_), Some(key)) = (&result, &cl_ord_key) {
2931            self.pending_cancels.remove(key);
2932        }
2933
2934        result
2935    }
2936
2937    /// Mass cancels all orders for a given instrument via WebSocket.
2938    ///
2939    /// # Errors
2940    ///
2941    /// Returns an error if instrument metadata cannot be resolved or if the
2942    /// cancel request fails to send.
2943    ///
2944    /// # References
2945    /// <https://www.okx.com/docs-v5/en/#order-book-trading-websocket-mass-cancel-order>
2946    pub async fn mass_cancel_orders(&self, instrument_id: InstrumentId) -> Result<(), OKXWsError> {
2947        let (inst_type, inst_family) = {
2948            let instrument = self
2949                .instruments_cache
2950                .get_cloned(&instrument_id.symbol.inner())
2951                .ok_or_else(|| {
2952                    OKXWsError::ClientError(format!("Unknown instrument {instrument_id}"))
2953                })?;
2954
2955            let inst_type = okx_instrument_type(&instrument)
2956                .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
2957
2958            let symbol = instrument.symbol().inner();
2959            let inst_family = match &instrument {
2960                InstrumentAny::CurrencyPair(_) => symbol.as_str().to_string(),
2961                InstrumentAny::CryptoPerpetual(_) => symbol
2962                    .as_str()
2963                    .strip_suffix("-SWAP")
2964                    .unwrap_or(symbol.as_str())
2965                    .to_string(),
2966                InstrumentAny::CryptoFuture(_) => {
2967                    let s = symbol.as_str();
2968                    if let Some(idx) = s.rfind('-') {
2969                        s[..idx].to_string()
2970                    } else {
2971                        s.to_string()
2972                    }
2973                }
2974                _ => {
2975                    return Err(OKXWsError::ClientError(
2976                        "Unsupported instrument type for mass cancel".to_string(),
2977                    ));
2978                }
2979            };
2980
2981            (inst_type, inst_family)
2982        };
2983
2984        let params = WsMassCancelParams {
2985            inst_type,
2986            inst_family: Ustr::from(&inst_family),
2987        };
2988
2989        let request_id = self.generate_unique_request_id();
2990        let request = OKXWsRequest {
2991            id: Some(request_id.clone()),
2992            op: super::enums::OKXWsOperation::MassCancel,
2993            exp_time: None,
2994            args: vec![
2995                serde_json::to_value(params).map_err(|e| OKXWsError::JsonError(e.to_string()))?,
2996            ],
2997        };
2998
2999        let payload = serde_json::to_string(&request)
3000            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize mass cancel: {e}")))?;
3001
3002        let cmd = HandlerCommand::Send {
3003            payload,
3004            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_MASS_CANCEL.to_vec()),
3005            request_id: Some(request_id),
3006            client_order_ids: Vec::new(),
3007            op: Some(super::enums::OKXWsOperation::MassCancel),
3008        };
3009
3010        self.send_cmd(cmd).await
3011    }
3012
3013    /// Submits multiple orders.
3014    ///
3015    /// The quantity-unit flag follows `reduce_only` in each tuple. `Some(true)` requests quote
3016    /// units and `Some(false)` requests base units for spot market orders.
3017    /// `None` uses venue defaults.
3018    ///
3019    /// # Errors
3020    ///
3021    /// Returns an error if any batch order parameters are invalid or if the
3022    /// batch request fails to send.
3023    #[expect(clippy::type_complexity)]
3024    pub async fn batch_submit_orders(
3025        &self,
3026        orders: Vec<(
3027            OKXInstrumentType,
3028            InstrumentId,
3029            OKXTradeMode,
3030            ClientOrderId,
3031            OrderSide,
3032            Option<PositionSide>,
3033            OrderType,
3034            Quantity,
3035            Option<Price>,
3036            Option<Price>,
3037            Option<bool>,
3038            Option<bool>,
3039            Option<bool>,
3040            Option<String>,
3041            Option<bool>,
3042            Option<bool>,
3043            Option<bool>,
3044        )>,
3045    ) -> Result<(), OKXWsError> {
3046        let client_order_ids: Vec<ClientOrderId> = orders.iter().map(|o| o.3).collect();
3047        let args: Vec<Value> = {
3048            let mut args = Vec::with_capacity(orders.len());
3049            let inst_id_codes = self.inst_id_code_cache.load();
3050            let instruments = self.instruments_cache.load();
3051
3052            for (
3053                inst_type,
3054                inst_id,
3055                td_mode,
3056                cl_ord_id,
3057                ord_side,
3058                pos_side,
3059                ord_type,
3060                qty,
3061                pr,
3062                tp,
3063                post_only,
3064                reduce_only,
3065                quote_quantity,
3066                outcome,
3067                rpi,
3068                rpi_taker_access,
3069                rpi_px_round,
3070            ) in orders
3071            {
3072                let rpi = rpi.unwrap_or(false);
3073                let mut builder = WsPostOrderParamsBuilder::default();
3074
3075                let (inst_id_symbol, inst_id_code) = Self::inst_id_symbol_and_code_from_snapshot(
3076                    &inst_id_codes,
3077                    &inst_id,
3078                    "submit",
3079                )?;
3080                builder.inst_id_code(inst_id_code);
3081
3082                builder.td_mode(td_mode);
3083                builder.cl_ord_id(cl_ord_id.as_str());
3084                builder.side(ord_side);
3085
3086                if inst_type != OKXInstrumentType::Events
3087                    && let Some(instrument) = instruments.get(&inst_id_symbol)
3088                {
3089                    builder.ccy(instrument.quote_currency().to_string());
3090                }
3091
3092                if let Some(ps) = pos_side {
3093                    builder.pos_side(OKXPositionSide::from(ps));
3094                } else if matches!(
3095                    inst_type,
3096                    OKXInstrumentType::Swap
3097                        | OKXInstrumentType::Futures
3098                        | OKXInstrumentType::Option
3099                ) {
3100                    builder.pos_side(OKXPositionSide::Net);
3101                }
3102
3103                if rpi && ord_type != OrderType::Limit {
3104                    return Err(OKXWsError::ClientError(
3105                        "OKX RPI batch orders require limit orders".to_string(),
3106                    ));
3107                }
3108
3109                let okx_ord_type = if rpi {
3110                    OKXOrderType::Rpi
3111                } else if post_only.unwrap_or(false) {
3112                    OKXOrderType::PostOnly
3113                } else {
3114                    match ord_type {
3115                        OrderType::Market => OKXOrderType::Market,
3116                        OrderType::Limit => OKXOrderType::Limit,
3117                        OrderType::MarketToLimit => OKXOrderType::Ioc,
3118                        _ => {
3119                            return Err(OKXWsError::ClientError(format!(
3120                                "Unsupported order type for batch submit: {ord_type:?}"
3121                            )));
3122                        }
3123                    }
3124                };
3125
3126                builder.ord_type(okx_ord_type);
3127                builder.sz(qty.to_string());
3128                let tgt_ccy =
3129                    okx_market_target_currency(inst_type, ord_side, ord_type, quote_quantity)
3130                        .map_err(|e| OKXWsError::ClientError(e.to_string()))?;
3131
3132                if let Some(p) = pr {
3133                    builder.px(p.to_string());
3134                } else if let Some(p) = tp {
3135                    builder.px(p.to_string());
3136                }
3137
3138                if let Some(reduce_only) =
3139                    okx_reduce_only_wire_value(inst_type, td_mode, ord_side, pos_side, reduce_only)
3140                        .map_err(OKXWsError::ClientError)?
3141                {
3142                    builder.reduce_only(reduce_only);
3143                }
3144
3145                if inst_type == OKXInstrumentType::Events && outcome.is_none() {
3146                    return Err(OKXWsError::ClientError(
3147                        "OKX event contract orders require `outcome`".to_string(),
3148                    ));
3149                }
3150
3151                if let Some(outcome) = outcome {
3152                    builder.outcome(outcome);
3153                }
3154
3155                if let Some(rpi_taker_access) = rpi_taker_access {
3156                    builder.rpi_taker_access(rpi_taker_access);
3157                }
3158
3159                if let Some(rpi_px_round) = rpi_px_round {
3160                    builder.rpi_px_round(rpi_px_round);
3161                }
3162
3163                if let Some(trade_quote_ccy) =
3164                    self.resolve_spot_trade_quote_ccy(inst_type, inst_id_symbol)?
3165                {
3166                    builder.trade_quote_ccy(trade_quote_ccy);
3167                }
3168
3169                builder.tag(OKX_NAUTILUS_BROKER_ID);
3170
3171                let mut params = builder.build().map_err(|e| {
3172                    OKXWsError::ClientError(format!("Build order params error: {e}"))
3173                })?;
3174
3175                params.tgt_ccy = tgt_ccy;
3176                let val = serde_json::to_value(params)
3177                    .map_err(|e| OKXWsError::JsonError(e.to_string()))?;
3178                args.push(val);
3179            }
3180            args
3181        };
3182
3183        self.ws_batch_place_orders(args, client_order_ids).await
3184    }
3185
3186    /// Modifies multiple orders.
3187    ///
3188    /// # Errors
3189    ///
3190    /// Returns an error if amend parameters are invalid or if the batch request
3191    /// fails to send.
3192    #[expect(clippy::type_complexity)]
3193    pub async fn batch_modify_orders(
3194        &self,
3195        orders: Vec<(
3196            OKXInstrumentType,
3197            InstrumentId,
3198            ClientOrderId,
3199            Option<String>,
3200            Option<Price>,
3201            Option<Quantity>,
3202            Option<bool>,
3203            Option<bool>,
3204        )>,
3205    ) -> Result<(), OKXWsError> {
3206        let client_order_ids: Vec<ClientOrderId> = orders.iter().map(|o| o.2).collect();
3207        let args: Vec<Value> = {
3208            let mut args = Vec::with_capacity(orders.len());
3209            let inst_id_codes = self.inst_id_code_cache.load();
3210
3211            for (
3212                _inst_type,
3213                inst_id,
3214                cl_ord_id,
3215                request_id,
3216                pr,
3217                sz,
3218                rpi_taker_access,
3219                rpi_px_round,
3220            ) in orders
3221            {
3222                let mut builder = WsAmendOrderParamsBuilder::default();
3223
3224                let (_, inst_id_code) =
3225                    Self::inst_id_symbol_and_code_from_snapshot(&inst_id_codes, &inst_id, "amend")?;
3226                builder.inst_id_code(inst_id_code);
3227
3228                builder.cl_ord_id(cl_ord_id.as_str());
3229
3230                if let Some(request_id) = request_id {
3231                    builder.req_id(request_id);
3232                }
3233
3234                if let Some(p) = pr {
3235                    builder.new_px(p.to_string());
3236                }
3237
3238                if let Some(q) = sz {
3239                    builder.new_sz(q.to_string());
3240                }
3241
3242                if let Some(rpi_taker_access) = rpi_taker_access {
3243                    builder.rpi_taker_access(rpi_taker_access);
3244                }
3245
3246                if let Some(rpi_px_round) = rpi_px_round {
3247                    builder.rpi_px_round(rpi_px_round);
3248                }
3249
3250                let params = builder.build().map_err(|e| {
3251                    OKXWsError::ClientError(format!("Build amend batch params error: {e}"))
3252                })?;
3253                let val = serde_json::to_value(params)
3254                    .map_err(|e| OKXWsError::JsonError(e.to_string()))?;
3255                args.push(val);
3256            }
3257            args
3258        };
3259
3260        self.ws_batch_amend_orders(args, client_order_ids).await
3261    }
3262
3263    /// Cancels multiple orders.
3264    ///
3265    /// Supports up to 20 orders per batch.
3266    ///
3267    /// # Errors
3268    ///
3269    /// Returns an error if cancel parameters are invalid or if the batch
3270    /// request fails to send.
3271    ///
3272    /// # References
3273    ///
3274    /// <https://www.okx.com/docs-v5/en/#order-book-trading-websocket-batch-cancel-orders>
3275    pub async fn batch_cancel_orders(
3276        &self,
3277        orders: Vec<(InstrumentId, Option<ClientOrderId>, Option<VenueOrderId>)>,
3278    ) -> Result<(), OKXWsError> {
3279        self.batch_cancel_orders_with_causation(orders, Vec::new())
3280            .await
3281    }
3282
3283    pub(crate) async fn batch_cancel_orders_with_causation(
3284        &self,
3285        orders: Vec<(InstrumentId, Option<ClientOrderId>, Option<VenueOrderId>)>,
3286        causation_ids: Vec<(ClientOrderId, UUID4)>,
3287    ) -> Result<(), OKXWsError> {
3288        let client_order_ids: Vec<ClientOrderId> = orders
3289            .iter()
3290            .filter_map(|(_, cl_ord_id, _)| *cl_ord_id)
3291            .collect();
3292        let args: Vec<Value> = {
3293            let mut args = Vec::with_capacity(orders.len());
3294            let inst_id_codes = self.inst_id_code_cache.load();
3295
3296            for (inst_id, cl_ord_id, ord_id) in orders {
3297                let mut builder = WsCancelOrderParamsBuilder::default();
3298
3299                let (_, inst_id_code) = Self::inst_id_symbol_and_code_from_snapshot(
3300                    &inst_id_codes,
3301                    &inst_id,
3302                    "cancel",
3303                )?;
3304                builder.inst_id_code(inst_id_code);
3305
3306                if let Some(c) = cl_ord_id {
3307                    builder.cl_ord_id(c.as_str());
3308                }
3309
3310                if let Some(o) = ord_id {
3311                    builder.ord_id(o.as_str());
3312                }
3313
3314                let params = builder.build().map_err(|e| {
3315                    OKXWsError::ClientError(format!("Build cancel batch params error: {e}"))
3316                })?;
3317                let val = serde_json::to_value(params)
3318                    .map_err(|e| OKXWsError::JsonError(e.to_string()))?;
3319                args.push(val);
3320            }
3321            args
3322        };
3323
3324        self.ws_batch_cancel_orders(args, client_order_ids, causation_ids)
3325            .await
3326    }
3327
3328    /// Rejects algo placement on the WebSocket transport; use the HTTP client instead.
3329    ///
3330    /// # Errors
3331    ///
3332    /// Returns an error if called: OKX does not accept this client's `order-algo` operation.
3333    #[expect(clippy::too_many_arguments)]
3334    #[expect(
3335        clippy::unused_async,
3336        clippy::unused_async_trait_impl,
3337        reason = "Preserves the published async API while rejecting an unsupported operation"
3338    )]
3339    pub async fn submit_algo_order(
3340        &self,
3341        _trader_id: TraderId,
3342        _strategy_id: StrategyId,
3343        _instrument_id: InstrumentId,
3344        _td_mode: OKXTradeMode,
3345        _client_order_id: ClientOrderId,
3346        _order_side: OrderSide,
3347        _order_type: OrderType,
3348        _quantity: Quantity,
3349        _trigger_price: Option<Price>,
3350        _trigger_type: Option<TriggerType>,
3351        _limit_price: Option<Price>,
3352        _reduce_only: Option<bool>,
3353        _callback_ratio: Option<String>,
3354        _callback_spread: Option<String>,
3355        _activation_price: Option<Price>,
3356    ) -> Result<(), OKXWsError> {
3357        Err(OKXWsError::ClientError(
3358            "OKX algo placement requires HTTP; use OKXHttpClient::place_algo_order_with_domain_types"
3359                .to_string(),
3360        ))
3361    }
3362
3363    /// Cancels an algo order.
3364    ///
3365    /// # Errors
3366    ///
3367    /// Returns an error if cancel parameters are invalid or if the request
3368    /// fails to send.
3369    ///
3370    /// # References
3371    ///
3372    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order>
3373    pub async fn cancel_algo_order(
3374        &self,
3375        _trader_id: TraderId,
3376        _strategy_id: StrategyId,
3377        instrument_id: InstrumentId,
3378        client_order_id: Option<ClientOrderId>,
3379        algo_order_id: Option<String>,
3380    ) -> Result<(), OKXWsError> {
3381        let mut builder = super::messages::WsCancelAlgoOrderParamsBuilder::default();
3382
3383        let inst_id_code = self
3384            .get_inst_id_code(&instrument_id.symbol.inner())
3385            .ok_or_else(|| {
3386                OKXWsError::ClientError(format!(
3387                    "No instIdCode cached for {instrument_id}, cannot cancel algo order"
3388                ))
3389            })?;
3390        builder.inst_id_code(inst_id_code);
3391
3392        if let Some(algo_id) = algo_order_id {
3393            builder.algo_id(algo_id);
3394        }
3395
3396        if let Some(cl_ord_id) = client_order_id {
3397            builder.algo_cl_ord_id(cl_ord_id.to_string());
3398        }
3399
3400        let params = builder
3401            .build()
3402            .map_err(|e| OKXWsError::ClientError(format!("Build cancel algo params error: {e}")))?;
3403
3404        let request_id = self.generate_unique_request_id();
3405        let request = OKXWsRequest {
3406            id: Some(request_id.clone()),
3407            op: super::enums::OKXWsOperation::CancelAlgos,
3408            exp_time: None,
3409            args: vec![params],
3410        };
3411
3412        let payload = serde_json::to_string(&request)
3413            .map_err(|e| OKXWsError::JsonError(format!("Failed to serialize cancel algo: {e}")))?;
3414
3415        let cmd = HandlerCommand::Send {
3416            payload,
3417            rate_limit_keys: Some(OKX_RATE_LIMIT_KEY_ALGO_CANCEL.to_vec()),
3418            request_id: Some(request_id),
3419            client_order_ids: client_order_id.into_iter().collect(),
3420            op: Some(super::enums::OKXWsOperation::CancelAlgos),
3421        };
3422
3423        self.send_cmd(cmd).await
3424    }
3425
3426    /// Sends a command to the handler.
3427    async fn send_cmd(&self, cmd: HandlerCommand) -> Result<(), OKXWsError> {
3428        self.cmd_tx
3429            .read()
3430            .await
3431            .send(cmd)
3432            .map_err(|e| OKXWsError::HandlerUnavailable(e.to_string()))
3433    }
3434}
3435
3436fn authentication_timestamp(now: UnixNanos) -> String {
3437    now.as_seconds().to_string()
3438}
3439
3440fn subscription_args(
3441    subscriptions: &DashMap<String, OKXSubscriptionArg>,
3442    subscriptions_state: &SubscriptionState,
3443) -> Vec<OKXSubscriptionArg> {
3444    let mut args: Vec<_> = subscriptions_state
3445        .all_topics()
3446        .iter()
3447        .filter_map(|topic| subscriptions.get(topic).map(|arg| arg.value().clone()))
3448        .collect();
3449    args.sort_unstable_by_key(topic_from_subscription_arg);
3450    args
3451}
3452
3453fn subscription_arg_batches(
3454    args: &[OKXSubscriptionArg],
3455) -> impl Iterator<Item = &[OKXSubscriptionArg]> {
3456    args.chunks(OKX_WS_SUBSCRIPTION_ARGS_MAX_PER_MESSAGE)
3457}
3458
3459fn advance_reconnect_epoch(
3460    reconnect_epoch: &mut u64,
3461    epoch: u64,
3462    stopping: bool,
3463    active: bool,
3464) -> bool {
3465    if stopping || !active || epoch == *reconnect_epoch {
3466        return false;
3467    }
3468
3469    *reconnect_epoch = epoch;
3470    true
3471}
3472
3473fn auth_attempt_superseded(error: &Error) -> bool {
3474    error.to_string().contains("superseded")
3475        || matches!(error, Error::Io(e) if matches!(
3476            e.get_ref().and_then(|e| e.downcast_ref::<SendError>()),
3477            Some(SendError::ConnectionChanged),
3478        ))
3479}
3480
3481async fn authenticate_session(
3482    credential: &Credential,
3483    auth_tracker: &AuthTracker,
3484    ws_client: &WebSocketClient,
3485    connection_epoch: u64,
3486    clock: &'static AtomicTime,
3487    auth_timeout_secs: u64,
3488) -> Result<(), Error> {
3489    if !ws_client.is_active() || ws_client.connection_epoch() != connection_epoch {
3490        return Err(Error::Io(std::io::Error::other(
3491            SendError::ConnectionChanged,
3492        )));
3493    }
3494
3495    let rx = auth_tracker.begin();
3496    let timestamp = authentication_timestamp(clock.get_time_ns());
3497    let signature = credential.sign(&timestamp, "GET", "/users/self/verify", "");
3498
3499    let auth_message = OKXAuthentication {
3500        op: "login",
3501        args: vec![OKXAuthenticationArg {
3502            api_key: SecretString::from(credential.api_key()),
3503            passphrase: SecretString::from(credential.api_passphrase()),
3504            timestamp,
3505            sign: SecretString::from(signature),
3506        }],
3507    };
3508
3509    let payload = serde_json::to_string(&auth_message)
3510        .map(SecretString::from)
3511        .map_err(|e| {
3512            Error::Io(std::io::Error::other(format!(
3513                "Failed to serialize auth message: {e}"
3514            )))
3515        })?;
3516
3517    ws_client
3518        .send_text_on_connection(
3519            payload.expose_secret().to_owned(),
3520            Some(OKX_RATE_LIMIT_KEY_SUBSCRIPTION.as_slice()),
3521            connection_epoch,
3522        )
3523        .await
3524        .map_err(|e| Error::Io(std::io::Error::other(e)))?;
3525
3526    match auth_tracker
3527        .wait_for_result::<OKXWsError>(Duration::from_secs(auth_timeout_secs), rx)
3528        .await
3529    {
3530        Ok(()) => {
3531            log::debug!("WebSocket authenticated");
3532            Ok(())
3533        }
3534        Err(e) => {
3535            let auth_error = Error::Io(std::io::Error::other(e.to_string()));
3536            if !auth_attempt_superseded(&auth_error) {
3537                log::warn!("WebSocket authentication failed: error={e}");
3538            }
3539
3540            Err(auth_error)
3541        }
3542    }
3543}
3544
3545#[allow(
3546    clippy::too_many_arguments,
3547    reason = "reconnect authentication uses the existing session and shutdown state"
3548)]
3549async fn reauthenticate_session(
3550    credential: Credential,
3551    auth_tracker: AuthTracker,
3552    ws_client: Arc<WebSocketClient>,
3553    connection_epoch: u64,
3554    clock: &'static AtomicTime,
3555    auth_timeout_secs: u64,
3556    signal: Arc<AtomicBool>,
3557    abort: CancellationToken,
3558) {
3559    if signal.load(Ordering::Acquire) || abort.is_cancelled() {
3560        return;
3561    }
3562
3563    if ws_client.connection_epoch() != connection_epoch || !ws_client.is_active() {
3564        return;
3565    }
3566
3567    let result = tokio::select! {
3568        biased;
3569        () = abort.cancelled() => return,
3570        result = authenticate_session(
3571            &credential,
3572            &auth_tracker,
3573            &ws_client,
3574            connection_epoch,
3575            clock,
3576            auth_timeout_secs,
3577        ) => result,
3578    };
3579
3580    match result {
3581        Ok(()) => log::debug!("Re-authenticated after reconnection"),
3582        Err(e) => {
3583            if signal.load(Ordering::Acquire)
3584                || abort.is_cancelled()
3585                || ws_client.connection_epoch() != connection_epoch
3586                || auth_tracker.is_authenticated()
3587            {
3588                return;
3589            }
3590
3591            log::warn!("Re-authentication failed, reconnecting: {e}");
3592            let _ = ws_client.reconnect_handle().request_reconnect();
3593        }
3594    }
3595}
3596
3597pub(crate) fn ws_channel_for_book(channel: OKXBookChannel) -> OKXWsChannel {
3598    match channel {
3599        OKXBookChannel::Book => OKXWsChannel::Books,
3600        OKXBookChannel::BookL2Tbt => OKXWsChannel::BooksTbt,
3601        OKXBookChannel::Books50L2Tbt => OKXWsChannel::Books50Tbt,
3602        OKXBookChannel::BooksRpi => OKXWsChannel::BooksRpi,
3603        OKXBookChannel::SprdBooks5 => OKXWsChannel::SprdBooks5,
3604    }
3605}
3606
3607fn log_receiver_dropped(signal: &AtomicBool, item: &str) {
3608    if signal.load(Ordering::Acquire) {
3609        log::debug!("Receiver dropped after stop signal while forwarding {item}");
3610    } else {
3611        log::error!("Failed to send {item} through channel: receiver dropped");
3612    }
3613}
3614
3615#[cfg(test)]
3616mod tests {
3617    use futures_util::StreamExt;
3618    use nautilus_core::time::get_atomic_clock_realtime;
3619    use nautilus_live::{SocketReconnectRegistry, SocketReconnectRequestOutcome};
3620    use nautilus_model::identifiers::ClientId;
3621    use nautilus_network::RECONNECTED;
3622    use rstest::rstest;
3623    use tokio_tungstenite::tungstenite::Message;
3624
3625    use super::*;
3626    use crate::{
3627        common::{
3628            consts::{OKX_POST_ONLY_CANCEL_SOURCE, OKX_VENUE},
3629            enums::{
3630                OKXExecType, OKXOrderCategory, OKXOrderStatus, OKXPriceType, OKXQuickMarginType,
3631                OKXSelfTradePreventionMode, OKXSide,
3632            },
3633        },
3634        websocket::{
3635            handler::is_post_only_auto_cancel,
3636            messages::{OKXOrderMsg, OKXWsFrame},
3637        },
3638    };
3639
3640    struct DropSignal(Option<tokio::sync::oneshot::Sender<()>>);
3641
3642    impl Drop for DropSignal {
3643        fn drop(&mut self) {
3644            if let Some(sender) = self.0.take() {
3645                let _ = sender.send(());
3646            }
3647        }
3648    }
3649
3650    struct BlockingDrop(Arc<(parking_lot::Mutex<bool>, parking_lot::Condvar)>);
3651
3652    impl Drop for BlockingDrop {
3653        fn drop(&mut self) {
3654            let (lock, condvar) = &*self.0;
3655            let mut released = lock.lock();
3656            condvar.wait_while(&mut released, |released| !*released);
3657        }
3658    }
3659
3660    #[rstest]
3661    #[case(OKXBookChannel::Book, OKXWsChannel::Books)]
3662    #[case(OKXBookChannel::BookL2Tbt, OKXWsChannel::BooksTbt)]
3663    #[case(OKXBookChannel::Books50L2Tbt, OKXWsChannel::Books50Tbt)]
3664    #[case(OKXBookChannel::BooksRpi, OKXWsChannel::BooksRpi)]
3665    #[case(OKXBookChannel::SprdBooks5, OKXWsChannel::SprdBooks5)]
3666    fn test_ws_channel_for_book(#[case] channel: OKXBookChannel, #[case] expected: OKXWsChannel) {
3667        assert_eq!(ws_channel_for_book(channel), expected);
3668    }
3669
3670    #[rstest]
3671    fn test_timestamp_format_for_websocket_auth() {
3672        let now = UnixNanos::new(1_700_000_000_999_999_999);
3673
3674        assert_eq!(authentication_timestamp(now), "1700000000");
3675    }
3676
3677    #[rstest]
3678    #[case(None, None)]
3679    #[case(Some(u64::MAX), Some(u64::MAX.to_string()))]
3680    fn test_order_request_exp_time(#[case] ttl_ms: Option<u64>, #[case] expected: Option<String>) {
3681        let client = OKXWebSocketClient::default().with_order_request_ttl_ms(ttl_ms);
3682
3683        assert_eq!(client.order_request_exp_time(), expected);
3684    }
3685
3686    #[rstest]
3687    fn test_subscription_args_are_sorted_by_topic() {
3688        let client = OKXWebSocketClient::default();
3689
3690        let args = [
3691            OKXSubscriptionArg {
3692                channel: OKXWsChannel::Instruments,
3693                inst_type: Some(OKXInstrumentType::Swap),
3694                inst_family: None,
3695                inst_id: None,
3696            },
3697            OKXSubscriptionArg {
3698                channel: OKXWsChannel::Instruments,
3699                inst_type: Some(OKXInstrumentType::Spot),
3700                inst_family: None,
3701                inst_id: None,
3702            },
3703            OKXSubscriptionArg {
3704                channel: OKXWsChannel::OpenInterest,
3705                inst_type: None,
3706                inst_family: Some(Ustr::from("BTC-USD")),
3707                inst_id: None,
3708            },
3709            OKXSubscriptionArg {
3710                channel: OKXWsChannel::Tickers,
3711                inst_type: None,
3712                inst_family: None,
3713                inst_id: Some(Ustr::from("ETH-USDT")),
3714            },
3715            OKXSubscriptionArg {
3716                channel: OKXWsChannel::Tickers,
3717                inst_type: None,
3718                inst_family: None,
3719                inst_id: Some(Ustr::from("BTC-USDT")),
3720            },
3721            OKXSubscriptionArg {
3722                channel: OKXWsChannel::Status,
3723                inst_type: None,
3724                inst_family: None,
3725                inst_id: None,
3726            },
3727        ];
3728
3729        client.record_subscriptions(&args);
3730
3731        let topics = subscription_args(&client.subscriptions, &client.subscriptions_state)
3732            .iter()
3733            .map(topic_from_subscription_arg)
3734            .collect::<Vec<_>>();
3735
3736        assert_eq!(
3737            topics,
3738            [
3739                "Instruments:Spot",
3740                "Instruments:Swap",
3741                "OpenInterest:BTC-USD",
3742                "Status",
3743                "Tickers:BTC-USDT",
3744                "Tickers:ETH-USDT",
3745            ]
3746        );
3747    }
3748
3749    #[rstest]
3750    #[case::channel_unknown(false, true)]
3751    #[case::symbol_unknown(true, false)]
3752    #[case::both_unknown(false, false)]
3753    fn subscription_lookup_does_not_intern_unknown_values(
3754        #[case] channel_known: bool,
3755        #[case] symbol_known: bool,
3756    ) {
3757        let state = SubscriptionState::new(OKX_WS_TOPIC_DELIMITER);
3758        state.mark_subscribe("Trades:BTC-USDT");
3759
3760        let channel = if channel_known {
3761            "Trades".to_string()
3762        } else {
3763            format!("unknown_okx_channel_{}", UUID4::new())
3764        };
3765
3766        let symbol = if symbol_known {
3767            "BTC-USDT".to_string()
3768        } else {
3769            format!("unknown_okx_symbol_{}", UUID4::new())
3770        };
3771
3772        let topic = format!("{channel}:{symbol}");
3773        let channel_before = Ustr::from_existing(&channel);
3774        let symbol_before = Ustr::from_existing(&symbol);
3775
3776        let subscribed = is_topic_subscribed(&state, &topic);
3777
3778        assert!(is_topic_subscribed(&state, "Trades:BTC-USDT"));
3779        assert!(!subscribed);
3780        assert_eq!(channel_before.is_some(), channel_known);
3781        assert_eq!(symbol_before.is_some(), symbol_known);
3782        assert_eq!(Ustr::from_existing(&channel), channel_before);
3783        assert_eq!(Ustr::from_existing(&symbol), symbol_before);
3784        assert_eq!(state.all_topics(), vec!["Trades:BTC-USDT".to_string()]);
3785    }
3786
3787    #[rstest]
3788    fn pending_unsubscribe_is_excluded_from_replay_arguments() {
3789        let client = OKXWebSocketClient::default();
3790
3791        let canceled = OKXSubscriptionArg {
3792            channel: OKXWsChannel::Trades,
3793            inst_type: None,
3794            inst_family: None,
3795            inst_id: Some(Ustr::from("BTC-USDT")),
3796        };
3797
3798        let retained = OKXSubscriptionArg {
3799            inst_id: Some(Ustr::from("ETH-USDT")),
3800            ..canceled.clone()
3801        };
3802
3803        client.record_subscriptions(&[canceled.clone(), retained.clone()]);
3804        let topic = topic_from_subscription_arg(&canceled);
3805        client.subscriptions_state.mark_unsubscribe(&topic);
3806
3807        client.subscriptions_state.reset_after_reconnect();
3808        let args = subscription_args(&client.subscriptions, &client.subscriptions_state);
3809
3810        assert!(client.subscriptions.contains_key(&topic));
3811        assert_eq!(args.len(), 1);
3812        assert_eq!(args[0].channel, retained.channel);
3813        assert_eq!(args[0].inst_id, retained.inst_id);
3814        assert_eq!(args[0].inst_type, None);
3815        assert_eq!(args[0].inst_family, None);
3816    }
3817
3818    #[tokio::test]
3819    async fn subscribe_during_connect_reaches_initialized_handler() {
3820        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3821        let addr = listener.local_addr().unwrap();
3822        let (received_tx, received_rx) = tokio::sync::oneshot::channel();
3823
3824        let server = tokio::spawn(async move {
3825            let (socket, _) = listener.accept().await.unwrap();
3826            let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
3827            if let Some(Ok(message)) = socket.next().await {
3828                let _ = received_tx.send(message);
3829
3830                while matches!(socket.next().await, Some(Ok(_))) {}
3831            }
3832        });
3833
3834        let mut ws_client = OKXWebSocketClient::new(
3835            Some(format!("ws://{addr}")),
3836            None,
3837            None,
3838            None,
3839            None,
3840            None,
3841            None,
3842            TransportBackend::default(),
3843            None,
3844        )
3845        .unwrap();
3846        let observer = ws_client.clone();
3847        let sender = Arc::clone(&ws_client.cmd_tx);
3848        let publication = sender.read().await;
3849        let mut connect = Box::pin(ws_client.connect());
3850
3851        tokio::time::timeout(Duration::from_secs(5), async {
3852            loop {
3853                assert!(futures_util::poll!(connect.as_mut()).is_pending());
3854
3855                if sender.try_read().is_err() {
3856                    break;
3857                }
3858
3859                tokio::task::yield_now().await;
3860            }
3861        })
3862        .await
3863        .expect("connect must wait to publish its sender");
3864
3865        let active_before_publication = observer.is_active();
3866        let mut subscribe =
3867            Box::pin(observer.subscribe_inst_id(OKXWsChannel::Trades, Ustr::from("BTC-USDT")));
3868        assert!(futures_util::poll!(subscribe.as_mut()).is_pending());
3869
3870        // Queue a writer behind Subscribe to hold any later SetClient read lock
3871        let mut barrier = Box::pin(sender.write());
3872        assert!(futures_util::poll!(barrier.as_mut()).is_pending());
3873        drop(publication);
3874        let connect_result = futures_util::poll!(connect.as_mut());
3875        subscribe.await.expect("concurrent subscribe command");
3876        let barrier = barrier.await;
3877        let received = tokio::time::timeout(Duration::from_secs(2), received_rx).await;
3878        drop(barrier);
3879
3880        if let std::task::Poll::Ready(result) = connect_result {
3881            result.expect("connect failed");
3882        } else {
3883            connect.as_mut().await.expect("connect failed");
3884        }
3885
3886        drop(connect);
3887        ws_client.close().await.expect("close failed");
3888        server.await.expect("server task failed");
3889
3890        assert!(
3891            !active_before_publication,
3892            "active before sender publication"
3893        );
3894        let message = received.expect("subscription must reach server").unwrap();
3895
3896        let Message::Text(text) = message else {
3897            panic!("expected text subscription")
3898        };
3899
3900        let payload: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
3901        assert_eq!(
3902            payload,
3903            serde_json::json!({
3904                "op": "subscribe",
3905                "args": [{ "channel": "trades", "instId": "BTC-USDT" }],
3906            })
3907        );
3908    }
3909
3910    #[rstest]
3911    #[tokio::test]
3912    async fn begin_shutdown_stops_handler_before_bounded_close() {
3913        let client_id = ClientId::from("OKX-TEST");
3914        let endpoint = Ustr::from("okx-test-stream");
3915        let registry = SocketReconnectRegistry::default();
3916        let control =
3917            SocketControl::with_registry(client_id, Some(*OKX_VENUE), endpoint, &registry);
3918        let _sink = control.sink();
3919        control.register(|| SocketReconnectRequestOutcome::Accepted);
3920        let mut client = OKXWebSocketClient::default().with_socket_control(control);
3921        client
3922            .connection_mode
3923            .load()
3924            .store(ConnectionMode::Active.as_u8(), Ordering::SeqCst);
3925        let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();
3926        let signal = DropSignal(Some(drop_tx));
3927        let handler_abort = CancellationToken::new();
3928        *client.handler_abort.lock() = handler_abort.clone();
3929        client
3930            .handler_tasks
3931            .spawn(async move {
3932                let _signal = signal;
3933                handler_abort.cancelled().await;
3934            })
3935            .expect("handler task should register");
3936
3937        assert!(registry.handle(client_id, endpoint).is_some());
3938        client.begin_shutdown();
3939
3940        tokio::time::timeout(Duration::from_secs(1), drop_rx)
3941            .await
3942            .expect("begin shutdown must drop the handler task")
3943            .expect("drop signal");
3944        assert!(client.is_closed());
3945        assert!(!client.handler_tasks.is_open());
3946        assert!(registry.handle(client_id, endpoint).is_some());
3947
3948        client.close().await.expect("bounded close");
3949        assert!(!client.has_task());
3950        assert!(registry.handle(client_id, endpoint).is_none());
3951    }
3952
3953    #[rstest]
3954    #[tokio::test]
3955    async fn connect_rollback_closes_handler_admission_and_deregisters_socket() {
3956        let client_id = ClientId::from("OKX-CONNECT-ROLLBACK");
3957        let endpoint = Ustr::from("okx-connect-rollback");
3958        let registry = SocketReconnectRegistry::default();
3959        let control =
3960            SocketControl::with_registry(client_id, Some(*OKX_VENUE), endpoint, &registry);
3961        control.register(|| SocketReconnectRequestOutcome::Accepted);
3962        let handler_tasks = Arc::new(TaskGroup::new());
3963        let signal = Arc::new(AtomicBool::new(false));
3964        let handler_abort = CancellationToken::new();
3965
3966        let rollback = ConnectRollback {
3967            handler_tasks: Arc::clone(&handler_tasks),
3968            signal: Arc::clone(&signal),
3969            handler_abort: handler_abort.clone(),
3970            socket_control: Some(Arc::new(control)),
3971            armed: true,
3972        };
3973
3974        drop(rollback);
3975
3976        assert!(!handler_tasks.is_open());
3977        assert!(signal.load(Ordering::Acquire));
3978        assert!(handler_abort.is_cancelled());
3979        assert!(registry.handle(client_id, endpoint).is_none());
3980        handler_tasks
3981            .finish_shutdown(Duration::ZERO, Duration::from_secs(1))
3982            .await
3983            .expect("empty handler scope should drain");
3984    }
3985
3986    #[rstest]
3987    #[tokio::test]
3988    async fn request_close_signals_before_handler_shutdown() {
3989        let mut client = OKXWebSocketClient::default();
3990        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3991        client.cmd_tx = Arc::new(tokio::sync::RwLock::new(cmd_tx));
3992        client.signal.store(false, Ordering::Release);
3993
3994        client.request_close().await;
3995
3996        assert!(client.signal.load(Ordering::Acquire));
3997        assert!(matches!(cmd_rx.try_recv(), Ok(HandlerCommand::Disconnect)));
3998    }
3999
4000    #[rstest]
4001    #[tokio::test]
4002    async fn close_joins_handler_shared_with_clone() {
4003        let mut client = OKXWebSocketClient::default();
4004        let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();
4005        let signal = DropSignal(Some(drop_tx));
4006        client
4007            .handler_tasks
4008            .spawn(async move {
4009                let _signal = signal;
4010                std::future::pending::<()>().await;
4011            })
4012            .expect("handler task should register");
4013        let retained = client.clone();
4014
4015        client.close().await.expect("close with retained clone");
4016
4017        tokio::time::timeout(Duration::from_secs(1), drop_rx)
4018            .await
4019            .expect("close must drop the handler task")
4020            .expect("drop signal");
4021        assert!(!client.has_task());
4022        assert!(!retained.has_task());
4023    }
4024
4025    #[rstest]
4026    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4027    async fn timeout_retains_unfinished_handler_task() {
4028        let mut client = OKXWebSocketClient::default();
4029        let release = Arc::new((parking_lot::Mutex::new(false), parking_lot::Condvar::new()));
4030        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4031        let blocking_drop = BlockingDrop(Arc::clone(&release));
4032        client
4033            .handler_tasks
4034            .spawn(async move {
4035                let _blocking_drop = blocking_drop;
4036                started_tx.send(()).expect("started receiver");
4037                std::future::pending::<()>().await;
4038            })
4039            .expect("handler task should register");
4040        started_rx.await.expect("blocking task started");
4041        client.begin_shutdown();
4042
4043        let result = client.close_stream_task(Duration::from_millis(10)).await;
4044        let retained = client.has_task();
4045        let reconnect_result = client.connect().await;
4046
4047        let (lock, condvar) = &*release;
4048        *lock.lock() = true;
4049        condvar.notify_all();
4050
4051        client
4052            .close_stream_task(Duration::from_secs(1))
4053            .await
4054            .expect("blocking handler task terminated");
4055
4056        assert!(result.is_err());
4057        assert!(retained);
4058        assert_eq!(
4059            reconnect_result
4060                .expect_err("reconnect with unfinished handler")
4061                .to_string(),
4062            "Cannot connect while previous WebSocket handler task is still running"
4063        );
4064        assert!(!client.has_task());
4065    }
4066
4067    #[rstest]
4068    fn test_feed_handler_reconnection_detection() {
4069        let msg = Message::Text(RECONNECTED.to_string().into());
4070        let result = OKXWsFeedHandler::parse_raw_message(msg);
4071        assert!(matches!(result, Some(OKXWsFrame::Reconnected)));
4072    }
4073
4074    #[rstest]
4075    fn test_feed_handler_normal_message_processing() {
4076        let ping_msg = Message::Text(TEXT_PING.to_string().into());
4077        let result = OKXWsFeedHandler::parse_raw_message(ping_msg);
4078        assert!(matches!(result, Some(OKXWsFrame::Ping)));
4079
4080        let sub_msg = r#"{
4081            "event": "subscribe",
4082            "arg": {
4083                "channel": "tickers",
4084                "instType": "SPOT"
4085            },
4086            "connId": "a4d3ae55"
4087        }"#;
4088
4089        let sub_result =
4090            OKXWsFeedHandler::parse_raw_message(Message::Text(sub_msg.to_string().into()));
4091        assert!(matches!(sub_result, Some(OKXWsFrame::Subscription { .. })));
4092    }
4093
4094    #[rstest]
4095    fn test_feed_handler_close_message() {
4096        let result = OKXWsFeedHandler::parse_raw_message(Message::Close(None));
4097        assert!(result.is_none());
4098    }
4099
4100    #[rstest]
4101    fn test_reconnection_message_constant() {
4102        assert_eq!(RECONNECTED, "__RECONNECTED__");
4103    }
4104
4105    #[rstest]
4106    fn resubscribe_batches_subscription_args_into_venue_message_size() {
4107        let args: Vec<_> = (0..300)
4108            .map(|i| OKXSubscriptionArg {
4109                channel: OKXWsChannel::Tickers,
4110                inst_type: None,
4111                inst_family: None,
4112                inst_id: Some(Ustr::from(&format!("INST-{i}"))),
4113            })
4114            .collect();
4115
4116        let batches: Vec<_> = subscription_arg_batches(&args).collect();
4117
4118        assert_eq!(OKX_WS_SUBSCRIPTION_ARGS_MAX_PER_MESSAGE, 256);
4119        assert_eq!(batches.len(), 2);
4120        assert_eq!(batches[0].len(), 256);
4121        assert_eq!(batches[1].len(), 44);
4122    }
4123
4124    #[rstest]
4125    #[case::buffered_notifications(false)]
4126    #[case::notification_during_install(true)]
4127    fn buffered_reconnects_advance_only_the_active_epoch(#[case] install_window: bool) {
4128        let mut reconnect_epoch = 0;
4129        if install_window {
4130            let advanced = advance_reconnect_epoch(&mut reconnect_epoch, 2, false, false);
4131            assert!(!advanced);
4132            assert_eq!(reconnect_epoch, 0);
4133        }
4134
4135        let first = advance_reconnect_epoch(&mut reconnect_epoch, 2, false, true);
4136        let duplicate = advance_reconnect_epoch(&mut reconnect_epoch, 2, false, true);
4137        let next = advance_reconnect_epoch(&mut reconnect_epoch, 3, false, true);
4138
4139        assert!(first);
4140        assert!(!duplicate);
4141        assert!(next);
4142        assert_eq!(reconnect_epoch, 3);
4143    }
4144
4145    #[rstest]
4146    fn stopped_reconnect_does_not_advance_the_epoch() {
4147        let mut reconnect_epoch = 1;
4148        let advanced = advance_reconnect_epoch(&mut reconnect_epoch, 2, true, true);
4149
4150        assert!(!advanced);
4151        assert_eq!(reconnect_epoch, 1);
4152    }
4153
4154    #[rstest]
4155    #[tokio::test]
4156    async fn authenticate_session_sends_login_and_completes_on_success() {
4157        let (ws_client, mut received, server) = connect_auth_socket().await;
4158        let auth_tracker = AuthTracker::new();
4159        let credential = Credential::new("key".into(), "secret".into(), "pass".into());
4160        let clock = Box::leak(Box::new(AtomicTime::new(
4161            false,
4162            UnixNanos::new(1_700_000_000_999_999_999),
4163        )));
4164        let timestamp = authentication_timestamp(clock.get_time_ns());
4165        let signature = credential.sign(&timestamp, "GET", "/users/self/verify", "");
4166        let tracker = auth_tracker.clone();
4167
4168        let task = {
4169            let ws_client = Arc::clone(&ws_client);
4170
4171            tokio::spawn(async move {
4172                authenticate_session(
4173                    &credential,
4174                    &auth_tracker,
4175                    &ws_client,
4176                    ws_client.connection_epoch(),
4177                    clock,
4178                    5,
4179                )
4180                .await
4181            })
4182        };
4183
4184        let frame = tokio::time::timeout(Duration::from_secs(5), received.recv())
4185            .await
4186            .unwrap()
4187            .unwrap();
4188        let payload: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap();
4189        tracker.succeed();
4190        task.await.unwrap().unwrap();
4191        ws_client.disconnect().await;
4192        server.abort();
4193
4194        assert_eq!(payload.as_object().unwrap().len(), 2);
4195        assert_eq!(payload["op"], "login");
4196        assert_eq!(payload["args"].as_array().unwrap().len(), 1);
4197        assert_eq!(payload["args"][0].as_object().unwrap().len(), 4);
4198        assert_eq!(payload["args"][0]["apiKey"], "key");
4199        assert_eq!(payload["args"][0]["passphrase"], "pass");
4200        assert_eq!(payload["args"][0]["timestamp"], timestamp);
4201        assert_eq!(payload["args"][0]["sign"], signature);
4202    }
4203
4204    #[rstest]
4205    #[tokio::test]
4206    async fn authenticate_session_rejects_mismatched_epoch_without_resetting_tracker() {
4207        let (ws_client, mut received, server) = connect_auth_socket().await;
4208        let auth_tracker = AuthTracker::new();
4209        auth_tracker.succeed();
4210        let credential = Credential::new("key".into(), "secret".into(), "pass".into());
4211
4212        let error = authenticate_session(
4213            &credential,
4214            &auth_tracker,
4215            &ws_client,
4216            ws_client.connection_epoch() + 1,
4217            get_atomic_clock_realtime(),
4218            5,
4219        )
4220        .await
4221        .unwrap_err();
4222        let authenticated = auth_tracker.is_authenticated();
4223        let frame = received.try_recv();
4224        ws_client.disconnect().await;
4225        server.abort();
4226
4227        assert!(matches!(error, Error::Io(e) if matches!(
4228            e.get_ref().and_then(|e| e.downcast_ref::<SendError>()),
4229            Some(SendError::ConnectionChanged),
4230        )));
4231        assert!(authenticated);
4232        assert!(matches!(
4233            frame,
4234            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
4235        ));
4236    }
4237
4238    #[rstest]
4239    fn auth_attempt_superseded_matches_tracker_message() {
4240        let error = Error::Io(std::io::Error::other("Authentication attempt superseded"));
4241        assert!(auth_attempt_superseded(&error));
4242        let changed = Error::Io(std::io::Error::other(SendError::ConnectionChanged));
4243        assert!(auth_attempt_superseded(&changed));
4244        let other = Error::Io(std::io::Error::other("Authentication timed out"));
4245        assert!(!auth_attempt_superseded(&other));
4246    }
4247
4248    #[rstest]
4249    #[tokio::test]
4250    async fn reauthenticate_session_starts_fresh_attempt_when_tracker_is_authenticated() {
4251        let (ws_client, mut rx, server) = connect_auth_socket().await;
4252        let auth_tracker = AuthTracker::new();
4253        auth_tracker.succeed();
4254        let tracker = auth_tracker.clone();
4255
4256        let task = {
4257            let ws_client = Arc::clone(&ws_client);
4258
4259            tokio::spawn(reauthenticate_session(
4260                Credential::new("key".into(), "secret".into(), "pass".into()),
4261                auth_tracker,
4262                Arc::clone(&ws_client),
4263                ws_client.connection_epoch(),
4264                get_atomic_clock_realtime(),
4265                5,
4266                Arc::new(AtomicBool::new(false)),
4267                CancellationToken::new(),
4268            ))
4269        };
4270
4271        let received = tokio::time::timeout(Duration::from_secs(1), rx.recv())
4272            .await
4273            .unwrap()
4274            .unwrap();
4275        let authenticated_before_ack = tracker.is_authenticated();
4276        tracker.succeed();
4277        task.await.unwrap();
4278        ws_client.disconnect().await;
4279        server.abort();
4280
4281        let payload: Value = serde_json::from_str(received.to_text().unwrap()).unwrap();
4282        assert_eq!(payload["op"], "login");
4283        assert!(!authenticated_before_ack);
4284        assert!(tracker.is_authenticated());
4285    }
4286
4287    #[rstest]
4288    #[tokio::test]
4289    async fn reauthenticate_session_stops_when_aborted() {
4290        let (ws_client, mut rx, server) = connect_auth_socket().await;
4291        let abort = CancellationToken::new();
4292        abort.cancel();
4293
4294        tokio::time::timeout(
4295            Duration::from_millis(200),
4296            reauthenticate_session(
4297                Credential::new("key".into(), "secret".into(), "pass".into()),
4298                AuthTracker::new(),
4299                Arc::clone(&ws_client),
4300                ws_client.connection_epoch(),
4301                get_atomic_clock_realtime(),
4302                5,
4303                Arc::new(AtomicBool::new(false)),
4304                abort,
4305            ),
4306        )
4307        .await
4308        .expect("aborted authentication must return without waiting");
4309        let received = rx.try_recv();
4310        ws_client.disconnect().await;
4311        server.abort();
4312        assert!(matches!(
4313            received,
4314            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
4315        ));
4316    }
4317
4318    async fn connect_auth_socket() -> (
4319        Arc<WebSocketClient>,
4320        tokio::sync::mpsc::UnboundedReceiver<Message>,
4321        tokio::task::JoinHandle<()>,
4322    ) {
4323        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4324        let addr = listener.local_addr().unwrap();
4325        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
4326
4327        let server = tokio::spawn(async move {
4328            let (socket, _) = listener.accept().await.unwrap();
4329            let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
4330            while let Some(Ok(frame)) = socket.next().await {
4331                if tx.send(frame).is_err() {
4332                    break;
4333                }
4334            }
4335        });
4336
4337        let config = WebSocketConfig::builder()
4338            .url(format!("ws://{addr}"))
4339            .build()
4340            .unwrap();
4341        let ws_client = WebSocketClient::builder()
4342            .config(config)
4343            .message_handler(Arc::new(|_| {}))
4344            .connect()
4345            .await
4346            .unwrap();
4347        (Arc::new(ws_client), rx, server)
4348    }
4349
4350    #[rstest]
4351    fn test_multiple_reconnection_signals() {
4352        for _ in 0..3 {
4353            let msg = Message::Text(RECONNECTED.to_string().into());
4354            let result = OKXWsFeedHandler::parse_raw_message(msg);
4355            assert!(matches!(result, Some(OKXWsFrame::Reconnected)));
4356        }
4357    }
4358
4359    fn sample_canceled_order_msg() -> OKXOrderMsg {
4360        OKXOrderMsg {
4361            acc_fill_sz: Some("0".to_string()),
4362            avg_px: "0".to_string(),
4363            c_time: 0,
4364            cancel_source: None,
4365            cancel_source_reason: None,
4366            category: OKXOrderCategory::Normal,
4367            ccy: Ustr::from("USDT"),
4368            cl_ord_id: "order-1".to_string(),
4369            algo_cl_ord_id: None,
4370            attach_algo_cl_ord_id: None,
4371            attach_algo_ords: Vec::new(),
4372            outcome: None,
4373            fee: None,
4374            fee_ccy: Ustr::from("USDT"),
4375            fill_px: "0".to_string(),
4376            fill_sz: "0".to_string(),
4377            fill_time: 0,
4378            inst_id: Ustr::from("ETH-USDT-SWAP"),
4379            inst_type: OKXInstrumentType::Swap,
4380            lever: "1".to_string(),
4381            ord_id: Ustr::from("123456"),
4382            ord_type: OKXOrderType::Limit,
4383            pnl: "0".to_string(),
4384            pos_side: OKXPositionSide::Net,
4385            px: "0".to_string(),
4386            reduce_only: "false".to_string(),
4387            side: OKXSide::Buy,
4388            state: OKXOrderStatus::Canceled,
4389            exec_type: OKXExecType::None,
4390            sz: "1".to_string(),
4391            td_mode: OKXTradeMode::Cross,
4392            tgt_ccy: None,
4393            trade_id: String::new(),
4394            algo_id: None,
4395            fill_fee: None,
4396            fill_fee_ccy: None,
4397            fill_mark_px: None,
4398            fill_mark_vol: None,
4399            fill_px_vol: None,
4400            fill_px_usd: None,
4401            fill_fwd_px: None,
4402            fill_notional_usd: None,
4403            fill_pnl: None,
4404            is_tp_limit: None,
4405            linked_algo_ord: None,
4406            notional_usd: None,
4407            px_type: OKXPriceType::None,
4408            px_usd: None,
4409            px_vol: None,
4410            quick_mgn_type: OKXQuickMarginType::None,
4411            rebate: None,
4412            rebate_ccy: None,
4413            sl_ord_px: None,
4414            sl_trigger_px: None,
4415            sl_trigger_px_type: None,
4416            source: None,
4417            stp_id: None,
4418            stp_mode: OKXSelfTradePreventionMode::None,
4419            tag: None,
4420            tp_ord_px: None,
4421            tp_trigger_px: None,
4422            tp_trigger_px_type: None,
4423            amend_result: None,
4424            req_id: None,
4425            code: None,
4426            msg: None,
4427            u_time: 0,
4428        }
4429    }
4430
4431    #[rstest]
4432    fn test_is_post_only_auto_cancel_detects_cancel_source() {
4433        let mut msg = sample_canceled_order_msg();
4434        msg.cancel_source = Some(OKX_POST_ONLY_CANCEL_SOURCE.to_string());
4435
4436        assert!(is_post_only_auto_cancel(&msg));
4437    }
4438
4439    #[rstest]
4440    fn test_is_post_only_auto_cancel_detects_reason() {
4441        let mut msg = sample_canceled_order_msg();
4442        msg.cancel_source_reason = Some("POST_ONLY would take liquidity".to_string());
4443
4444        assert!(is_post_only_auto_cancel(&msg));
4445    }
4446
4447    #[rstest]
4448    fn test_is_post_only_auto_cancel_false_without_markers() {
4449        let msg = sample_canceled_order_msg();
4450
4451        assert!(!is_post_only_auto_cancel(&msg));
4452    }
4453
4454    #[rstest]
4455    fn test_is_post_only_auto_cancel_false_for_order_type_only() {
4456        let mut msg = sample_canceled_order_msg();
4457        msg.ord_type = OKXOrderType::PostOnly;
4458
4459        assert!(!is_post_only_auto_cancel(&msg));
4460    }
4461}