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