Skip to main content

nautilus_bybit/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//! Bybit WebSocket client providing public market data streaming.
17//!
18//! Bybit API reference <https://bybit-exchange.github.io/docs/>.
19
20use std::{
21    collections::HashSet,
22    fmt::Debug,
23    num::NonZeroU32,
24    sync::{
25        Arc,
26        atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
27    },
28    time::Duration,
29};
30
31use arc_swap::ArcSwap;
32#[cfg(test)]
33use nautilus_common::live::get_runtime;
34use nautilus_core::{AtomicMap, AtomicSet, UUID4, string::secret::SecretString};
35use nautilus_live::{
36    SocketControl,
37    book::snapshot::SnapshotGate,
38    task::{SharedTaskSlot, TaskJoinOutcome},
39};
40use nautilus_model::{
41    data::BarType,
42    enums::{AggregationSource, OrderSide, OrderType, PriceType, TimeInForce, TriggerType},
43    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
44    instruments::{Instrument, InstrumentAny},
45    types::{Price, Quantity},
46};
47use nautilus_network::{
48    ConnectionUrl,
49    http::create_standard_nautilus_headers,
50    mode::ConnectionMode,
51    ratelimiter::{RateLimiter, clock::MonotonicClock},
52    websocket::{
53        AuthTracker, InitialConnectRetryPolicy, SubscriptionState, TransportBackend,
54        WebSocketClient, WebSocketConfig, channel_message_handler,
55    },
56};
57use serde_json::Value;
58use tokio_util::sync::CancellationToken;
59use ustr::Ustr;
60use zeroize::Zeroizing;
61
62use crate::{
63    common::{
64        consts::{BYBIT_NAUTILUS_BROKER_ID, BYBIT_WS_TOPIC_DELIMITER},
65        credential::Credential,
66        enums::{
67            BybitBboSideType, BybitEnvironment, BybitOrderSide, BybitOrderSmpType, BybitOrderType,
68            BybitPositionIdx, BybitProductType, BybitTimeInForce, BybitTpSlMode,
69            BybitWsOrderRequestOp, resolve_trigger_type,
70        },
71        parse::{
72            bar_spec_to_bybit_interval, extract_base_coin, extract_raw_symbol, map_time_in_force,
73            spot_leverage, spot_market_unit, trigger_direction,
74        },
75        rate_limit::{
76            BYBIT_OPTION_SUBSCRIPTION_LIMIT, BybitRateLimiter, batch_send_limit, batch_weight,
77            websocket_connection_key, websocket_connection_limiter,
78        },
79        symbol::BybitSymbol,
80        urls::{bybit_ws_private_url, bybit_ws_public_url, bybit_ws_trade_url},
81    },
82    http::client::BybitHttpClient,
83    websocket::{
84        enums::{BybitWsOperation, BybitWsPrivateChannel, BybitWsPublicChannel},
85        error::{BybitWsError, BybitWsResult},
86        handler::{BybitWsFeedHandler, BybitWsOrderCommand, HandlerCommand},
87        messages::{
88            BybitAuthRequest, BybitSubscription, BybitWsAmendOrderParams, BybitWsBatchAmendItem,
89            BybitWsBatchAmendOrderArgs, BybitWsBatchCancelItem, BybitWsBatchCancelOrderArgs,
90            BybitWsBatchPlaceItem, BybitWsBatchPlaceOrderArgs, BybitWsCancelOrderParams,
91            BybitWsMessage, BybitWsPlaceOrderParams,
92        },
93    },
94};
95
96const WEBSOCKET_AUTH_WINDOW_MS: i64 = 5_000;
97const AUTH_WAIT_TIMEOUT: Duration = Duration::from_secs(5);
98/// Legacy non-Spot batch endpoint maximum.
99pub const BATCH_PROCESSING_LIMIT: usize = 20;
100/// Public/market data WebSocket client for Bybit.
101pub struct BybitWebSocketClient {
102    url: ConnectionUrl,
103    environment: BybitEnvironment,
104    product_type: Option<BybitProductType>,
105    credential: Option<Credential>,
106    http_client: Option<BybitHttpClient>,
107    requires_auth: bool,
108    auth_tracker: AuthTracker,
109    heartbeat: Option<u64>,
110    auth_wait_timeout: Duration,
111    connection_mode: Arc<ArcSwap<AtomicU8>>,
112    cmd_tx: Arc<tokio::sync::RwLock<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>>,
113    out_rx: Option<Arc<tokio::sync::mpsc::UnboundedReceiver<BybitWsMessage>>>,
114    signal: Arc<AtomicBool>,
115    task_handle: Arc<SharedTaskSlot<()>>,
116    connect_lock: Arc<tokio::sync::Mutex<()>>,
117    subscriptions: SubscriptionState,
118    subscription_guard: Arc<tokio::sync::Mutex<()>>,
119    rate_limiter: BybitRateLimiter,
120    recv_window_ms: Arc<AtomicU64>,
121    account_id: Option<AccountId>,
122    bar_types_cache: Arc<AtomicMap<String, BarType>>,
123    instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
124    trade_subs: Arc<AtomicSet<InstrumentId>>,
125    option_greeks_subs: Arc<AtomicSet<InstrumentId>>,
126    transport_backend: TransportBackend,
127    cancellation_token: Arc<ArcSwap<CancellationToken>>,
128    proxy_url: Option<SecretString>,
129    socket_control: Option<SocketControl>,
130}
131
132struct ConnectRollback {
133    signal: Arc<AtomicBool>,
134    cancellation_token: Arc<ArcSwap<CancellationToken>>,
135    task_handle: Arc<SharedTaskSlot<()>>,
136    armed: bool,
137}
138
139impl ConnectRollback {
140    fn new(client: &BybitWebSocketClient) -> Self {
141        Self {
142            signal: Arc::clone(&client.signal),
143            cancellation_token: Arc::clone(&client.cancellation_token),
144            task_handle: Arc::clone(&client.task_handle),
145            armed: true,
146        }
147    }
148
149    fn disarm(&mut self) {
150        self.armed = false;
151    }
152}
153
154impl Drop for ConnectRollback {
155    fn drop(&mut self) {
156        if self.armed {
157            self.signal.store(true, Ordering::Release);
158            self.cancellation_token.load().cancel();
159            self.task_handle.abort();
160        }
161    }
162}
163
164impl Debug for BybitWebSocketClient {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        f.debug_struct(stringify!(BybitWebSocketClient))
167            .field("url", &self.url)
168            .field("environment", &self.environment)
169            .field("product_type", &self.product_type)
170            .field("requires_auth", &self.requires_auth)
171            .field("heartbeat", &self.heartbeat)
172            .field("confirmed_subscriptions", &self.subscriptions.len())
173            .finish()
174    }
175}
176
177impl Clone for BybitWebSocketClient {
178    fn clone(&self) -> Self {
179        Self {
180            url: self.url.clone(),
181            environment: self.environment,
182            product_type: self.product_type,
183            credential: self.credential.clone(),
184            http_client: self.http_client.clone(),
185            requires_auth: self.requires_auth,
186            auth_tracker: self.auth_tracker.clone(),
187            heartbeat: self.heartbeat,
188            auth_wait_timeout: self.auth_wait_timeout,
189            connection_mode: Arc::clone(&self.connection_mode),
190            cmd_tx: Arc::clone(&self.cmd_tx),
191            out_rx: None, // Each clone gets its own receiver
192            signal: Arc::clone(&self.signal),
193            task_handle: Arc::clone(&self.task_handle),
194            connect_lock: Arc::clone(&self.connect_lock),
195            subscriptions: self.subscriptions.clone(),
196            subscription_guard: Arc::clone(&self.subscription_guard),
197            rate_limiter: self.rate_limiter.clone(),
198            recv_window_ms: Arc::clone(&self.recv_window_ms),
199            account_id: self.account_id,
200            bar_types_cache: Arc::clone(&self.bar_types_cache),
201            instruments_cache: Arc::clone(&self.instruments_cache),
202            trade_subs: Arc::clone(&self.trade_subs),
203            option_greeks_subs: Arc::clone(&self.option_greeks_subs),
204            transport_backend: self.transport_backend,
205            cancellation_token: Arc::clone(&self.cancellation_token),
206            proxy_url: self.proxy_url.clone(),
207            socket_control: self.socket_control.clone(),
208        }
209    }
210}
211
212impl BybitWebSocketClient {
213    fn initial_connect_retry_policy() -> InitialConnectRetryPolicy {
214        InitialConnectRetryPolicy {
215            max_attempts: NonZeroU32::new(5).expect("initial connect attempts must be non-zero"),
216            delay_initial: Duration::from_millis(500),
217            delay_max: Duration::from_secs(5),
218            backoff_factor: 2.0,
219            jitter_ms: 250,
220        }
221    }
222
223    /// Creates a new Bybit public WebSocket client.
224    #[must_use]
225    pub fn new_public(url: Option<String>, heartbeat: u64) -> Self {
226        Self::new_public_with(
227            BybitProductType::Linear,
228            BybitEnvironment::Mainnet,
229            url,
230            heartbeat,
231            TransportBackend::default(),
232            None,
233        )
234    }
235
236    /// Sets the timeout for waiting on (re)authentication before failing an
237    /// authenticated operation. Defaults to `AUTH_WAIT_TIMEOUT` (5s).
238    pub fn set_auth_wait_timeout(&mut self, timeout: Duration) {
239        self.auth_wait_timeout = timeout;
240    }
241
242    /// Sets the receive window sent with WebSocket trade commands.
243    pub fn set_recv_window_ms(&self, recv_window_ms: u64) {
244        self.recv_window_ms.store(recv_window_ms, Ordering::Release);
245    }
246
247    /// Creates a new Bybit public WebSocket client targeting the specified product/environment.
248    #[must_use]
249    pub fn new_public_with(
250        product_type: BybitProductType,
251        environment: BybitEnvironment,
252        url: Option<String>,
253        heartbeat: u64,
254        transport_backend: TransportBackend,
255        proxy_url: Option<String>,
256    ) -> Self {
257        let (cmd_tx, _cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
258
259        let initial_mode = AtomicU8::new(ConnectionMode::Closed.as_u8());
260        let connection_mode = Arc::new(ArcSwap::from_pointee(initial_mode));
261        let resolved_url = url.unwrap_or_else(|| bybit_ws_public_url(product_type, environment));
262        let rate_limiter =
263            BybitRateLimiter::for_websocket(&resolved_url, None, proxy_url.as_deref());
264
265        Self {
266            url: resolved_url.into(),
267            environment,
268            product_type: Some(product_type),
269            credential: None,
270            http_client: None,
271            requires_auth: false,
272            auth_tracker: AuthTracker::new(),
273            heartbeat: Some(heartbeat),
274            auth_wait_timeout: AUTH_WAIT_TIMEOUT,
275            connection_mode,
276            cmd_tx: Arc::new(tokio::sync::RwLock::new(cmd_tx)),
277            out_rx: None,
278            signal: Arc::new(AtomicBool::new(false)),
279            task_handle: Arc::new(SharedTaskSlot::new()),
280            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
281            subscriptions: SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER),
282            subscription_guard: Arc::new(tokio::sync::Mutex::new(())),
283            rate_limiter,
284            recv_window_ms: Arc::new(AtomicU64::new(5_000)),
285            bar_types_cache: Arc::new(AtomicMap::new()),
286            instruments_cache: Arc::new(AtomicMap::new()),
287            trade_subs: Arc::new(AtomicSet::new()),
288            option_greeks_subs: Arc::new(AtomicSet::new()),
289            account_id: None,
290            transport_backend,
291            cancellation_token: Arc::new(ArcSwap::from_pointee(CancellationToken::new())),
292            proxy_url: proxy_url.map(SecretString::from),
293            socket_control: None,
294        }
295    }
296
297    /// Configures socket state reporting and reconnect control.
298    #[must_use]
299    pub fn with_socket_control(mut self, control: SocketControl) -> Self {
300        self.socket_control = Some(control);
301        self
302    }
303
304    /// Creates a new Bybit private WebSocket client.
305    ///
306    /// If `api_key` or `api_secret` are not provided, they will be loaded from
307    /// environment variables based on the environment:
308    /// - Demo: `BYBIT_DEMO_API_KEY`, `BYBIT_DEMO_API_SECRET`
309    /// - Testnet: `BYBIT_TESTNET_API_KEY`, `BYBIT_TESTNET_API_SECRET`
310    /// - Mainnet: `BYBIT_API_KEY`, `BYBIT_API_SECRET`
311    #[must_use]
312    pub fn new_private(
313        environment: BybitEnvironment,
314        api_key: Option<String>,
315        api_secret: Option<String>,
316        url: Option<String>,
317        heartbeat: u64,
318        transport_backend: TransportBackend,
319        proxy_url: Option<String>,
320    ) -> Self {
321        let credential = Credential::resolve(api_key, api_secret, environment);
322
323        let (cmd_tx, _cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
324
325        let initial_mode = AtomicU8::new(ConnectionMode::Closed.as_u8());
326        let connection_mode = Arc::new(ArcSwap::from_pointee(initial_mode));
327        let resolved_url = url.unwrap_or_else(|| bybit_ws_private_url(environment).to_string());
328        let rate_limiter = BybitRateLimiter::for_websocket(
329            &resolved_url,
330            credential.as_ref().map(Credential::api_key),
331            proxy_url.as_deref(),
332        );
333
334        Self {
335            url: resolved_url.into(),
336            environment,
337            product_type: None,
338            credential,
339            http_client: None,
340            requires_auth: true,
341            auth_tracker: AuthTracker::new(),
342            heartbeat: Some(heartbeat),
343            auth_wait_timeout: AUTH_WAIT_TIMEOUT,
344            connection_mode,
345            cmd_tx: Arc::new(tokio::sync::RwLock::new(cmd_tx)),
346            out_rx: None,
347            signal: Arc::new(AtomicBool::new(false)),
348            task_handle: Arc::new(SharedTaskSlot::new()),
349            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
350            subscriptions: SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER),
351            subscription_guard: Arc::new(tokio::sync::Mutex::new(())),
352            rate_limiter,
353            recv_window_ms: Arc::new(AtomicU64::new(5_000)),
354            bar_types_cache: Arc::new(AtomicMap::new()),
355            instruments_cache: Arc::new(AtomicMap::new()),
356            trade_subs: Arc::new(AtomicSet::new()),
357            option_greeks_subs: Arc::new(AtomicSet::new()),
358            account_id: None,
359            transport_backend,
360            cancellation_token: Arc::new(ArcSwap::from_pointee(CancellationToken::new())),
361            proxy_url: proxy_url.map(SecretString::from),
362            socket_control: None,
363        }
364    }
365
366    /// Creates a new Bybit trade WebSocket client for order operations.
367    ///
368    /// Uses the HTTP client's credentials and detects the market-maker level
369    /// in the background through its API-key information endpoint on first use.
370    #[must_use]
371    pub fn new_trade(
372        environment: BybitEnvironment,
373        http_client: BybitHttpClient,
374        url: Option<String>,
375        heartbeat: u64,
376        transport_backend: TransportBackend,
377        proxy_url: Option<String>,
378    ) -> Self {
379        let credential = http_client.credential().cloned();
380
381        let (cmd_tx, _) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
382
383        let initial_mode = AtomicU8::new(ConnectionMode::Closed.as_u8());
384        let connection_mode = Arc::new(ArcSwap::from_pointee(initial_mode));
385        let resolved_url = url.unwrap_or_else(|| bybit_ws_trade_url(environment).to_string());
386        let rate_limiter = BybitRateLimiter::for_websocket(
387            &resolved_url,
388            credential.as_ref().map(Credential::api_key),
389            proxy_url.as_deref(),
390        );
391
392        Self {
393            url: resolved_url.into(),
394            environment,
395            product_type: None,
396            credential,
397            http_client: Some(http_client),
398            requires_auth: true,
399            auth_tracker: AuthTracker::new(),
400            heartbeat: Some(heartbeat),
401            auth_wait_timeout: AUTH_WAIT_TIMEOUT,
402            connection_mode,
403            cmd_tx: Arc::new(tokio::sync::RwLock::new(cmd_tx)),
404            out_rx: None,
405            signal: Arc::new(AtomicBool::new(false)),
406            task_handle: Arc::new(SharedTaskSlot::new()),
407            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
408            subscriptions: SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER),
409            subscription_guard: Arc::new(tokio::sync::Mutex::new(())),
410            rate_limiter,
411            recv_window_ms: Arc::new(AtomicU64::new(5_000)),
412            bar_types_cache: Arc::new(AtomicMap::new()),
413            instruments_cache: Arc::new(AtomicMap::new()),
414            trade_subs: Arc::new(AtomicSet::new()),
415            option_greeks_subs: Arc::new(AtomicSet::new()),
416            account_id: None,
417            transport_backend,
418            cancellation_token: Arc::new(ArcSwap::from_pointee(CancellationToken::new())),
419            proxy_url: proxy_url.map(SecretString::from),
420            socket_control: None,
421        }
422    }
423
424    pub(crate) fn begin_shutdown(&self) {
425        self.cancellation_token.load().cancel();
426        self.signal.store(true, Ordering::Release);
427    }
428
429    /// Establishes the WebSocket connection.
430    ///
431    /// Clears subscription state from earlier sessions, so callers resubscribe after connecting.
432    ///
433    /// # Errors
434    ///
435    /// Returns an error if the underlying WebSocket connection cannot be established,
436    /// after retrying multiple times with exponential backoff.
437    pub async fn connect(&mut self) -> BybitWsResult<()> {
438        let connect_lock = Arc::clone(&self.connect_lock);
439        let _guard = connect_lock.lock().await;
440        self.connect_locked().await
441    }
442
443    async fn connect_locked(&mut self) -> BybitWsResult<()> {
444        if !self.task_handle.is_empty() {
445            self.close_locked().await?;
446        }
447
448        self.signal.store(false, Ordering::Relaxed);
449        let cancellation_token = CancellationToken::new();
450        self.cancellation_token
451            .store(Arc::new(cancellation_token.clone()));
452
453        if let Some(http_client) = &self.http_client {
454            http_client.start_mm_detection();
455        }
456
457        let (raw_handler, raw_rx) = channel_message_handler();
458
459        // Inbound Ping frames are answered by the transport, so no ping handler is needed;
460        // the reader routes them away from the message channel and the handler never sees them.
461
462        let ping_msg = serde_json::to_string(&BybitSubscription {
463            op: BybitWsOperation::Ping,
464            args: vec![],
465            req_id: None,
466        })?;
467
468        let config = WebSocketConfig {
469            url: self.url.expose().to_owned(),
470            headers: Self::default_headers(),
471            heartbeat_interval_secs: self.heartbeat,
472            heartbeat_payload: Some(ping_msg),
473            connect_timeout_ms: Some(5_000),
474            reconnect_delay_initial_ms: Some(500),
475            reconnect_delay_max_ms: Some(5_000),
476            reconnect_backoff_factor: Some(1.5),
477            reconnect_jitter_ms: Some(250),
478            reconnect_max_attempts: None,
479            heartbeat_timeout_secs: None,
480            idle_timeout_ms: None,
481            writer_capacity: None,
482            backend: self.transport_backend,
483            proxy_url: self
484                .proxy_url
485                .as_ref()
486                .map(|value| value.expose_secret().to_owned()),
487            max_message_size_bytes: None,
488            max_frame_size_bytes: None,
489        };
490
491        let message_rate_limiter = Arc::new(RateLimiter::<Ustr, MonotonicClock>::new_with_quota(
492            None,
493            vec![],
494        ));
495        let connection_rate_limiter = websocket_connection_limiter(
496            self.url.expose(),
497            self.proxy_url.as_ref().map(SecretString::expose_secret),
498        );
499        let connection_rate_keys: Arc<[Ustr]> = Arc::from([websocket_connection_key()]);
500        let client = WebSocketClient::builder()
501            .config(config.clone())
502            .message_handler(raw_handler.clone())
503            .rate_limiter(Arc::clone(&message_rate_limiter))
504            .connection_rate_limiter(Arc::clone(&connection_rate_limiter))
505            .connection_rate_keys(Arc::clone(&connection_rate_keys))
506            .initial_connect_retry_policy(Self::initial_connect_retry_policy())
507            .cancellation_token(cancellation_token)
508            .maybe_state_sink(self.socket_control.as_ref().map(SocketControl::sink))
509            .connect()
510            .await
511            .map_err(|e| {
512                BybitWsError::Transport(format!(
513                    "WebSocket connection failed: {}: {}",
514                    self.url.origin(),
515                    e.redacted_message()
516                ))
517            })?;
518
519        let connection_mode = client.connection_mode_atomic();
520        let reconnect_handle = client.reconnect_handle();
521        client.set_auth_tracker(self.auth_tracker.clone(), self.requires_auth);
522
523        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<BybitWsMessage>();
524        self.out_rx = Some(Arc::new(out_rx));
525
526        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
527
528        // Queue the client first so no subscribe reaches the handler before it
529        cmd_tx
530            .send(HandlerCommand::SetClient(client))
531            .map_err(|e| BybitWsError::Send(e.to_string()))?;
532
533        {
534            // Commands sent before this swap went to a closed channel and close skips
535            // unsubscribes, so the new session starts from clean subscription state.
536            let _guard = self.subscription_guard.lock().await;
537            let mut command_sender = self.cmd_tx.write().await;
538            self.subscriptions.clear();
539            *command_sender = cmd_tx.clone();
540            self.connection_mode.store(connection_mode);
541        }
542
543        let signal = Arc::clone(&self.signal);
544        let subscriptions = self.subscriptions.clone();
545        let credential = self.credential.clone();
546        let requires_auth = self.requires_auth;
547        let cmd_tx_for_reconnect = cmd_tx.clone();
548        let auth_tracker = self.auth_tracker.clone();
549        let auth_tracker_for_handler = auth_tracker.clone();
550        let rate_limiter = self.rate_limiter.clone();
551        let recv_window_ms = Arc::clone(&self.recv_window_ms);
552        let mut rollback = ConnectRollback::new(self);
553
554        if let Err(e) = self.task_handle.spawn(async move {
555            let mut handler = BybitWsFeedHandler::new(
556                signal.clone(),
557                cmd_rx,
558                raw_rx,
559                auth_tracker_for_handler,
560                subscriptions.clone(),
561                rate_limiter,
562                recv_window_ms,
563            );
564
565            // Resubscribe all tracked subscriptions after reconnection
566            let resubscribe_all = || async {
567                let topics = subscriptions.all_topics();
568
569                if topics.is_empty() {
570                    return;
571                }
572
573                log::debug!(
574                    "Resubscribing to confirmed subscriptions: count={}",
575                    topics.len()
576                );
577
578                for topic in &topics {
579                    subscriptions.mark_subscribe(topic.as_str());
580                }
581
582                let mut payloads = Vec::with_capacity(topics.len());
583                for topic in &topics {
584                    let message = BybitSubscription {
585                        op: BybitWsOperation::Subscribe,
586                        args: vec![topic.clone()],
587                        req_id: Some(topic.clone()),
588                    };
589
590                    if let Ok(payload) = serde_json::to_string(&message) {
591                        payloads.push(payload);
592                    }
593                }
594
595                let cmd = HandlerCommand::Subscribe { topics: payloads };
596
597                if let Err(e) = cmd_tx_for_reconnect.send(cmd) {
598                    log::error!("Failed to send resubscribe command: {e}");
599                }
600            };
601
602            // Run message processing with reconnection handling
603            loop {
604                match handler.next().await {
605                    Some(BybitWsMessage::Reconnected) => {
606                        if signal.load(Ordering::Relaxed) {
607                            continue;
608                        }
609
610                        log::info!("WebSocket reconnected");
611
612                        subscriptions.reset_after_reconnect();
613
614                        if requires_auth {
615                            log::debug!("Re-authenticating after reconnection");
616
617                            if let Some(cred) = &credential {
618                                // Begin auth attempt so succeed() will update state
619                                let _rx = auth_tracker.begin();
620
621                                let expires = jiff::Timestamp::now().as_millisecond()
622                                    + WEBSOCKET_AUTH_WINDOW_MS;
623                                let signature = cred.sign_websocket_auth(expires);
624
625                                let auth_message = Zeroizing::new(BybitAuthRequest {
626                                    op: BybitWsOperation::Auth,
627                                    args: vec![
628                                        Value::String(cred.api_key().to_string()),
629                                        Value::Number(expires.into()),
630                                        Value::String(signature),
631                                    ],
632                                });
633
634                                if let Ok(payload) =
635                                    serde_json::to_string(&*auth_message).map(SecretString::from)
636                                {
637                                    let cmd = HandlerCommand::Authenticate { payload };
638                                    if let Err(e) = cmd_tx_for_reconnect.send(cmd) {
639                                        log::error!(
640                                            "Failed to send reconnection auth command: error={e}"
641                                        );
642                                    }
643                                } else {
644                                    log::error!("Failed to serialize reconnection auth message");
645                                }
646                            }
647                        }
648
649                        // Unauthenticated sessions resubscribe immediately after reconnection,
650                        // authenticated sessions wait for Auth message
651                        if !requires_auth {
652                            log::debug!("No authentication required, resubscribing immediately");
653                            resubscribe_all().await;
654                        }
655
656                        // Forward to out_tx so caller sees the Reconnected message
657                        if out_tx.send(BybitWsMessage::Reconnected).is_err() {
658                            if handler.is_stopped() {
659                                log::debug!("Receiver dropped, stopping");
660                            } else {
661                                log::error!("Receiver dropped, stopping");
662                            }
663                            break;
664                        }
665                    }
666                    Some(BybitWsMessage::Auth(ref auth)) => {
667                        let is_success = auth.success.unwrap_or(false) || auth.ret_code == Some(0);
668                        if is_success {
669                            log::debug!("Authenticated, resubscribing");
670                            resubscribe_all().await;
671                        }
672
673                        if out_tx.send(BybitWsMessage::Auth(auth.clone())).is_err() {
674                            if handler.is_stopped() {
675                                log::debug!("Failed to send message (receiver dropped)");
676                            } else {
677                                log::error!("Failed to send message (receiver dropped)");
678                            }
679                            break;
680                        }
681                    }
682                    Some(msg) => {
683                        if out_tx.send(msg).is_err() {
684                            if handler.is_stopped() {
685                                log::debug!("Failed to send message (receiver dropped)");
686                            } else {
687                                log::error!("Failed to send message (receiver dropped)");
688                            }
689                            break;
690                        }
691                    }
692                    None => {
693                        // Stream ended - check if it's a stop signal
694                        if handler.is_stopped() {
695                            log::debug!("Stop signal received, ending message processing");
696                            break;
697                        }
698                        // Otherwise it's an unexpected stream end
699                        log::warn!("WebSocket stream ended unexpectedly");
700                        break;
701                    }
702                }
703            }
704
705            log::debug!("Handler task exiting");
706        }) {
707            let shutdown_result = self.close_locked().await;
708            return Err(BybitWsError::ClientError(match shutdown_result {
709                Ok(()) => format!("Failed to start WebSocket handler task: {e}"),
710                Err(shutdown_error) => format!(
711                    "Failed to start WebSocket handler task: {e}; startup rollback failed: \
712                     {shutdown_error}"
713                ),
714            }));
715        }
716
717        if let Some(control) = &self.socket_control {
718            control.register(move || reconnect_handle.request_reconnect());
719        }
720
721        if requires_auth && let Err(e) = self.authenticate_if_required().await {
722            let result = match self.close_locked().await {
723                Ok(()) => Err(e),
724                Err(shutdown_error) => Err(BybitWsError::ClientError(format!(
725                    "{e}; startup rollback failed: {shutdown_error}"
726                ))),
727            };
728            rollback.disarm();
729            return result;
730        }
731
732        rollback.disarm();
733        Ok(())
734    }
735
736    /// Disconnects the WebSocket client and stops the background task.
737    pub async fn close(&mut self) -> BybitWsResult<()> {
738        let connect_lock = Arc::clone(&self.connect_lock);
739        let _guard = connect_lock.lock().await;
740        self.close_locked().await
741    }
742
743    async fn close_locked(&self) -> BybitWsResult<()> {
744        log::debug!("Starting close process");
745
746        self.signal.store(true, Ordering::Relaxed);
747        self.cancellation_token.load().cancel();
748
749        let cmd = HandlerCommand::Disconnect;
750        if let Err(e) = self.cmd_tx.read().await.send(cmd) {
751            log::debug!(
752                "Failed to send disconnect command (handler may already be shut down): {e}"
753            );
754        }
755
756        let task_result = if self.task_handle.is_empty() {
757            log::debug!("No task handle to await");
758            Ok(())
759        } else {
760            log::debug!("Waiting for task handle to complete");
761
762            if let Some(outcome) = self
763                .task_handle
764                .finish(Duration::from_secs(2), Duration::from_secs(2))
765                .await
766            {
767                match outcome {
768                    TaskJoinOutcome::Completed(()) | TaskJoinOutcome::Aborted => Ok(()),
769                    TaskJoinOutcome::Failed(error) => Err(BybitWsError::ClientError(format!(
770                        "WebSocket handler task failed: {error}"
771                    ))),
772                    TaskJoinOutcome::Incomplete => Err(BybitWsError::ClientError(
773                        "WebSocket handler task did not stop after abort".to_string(),
774                    )),
775                }
776            } else {
777                Ok(())
778            }
779        };
780
781        self.auth_tracker.invalidate();
782
783        if let Some(control) = &self.socket_control {
784            control.deregister();
785        }
786
787        log::debug!("Closed");
788
789        task_result
790    }
791
792    /// Returns a value indicating whether the client is active.
793    #[must_use]
794    pub fn is_active(&self) -> bool {
795        let connection_mode_arc = self.connection_mode.load();
796        ConnectionMode::from_atomic(&connection_mode_arc).is_active()
797            && !self.signal.load(Ordering::Relaxed)
798    }
799
800    /// Returns a value indicating whether the client is closed.
801    pub fn is_closed(&self) -> bool {
802        let connection_mode_arc = self.connection_mode.load();
803        ConnectionMode::from_atomic(&connection_mode_arc).is_closed()
804            || self.signal.load(Ordering::Relaxed)
805    }
806
807    /// Waits until the WebSocket client becomes active or times out.
808    ///
809    /// # Errors
810    ///
811    /// Returns an error if the timeout is exceeded before the client becomes active.
812    pub async fn wait_until_active(&self, timeout_secs: f64) -> BybitWsResult<()> {
813        let timeout = tokio::time::Duration::from_secs_f64(timeout_secs);
814
815        tokio::time::timeout(timeout, async {
816            while !self.is_active() {
817                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
818            }
819        })
820        .await
821        .map_err(|_| {
822            BybitWsError::ClientError(format!(
823                "WebSocket connection timeout after {timeout_secs} seconds"
824            ))
825        })?;
826
827        Ok(())
828    }
829
830    /// Subscribe to the provided topic strings.
831    pub async fn subscribe(&self, topics: Vec<String>) -> BybitWsResult<()> {
832        if topics.is_empty() {
833            return Ok(());
834        }
835        let _guard = self.subscription_guard.lock().await;
836
837        log::debug!("Subscribing to topics: {topics:?}");
838
839        let payloads = self.register_subscribe(topics)?;
840
841        if payloads.is_empty() {
842            return Ok(());
843        }
844
845        let cmd = HandlerCommand::Subscribe { topics: payloads };
846        self.cmd_tx
847            .read()
848            .await
849            .send(cmd)
850            .map_err(|e| BybitWsError::Send(format!("Failed to send subscribe command: {e}")))?;
851
852        Ok(())
853    }
854
855    // Adds a reference to each topic, returning subscribe payloads for topics no other
856    // subscription holds; the caller holds the subscription guard
857    fn register_subscribe(&self, topics: Vec<String>) -> BybitWsResult<Vec<String>> {
858        if self.product_type == Some(BybitProductType::Option) {
859            let occupied_topics = self
860                .subscriptions
861                .all_topics()
862                .into_iter()
863                .chain(self.subscriptions.pending_unsubscribe_topics())
864                .collect::<HashSet<_>>();
865            let new_topics = topics
866                .iter()
867                .filter(|topic| !occupied_topics.contains(topic.as_str()))
868                .collect::<HashSet<_>>()
869                .len();
870            let requested = occupied_topics.len() + new_topics;
871            if requested > BYBIT_OPTION_SUBSCRIPTION_LIMIT {
872                return Err(BybitWsError::ClientError(format!(
873                    "Option WebSocket subscription limit is {BYBIT_OPTION_SUBSCRIPTION_LIMIT} arguments per connection, requested {requested}"
874                )));
875            }
876        }
877
878        // Use reference counting to deduplicate subscriptions
879        let mut topics_to_send = Vec::new();
880
881        for topic in topics {
882            // Returns true if this is the first subscription (ref count 0 -> 1)
883            if self.subscriptions.add_reference(&topic) {
884                self.subscriptions.mark_subscribe(&topic);
885                topics_to_send.push(topic.clone());
886            } else {
887                log::debug!("Already subscribed to {topic}, skipping duplicate subscription");
888            }
889        }
890
891        // Serialize subscription messages
892        let mut payloads = Vec::with_capacity(topics_to_send.len());
893        for topic in &topics_to_send {
894            let message = BybitSubscription {
895                op: BybitWsOperation::Subscribe,
896                args: vec![topic.clone()],
897                req_id: Some(topic.clone()),
898            };
899            let payload = serde_json::to_string(&message).map_err(|e| {
900                BybitWsError::Json(format!("Failed to serialize subscription: {e}"))
901            })?;
902            payloads.push(payload);
903        }
904
905        Ok(payloads)
906    }
907
908    /// Unsubscribe from the provided topics.
909    pub async fn unsubscribe(&self, topics: Vec<String>) -> BybitWsResult<()> {
910        if topics.is_empty() {
911            return Ok(());
912        }
913
914        log::debug!("Attempting to unsubscribe from topics: {topics:?}");
915
916        if self.signal.load(Ordering::Relaxed) {
917            log::debug!("Shutdown signal detected, skipping unsubscribe");
918            return Ok(());
919        }
920        let _guard = self.subscription_guard.lock().await;
921
922        // Use reference counting to avoid unsubscribing while other consumers still need the topic
923        let mut topics_to_send = Vec::new();
924
925        for topic in topics {
926            // Returns true if this was the last subscription (ref count 1 -> 0)
927            if self.subscriptions.remove_reference(&topic) {
928                self.subscriptions.mark_unsubscribe(&topic);
929                topics_to_send.push(topic.clone());
930            } else {
931                log::debug!("Topic {topic} still has active subscriptions, not unsubscribing");
932            }
933        }
934
935        if topics_to_send.is_empty() {
936            return Ok(());
937        }
938
939        // Serialize unsubscription messages
940        let mut payloads = Vec::with_capacity(topics_to_send.len());
941        for topic in &topics_to_send {
942            let message = BybitSubscription {
943                op: BybitWsOperation::Unsubscribe,
944                args: vec![topic.clone()],
945                req_id: Some(topic.clone()),
946            };
947
948            if let Ok(payload) = serde_json::to_string(&message) {
949                payloads.push(payload);
950            }
951        }
952
953        let cmd = HandlerCommand::Unsubscribe { topics: payloads };
954        if let Err(e) = self.cmd_tx.read().await.send(cmd) {
955            log::debug!("Failed to send unsubscribe command: error={e}");
956        }
957
958        Ok(())
959    }
960
961    /// Returns a stream of venue-typed [`BybitWsMessage`] items.
962    ///
963    /// # Panics
964    ///
965    /// Panics if called before [`Self::connect`] or if the stream has already been taken.
966    pub fn stream(&mut self) -> impl futures_util::Stream<Item = BybitWsMessage> + use<> {
967        let rx = self
968            .out_rx
969            .take()
970            .expect("Stream receiver already taken or client not connected");
971        let mut rx = Arc::try_unwrap(rx).expect("Cannot take ownership - other references exist");
972        async_stream::stream! {
973            while let Some(msg) = rx.recv().await {
974                yield msg;
975            }
976        }
977    }
978
979    /// Returns the number of currently registered subscriptions.
980    #[must_use]
981    pub fn subscription_count(&self) -> usize {
982        self.subscriptions.len()
983    }
984
985    /// Returns the credential associated with this client, if any.
986    #[must_use]
987    pub fn credential(&self) -> Option<&Credential> {
988        self.credential.as_ref()
989    }
990
991    /// Sets the account ID for account message parsing.
992    pub fn set_account_id(&mut self, account_id: AccountId) {
993        self.account_id = Some(account_id);
994    }
995
996    /// Returns the account ID if set.
997    #[must_use]
998    pub fn account_id(&self) -> Option<AccountId> {
999        self.account_id
1000    }
1001
1002    /// Returns the product type for public connections.
1003    #[must_use]
1004    pub fn product_type(&self) -> Option<BybitProductType> {
1005        self.product_type
1006    }
1007
1008    /// Returns a reference to the bar types cache.
1009    #[must_use]
1010    pub fn bar_types_cache(&self) -> &Arc<AtomicMap<String, BarType>> {
1011        &self.bar_types_cache
1012    }
1013
1014    /// Adds an instrument to the shared instruments cache.
1015    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1016        self.instruments_cache
1017            .insert(instrument.id().symbol.inner(), instrument);
1018    }
1019
1020    /// Returns a snapshot of the instruments cache keyed by symbol.
1021    #[must_use]
1022    pub fn instruments_snapshot(&self) -> ahash::AHashMap<Ustr, InstrumentAny> {
1023        (**self.instruments_cache.load()).clone()
1024    }
1025
1026    /// Adds an instrument ID to the option greeks subscription set.
1027    pub fn add_option_greeks_sub(&self, instrument_id: InstrumentId) {
1028        self.option_greeks_subs.insert(instrument_id);
1029    }
1030
1031    /// Removes an instrument ID from the option greeks subscription set.
1032    pub fn remove_option_greeks_sub(&self, instrument_id: &InstrumentId) {
1033        self.option_greeks_subs.remove(instrument_id);
1034    }
1035
1036    /// Returns a reference to the option greeks subscription set.
1037    #[must_use]
1038    pub fn option_greeks_subs(&self) -> &Arc<AtomicSet<InstrumentId>> {
1039        &self.option_greeks_subs
1040    }
1041
1042    /// Returns a reference to the trade subscriptions set.
1043    #[must_use]
1044    pub fn trade_subs(&self) -> &Arc<AtomicSet<InstrumentId>> {
1045        &self.trade_subs
1046    }
1047
1048    /// Returns a reference to the live instruments cache Arc.
1049    #[must_use]
1050    pub fn instruments_cache_ref(&self) -> &Arc<AtomicMap<Ustr, InstrumentAny>> {
1051        &self.instruments_cache
1052    }
1053
1054    /// Subscribes to orderbook updates for a specific instrument.
1055    ///
1056    /// # Errors
1057    ///
1058    /// Returns an error if the subscription request fails.
1059    ///
1060    /// # References
1061    ///
1062    /// <https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook>
1063    pub async fn subscribe_orderbook(
1064        &self,
1065        instrument_id: InstrumentId,
1066        depth: u32,
1067    ) -> BybitWsResult<()> {
1068        let topic = orderbook_topic(instrument_id, depth);
1069        self.subscribe(vec![topic]).await
1070    }
1071
1072    /// Subscribes to an order book topic, opening `gate` once the connection confirms the
1073    /// subscribe write.
1074    ///
1075    /// A topic another subscription already holds, such as the depth-1 topic quotes use, sends
1076    /// nothing and opens `gate` at once. A failed write returns [`BybitWsError::Transport`]; any
1077    /// other error means the request never reached the connection.
1078    pub(crate) async fn subscribe_book(
1079        &self,
1080        instrument_id: InstrumentId,
1081        depth: u32,
1082        cancel: CancellationToken,
1083        gate: SnapshotGate,
1084    ) -> BybitWsResult<()> {
1085        let (completion, receiver) = tokio::sync::oneshot::channel();
1086
1087        {
1088            let _guard = self.subscription_guard.lock().await;
1089            let topic = orderbook_topic(instrument_id, depth);
1090
1091            let Some(payload) = self.register_subscribe(vec![topic])?.pop() else {
1092                gate.open();
1093                return Ok(());
1094            };
1095
1096            let cmd = HandlerCommand::SubscribeBook {
1097                payload,
1098                gate,
1099                completion,
1100            };
1101
1102            self.cmd_tx.read().await.send(cmd).map_err(|e| {
1103                BybitWsError::Send(format!("Failed to send subscribe command: {e}"))
1104            })?;
1105        }
1106
1107        tokio::select! {
1108            biased;
1109            () = cancel.cancelled() => Ok(()),
1110            result = receiver => result.map_err(|e| BybitWsError::Send(e.to_string()))?,
1111        }
1112    }
1113
1114    /// Requests a fresh snapshot by replacing an order book subscription on the current
1115    /// connection.
1116    pub(crate) async fn resubscribe_book(
1117        &self,
1118        instrument_id: InstrumentId,
1119        depth: u32,
1120        cancel: CancellationToken,
1121        gate: SnapshotGate,
1122    ) -> BybitWsResult<()> {
1123        let topic = orderbook_topic(instrument_id, depth);
1124        let (completion, receiver) = tokio::sync::oneshot::channel();
1125        let sender = self.cmd_tx.read().await;
1126
1127        if cancel.is_cancelled() {
1128            return Err(BybitWsError::ClientError(
1129                "Book recovery canceled".to_string(),
1130            ));
1131        }
1132
1133        let cmd = HandlerCommand::ResubscribeBook {
1134            topic,
1135            cancel,
1136            gate,
1137            completion,
1138        };
1139
1140        sender
1141            .send(cmd)
1142            .map_err(|e| BybitWsError::Send(format!("Failed to send resubscribe command: {e}")))?;
1143        drop(sender);
1144
1145        receiver
1146            .await
1147            .map_err(|e| BybitWsError::Send(e.to_string()))?
1148    }
1149
1150    /// Unsubscribes from orderbook updates for a specific instrument.
1151    pub async fn unsubscribe_orderbook(
1152        &self,
1153        instrument_id: InstrumentId,
1154        depth: u32,
1155    ) -> BybitWsResult<()> {
1156        let topic = orderbook_topic(instrument_id, depth);
1157        self.unsubscribe(vec![topic]).await
1158    }
1159
1160    /// Subscribes to public trade updates for a specific instrument.
1161    ///
1162    /// # Errors
1163    ///
1164    /// Returns an error if the subscription request fails.
1165    ///
1166    /// # References
1167    ///
1168    /// <https://bybit-exchange.github.io/docs/v5/websocket/public/trade>
1169    pub async fn subscribe_trades(&self, instrument_id: InstrumentId) -> BybitWsResult<()> {
1170        self.trade_subs.insert(instrument_id);
1171        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1172        // Bybit option trades use baseCoin topic (e.g. publicTrade.BTC)
1173        let topic_symbol = match self.product_type {
1174            Some(BybitProductType::Option) => extract_base_coin(raw_symbol),
1175            _ => raw_symbol,
1176        };
1177        let topic = format!(
1178            "{}.{topic_symbol}",
1179            BybitWsPublicChannel::PublicTrade.as_ref()
1180        );
1181        self.subscribe(vec![topic]).await
1182    }
1183
1184    /// Unsubscribes from public trade updates for a specific instrument.
1185    pub async fn unsubscribe_trades(&self, instrument_id: InstrumentId) -> BybitWsResult<()> {
1186        self.trade_subs.remove(&instrument_id);
1187        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1188        let topic_symbol = match self.product_type {
1189            Some(BybitProductType::Option) => extract_base_coin(raw_symbol),
1190            _ => raw_symbol,
1191        };
1192        let topic = format!(
1193            "{}.{topic_symbol}",
1194            BybitWsPublicChannel::PublicTrade.as_ref()
1195        );
1196        self.unsubscribe(vec![topic]).await
1197    }
1198
1199    /// Subscribes to public liquidation updates for a specific instrument.
1200    ///
1201    /// Bybit publishes this stream for linear and inverse contracts only.
1202    ///
1203    /// # Errors
1204    ///
1205    /// Returns an error if the subscription request fails.
1206    ///
1207    /// # References
1208    ///
1209    /// <https://bybit-exchange.github.io/docs/v5/websocket/public/all-liquidation>
1210    pub async fn subscribe_liquidations(&self, instrument_id: InstrumentId) -> BybitWsResult<()> {
1211        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1212        let topic = format!(
1213            "{}.{raw_symbol}",
1214            BybitWsPublicChannel::AllLiquidation.as_ref()
1215        );
1216        self.subscribe(vec![topic]).await
1217    }
1218
1219    /// Unsubscribes from public liquidation updates for a specific instrument.
1220    pub async fn unsubscribe_liquidations(&self, instrument_id: InstrumentId) -> BybitWsResult<()> {
1221        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1222        let topic = format!(
1223            "{}.{raw_symbol}",
1224            BybitWsPublicChannel::AllLiquidation.as_ref()
1225        );
1226        self.unsubscribe(vec![topic]).await
1227    }
1228
1229    /// Subscribes to ticker updates for a specific instrument.
1230    ///
1231    /// # Errors
1232    ///
1233    /// Returns an error if the subscription request fails.
1234    ///
1235    /// # References
1236    ///
1237    /// <https://bybit-exchange.github.io/docs/v5/websocket/public/ticker>
1238    pub async fn subscribe_ticker(&self, instrument_id: InstrumentId) -> BybitWsResult<()> {
1239        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1240        let topic = format!("{}.{raw_symbol}", BybitWsPublicChannel::Tickers.as_ref());
1241        self.subscribe(vec![topic]).await
1242    }
1243
1244    /// Unsubscribes from ticker updates for a specific instrument.
1245    pub async fn unsubscribe_ticker(&self, instrument_id: InstrumentId) -> BybitWsResult<()> {
1246        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1247        let topic = format!("{}.{raw_symbol}", BybitWsPublicChannel::Tickers.as_ref());
1248        self.unsubscribe(vec![topic]).await
1249    }
1250
1251    /// Subscribes to kline/candlestick updates for a specific instrument.
1252    ///
1253    /// # Errors
1254    ///
1255    /// Returns an error if the subscription request fails.
1256    ///
1257    /// # References
1258    ///
1259    /// <https://bybit-exchange.github.io/docs/v5/websocket/public/kline>
1260    pub async fn subscribe_bars(&self, bar_type: BarType) -> BybitWsResult<()> {
1261        if self.product_type == Some(BybitProductType::Option) {
1262            return Err(BybitWsError::ClientError(
1263                "Bybit does not support kline/bar data for options".to_string(),
1264            ));
1265        }
1266
1267        let spec = bar_type.spec();
1268
1269        if spec.price_type != PriceType::Last {
1270            return Err(BybitWsError::ClientError(format!(
1271                "Invalid bar type: Bybit bars only support LAST price type, received {}",
1272                spec.price_type
1273            )));
1274        }
1275
1276        if bar_type.aggregation_source() != AggregationSource::External {
1277            return Err(BybitWsError::ClientError(format!(
1278                "Invalid bar type: Bybit bars only support EXTERNAL aggregation source, received {}",
1279                bar_type.aggregation_source()
1280            )));
1281        }
1282
1283        let interval = bar_spec_to_bybit_interval(spec.aggregation, spec.step.get() as u64)
1284            .map_err(|e| BybitWsError::ClientError(e.to_string()))?;
1285
1286        let instrument_id = bar_type.instrument_id();
1287        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1288        let topic = format!(
1289            "{}.{}.{raw_symbol}",
1290            BybitWsPublicChannel::Kline.as_ref(),
1291            interval
1292        );
1293
1294        // Coordinate with reference counting to avoid duplicate cache entries
1295        if self.subscriptions.get_reference_count(&topic) == 0 {
1296            self.bar_types_cache.insert(topic.clone(), bar_type);
1297        }
1298
1299        self.subscribe(vec![topic]).await
1300    }
1301
1302    /// Unsubscribes from kline/candlestick updates for a specific instrument.
1303    pub async fn unsubscribe_bars(&self, bar_type: BarType) -> BybitWsResult<()> {
1304        let spec = bar_type.spec();
1305        let interval = bar_spec_to_bybit_interval(spec.aggregation, spec.step.get() as u64)
1306            .map_err(|e| BybitWsError::ClientError(e.to_string()))?;
1307
1308        let instrument_id = bar_type.instrument_id();
1309        let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
1310        let topic = format!(
1311            "{}.{}.{raw_symbol}",
1312            BybitWsPublicChannel::Kline.as_ref(),
1313            interval
1314        );
1315
1316        // Coordinate with reference counting to preserve cache for other subscribers
1317        if self.subscriptions.get_reference_count(&topic) == 1 {
1318            self.bar_types_cache.remove(&topic);
1319        }
1320
1321        self.unsubscribe(vec![topic]).await
1322    }
1323
1324    /// Subscribes to order updates.
1325    ///
1326    /// # Errors
1327    ///
1328    /// Returns an error if the subscription request fails or if not authenticated.
1329    ///
1330    /// # References
1331    ///
1332    /// <https://bybit-exchange.github.io/docs/v5/websocket/private/order>
1333    pub async fn subscribe_orders(&self) -> BybitWsResult<()> {
1334        if !self.requires_auth {
1335            return Err(BybitWsError::Authentication(
1336                "Order subscription requires authentication".to_string(),
1337            ));
1338        }
1339        self.subscribe(vec![BybitWsPrivateChannel::Order.as_ref().to_string()])
1340            .await
1341    }
1342
1343    /// Unsubscribes from order updates.
1344    pub async fn unsubscribe_orders(&self) -> BybitWsResult<()> {
1345        self.unsubscribe(vec![BybitWsPrivateChannel::Order.as_ref().to_string()])
1346            .await
1347    }
1348
1349    /// Subscribes to execution/fill updates.
1350    ///
1351    /// # Errors
1352    ///
1353    /// Returns an error if the subscription request fails or if not authenticated.
1354    ///
1355    /// # References
1356    ///
1357    /// <https://bybit-exchange.github.io/docs/v5/websocket/private/execution>
1358    pub async fn subscribe_executions(&self) -> BybitWsResult<()> {
1359        if !self.requires_auth {
1360            return Err(BybitWsError::Authentication(
1361                "Execution subscription requires authentication".to_string(),
1362            ));
1363        }
1364        self.subscribe(vec![BybitWsPrivateChannel::Execution.as_ref().to_string()])
1365            .await
1366    }
1367
1368    /// Unsubscribes from execution/fill updates.
1369    pub async fn unsubscribe_executions(&self) -> BybitWsResult<()> {
1370        self.unsubscribe(vec![BybitWsPrivateChannel::Execution.as_ref().to_string()])
1371            .await
1372    }
1373
1374    /// Subscribes to fast execution updates (slim payload, lower latency).
1375    ///
1376    /// # Errors
1377    ///
1378    /// Returns an error if the subscription request fails or if not authenticated.
1379    ///
1380    /// # References
1381    ///
1382    /// <https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution>
1383    pub async fn subscribe_executions_fast(&self) -> BybitWsResult<()> {
1384        if !self.requires_auth {
1385            return Err(BybitWsError::Authentication(
1386                "Fast execution subscription requires authentication".to_string(),
1387            ));
1388        }
1389        self.subscribe(vec![
1390            BybitWsPrivateChannel::ExecutionFast.as_ref().to_string(),
1391        ])
1392        .await
1393    }
1394
1395    /// Unsubscribes from fast execution updates.
1396    pub async fn unsubscribe_executions_fast(&self) -> BybitWsResult<()> {
1397        self.unsubscribe(vec![
1398            BybitWsPrivateChannel::ExecutionFast.as_ref().to_string(),
1399        ])
1400        .await
1401    }
1402
1403    /// Subscribes to position updates.
1404    ///
1405    /// # Errors
1406    ///
1407    /// Returns an error if the subscription request fails or if not authenticated.
1408    ///
1409    /// # References
1410    ///
1411    /// <https://bybit-exchange.github.io/docs/v5/websocket/private/position>
1412    pub async fn subscribe_positions(&self) -> BybitWsResult<()> {
1413        if !self.requires_auth {
1414            return Err(BybitWsError::Authentication(
1415                "Position subscription requires authentication".to_string(),
1416            ));
1417        }
1418        self.subscribe(vec![BybitWsPrivateChannel::Position.as_ref().to_string()])
1419            .await
1420    }
1421
1422    /// Unsubscribes from position updates.
1423    pub async fn unsubscribe_positions(&self) -> BybitWsResult<()> {
1424        self.unsubscribe(vec![BybitWsPrivateChannel::Position.as_ref().to_string()])
1425            .await
1426    }
1427
1428    /// Subscribes to wallet/balance updates.
1429    ///
1430    /// # Errors
1431    ///
1432    /// Returns an error if the subscription request fails or if not authenticated.
1433    ///
1434    /// # References
1435    ///
1436    /// <https://bybit-exchange.github.io/docs/v5/websocket/private/wallet>
1437    pub async fn subscribe_wallet(&self) -> BybitWsResult<()> {
1438        if !self.requires_auth {
1439            return Err(BybitWsError::Authentication(
1440                "Wallet subscription requires authentication".to_string(),
1441            ));
1442        }
1443        self.subscribe(vec![BybitWsPrivateChannel::Wallet.as_ref().to_string()])
1444            .await
1445    }
1446
1447    /// Unsubscribes from wallet/balance updates.
1448    pub async fn unsubscribe_wallet(&self) -> BybitWsResult<()> {
1449        self.unsubscribe(vec![BybitWsPrivateChannel::Wallet.as_ref().to_string()])
1450            .await
1451    }
1452
1453    /// Waits for the session to be authenticated, aborting early if the client
1454    /// enters a terminal state (closed or disconnecting) during the wait.
1455    async fn require_authenticated(&self) -> BybitWsResult<()> {
1456        if self.is_closed() {
1457            return Err(BybitWsError::ClientError(
1458                "WebSocket client is closed".to_string(),
1459            ));
1460        }
1461
1462        if self.auth_tracker.is_authenticated() {
1463            return Ok(());
1464        }
1465
1466        tokio::select! {
1467            authenticated = self.auth_tracker.wait_for_authenticated(self.auth_wait_timeout) => {
1468                if authenticated {
1469                    Ok(())
1470                } else {
1471                    Err(BybitWsError::Authentication(
1472                        "Must be authenticated".to_string(),
1473                    ))
1474                }
1475            }
1476            () = async {
1477                loop {
1478                    tokio::time::sleep(Duration::from_millis(100)).await;
1479
1480                    if self.is_closed() {
1481                        return;
1482                    }
1483                }
1484            } => {
1485                Err(BybitWsError::ClientError(
1486                    "WebSocket client closed during authentication wait".to_string(),
1487                ))
1488            }
1489        }
1490    }
1491
1492    /// Allocates correlation IDs for product-specific batch chunks.
1493    #[must_use]
1494    pub(crate) fn batch_request_ids(category: BybitProductType, order_count: usize) -> Vec<String> {
1495        let request_count = order_count.div_ceil(batch_send_limit(category));
1496        (0..request_count)
1497            .map(|_| UUID4::new().to_string())
1498            .collect()
1499    }
1500
1501    fn batch_category(
1502        mut categories: impl Iterator<Item = BybitProductType>,
1503    ) -> BybitWsResult<BybitProductType> {
1504        let category = categories.next().ok_or_else(|| {
1505            BybitWsError::ClientError("Batch order request cannot be empty".to_string())
1506        })?;
1507
1508        if categories.any(|candidate| candidate != category) {
1509            return Err(BybitWsError::ClientError(
1510                "Batch order request cannot mix product categories".to_string(),
1511            ));
1512        }
1513        Ok(category)
1514    }
1515
1516    /// Places an order via WebSocket, returning the request ID for correlation.
1517    ///
1518    /// # Errors
1519    ///
1520    /// Returns an error if the order request fails or if not authenticated.
1521    pub async fn place_order(&self, params: BybitWsPlaceOrderParams) -> BybitWsResult<String> {
1522        let req_id = UUID4::new().to_string();
1523        self.place_order_with_id(params, req_id.clone()).await?;
1524        Ok(req_id)
1525    }
1526
1527    pub(crate) async fn place_order_with_id(
1528        &self,
1529        params: BybitWsPlaceOrderParams,
1530        req_id: String,
1531    ) -> BybitWsResult<()> {
1532        self.require_authenticated().await?;
1533        let category = params.category;
1534
1535        let referer = if self.include_referer_header(params.time_in_force) {
1536            Some(BYBIT_NAUTILUS_BROKER_ID.to_string())
1537        } else {
1538            None
1539        };
1540
1541        let command = BybitWsOrderCommand {
1542            req_id,
1543            op: BybitWsOrderRequestOp::Create,
1544            category,
1545            weight: 1,
1546            referer,
1547            args: vec![serde_json::to_value(params)?],
1548        };
1549        self.send_cmd(HandlerCommand::SendOrder { command }).await
1550    }
1551
1552    /// Amends an existing order via WebSocket, returning the request ID for correlation.
1553    ///
1554    /// # Errors
1555    ///
1556    /// Returns an error if the amend request fails or if not authenticated.
1557    pub async fn amend_order(&self, params: BybitWsAmendOrderParams) -> BybitWsResult<String> {
1558        let req_id = UUID4::new().to_string();
1559        self.amend_order_with_id(params, req_id.clone()).await?;
1560        Ok(req_id)
1561    }
1562
1563    pub(crate) async fn amend_order_with_id(
1564        &self,
1565        params: BybitWsAmendOrderParams,
1566        req_id: String,
1567    ) -> BybitWsResult<()> {
1568        self.require_authenticated().await?;
1569        let command = BybitWsOrderCommand {
1570            category: params.category,
1571            req_id,
1572            op: BybitWsOrderRequestOp::Amend,
1573            weight: 1,
1574            referer: None,
1575            args: vec![serde_json::to_value(params)?],
1576        };
1577        self.send_cmd(HandlerCommand::SendOrder { command }).await
1578    }
1579
1580    /// Cancels an order via WebSocket, returning the request ID for correlation.
1581    ///
1582    /// # Errors
1583    ///
1584    /// Returns an error if the cancel request fails or if not authenticated.
1585    pub async fn cancel_order(&self, params: BybitWsCancelOrderParams) -> BybitWsResult<String> {
1586        let req_id = UUID4::new().to_string();
1587        self.cancel_order_with_id(params, req_id.clone()).await?;
1588        Ok(req_id)
1589    }
1590
1591    pub(crate) async fn cancel_order_with_id(
1592        &self,
1593        params: BybitWsCancelOrderParams,
1594        req_id: String,
1595    ) -> BybitWsResult<()> {
1596        self.require_authenticated().await?;
1597        let command = BybitWsOrderCommand {
1598            category: params.category,
1599            req_id,
1600            op: BybitWsOrderRequestOp::Cancel,
1601            weight: 1,
1602            referer: None,
1603            args: vec![serde_json::to_value(params)?],
1604        };
1605        self.send_cmd(HandlerCommand::SendOrder { command }).await
1606    }
1607
1608    /// Batch creates multiple orders via WebSocket, returning the request ID for correlation.
1609    ///
1610    /// # Errors
1611    ///
1612    /// Returns an error if the batch request fails or if not authenticated.
1613    pub async fn batch_place_orders(
1614        &self,
1615        orders: Vec<BybitWsPlaceOrderParams>,
1616    ) -> BybitWsResult<Vec<String>> {
1617        self.require_authenticated().await?;
1618
1619        if orders.is_empty() {
1620            log::warn!("Batch place orders called with empty orders list");
1621            return Ok(vec![]);
1622        }
1623
1624        let category = Self::batch_category(orders.iter().map(|order| order.category))?;
1625        let req_ids = Self::batch_request_ids(category, orders.len());
1626        self.batch_place_orders_with_ids(orders, req_ids.clone())
1627            .await?;
1628        Ok(req_ids)
1629    }
1630
1631    pub(crate) async fn batch_place_orders_with_ids(
1632        &self,
1633        orders: Vec<BybitWsPlaceOrderParams>,
1634        req_ids: Vec<String>,
1635    ) -> BybitWsResult<()> {
1636        self.require_authenticated().await?;
1637        let category = Self::batch_category(orders.iter().map(|order| order.category))?;
1638        let chunk_limit = batch_send_limit(category);
1639        if req_ids.len() != orders.len().div_ceil(chunk_limit) {
1640            return Err(BybitWsError::ClientError(
1641                "Batch request ID count does not match order chunks".to_string(),
1642            ));
1643        }
1644
1645        let mut commands = Vec::with_capacity(req_ids.len());
1646        for (orders, req_id) in orders.chunks(chunk_limit).zip(req_ids) {
1647            commands.push(self.build_batch_place_command(orders.to_vec(), req_id)?);
1648        }
1649        self.send_cmd(HandlerCommand::SendOrders { commands }).await
1650    }
1651
1652    fn build_batch_place_command(
1653        &self,
1654        orders: Vec<BybitWsPlaceOrderParams>,
1655        req_id: String,
1656    ) -> BybitWsResult<BybitWsOrderCommand> {
1657        let category = orders[0].category;
1658        let order_count = orders.len();
1659
1660        let mm_level = self
1661            .http_client
1662            .as_ref()
1663            .map_or(0, BybitHttpClient::mm_level);
1664        let has_non_post_only = orders
1665            .iter()
1666            .any(|o| !matches!(o.time_in_force, Some(BybitTimeInForce::PostOnly)));
1667        let referer = if has_non_post_only || mm_level == 0 {
1668            Some(BYBIT_NAUTILUS_BROKER_ID.to_string())
1669        } else {
1670            None
1671        };
1672
1673        let request_items: Vec<BybitWsBatchPlaceItem> = orders
1674            .into_iter()
1675            .map(|order| BybitWsBatchPlaceItem {
1676                symbol: order.symbol,
1677                side: order.side,
1678                order_type: order.order_type,
1679                qty: order.qty,
1680                is_leverage: order.is_leverage,
1681                market_unit: order.market_unit,
1682                price: order.price,
1683                time_in_force: order.time_in_force,
1684                order_link_id: order.order_link_id,
1685                reduce_only: order.reduce_only,
1686                close_on_trigger: order.close_on_trigger,
1687                trigger_price: order.trigger_price,
1688                trigger_by: order.trigger_by,
1689                trigger_direction: order.trigger_direction,
1690                tpsl_mode: order.tpsl_mode,
1691                take_profit: order.take_profit,
1692                stop_loss: order.stop_loss,
1693                tp_trigger_by: order.tp_trigger_by,
1694                sl_trigger_by: order.sl_trigger_by,
1695                sl_trigger_price: order.sl_trigger_price,
1696                tp_trigger_price: order.tp_trigger_price,
1697                sl_order_type: order.sl_order_type,
1698                tp_order_type: order.tp_order_type,
1699                sl_limit_price: order.sl_limit_price,
1700                tp_limit_price: order.tp_limit_price,
1701                order_iv: order.order_iv,
1702                smp_type: order.smp_type,
1703                mmp: order.mmp,
1704                position_idx: order.position_idx,
1705                bbo_side_type: order.bbo_side_type,
1706                bbo_level: order.bbo_level,
1707            })
1708            .collect();
1709
1710        let args = BybitWsBatchPlaceOrderArgs {
1711            category,
1712            request: request_items,
1713        };
1714
1715        Ok(BybitWsOrderCommand {
1716            req_id,
1717            op: BybitWsOrderRequestOp::CreateBatch,
1718            category,
1719            weight: batch_weight(category, order_count),
1720            referer,
1721            args: vec![serde_json::to_value(args)?],
1722        })
1723    }
1724
1725    /// Batch amends multiple orders via WebSocket.
1726    ///
1727    /// # Errors
1728    ///
1729    /// Returns an error if the batch request fails or if not authenticated.
1730    pub async fn batch_amend_orders(
1731        &self,
1732        orders: Vec<BybitWsAmendOrderParams>,
1733    ) -> BybitWsResult<Vec<String>> {
1734        self.require_authenticated().await?;
1735
1736        if orders.is_empty() {
1737            log::warn!("Batch amend orders called with empty orders list");
1738            return Ok(vec![]);
1739        }
1740
1741        let category = Self::batch_category(orders.iter().map(|order| order.category))?;
1742        let req_ids = Self::batch_request_ids(category, orders.len());
1743        self.batch_amend_orders_with_ids(orders, req_ids.clone())
1744            .await?;
1745        Ok(req_ids)
1746    }
1747
1748    pub(crate) async fn batch_amend_orders_with_ids(
1749        &self,
1750        orders: Vec<BybitWsAmendOrderParams>,
1751        req_ids: Vec<String>,
1752    ) -> BybitWsResult<()> {
1753        self.require_authenticated().await?;
1754        let category = Self::batch_category(orders.iter().map(|order| order.category))?;
1755        let chunk_limit = batch_send_limit(category);
1756        if req_ids.len() != orders.len().div_ceil(chunk_limit) {
1757            return Err(BybitWsError::ClientError(
1758                "Batch request ID count does not match order chunks".to_string(),
1759            ));
1760        }
1761
1762        let mut commands = Vec::with_capacity(req_ids.len());
1763        for (orders, req_id) in orders.chunks(chunk_limit).zip(req_ids) {
1764            commands.push(Self::build_batch_amend_command(orders.to_vec(), req_id)?);
1765        }
1766        self.send_cmd(HandlerCommand::SendOrders { commands }).await
1767    }
1768
1769    fn build_batch_amend_command(
1770        orders: Vec<BybitWsAmendOrderParams>,
1771        req_id: String,
1772    ) -> BybitWsResult<BybitWsOrderCommand> {
1773        let category = orders[0].category;
1774        let order_count = orders.len();
1775
1776        let request_items = orders
1777            .into_iter()
1778            .map(|order| BybitWsBatchAmendItem {
1779                symbol: order.symbol,
1780                order_id: order.order_id,
1781                order_link_id: order.order_link_id,
1782                qty: order.qty,
1783                price: order.price,
1784                trigger_price: order.trigger_price,
1785                take_profit: order.take_profit,
1786                stop_loss: order.stop_loss,
1787                tp_trigger_by: order.tp_trigger_by,
1788                sl_trigger_by: order.sl_trigger_by,
1789                order_iv: order.order_iv,
1790            })
1791            .collect();
1792
1793        let args = BybitWsBatchAmendOrderArgs {
1794            category,
1795            request: request_items,
1796        };
1797
1798        Ok(BybitWsOrderCommand {
1799            req_id,
1800            op: BybitWsOrderRequestOp::AmendBatch,
1801            category,
1802            weight: batch_weight(category, order_count),
1803            referer: None,
1804            args: vec![serde_json::to_value(args)?],
1805        })
1806    }
1807
1808    /// Batch cancels multiple orders via WebSocket, returning the request ID for correlation.
1809    ///
1810    /// # Errors
1811    ///
1812    /// Returns an error if the batch request fails or if not authenticated.
1813    pub async fn batch_cancel_orders(
1814        &self,
1815        orders: Vec<BybitWsCancelOrderParams>,
1816    ) -> BybitWsResult<Vec<String>> {
1817        self.require_authenticated().await?;
1818
1819        if orders.is_empty() {
1820            log::warn!("Batch cancel orders called with empty orders list");
1821            return Ok(vec![]);
1822        }
1823
1824        let category = Self::batch_category(orders.iter().map(|order| order.category))?;
1825        let req_ids = Self::batch_request_ids(category, orders.len());
1826        self.batch_cancel_orders_with_ids(orders, req_ids.clone())
1827            .await?;
1828        Ok(req_ids)
1829    }
1830
1831    pub(crate) async fn batch_cancel_orders_with_ids(
1832        &self,
1833        orders: Vec<BybitWsCancelOrderParams>,
1834        req_ids: Vec<String>,
1835    ) -> BybitWsResult<()> {
1836        self.require_authenticated().await?;
1837
1838        if orders.is_empty() {
1839            return Ok(());
1840        }
1841
1842        let category = Self::batch_category(orders.iter().map(|order| order.category))?;
1843        let chunk_limit = batch_send_limit(category);
1844        if req_ids.len() != orders.len().div_ceil(chunk_limit) {
1845            return Err(BybitWsError::ClientError(
1846                "Batch request ID count does not match order chunks".to_string(),
1847            ));
1848        }
1849
1850        let mut commands = Vec::with_capacity(req_ids.len());
1851        for (orders, req_id) in orders.chunks(chunk_limit).zip(req_ids) {
1852            commands.push(Self::build_batch_cancel_command(orders.to_vec(), req_id)?);
1853        }
1854        self.send_cmd(HandlerCommand::SendOrders { commands }).await
1855    }
1856
1857    fn build_batch_cancel_command(
1858        orders: Vec<BybitWsCancelOrderParams>,
1859        req_id: String,
1860    ) -> BybitWsResult<BybitWsOrderCommand> {
1861        let category = orders[0].category;
1862        let order_count = orders.len();
1863
1864        let request_items: Vec<BybitWsBatchCancelItem> = orders
1865            .into_iter()
1866            .map(|order| BybitWsBatchCancelItem {
1867                symbol: order.symbol,
1868                order_id: order.order_id,
1869                order_link_id: order.order_link_id,
1870            })
1871            .collect();
1872
1873        let args = BybitWsBatchCancelOrderArgs {
1874            category,
1875            request: request_items,
1876        };
1877
1878        Ok(BybitWsOrderCommand {
1879            req_id,
1880            op: BybitWsOrderRequestOp::CancelBatch,
1881            category,
1882            weight: batch_weight(category, order_count),
1883            referer: None,
1884            args: vec![serde_json::to_value(args)?],
1885        })
1886    }
1887
1888    /// Submits an order using Nautilus domain objects.
1889    ///
1890    /// # Errors
1891    ///
1892    /// Returns an error if order submission fails or if not authenticated.
1893    #[expect(clippy::too_many_arguments)]
1894    pub async fn submit_order(
1895        &self,
1896        product_type: BybitProductType,
1897        instrument_id: InstrumentId,
1898        client_order_id: ClientOrderId,
1899        order_side: OrderSide,
1900        order_type: OrderType,
1901        quantity: Quantity,
1902        is_quote_quantity: bool,
1903        time_in_force: Option<TimeInForce>,
1904        price: Option<Price>,
1905        trigger_price: Option<Price>,
1906        trigger_type: Option<TriggerType>,
1907        post_only: Option<bool>,
1908        reduce_only: Option<bool>,
1909        is_leverage: bool,
1910        position_idx: Option<BybitPositionIdx>,
1911        bbo_side_type: Option<BybitBboSideType>,
1912        bbo_level: Option<String>,
1913        smp_type: Option<BybitOrderSmpType>,
1914    ) -> BybitWsResult<String> {
1915        let params = self.build_place_order_params(
1916            product_type,
1917            instrument_id,
1918            client_order_id,
1919            order_side,
1920            order_type,
1921            quantity,
1922            is_quote_quantity,
1923            time_in_force,
1924            price,
1925            trigger_price,
1926            trigger_type,
1927            post_only,
1928            reduce_only,
1929            is_leverage,
1930            None,
1931            None,
1932            position_idx,
1933            bbo_side_type,
1934            bbo_level,
1935            smp_type,
1936        )?;
1937
1938        self.place_order(params).await
1939    }
1940
1941    /// Modifies an existing order using Nautilus domain objects.
1942    ///
1943    /// # Errors
1944    ///
1945    /// Returns an error if modification fails or if not authenticated.
1946    pub async fn modify_order(
1947        &self,
1948        product_type: BybitProductType,
1949        instrument_id: InstrumentId,
1950        client_order_id: ClientOrderId,
1951        venue_order_id: Option<VenueOrderId>,
1952        quantity: Option<Quantity>,
1953        price: Option<Price>,
1954    ) -> BybitWsResult<String> {
1955        let params = self.build_amend_order_params(
1956            product_type,
1957            instrument_id,
1958            venue_order_id,
1959            Some(client_order_id),
1960            quantity,
1961            price,
1962        )?;
1963
1964        self.amend_order(params).await
1965    }
1966
1967    /// Cancels an order using Nautilus domain objects.
1968    ///
1969    /// # Errors
1970    ///
1971    /// Returns an error if cancellation fails or if not authenticated.
1972    pub async fn cancel_order_by_id(
1973        &self,
1974        product_type: BybitProductType,
1975        instrument_id: InstrumentId,
1976        client_order_id: ClientOrderId,
1977        venue_order_id: Option<VenueOrderId>,
1978    ) -> BybitWsResult<String> {
1979        let params = self.build_cancel_order_params(
1980            product_type,
1981            instrument_id,
1982            venue_order_id,
1983            Some(client_order_id),
1984        )?;
1985
1986        self.cancel_order(params).await
1987    }
1988
1989    /// Builds order params for placing an order.
1990    #[expect(clippy::too_many_arguments)]
1991    pub fn build_place_order_params(
1992        &self,
1993        product_type: BybitProductType,
1994        instrument_id: InstrumentId,
1995        client_order_id: ClientOrderId,
1996        order_side: OrderSide,
1997        order_type: OrderType,
1998        quantity: Quantity,
1999        is_quote_quantity: bool,
2000        time_in_force: Option<TimeInForce>,
2001        price: Option<Price>,
2002        trigger_price: Option<Price>,
2003        trigger_type: Option<TriggerType>,
2004        post_only: Option<bool>,
2005        reduce_only: Option<bool>,
2006        is_leverage: bool,
2007        take_profit: Option<Price>,
2008        stop_loss: Option<Price>,
2009        position_idx: Option<BybitPositionIdx>,
2010        bbo_side_type: Option<BybitBboSideType>,
2011        bbo_level: Option<String>,
2012        smp_type: Option<BybitOrderSmpType>,
2013    ) -> BybitWsResult<BybitWsPlaceOrderParams> {
2014        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())
2015            .map_err(|e| BybitWsError::ClientError(e.to_string()))?;
2016        let raw_symbol = Ustr::from(bybit_symbol.raw_symbol());
2017
2018        let bybit_side = match order_side {
2019            OrderSide::Buy => BybitOrderSide::Buy,
2020            OrderSide::Sell => BybitOrderSide::Sell,
2021        };
2022
2023        let (bybit_order_type, is_stop_order) = match order_type {
2024            OrderType::Market => (BybitOrderType::Market, false),
2025            OrderType::Limit => (BybitOrderType::Limit, false),
2026            OrderType::StopMarket | OrderType::MarketIfTouched => (BybitOrderType::Market, true),
2027            OrderType::StopLimit | OrderType::LimitIfTouched => (BybitOrderType::Limit, true),
2028            _ => {
2029                return Err(BybitWsError::ClientError(format!(
2030                    "Unsupported order type: {order_type:?}"
2031                )));
2032            }
2033        };
2034
2035        let bybit_tif =
2036            map_time_in_force(bybit_order_type, time_in_force, post_only).map_err(|tif| {
2037                BybitWsError::ClientError(format!("Unsupported time in force: {tif:?}"))
2038            })?;
2039        let market_unit = spot_market_unit(product_type, bybit_order_type, is_quote_quantity);
2040        let is_leverage_value = spot_leverage(product_type, is_leverage);
2041        let trigger_dir =
2042            trigger_direction(order_type, order_side, is_stop_order).map(|d| d as i32);
2043
2044        let params = if is_stop_order {
2045            BybitWsPlaceOrderParams {
2046                category: product_type,
2047                symbol: raw_symbol,
2048                side: bybit_side,
2049                order_type: bybit_order_type,
2050                qty: quantity.to_string(),
2051                is_leverage: is_leverage_value,
2052                market_unit,
2053                price: if bbo_side_type.is_some() {
2054                    None
2055                } else {
2056                    price.map(|p| p.to_string())
2057                },
2058                time_in_force: bybit_tif,
2059                order_link_id: Some(client_order_id.to_string()),
2060                reduce_only: reduce_only.filter(|&r| r),
2061                close_on_trigger: None,
2062                trigger_price: trigger_price.map(|p| p.to_string()),
2063                trigger_by: Some(resolve_trigger_type(trigger_type)),
2064                trigger_direction: trigger_dir,
2065                tpsl_mode: if take_profit.is_some() || stop_loss.is_some() {
2066                    Some(BybitTpSlMode::Full)
2067                } else {
2068                    None
2069                },
2070                take_profit: take_profit.map(|p| p.to_string()),
2071                stop_loss: stop_loss.map(|p| p.to_string()),
2072                tp_trigger_by: take_profit.map(|_| resolve_trigger_type(trigger_type)),
2073                sl_trigger_by: stop_loss.map(|_| resolve_trigger_type(trigger_type)),
2074                sl_trigger_price: None,
2075                tp_trigger_price: None,
2076                sl_order_type: None,
2077                tp_order_type: None,
2078                sl_limit_price: None,
2079                tp_limit_price: None,
2080                order_iv: None,
2081                smp_type,
2082                mmp: None,
2083                position_idx,
2084                bbo_side_type,
2085                bbo_level,
2086            }
2087        } else {
2088            BybitWsPlaceOrderParams {
2089                category: product_type,
2090                symbol: raw_symbol,
2091                side: bybit_side,
2092                order_type: bybit_order_type,
2093                qty: quantity.to_string(),
2094                is_leverage: is_leverage_value,
2095                market_unit,
2096                price: if bbo_side_type.is_some() {
2097                    None
2098                } else {
2099                    price.map(|p| p.to_string())
2100                },
2101                time_in_force: bybit_tif,
2102                order_link_id: Some(client_order_id.to_string()),
2103                reduce_only: reduce_only.filter(|&r| r),
2104                close_on_trigger: None,
2105                trigger_price: None,
2106                trigger_by: None,
2107                trigger_direction: None,
2108                tpsl_mode: if take_profit.is_some() || stop_loss.is_some() {
2109                    Some(BybitTpSlMode::Full)
2110                } else {
2111                    None
2112                },
2113                take_profit: take_profit.map(|p| p.to_string()),
2114                stop_loss: stop_loss.map(|p| p.to_string()),
2115                tp_trigger_by: take_profit.map(|_| resolve_trigger_type(trigger_type)),
2116                sl_trigger_by: stop_loss.map(|_| resolve_trigger_type(trigger_type)),
2117                sl_trigger_price: None,
2118                tp_trigger_price: None,
2119                sl_order_type: None,
2120                tp_order_type: None,
2121                sl_limit_price: None,
2122                tp_limit_price: None,
2123                order_iv: None,
2124                smp_type,
2125                mmp: None,
2126                position_idx,
2127                bbo_side_type,
2128                bbo_level,
2129            }
2130        };
2131
2132        Ok(params)
2133    }
2134
2135    /// Builds order params for amending an order.
2136    pub fn build_amend_order_params(
2137        &self,
2138        product_type: BybitProductType,
2139        instrument_id: InstrumentId,
2140        venue_order_id: Option<VenueOrderId>,
2141        client_order_id: Option<ClientOrderId>,
2142        quantity: Option<Quantity>,
2143        price: Option<Price>,
2144    ) -> BybitWsResult<BybitWsAmendOrderParams> {
2145        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())
2146            .map_err(|e| BybitWsError::ClientError(e.to_string()))?;
2147        let raw_symbol = Ustr::from(bybit_symbol.raw_symbol());
2148
2149        Ok(BybitWsAmendOrderParams {
2150            category: product_type,
2151            symbol: raw_symbol,
2152            order_id: venue_order_id.map(|v| v.to_string()),
2153            order_link_id: client_order_id.map(|c| c.to_string()),
2154            qty: quantity.map(|q| q.to_string()),
2155            price: price.map(|p| p.to_string()),
2156            trigger_price: None,
2157            take_profit: None,
2158            stop_loss: None,
2159            tp_trigger_by: None,
2160            sl_trigger_by: None,
2161            order_iv: None,
2162        })
2163    }
2164
2165    /// Builds order params for canceling an order via WebSocket.
2166    ///
2167    /// # Errors
2168    ///
2169    /// Returns an error if symbol parsing fails or if neither venue_order_id
2170    /// nor client_order_id is provided.
2171    pub fn build_cancel_order_params(
2172        &self,
2173        product_type: BybitProductType,
2174        instrument_id: InstrumentId,
2175        venue_order_id: Option<VenueOrderId>,
2176        client_order_id: Option<ClientOrderId>,
2177    ) -> BybitWsResult<BybitWsCancelOrderParams> {
2178        if venue_order_id.is_none() && client_order_id.is_none() {
2179            return Err(BybitWsError::ClientError(
2180                "Either venue_order_id or client_order_id must be provided".to_string(),
2181            ));
2182        }
2183
2184        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())
2185            .map_err(|e| BybitWsError::ClientError(e.to_string()))?;
2186        let raw_symbol = Ustr::from(bybit_symbol.raw_symbol());
2187
2188        Ok(BybitWsCancelOrderParams {
2189            category: product_type,
2190            symbol: raw_symbol,
2191            order_id: venue_order_id.map(|v| v.to_string()),
2192            order_link_id: client_order_id.map(|c| c.to_string()),
2193        })
2194    }
2195
2196    fn include_referer_header(&self, time_in_force: Option<BybitTimeInForce>) -> bool {
2197        let is_post_only = matches!(time_in_force, Some(BybitTimeInForce::PostOnly));
2198        let mm_level = self
2199            .http_client
2200            .as_ref()
2201            .map_or(0, BybitHttpClient::mm_level);
2202        !(is_post_only && mm_level > 0)
2203    }
2204
2205    fn default_headers() -> Vec<(String, String)> {
2206        let mut headers = create_standard_nautilus_headers();
2207        headers.push(("Content-Type".to_string(), "application/json".to_string()));
2208        headers
2209    }
2210
2211    async fn authenticate_if_required(&self) -> BybitWsResult<()> {
2212        if !self.requires_auth {
2213            return Ok(());
2214        }
2215
2216        let credential = self.credential.as_ref().ok_or_else(|| {
2217            BybitWsError::Authentication("Credentials required for authentication".to_string())
2218        })?;
2219
2220        let expires = jiff::Timestamp::now().as_millisecond() + WEBSOCKET_AUTH_WINDOW_MS;
2221        let signature = credential.sign_websocket_auth(expires);
2222
2223        let auth_message = Zeroizing::new(BybitAuthRequest {
2224            op: BybitWsOperation::Auth,
2225            args: vec![
2226                Value::String(credential.api_key().to_string()),
2227                Value::Number(expires.into()),
2228                Value::String(signature),
2229            ],
2230        });
2231
2232        let payload = SecretString::from(serde_json::to_string(&*auth_message)?);
2233        drop(auth_message);
2234
2235        // Begin auth attempt so succeed() will update state
2236        let _rx = self.auth_tracker.begin();
2237
2238        self.cmd_tx
2239            .read()
2240            .await
2241            .send(HandlerCommand::Authenticate { payload })
2242            .map_err(|e| BybitWsError::Send(format!("Failed to send auth command: {e}")))?;
2243
2244        Ok(())
2245    }
2246
2247    async fn send_cmd(&self, cmd: HandlerCommand) -> BybitWsResult<()> {
2248        self.cmd_tx
2249            .read()
2250            .await
2251            .send(cmd)
2252            .map_err(|e| BybitWsError::Send(e.to_string()))
2253    }
2254}
2255
2256impl Drop for BybitWebSocketClient {
2257    fn drop(&mut self) {
2258        if Arc::strong_count(&self.task_handle) == 1 && !self.task_handle.is_empty() {
2259            self.cancellation_token.load().cancel();
2260            self.signal.store(true, Ordering::Relaxed);
2261            self.task_handle.abort();
2262        }
2263    }
2264}
2265
2266fn orderbook_topic(instrument_id: InstrumentId, depth: u32) -> String {
2267    let raw_symbol = extract_raw_symbol(instrument_id.symbol.as_str());
2268    format!(
2269        "{}.{depth}.{raw_symbol}",
2270        BybitWsPublicChannel::OrderBook.as_ref()
2271    )
2272}
2273
2274#[cfg(test)]
2275mod tests {
2276    use futures_util::StreamExt;
2277    use nautilus_testkit::connection::race_command_with_publication;
2278    use rstest::rstest;
2279
2280    use super::*;
2281    use crate::{
2282        common::{enums::BybitMarketUnit, testing::load_test_json},
2283        websocket::{messages::BybitWsFrame, parse_bybit_ws_frame},
2284    };
2285
2286    #[tokio::test]
2287    async fn command_during_sender_publication_reaches_initialized_handler() {
2288        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2289        let addr = listener.local_addr().unwrap();
2290        let (received_tx, mut received_rx) = tokio::sync::mpsc::unbounded_channel();
2291
2292        let server = tokio::spawn(async move {
2293            let (socket, _) = listener.accept().await.unwrap();
2294            let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
2295            while let Some(Ok(message)) = socket.next().await {
2296                if let tokio_tungstenite::tungstenite::Message::Text(text) = message {
2297                    let payload: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
2298                    let _ = received_tx.send(payload);
2299                }
2300            }
2301        });
2302
2303        let url = format!("ws://{addr}");
2304        let mut ws_client = BybitWebSocketClient::new_public(Some(url), 30);
2305        let observer = ws_client.clone();
2306        let expected = serde_json::json!({
2307            "op": "subscribe",
2308            "args": [
2309                "publicTrade.BTCUSDT"
2310            ]
2311        });
2312
2313        let command = HandlerCommand::Subscribe {
2314            topics: vec![expected.to_string()],
2315        };
2316
2317        race_command_with_publication(
2318            Arc::clone(&ws_client.cmd_tx),
2319            ws_client.connect(),
2320            move || command,
2321            || observer.is_active(),
2322        )
2323        .await
2324        .expect("connect failed");
2325        let received = tokio::time::timeout(Duration::from_secs(2), received_rx.recv()).await;
2326        ws_client.close().await.expect("disconnect failed");
2327        server.abort();
2328
2329        let payload = received
2330            .expect("startup command must reach server")
2331            .unwrap();
2332        assert_eq!(payload, expected);
2333    }
2334
2335    #[rstest]
2336    #[case("wss://stream.example.com/feed", "wss://stream.example.com")]
2337    #[case(
2338        "wss://SYN-user:SYN-password@stream.example.com:9443/SYN-path?token=SYN-query#SYN-fragment",
2339        "wss://stream.example.com:9443"
2340    )]
2341    fn test_debug_preserves_url_origin(#[case] url: &str, #[case] origin: &str) {
2342        let client = BybitWebSocketClient::new_public(Some(url.to_string()), 30);
2343        let debug = format!("{client:?}");
2344        assert!(debug.contains(&format!("url: {origin:?}")));
2345        assert!(!debug.contains("SYN-"));
2346        assert_eq!(client.url.expose(), url);
2347    }
2348
2349    #[tokio::test]
2350    async fn test_drop_clone_does_not_cancel_handler() {
2351        let client = BybitWebSocketClient::new_public(Some("wss://test".to_string()), 30);
2352        let cancellation_token = CancellationToken::new();
2353        client
2354            .cancellation_token
2355            .store(Arc::new(cancellation_token.clone()));
2356        client
2357            .task_handle
2358            .insert(get_runtime().spawn(std::future::pending()));
2359        let clone = client.clone();
2360
2361        drop(clone);
2362
2363        assert!(!cancellation_token.is_cancelled());
2364        assert!(!client.task_handle.is_empty());
2365    }
2366
2367    // An unconnected client rejects every command, so success proves nothing was sent
2368    #[tokio::test]
2369    async fn test_subscribe_book_opens_gate_for_held_topic_without_sending() {
2370        let client = BybitWebSocketClient::new_public(None, 20);
2371        let instrument_id = InstrumentId::from("BTCUSDT-LINEAR.BYBIT");
2372        let topic = "orderbook.1.BTCUSDT";
2373        assert!(client.subscriptions.add_reference(topic));
2374        let gate = SnapshotGate::default();
2375        gate.lock().close();
2376
2377        let result = client
2378            .subscribe_book(instrument_id, 1, CancellationToken::new(), gate.clone())
2379            .await;
2380
2381        assert!(result.is_ok());
2382        assert!(!gate.lock().is_closed());
2383        assert_eq!(client.subscriptions.get_reference_count(topic), 2);
2384    }
2385
2386    #[tokio::test]
2387    async fn test_subscribe_book_keeps_gate_closed_when_send_fails() {
2388        let client = BybitWebSocketClient::new_public(None, 20);
2389        let instrument_id = InstrumentId::from("BTCUSDT-LINEAR.BYBIT");
2390        let gate = SnapshotGate::default();
2391        gate.lock().close();
2392
2393        let error = client
2394            .subscribe_book(instrument_id, 50, CancellationToken::new(), gate.clone())
2395            .await
2396            .unwrap_err();
2397
2398        assert_eq!(
2399            error.to_string(),
2400            "WebSocket send error: Failed to send subscribe command: channel closed"
2401        );
2402        assert!(gate.lock().is_closed());
2403        assert_eq!(
2404            client
2405                .subscriptions
2406                .get_reference_count("orderbook.50.BTCUSDT"),
2407            1
2408        );
2409    }
2410
2411    #[rstest]
2412    fn classify_orderbook_snapshot() {
2413        let json: Value = serde_json::from_str(&load_test_json("ws_orderbook_snapshot.json"))
2414            .expect("invalid fixture");
2415        let frame = parse_bybit_ws_frame(json);
2416        assert!(matches!(frame, BybitWsFrame::Orderbook(_)));
2417    }
2418
2419    #[rstest]
2420    fn classify_trade_snapshot() {
2421        let json: Value =
2422            serde_json::from_str(&load_test_json("ws_public_trade.json")).expect("invalid fixture");
2423        let frame = parse_bybit_ws_frame(json);
2424        assert!(matches!(frame, BybitWsFrame::Trade(_)));
2425    }
2426
2427    #[rstest]
2428    fn classify_ticker_linear_snapshot() {
2429        let json: Value = serde_json::from_str(&load_test_json("ws_ticker_linear.json"))
2430            .expect("invalid fixture");
2431        let frame = parse_bybit_ws_frame(json);
2432        assert!(matches!(frame, BybitWsFrame::TickerLinear(_)));
2433    }
2434
2435    #[rstest]
2436    fn classify_ticker_option_snapshot() {
2437        let json: Value = serde_json::from_str(&load_test_json("ws_ticker_option.json"))
2438            .expect("invalid fixture");
2439        let frame = parse_bybit_ws_frame(json);
2440        assert!(matches!(frame, BybitWsFrame::TickerOption(_)));
2441    }
2442
2443    #[rstest]
2444    fn test_race_unsubscribe_failure_recovery() {
2445        let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
2446        let topic = "publicTrade.BTCUSDT";
2447
2448        subscriptions.mark_subscribe(topic);
2449        subscriptions.confirm_subscribe(topic);
2450        assert_eq!(subscriptions.len(), 1);
2451
2452        subscriptions.mark_unsubscribe(topic);
2453        assert_eq!(subscriptions.len(), 0);
2454        assert_eq!(subscriptions.pending_unsubscribe_topics(), vec![topic]);
2455
2456        subscriptions.confirm_unsubscribe(topic);
2457        subscriptions.mark_subscribe(topic);
2458        subscriptions.confirm_subscribe(topic);
2459
2460        assert_eq!(subscriptions.len(), 1);
2461        assert!(subscriptions.pending_unsubscribe_topics().is_empty());
2462        assert!(subscriptions.pending_subscribe_topics().is_empty());
2463
2464        let all = subscriptions.all_topics();
2465        assert_eq!(all.len(), 1);
2466        assert!(all.contains(&topic.to_string()));
2467    }
2468
2469    #[rstest]
2470    fn test_race_resubscribe_before_unsubscribe_ack() {
2471        let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
2472        let topic = "orderbook.50.BTCUSDT";
2473
2474        subscriptions.mark_subscribe(topic);
2475        subscriptions.confirm_subscribe(topic);
2476        assert_eq!(subscriptions.len(), 1);
2477
2478        subscriptions.mark_unsubscribe(topic);
2479        assert_eq!(subscriptions.len(), 0);
2480        assert_eq!(subscriptions.pending_unsubscribe_topics(), vec![topic]);
2481
2482        subscriptions.mark_subscribe(topic);
2483        assert_eq!(subscriptions.pending_subscribe_topics(), vec![topic]);
2484
2485        subscriptions.confirm_unsubscribe(topic);
2486        assert!(subscriptions.pending_unsubscribe_topics().is_empty());
2487        assert_eq!(subscriptions.pending_subscribe_topics(), vec![topic]);
2488
2489        subscriptions.confirm_subscribe(topic);
2490        assert_eq!(subscriptions.len(), 1);
2491        assert!(subscriptions.pending_subscribe_topics().is_empty());
2492
2493        let all = subscriptions.all_topics();
2494        assert_eq!(all.len(), 1);
2495        assert!(all.contains(&topic.to_string()));
2496    }
2497
2498    #[rstest]
2499    fn test_race_late_subscribe_confirmation_after_unsubscribe() {
2500        let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
2501        let topic = "tickers.ETHUSDT";
2502
2503        subscriptions.mark_subscribe(topic);
2504        assert_eq!(subscriptions.pending_subscribe_topics(), vec![topic]);
2505
2506        subscriptions.mark_unsubscribe(topic);
2507        assert!(subscriptions.pending_subscribe_topics().is_empty());
2508        assert_eq!(subscriptions.pending_unsubscribe_topics(), vec![topic]);
2509
2510        subscriptions.confirm_subscribe(topic);
2511        assert_eq!(subscriptions.len(), 0);
2512        assert_eq!(subscriptions.pending_unsubscribe_topics(), vec![topic]);
2513
2514        subscriptions.confirm_unsubscribe(topic);
2515
2516        assert!(subscriptions.is_empty());
2517        assert!(subscriptions.all_topics().is_empty());
2518    }
2519
2520    #[rstest]
2521    fn test_race_reconnection_with_pending_states() {
2522        let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
2523
2524        let trade_btc = "publicTrade.BTCUSDT";
2525        subscriptions.mark_subscribe(trade_btc);
2526        subscriptions.confirm_subscribe(trade_btc);
2527
2528        let trade_eth = "publicTrade.ETHUSDT";
2529        subscriptions.mark_subscribe(trade_eth);
2530
2531        let book_btc = "orderbook.50.BTCUSDT";
2532        subscriptions.mark_subscribe(book_btc);
2533        subscriptions.confirm_subscribe(book_btc);
2534        subscriptions.mark_unsubscribe(book_btc);
2535
2536        let topics_to_restore = subscriptions.all_topics();
2537
2538        assert_eq!(topics_to_restore.len(), 2);
2539        assert!(topics_to_restore.contains(&trade_btc.to_string()));
2540        assert!(topics_to_restore.contains(&trade_eth.to_string()));
2541        assert!(!topics_to_restore.contains(&book_btc.to_string()));
2542    }
2543
2544    #[tokio::test]
2545    async fn option_limit_counts_pending_unsubscriptions() {
2546        let client = BybitWebSocketClient::new_public_with(
2547            BybitProductType::Option,
2548            BybitEnvironment::Mainnet,
2549            Some("ws://option-pending-limit.invalid/v5/public/option".to_string()),
2550            20,
2551            TransportBackend::default(),
2552            None,
2553        );
2554
2555        for index in 0..BYBIT_OPTION_SUBSCRIPTION_LIMIT {
2556            let topic = format!("tickers.OPTION-{index}");
2557            assert!(client.subscriptions.add_reference(&topic));
2558            client.subscriptions.mark_subscribe(&topic);
2559            client.subscriptions.confirm_subscribe(&topic);
2560        }
2561        let pending = "tickers.OPTION-0";
2562        assert!(client.subscriptions.remove_reference(pending));
2563        client.subscriptions.mark_unsubscribe(pending);
2564
2565        let new_topic = "tickers.OPTION-new";
2566        let error = client
2567            .subscribe(vec![new_topic.to_string()])
2568            .await
2569            .unwrap_err();
2570
2571        assert!(error.to_string().contains("2000 arguments"));
2572        assert_eq!(client.subscriptions.get_reference_count(new_topic), 0);
2573        assert_eq!(
2574            client.subscriptions.pending_unsubscribe_topics(),
2575            vec![pending]
2576        );
2577    }
2578
2579    #[tokio::test]
2580    async fn batch_chunks_enter_handler_atomically() {
2581        let client = BybitWebSocketClient::new_trade(
2582            BybitEnvironment::Testnet,
2583            trade_http_client(),
2584            None,
2585            20,
2586            TransportBackend::default(),
2587            None,
2588        );
2589        client
2590            .connection_mode
2591            .load()
2592            .store(ConnectionMode::Active.as_u8(), Ordering::Release);
2593        client.auth_tracker.succeed();
2594        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
2595        *client.cmd_tx.write().await = cmd_tx;
2596        let orders = (0..21)
2597            .map(|index| BybitWsCancelOrderParams {
2598                category: BybitProductType::Linear,
2599                symbol: Ustr::from("BTCUSDT"),
2600                order_id: Some(format!("order-{index}")),
2601                order_link_id: Some(format!("client-order-{index}")),
2602            })
2603            .collect::<Vec<_>>();
2604        let req_ids =
2605            BybitWebSocketClient::batch_request_ids(BybitProductType::Linear, orders.len());
2606
2607        client
2608            .batch_cancel_orders_with_ids(orders, req_ids.clone())
2609            .await
2610            .unwrap();
2611
2612        let command = cmd_rx.recv().await.expect("expected batch command");
2613        let HandlerCommand::SendOrders { commands } = command else {
2614            panic!("expected atomic batch command, was {command:?}");
2615        };
2616        assert_eq!(commands.len(), 3);
2617        assert_eq!(
2618            commands
2619                .iter()
2620                .map(|command| command.req_id.as_str())
2621                .collect::<Vec<_>>(),
2622            req_ids.iter().map(String::as_str).collect::<Vec<_>>()
2623        );
2624        assert_eq!(
2625            commands
2626                .iter()
2627                .map(|command| command.weight)
2628                .collect::<Vec<_>>(),
2629            vec![10, 10, 1]
2630        );
2631        assert!(cmd_rx.try_recv().is_err());
2632    }
2633
2634    #[tokio::test]
2635    async fn option_batch_chunks_preserve_request_correlation() {
2636        let client = BybitWebSocketClient::new_trade(
2637            BybitEnvironment::Testnet,
2638            trade_http_client(),
2639            None,
2640            20,
2641            TransportBackend::default(),
2642            None,
2643        );
2644        client
2645            .connection_mode
2646            .load()
2647            .store(ConnectionMode::Active.as_u8(), Ordering::Release);
2648        client.auth_tracker.succeed();
2649        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
2650        *client.cmd_tx.write().await = cmd_tx;
2651
2652        let place_template = BybitWsPlaceOrderParams {
2653            category: BybitProductType::Option,
2654            symbol: Ustr::from("BTC-30JUN25-100000-C"),
2655            side: BybitOrderSide::Buy,
2656            order_type: BybitOrderType::Limit,
2657            qty: "0.1".to_string(),
2658            is_leverage: None,
2659            market_unit: None,
2660            price: Some("500".to_string()),
2661            time_in_force: Some(BybitTimeInForce::Gtc),
2662            order_link_id: None,
2663            reduce_only: None,
2664            close_on_trigger: None,
2665            trigger_price: None,
2666            trigger_by: None,
2667            trigger_direction: None,
2668            tpsl_mode: None,
2669            take_profit: None,
2670            stop_loss: None,
2671            tp_trigger_by: None,
2672            sl_trigger_by: None,
2673            sl_trigger_price: None,
2674            tp_trigger_price: None,
2675            sl_order_type: None,
2676            tp_order_type: None,
2677            sl_limit_price: None,
2678            tp_limit_price: None,
2679            order_iv: Some("0.80".to_string()),
2680            smp_type: None,
2681            mmp: Some(true),
2682            position_idx: None,
2683            bbo_side_type: None,
2684            bbo_level: None,
2685        };
2686        let place_order_link_ids = (0..6)
2687            .map(|index| format!("option-place-{index}"))
2688            .collect::<Vec<_>>();
2689        let place_orders = place_order_link_ids
2690            .iter()
2691            .map(|order_link_id| BybitWsPlaceOrderParams {
2692                order_link_id: Some(order_link_id.clone()),
2693                ..place_template.clone()
2694            })
2695            .collect::<Vec<_>>();
2696        let place_req_ids =
2697            BybitWebSocketClient::batch_request_ids(BybitProductType::Option, place_orders.len());
2698
2699        client
2700            .batch_place_orders_with_ids(place_orders, place_req_ids.clone())
2701            .await
2702            .unwrap();
2703
2704        let command = cmd_rx.recv().await.expect("expected place batch command");
2705        let HandlerCommand::SendOrders { commands } = command else {
2706            panic!("expected atomic place batch command, was {command:?}");
2707        };
2708        assert_option_batch_commands(
2709            &commands,
2710            &place_req_ids,
2711            BybitWsOrderRequestOp::CreateBatch,
2712            &place_order_link_ids,
2713            batch_nested_items,
2714        );
2715
2716        let amend_template = BybitWsAmendOrderParams {
2717            category: BybitProductType::Option,
2718            symbol: Ustr::from("BTC-30JUN25-100000-C"),
2719            order_id: Some("venue-option-amend".to_string()),
2720            order_link_id: None,
2721            qty: Some("0.23".to_string()),
2722            price: Some("510.5".to_string()),
2723            trigger_price: Some("505.5".to_string()),
2724            take_profit: Some("530.5".to_string()),
2725            stop_loss: Some("490.5".to_string()),
2726            tp_trigger_by: Some(crate::common::enums::BybitTriggerType::MarkPrice),
2727            sl_trigger_by: Some(crate::common::enums::BybitTriggerType::IndexPrice),
2728            order_iv: Some("0.91".to_string()),
2729        };
2730        let amend_order_link_ids = (0..6)
2731            .map(|index| format!("option-amend-{index}"))
2732            .collect::<Vec<_>>();
2733        let amend_orders = amend_order_link_ids
2734            .iter()
2735            .map(|order_link_id| BybitWsAmendOrderParams {
2736                order_link_id: Some(order_link_id.clone()),
2737                ..amend_template.clone()
2738            })
2739            .collect::<Vec<_>>();
2740        let amend_req_ids =
2741            BybitWebSocketClient::batch_request_ids(BybitProductType::Option, amend_orders.len());
2742
2743        client
2744            .batch_amend_orders_with_ids(amend_orders, amend_req_ids.clone())
2745            .await
2746            .unwrap();
2747
2748        let command = cmd_rx.recv().await.expect("expected amend batch command");
2749        let HandlerCommand::SendOrders { commands } = command else {
2750            panic!("expected atomic amend batch command, was {command:?}");
2751        };
2752        assert_option_batch_commands(
2753            &commands,
2754            &amend_req_ids,
2755            BybitWsOrderRequestOp::AmendBatch,
2756            &amend_order_link_ids,
2757            batch_nested_items,
2758        );
2759        assert!(commands.iter().all(|command| command.args.len() == 1));
2760        assert!(
2761            commands
2762                .iter()
2763                .all(|command| command.args[0]["category"] == "option")
2764        );
2765        assert_eq!(
2766            commands[0].args[0]["request"][0],
2767            serde_json::json!({
2768                "symbol": "BTC-30JUN25-100000-C",
2769                "orderId": "venue-option-amend",
2770                "orderLinkId": "option-amend-0",
2771                "qty": "0.23",
2772                "price": "510.5",
2773                "triggerPrice": "505.5",
2774                "takeProfit": "530.5",
2775                "stopLoss": "490.5",
2776                "tpTriggerBy": "MarkPrice",
2777                "slTriggerBy": "IndexPrice",
2778                "orderIv": "0.91",
2779            })
2780        );
2781        assert!(
2782            commands
2783                .iter()
2784                .flat_map(batch_nested_items)
2785                .all(|order| order.get("category").is_none())
2786        );
2787
2788        let cancel_order_link_ids = (0..6)
2789            .map(|index| format!("option-cancel-{index}"))
2790            .collect::<Vec<_>>();
2791        let cancel_orders = cancel_order_link_ids
2792            .iter()
2793            .enumerate()
2794            .map(|(index, order_link_id)| BybitWsCancelOrderParams {
2795                category: BybitProductType::Option,
2796                symbol: Ustr::from("BTC-30JUN25-100000-C"),
2797                order_id: Some(format!("venue-option-{index}")),
2798                order_link_id: Some(order_link_id.clone()),
2799            })
2800            .collect::<Vec<_>>();
2801        let cancel_req_ids =
2802            BybitWebSocketClient::batch_request_ids(BybitProductType::Option, cancel_orders.len());
2803
2804        client
2805            .batch_cancel_orders_with_ids(cancel_orders, cancel_req_ids.clone())
2806            .await
2807            .unwrap();
2808
2809        let command = cmd_rx.recv().await.expect("expected cancel batch command");
2810        let HandlerCommand::SendOrders { commands } = command else {
2811            panic!("expected atomic cancel batch command, was {command:?}");
2812        };
2813        assert_option_batch_commands(
2814            &commands,
2815            &cancel_req_ids,
2816            BybitWsOrderRequestOp::CancelBatch,
2817            &cancel_order_link_ids,
2818            batch_nested_items,
2819        );
2820        assert!(cmd_rx.try_recv().is_err());
2821    }
2822
2823    fn assert_option_batch_commands(
2824        commands: &[BybitWsOrderCommand],
2825        req_ids: &[String],
2826        op: BybitWsOrderRequestOp,
2827        order_link_ids: &[String],
2828        items: for<'a> fn(&'a BybitWsOrderCommand) -> &'a [Value],
2829    ) {
2830        assert_eq!(req_ids.len(), 2);
2831        assert_ne!(req_ids[0], req_ids[1]);
2832        assert_eq!(commands.len(), 2);
2833        assert_eq!(
2834            commands
2835                .iter()
2836                .map(|command| command.req_id.as_str())
2837                .collect::<Vec<_>>(),
2838            req_ids.iter().map(String::as_str).collect::<Vec<_>>()
2839        );
2840        assert!(commands.iter().all(|command| command.op == op));
2841        assert_eq!(
2842            commands
2843                .iter()
2844                .map(|command| items(command).len())
2845                .collect::<Vec<_>>(),
2846            vec![5, 1]
2847        );
2848        assert_eq!(
2849            commands
2850                .iter()
2851                .flat_map(items)
2852                .map(|order| order["orderLinkId"].as_str().unwrap().to_string())
2853                .collect::<Vec<_>>(),
2854            order_link_ids
2855        );
2856        assert!(commands.iter().all(|command| command.weight == 1));
2857    }
2858
2859    fn batch_nested_items(command: &BybitWsOrderCommand) -> &[Value] {
2860        command.args[0]["request"].as_array().unwrap()
2861    }
2862
2863    #[rstest]
2864    fn batch_place_command_carries_smp_type_per_order() {
2865        let client = BybitWebSocketClient::new_trade(
2866            BybitEnvironment::Testnet,
2867            trade_http_client(),
2868            None,
2869            20,
2870            TransportBackend::default(),
2871            None,
2872        );
2873
2874        let expectations = [
2875            (Some(BybitOrderSmpType::CancelMaker), Some("CancelMaker")),
2876            (Some(BybitOrderSmpType::CancelBoth), Some("CancelBoth")),
2877            (None, None),
2878        ];
2879
2880        let orders = expectations
2881            .into_iter()
2882            .enumerate()
2883            .map(|(index, (smp_type, _))| {
2884                client
2885                    .build_place_order_params(
2886                        BybitProductType::Linear,
2887                        InstrumentId::from("ETHUSDT-LINEAR.BYBIT"),
2888                        ClientOrderId::from(format!("smp-batch-{index}").as_str()),
2889                        OrderSide::Buy,
2890                        OrderType::Limit,
2891                        Quantity::from("1.0"),
2892                        false,
2893                        Some(TimeInForce::Gtc),
2894                        Some(Price::from("50000.0")),
2895                        None,
2896                        None,
2897                        None,
2898                        None,
2899                        false,
2900                        None,
2901                        None,
2902                        None,
2903                        None,
2904                        None,
2905                        smp_type,
2906                    )
2907                    .expect("failed to build params")
2908            })
2909            .collect::<Vec<_>>();
2910
2911        let command = client
2912            .build_batch_place_command(orders, "req-smp-batch".to_string())
2913            .expect("failed to build batch command");
2914
2915        let items = batch_nested_items(&command);
2916
2917        assert_eq!(items.len(), expectations.len());
2918
2919        for (item, (_, expected)) in items.iter().zip(expectations) {
2920            assert_eq!(item.get("smpType").and_then(Value::as_str), expected);
2921        }
2922    }
2923
2924    #[rstest]
2925    fn test_race_duplicate_subscribe_messages_idempotent() {
2926        let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
2927        let topic = "publicTrade.BTCUSDT";
2928
2929        subscriptions.mark_subscribe(topic);
2930        subscriptions.confirm_subscribe(topic);
2931        assert_eq!(subscriptions.len(), 1);
2932
2933        subscriptions.mark_subscribe(topic);
2934        assert!(subscriptions.pending_subscribe_topics().is_empty());
2935        assert_eq!(subscriptions.len(), 1);
2936
2937        subscriptions.confirm_subscribe(topic);
2938        assert_eq!(subscriptions.len(), 1);
2939
2940        let all = subscriptions.all_topics();
2941        assert_eq!(all.len(), 1);
2942        assert_eq!(all[0], topic);
2943    }
2944
2945    #[rstest]
2946    #[case::spot_with_leverage(BybitProductType::Spot, true, Some(1))]
2947    #[case::spot_without_leverage(BybitProductType::Spot, false, Some(0))]
2948    #[case::linear_with_leverage(BybitProductType::Linear, true, None)]
2949    #[case::linear_without_leverage(BybitProductType::Linear, false, None)]
2950    #[case::inverse_with_leverage(BybitProductType::Inverse, true, None)]
2951    #[case::option_with_leverage(BybitProductType::Option, true, None)]
2952    fn test_is_leverage_parameter(
2953        #[case] product_type: BybitProductType,
2954        #[case] is_leverage: bool,
2955        #[case] expected: Option<i32>,
2956    ) {
2957        let symbol = match product_type {
2958            BybitProductType::Spot => "BTCUSDT-SPOT.BYBIT",
2959            BybitProductType::Linear => "ETHUSDT-LINEAR.BYBIT",
2960            BybitProductType::Inverse => "BTCUSD-INVERSE.BYBIT",
2961            BybitProductType::Option => "BTC-31MAY24-50000-C-OPTION.BYBIT",
2962        };
2963
2964        let instrument_id = InstrumentId::from(symbol);
2965        let client_order_id = ClientOrderId::from("test-order-1");
2966        let quantity = Quantity::from("1.0");
2967
2968        let client = BybitWebSocketClient::new_trade(
2969            BybitEnvironment::Testnet,
2970            trade_http_client(),
2971            None,
2972            20,
2973            TransportBackend::default(),
2974            None,
2975        );
2976
2977        let params = client
2978            .build_place_order_params(
2979                product_type,
2980                instrument_id,
2981                client_order_id,
2982                OrderSide::Buy,
2983                OrderType::Limit,
2984                quantity,
2985                false,
2986                Some(TimeInForce::Gtc),
2987                Some(Price::from("50000.0")),
2988                None,
2989                None,
2990                None,
2991                None,
2992                is_leverage,
2993                None,
2994                None,
2995                None,
2996                None,
2997                None,
2998                None,
2999            )
3000            .expect("Failed to build params");
3001
3002        assert_eq!(params.is_leverage, expected);
3003    }
3004
3005    #[rstest]
3006    #[case::spot_market_quote_quantity(
3007        BybitProductType::Spot,
3008        OrderType::Market,
3009        true,
3010        Some(BybitMarketUnit::QuoteCoin)
3011    )]
3012    #[case::spot_market_base_quantity(
3013        BybitProductType::Spot,
3014        OrderType::Market,
3015        false,
3016        Some(BybitMarketUnit::BaseCoin)
3017    )]
3018    #[case::spot_limit_no_unit(BybitProductType::Spot, OrderType::Limit, false, None)]
3019    #[case::spot_limit_quote(BybitProductType::Spot, OrderType::Limit, true, None)]
3020    #[case::linear_market_no_unit(BybitProductType::Linear, OrderType::Market, false, None)]
3021    #[case::inverse_market_no_unit(BybitProductType::Inverse, OrderType::Market, true, None)]
3022    fn test_is_quote_quantity_parameter(
3023        #[case] product_type: BybitProductType,
3024        #[case] order_type: OrderType,
3025        #[case] is_quote_quantity: bool,
3026        #[case] expected: Option<BybitMarketUnit>,
3027    ) {
3028        let symbol = match product_type {
3029            BybitProductType::Spot => "BTCUSDT-SPOT.BYBIT",
3030            BybitProductType::Linear => "ETHUSDT-LINEAR.BYBIT",
3031            BybitProductType::Inverse => "BTCUSD-INVERSE.BYBIT",
3032            BybitProductType::Option => "BTC-31MAY24-50000-C-OPTION.BYBIT",
3033        };
3034
3035        let instrument_id = InstrumentId::from(symbol);
3036        let client_order_id = ClientOrderId::from("test-order-1");
3037        let quantity = Quantity::from("1.0");
3038
3039        let client = BybitWebSocketClient::new_trade(
3040            BybitEnvironment::Testnet,
3041            trade_http_client(),
3042            None,
3043            20,
3044            TransportBackend::default(),
3045            None,
3046        );
3047
3048        let params = client
3049            .build_place_order_params(
3050                product_type,
3051                instrument_id,
3052                client_order_id,
3053                OrderSide::Buy,
3054                order_type,
3055                quantity,
3056                is_quote_quantity,
3057                Some(TimeInForce::Gtc),
3058                if order_type == OrderType::Market {
3059                    None
3060                } else {
3061                    Some(Price::from("50000.0"))
3062                },
3063                None,
3064                None,
3065                None,
3066                None,
3067                false,
3068                None,
3069                None,
3070                None,
3071                None,
3072                None,
3073                None,
3074            )
3075            .expect("Failed to build params");
3076
3077        assert_eq!(params.market_unit, expected);
3078    }
3079
3080    #[rstest]
3081    fn test_build_place_order_params_with_bbo_omits_price() {
3082        let client = BybitWebSocketClient::new_trade(
3083            BybitEnvironment::Testnet,
3084            trade_http_client(),
3085            None,
3086            20,
3087            TransportBackend::default(),
3088            None,
3089        );
3090
3091        let params = client
3092            .build_place_order_params(
3093                BybitProductType::Linear,
3094                InstrumentId::from("ETHUSDT-LINEAR.BYBIT"),
3095                ClientOrderId::from("test-bbo-order-1"),
3096                OrderSide::Buy,
3097                OrderType::Limit,
3098                Quantity::from("1.0"),
3099                false,
3100                Some(TimeInForce::Gtc),
3101                Some(Price::from("50000.0")),
3102                None,
3103                None,
3104                None,
3105                None,
3106                false,
3107                None,
3108                None,
3109                None,
3110                Some(BybitBboSideType::Queue),
3111                Some("2".to_string()),
3112                None,
3113            )
3114            .expect("Failed to build params");
3115
3116        assert_eq!(params.price, None);
3117        assert_eq!(params.bbo_side_type, Some(BybitBboSideType::Queue));
3118        assert_eq!(params.bbo_level.as_deref(), Some("2"));
3119    }
3120
3121    fn trade_http_client() -> BybitHttpClient {
3122        BybitHttpClient::with_credentials(
3123            "test-key".to_string(),
3124            "test-secret".to_string(),
3125            Some("http://127.0.0.1:1".to_string()),
3126            2,
3127            0,
3128            1,
3129            1,
3130            5_000,
3131            None,
3132        )
3133        .unwrap()
3134    }
3135}