Skip to main content

nautilus_bybit/websocket/
handler.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//! WebSocket message handler for Bybit.
17
18use std::{
19    collections::VecDeque,
20    sync::{
21        Arc,
22        atomic::{AtomicBool, AtomicU64, Ordering},
23    },
24};
25
26use dashmap::DashMap;
27use nautilus_core::string::secret::SecretString;
28use nautilus_live::book::snapshot::SnapshotGate;
29use nautilus_network::{
30    error::SendError,
31    retry::{RetryManager, create_websocket_retry_manager},
32    websocket::{AuthTracker, SubscriptionState, WebSocketClient},
33};
34use serde::Serialize;
35use serde_json::Value;
36use tokio_tungstenite::tungstenite::Message;
37use tokio_util::sync::CancellationToken;
38
39use super::{
40    enums::BybitWsOperation,
41    error::{BybitWsError, BybitWsResult, create_bybit_timeout_error, should_retry_bybit_error},
42    messages::{
43        BybitSubscription, BybitWebSocketError, BybitWsFrame, BybitWsMessage, BybitWsResponse,
44        BybitWsSubscriptionMsg,
45    },
46    parse::parse_bybit_ws_frame,
47};
48use crate::common::{
49    enums::{BybitProductType, BybitWsOrderRequestOp},
50    rate_limit::{
51        BYBIT_RATE_LIMIT_HEADER, BYBIT_RATE_LIMIT_RESET_HEADER, BYBIT_RATE_LIMIT_STATUS_HEADER,
52        BybitRateLimiter,
53    },
54};
55
56/// Semantic order command whose time-sensitive header is built at send time.
57#[derive(Debug)]
58pub struct BybitWsOrderCommand {
59    pub(crate) req_id: String,
60    pub(crate) op: BybitWsOrderRequestOp,
61    pub(crate) category: BybitProductType,
62    pub(crate) weight: u32,
63    pub(crate) referer: Option<String>,
64    pub(crate) args: Vec<Value>,
65}
66
67#[derive(Debug, Serialize)]
68#[serde(rename_all = "camelCase")]
69struct BybitWsSignedOrderRequest {
70    req_id: String,
71    op: BybitWsOrderRequestOp,
72    header: BybitWsSignedOrderHeader,
73    args: Vec<Value>,
74}
75
76#[derive(Debug, Serialize)]
77#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
78struct BybitWsSignedOrderHeader {
79    x_bapi_timestamp: String,
80    x_bapi_recv_window: String,
81    #[serde(rename = "Referer", skip_serializing_if = "Option::is_none")]
82    referer: Option<String>,
83}
84
85#[derive(Clone, Copy, Debug)]
86struct PendingRate {
87    endpoint: &'static str,
88    category: BybitProductType,
89}
90
91#[derive(Debug)]
92enum OrderSendFailure {
93    NotSent(BybitWsError),
94    Ambiguous(BybitWsError),
95}
96
97/// Commands sent from the outer client to the inner message handler.
98#[derive(Debug)]
99pub enum HandlerCommand {
100    SetClient(WebSocketClient),
101    Disconnect,
102    Authenticate {
103        payload: SecretString,
104    },
105    Subscribe {
106        topics: Vec<String>,
107    },
108    /// Subscribes to a book topic, opening `gate` once the connection confirms the write.
109    ///
110    /// A queued write always runs, since another subscription can hold the same topic.
111    SubscribeBook {
112        payload: String,
113        gate: SnapshotGate,
114        completion: tokio::sync::oneshot::Sender<BybitWsResult<()>>,
115    },
116    Unsubscribe {
117        topics: Vec<String>,
118    },
119    /// Replaces a book subscription on the current connection, opening `gate` once both writes
120    /// complete.
121    ResubscribeBook {
122        topic: String,
123        cancel: CancellationToken,
124        gate: SnapshotGate,
125        completion: tokio::sync::oneshot::Sender<BybitWsResult<()>>,
126    },
127    SendOrder {
128        command: BybitWsOrderCommand,
129    },
130    SendOrders {
131        commands: Vec<BybitWsOrderCommand>,
132    },
133}
134
135pub(super) struct BybitWsFeedHandler {
136    signal: Arc<AtomicBool>,
137    inner: Option<WebSocketClient>,
138    cmd_rx: tokio::sync::mpsc::UnboundedReceiver<HandlerCommand>,
139    raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
140    auth_tracker: AuthTracker,
141    subscriptions: SubscriptionState,
142    rate_limiter: BybitRateLimiter,
143    recv_window_ms: Arc<AtomicU64>,
144    pending_rates: DashMap<String, PendingRate>,
145    pending_orders: VecDeque<BybitWsOrderCommand>,
146    retry_manager: RetryManager<BybitWsError>,
147}
148
149impl BybitWsFeedHandler {
150    /// Creates a new [`BybitWsFeedHandler`] instance.
151    pub(super) fn new(
152        signal: Arc<AtomicBool>,
153        cmd_rx: tokio::sync::mpsc::UnboundedReceiver<HandlerCommand>,
154        raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
155        auth_tracker: AuthTracker,
156        subscriptions: SubscriptionState,
157        rate_limiter: BybitRateLimiter,
158        recv_window_ms: Arc<AtomicU64>,
159    ) -> Self {
160        Self {
161            signal,
162            inner: None,
163            cmd_rx,
164            raw_rx,
165            auth_tracker,
166            subscriptions,
167            rate_limiter,
168            recv_window_ms,
169            pending_rates: DashMap::new(),
170            pending_orders: VecDeque::new(),
171            retry_manager: create_websocket_retry_manager(),
172        }
173    }
174
175    pub(super) fn is_stopped(&self) -> bool {
176        self.signal.load(Ordering::Relaxed)
177    }
178
179    /// Sends a WebSocket message with retry logic.
180    async fn send_with_retry(&self, payload: String) -> Result<(), BybitWsError> {
181        self.send_secret_with_retry(payload.into(), None).await
182    }
183
184    async fn send_secret_with_retry(
185        &self,
186        payload: SecretString,
187        connection_epoch: Option<u64>,
188    ) -> Result<(), BybitWsError> {
189        if let Some(client) = &self.inner {
190            self.retry_manager
191                .invocation(
192                    "websocket_send",
193                    || {
194                        let payload = payload.clone();
195                        async move {
196                            let payload = payload.expose_secret().to_owned();
197
198                            let result = match connection_epoch {
199                                Some(epoch) => {
200                                    client.send_text_on_connection(payload, None, epoch).await
201                                }
202                                None => client.send_text(payload, None).await,
203                            };
204
205                            result.map_err(|e| match e {
206                                SendError::ConnectionChanged => BybitWsError::Authentication(
207                                    "Connection changed before authentication".to_string(),
208                                ),
209                                e => BybitWsError::Transport(format!("Send failed: {e}")),
210                            })
211                        }
212                    },
213                    should_retry_bybit_error,
214                    |e| create_bybit_timeout_error(e.to_string()),
215                )
216                .execute()
217                .await
218        } else {
219            Err(BybitWsError::ClientError(
220                "No active WebSocket client".to_string(),
221            ))
222        }
223    }
224
225    // Confirms the write on the current connection; a failed write is not replayed on the next
226    async fn write_book_subscription(&self, payload: String) -> BybitWsResult<()> {
227        let client = self.inner.as_ref().ok_or(BybitWsError::NotConnected)?;
228        let epoch = client.connection_epoch();
229
230        client
231            .send_text_on_connection(payload, None, epoch)
232            .await
233            .map_err(|e| BybitWsError::Transport(e.to_string()))
234    }
235
236    // Writes both requests on one connection so the venue replaces the subscription it serves,
237    // and never stops between them, since a depth-1 topic can also carry quotes
238    async fn resubscribe_book(&self, topic: &str) -> BybitWsResult<()> {
239        let client = self.inner.as_ref().ok_or(BybitWsError::NotConnected)?;
240        let epoch = client.connection_epoch();
241
242        // Keeps the topic replayed on reconnect until the venue confirms the new subscription
243        self.subscriptions.mark_failure(topic);
244
245        let topic = topic.to_string();
246
247        for op in [BybitWsOperation::Unsubscribe, BybitWsOperation::Subscribe] {
248            let request = BybitSubscription {
249                op,
250                args: vec![topic.clone()],
251                req_id: Some(topic.clone()),
252            };
253
254            let payload = serde_json::to_string(&request)?;
255            client.send_text_on_connection(payload, None, epoch).await?;
256        }
257
258        Ok(())
259    }
260
261    async fn send_order(&self, command: &BybitWsOrderCommand) -> Result<bool, OrderSendFailure> {
262        if !self.auth_tracker.is_authenticated() {
263            return Ok(false);
264        }
265
266        let client = self.inner.as_ref().ok_or_else(|| {
267            OrderSendFailure::NotSent(BybitWsError::ClientError(
268                "No active WebSocket client".to_string(),
269            ))
270        })?;
271        let (endpoint, _) = order_operation(command.op);
272
273        self.rate_limiter
274            .acquire_ws_order(endpoint, command.category, command.weight)
275            .await
276            .map_err(|e| OrderSendFailure::NotSent(BybitWsError::ClientError(e)))?;
277
278        if !self.auth_tracker.is_authenticated() {
279            return Ok(false);
280        }
281
282        let connection_epoch = client.connection_epoch();
283        let recv_window_ms = self.recv_window_ms.load(Ordering::Acquire);
284        let request = BybitWsSignedOrderRequest {
285            req_id: command.req_id.clone(),
286            op: command.op,
287            header: BybitWsSignedOrderHeader {
288                x_bapi_timestamp: nautilus_core::time::get_atomic_clock_realtime()
289                    .get_time_ms()
290                    .to_string(),
291                x_bapi_recv_window: recv_window_ms.to_string(),
292                referer: command.referer.clone(),
293            },
294            args: command.args.clone(),
295        };
296        let payload = serde_json::to_string(&request)
297            .map_err(|e| OrderSendFailure::NotSent(BybitWsError::Json(e.to_string())))?;
298        self.pending_rates.insert(
299            command.req_id.clone(),
300            PendingRate {
301                endpoint,
302                category: command.category,
303            },
304        );
305
306        match client
307            .send_text_on_connection(payload, None, connection_epoch)
308            .await
309        {
310            Ok(()) => Ok(true),
311            Err(e) => self.classify_order_send_error(&command.req_id, e),
312        }
313    }
314
315    fn classify_order_send_error(
316        &self,
317        req_id: &str,
318        error: SendError,
319    ) -> Result<bool, OrderSendFailure> {
320        match error {
321            SendError::ConnectionChanged => {
322                self.pending_rates.remove(req_id);
323                self.auth_tracker.invalidate();
324                Ok(false)
325            }
326            SendError::Timeout => {
327                self.pending_rates.remove(req_id);
328                self.auth_tracker.invalidate();
329                Err(OrderSendFailure::NotSent(BybitWsError::ClientError(
330                    "Order command was not written".to_string(),
331                )))
332            }
333            SendError::InvalidInput(_) | SendError::BufferFull | SendError::Closed => {
334                self.pending_rates.remove(req_id);
335                Err(OrderSendFailure::NotSent(BybitWsError::ClientError(
336                    "Order command was not written".to_string(),
337                )))
338            }
339            error => Err(OrderSendFailure::Ambiguous(BybitWsError::Send(
340                error.to_string(),
341            ))),
342        }
343    }
344
345    pub(super) async fn next(&mut self) -> Option<BybitWsMessage> {
346        loop {
347            if self.auth_tracker.is_authenticated()
348                && let Some(command) = self.pending_orders.pop_front()
349            {
350                let req_id = command.req_id.clone();
351                match self.send_order(&command).await {
352                    Ok(true) => {}
353                    Ok(false) => self.pending_orders.push_front(command),
354                    Err(OrderSendFailure::NotSent(error)) => {
355                        return Some(order_not_sent_message(&command, &error));
356                    }
357                    Err(OrderSendFailure::Ambiguous(error)) => {
358                        log::warn!("Ambiguous order send failure: req_id={req_id}, error={error}");
359                    }
360                }
361                continue;
362            }
363
364            tokio::select! {
365                Some(cmd) = self.cmd_rx.recv() => {
366                    match cmd {
367                        HandlerCommand::SetClient(client) => {
368                            log::debug!("WebSocketClient received by handler");
369                            self.inner = Some(client);
370                        }
371                        HandlerCommand::Disconnect => {
372                            log::debug!("Disconnect command received");
373
374                            if let Some(client) = self.inner.take() {
375                                client.disconnect().await;
376                            }
377                        }
378                        HandlerCommand::Authenticate { payload } => {
379                            log::debug!("Authenticate command received");
380
381                            let epoch = self.inner.as_ref().map(WebSocketClient::connection_epoch);
382                            if let Err(e) = self.send_secret_with_retry(payload, epoch).await {
383                                log::error!("Failed to send authentication after retries: {e}");
384                            }
385                        }
386                        HandlerCommand::Subscribe { topics } => {
387                            for topic in topics {
388                                log::debug!("Subscribing to topic: topic={topic}");
389                                if let Err(e) = self.send_with_retry(topic.clone()).await {
390                                    log::error!("Failed to send subscription after retries: topic={topic}, error={e}");
391                                }
392                            }
393                        }
394                        HandlerCommand::SubscribeBook { payload, gate, completion } => {
395                            let result = self.write_book_subscription(payload).await;
396
397                            if result.is_ok() {
398                                gate.open();
399                            }
400                            let _ = completion.send(result);
401                        }
402                        HandlerCommand::Unsubscribe { topics } => {
403                            for topic in topics {
404                                log::debug!("Unsubscribing from topic: topic={topic}");
405                                if let Err(e) = self.send_with_retry(topic.clone()).await {
406                                    log::error!("Failed to send unsubscription after retries: topic={topic}, error={e}");
407                                }
408                            }
409                        }
410                        HandlerCommand::ResubscribeBook { topic, cancel, gate, completion } => {
411                            if cancel.is_cancelled() {
412                                continue;
413                            }
414
415                            let result = self.resubscribe_book(&topic).await;
416
417                            if result.is_ok() {
418                                gate.open();
419                            }
420                            let _ = completion.send(result);
421                        }
422                        HandlerCommand::SendOrder { command } => {
423                            let req_id = command.req_id.clone();
424                            match self.send_order(&command).await {
425                                Ok(true) => {}
426                                Ok(false) => self.pending_orders.push_back(command),
427                                Err(OrderSendFailure::NotSent(error)) => {
428                                    return Some(order_not_sent_message(&command, &error));
429                                }
430                                Err(OrderSendFailure::Ambiguous(error)) => {
431                                    log::warn!(
432                                        "Ambiguous order send failure: req_id={req_id}, error={error}"
433                                    );
434                                }
435                            }
436                        }
437                        HandlerCommand::SendOrders { commands } => {
438                            self.pending_orders.extend(commands);
439                        }
440                    }
441                }
442
443                () = tokio::time::sleep(std::time::Duration::from_millis(100)) => {
444                    if self.signal.load(Ordering::Relaxed) {
445                        log::debug!("Stop signal received during idle period");
446                        return None;
447                    }
448                }
449
450                msg = self.raw_rx.recv() => {
451                    let msg = match msg {
452                        Some(msg) => msg,
453                        None => {
454                            log::debug!("WebSocket stream closed");
455                            return None;
456                        }
457                    };
458
459                    if let Message::Ping(data) = &msg {
460                        log::trace!("Received ping frame with {} bytes", data.len());
461
462                        if let Some(client) = &self.inner
463                            && let Err(e) = client.send_pong(data.to_vec()).await
464                        {
465                            log::warn!("Failed to send pong frame: error={e}");
466                        }
467                        continue;
468                    }
469
470                    let frame = match Self::parse_raw_frame(msg) {
471                        Some(frame) => frame,
472                        None => continue,
473                    };
474
475                    if self.signal.load(Ordering::Relaxed) {
476                        log::debug!("Stop signal received");
477                        return None;
478                    }
479
480                    match frame {
481                        BybitWsFrame::Subscription(ref sub_msg) => {
482                            self.handle_subscription_ack(sub_msg);
483                        }
484                        BybitWsFrame::Auth(auth_response) => {
485                            let is_success = auth_response.success.unwrap_or(false)
486                                || (auth_response.ret_code == Some(0));
487
488                            if is_success {
489                                self.auth_tracker.succeed();
490                                log::debug!("WebSocket authenticated");
491                            } else {
492                                let error_msg = auth_response
493                                    .ret_msg
494                                    .as_deref()
495                                    .unwrap_or("Authentication rejected");
496                                self.auth_tracker.fail(error_msg);
497                                log::error!("WebSocket authentication failed: error={error_msg}");
498                            }
499                            return Some(BybitWsMessage::Auth(auth_response));
500                        }
501                        BybitWsFrame::ErrorResponse(ref resp) => {
502                            // Failed subscription/unsubscription ACKs arrive as
503                            // ErrorResponse when success=false. Route them through
504                            // the subscription state machine when the op field is
505                            // present, otherwise forward as a generic error.
506                            if let Some(op) = &resp.op {
507                                if *op == BybitWsOperation::Subscribe
508                                    || *op == BybitWsOperation::Unsubscribe
509                                {
510                                    self.handle_subscription_error(resp);
511                                } else {
512                                    let error = BybitWebSocketError::from_response(resp);
513                                    return Some(BybitWsMessage::Error(error));
514                                }
515                            } else {
516                                let error = BybitWebSocketError::from_response(resp);
517                                return Some(BybitWsMessage::Error(error));
518                            }
519                        }
520                        BybitWsFrame::OrderResponse(resp) => {
521                            self.observe_order_rate_limit(&resp);
522                            return Some(BybitWsMessage::OrderResponse(resp));
523                        }
524                        BybitWsFrame::Orderbook(msg) => {
525                            return Some(BybitWsMessage::Orderbook(msg));
526                        }
527                        BybitWsFrame::Trade(msg) => {
528                            return Some(BybitWsMessage::Trade(msg));
529                        }
530                        BybitWsFrame::Liquidation(msg) => {
531                            return Some(BybitWsMessage::Liquidation(msg));
532                        }
533                        BybitWsFrame::Kline(msg) => {
534                            return Some(BybitWsMessage::Kline(msg));
535                        }
536                        BybitWsFrame::TickerLinear(msg) => {
537                            return Some(BybitWsMessage::TickerLinear(msg));
538                        }
539                        BybitWsFrame::TickerOption(msg) => {
540                            return Some(BybitWsMessage::TickerOption(msg));
541                        }
542                        BybitWsFrame::AccountOrder(msg) => {
543                            return Some(BybitWsMessage::AccountOrder(msg));
544                        }
545                        BybitWsFrame::AccountExecution(msg) => {
546                            return Some(BybitWsMessage::AccountExecution(msg));
547                        }
548                        BybitWsFrame::AccountExecutionFast(msg) => {
549                            return Some(BybitWsMessage::AccountExecutionFast(msg));
550                        }
551                        BybitWsFrame::AccountWallet(msg) => {
552                            return Some(BybitWsMessage::AccountWallet(msg));
553                        }
554                        BybitWsFrame::AccountPosition(msg) => {
555                            return Some(BybitWsMessage::AccountPosition(msg));
556                        }
557                        BybitWsFrame::Reconnected => {
558                            self.auth_tracker.invalidate();
559                            return Some(BybitWsMessage::Reconnected);
560                        }
561                        BybitWsFrame::Unknown(value) => {
562                            log::debug!("Unknown WebSocket frame: {value}");
563                        }
564                    }
565                }
566            }
567        }
568    }
569
570    fn observe_order_rate_limit(&self, response: &super::messages::BybitWsOrderResponse) {
571        let Some(req_id) = response.req_id.as_deref() else {
572            return;
573        };
574        let Some((_, pending)) = self.pending_rates.remove(req_id) else {
575            return;
576        };
577        let Some(header) = response.header.as_ref() else {
578            return;
579        };
580        let parse_u32 = |key: &str| {
581            header.get(key).and_then(|value| {
582                value
583                    .as_u64()
584                    .and_then(|value| u32::try_from(value).ok())
585                    .or_else(|| value.as_str()?.parse::<u32>().ok())
586            })
587        };
588        let Some(limit) = parse_u32(BYBIT_RATE_LIMIT_HEADER) else {
589            return;
590        };
591        let Some(remaining) = parse_u32(BYBIT_RATE_LIMIT_STATUS_HEADER) else {
592            return;
593        };
594        let reset_timestamp_ms = header.get(BYBIT_RATE_LIMIT_RESET_HEADER).and_then(|value| {
595            value
596                .as_i64()
597                .or_else(|| value.as_str()?.parse::<i64>().ok())
598        });
599        self.rate_limiter.observe_account(
600            pending.endpoint,
601            Some(pending.category),
602            limit,
603            remaining,
604            reset_timestamp_ms,
605        );
606    }
607
608    fn handle_subscription_ack(&self, sub_msg: &BybitWsSubscriptionMsg) {
609        match sub_msg.op {
610            BybitWsOperation::Subscribe => {
611                if sub_msg.success {
612                    if let Some(topic) = &sub_msg.req_id {
613                        self.subscriptions.confirm_subscribe(topic);
614                        log::debug!("Subscription confirmed: topic={topic}");
615                    } else {
616                        // No req_id, fall back to confirming all pending
617                        for topic in self.subscriptions.pending_subscribe_topics() {
618                            self.subscriptions.confirm_subscribe(&topic);
619                            log::debug!("Subscription confirmed (bulk): topic={topic}");
620                        }
621                    }
622                } else if let Some(topic) = &sub_msg.req_id {
623                    self.subscriptions.mark_failure(topic);
624                    log::warn!(
625                        "Subscription failed: topic={topic}, error={:?}",
626                        sub_msg.ret_msg
627                    );
628                } else {
629                    for topic in self.subscriptions.pending_subscribe_topics() {
630                        self.subscriptions.mark_failure(&topic);
631                        log::warn!(
632                            "Subscription failed (bulk): topic={topic}, error={:?}",
633                            sub_msg.ret_msg
634                        );
635                    }
636                }
637            }
638            BybitWsOperation::Unsubscribe => {
639                if sub_msg.success {
640                    if let Some(topic) = &sub_msg.req_id {
641                        self.subscriptions.confirm_unsubscribe(topic);
642                        log::debug!("Unsubscription confirmed: topic={topic}");
643                    } else {
644                        for topic in self.subscriptions.pending_unsubscribe_topics() {
645                            self.subscriptions.confirm_unsubscribe(&topic);
646                            log::debug!("Unsubscription confirmed (bulk): topic={topic}");
647                        }
648                    }
649                } else {
650                    let topic_desc = sub_msg.req_id.as_deref().unwrap_or("unknown");
651                    log::warn!(
652                        "Unsubscription failed: topic={topic_desc}, error={:?}",
653                        sub_msg.ret_msg
654                    );
655                }
656            }
657            _ => {}
658        }
659    }
660
661    fn handle_subscription_error(&self, resp: &BybitWsResponse) {
662        let topic = resp.req_id.as_deref().unwrap_or("unknown");
663        let error_msg = resp.ret_msg.as_deref().unwrap_or("unknown error");
664
665        match resp.op {
666            Some(BybitWsOperation::Subscribe) => {
667                // Duplicate subscribe is harmless: the topic is active on the
668                // venue, so confirm it instead of looping retries every reconnect.
669                if is_already_subscribed_error(error_msg)
670                    && let Some(ref req_id) = resp.req_id
671                {
672                    self.subscriptions.confirm_subscribe(req_id);
673                    log::debug!("Subscription duplicate ignored: topic={topic}, error={error_msg}");
674                    return;
675                }
676
677                if let Some(ref req_id) = resp.req_id {
678                    self.subscriptions.mark_failure(req_id);
679                } else {
680                    for t in self.subscriptions.pending_subscribe_topics() {
681                        self.subscriptions.mark_failure(&t);
682                    }
683                }
684                log::warn!("Subscription error: topic={topic}, error={error_msg}");
685            }
686            Some(BybitWsOperation::Unsubscribe) => {
687                log::warn!("Unsubscription error: topic={topic}, error={error_msg}");
688            }
689            _ => {}
690        }
691    }
692
693    fn parse_raw_frame(msg: Message) -> Option<BybitWsFrame> {
694        match msg {
695            Message::Text(text) => {
696                if text == nautilus_network::RECONNECTED {
697                    log::debug!("Received WebSocket reconnected signal");
698                    return Some(BybitWsFrame::Reconnected);
699                }
700
701                if text.trim().eq_ignore_ascii_case("pong") {
702                    return None;
703                }
704
705                log::trace!("Raw websocket message: {text}");
706
707                let value: serde_json::Value = match serde_json::from_str(&text) {
708                    Ok(v) => v,
709                    Err(e) => {
710                        log::error!("Failed to parse WebSocket message: {e}: {text}");
711                        return None;
712                    }
713                };
714
715                if value
716                    .get("op")
717                    .and_then(serde_json::Value::as_str)
718                    .is_some_and(|op| op == BybitWsOperation::Pong.as_ref())
719                {
720                    return None;
721                }
722
723                Some(parse_bybit_ws_frame(value))
724            }
725            Message::Binary(msg) => {
726                log::debug!("Raw binary frame ({} bytes)", msg.len());
727                log::trace!("Raw binary: {msg:?}");
728                None
729            }
730            Message::Close(_) => {
731                log::debug!("Received close message, waiting for reconnection");
732                None
733            }
734            _ => None,
735        }
736    }
737}
738
739fn order_operation(op: BybitWsOrderRequestOp) -> (&'static str, &'static str) {
740    match op {
741        BybitWsOrderRequestOp::Create => ("/v5/order/create", "order.create"),
742        BybitWsOrderRequestOp::Amend => ("/v5/order/amend", "order.amend"),
743        BybitWsOrderRequestOp::Cancel => ("/v5/order/cancel", "order.cancel"),
744        BybitWsOrderRequestOp::CreateBatch => ("/v5/order/create-batch", "order.create-batch"),
745        BybitWsOrderRequestOp::AmendBatch => ("/v5/order/amend-batch", "order.amend-batch"),
746        BybitWsOrderRequestOp::CancelBatch => ("/v5/order/cancel-batch", "order.cancel-batch"),
747    }
748}
749
750fn order_not_sent_message(command: &BybitWsOrderCommand, error: &BybitWsError) -> BybitWsMessage {
751    BybitWsMessage::OrderNotSent {
752        request_id: command.req_id.clone(),
753        reason: error.to_string(),
754    }
755}
756
757fn is_already_subscribed_error(error_msg: &str) -> bool {
758    error_msg
759        .to_ascii_lowercase()
760        .contains("already subscribed")
761}
762
763#[cfg(test)]
764mod tests {
765    use std::time::Duration;
766
767    use futures_util::{SinkExt, StreamExt};
768    use nautilus_common::testing::wait_until_async;
769    use nautilus_core::string::secret::REDACTED;
770    use nautilus_network::websocket::{WebSocketConfig, channel_message_handler};
771    use rstest::rstest;
772    use ustr::Ustr;
773
774    use super::*;
775    use crate::common::{
776        consts::BYBIT_WS_TOPIC_DELIMITER, rate_limit::BybitRateLimiter, testing::load_test_json,
777    };
778
779    fn create_test_handler() -> BybitWsFeedHandler {
780        let signal = Arc::new(AtomicBool::new(false));
781        let (_cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
782        let (_raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
783        let auth_tracker = AuthTracker::new();
784        let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
785
786        BybitWsFeedHandler::new(
787            signal,
788            cmd_rx,
789            raw_rx,
790            auth_tracker,
791            subscriptions,
792            BybitRateLimiter::for_websocket(
793                "wss://bybit-handler-test.invalid",
794                Some("test-key"),
795                None,
796            ),
797            Arc::new(AtomicU64::new(5_000)),
798        )
799    }
800
801    #[tokio::test]
802    async fn test_authentication_with_full_replay_buffer() {
803        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
804        let address = listener.local_addr().unwrap();
805        let (replayed_tx, replayed_rx) = tokio::sync::oneshot::channel();
806
807        let server = tokio::spawn(async move {
808            let (first, _) = listener.accept().await.unwrap();
809            let _first = tokio_tungstenite::accept_async(first).await.unwrap();
810            let (replacement, _) = listener.accept().await.unwrap();
811            let mut replacement = tokio_tungstenite::accept_async(replacement).await.unwrap();
812            assert_eq!(
813                replacement.next().await.unwrap().unwrap(),
814                Message::text("authenticate")
815            );
816            replacement
817                .send(Message::text(load_test_json("ws_auth_success.json")))
818                .await
819                .unwrap();
820            assert_eq!(
821                replacement.next().await.unwrap().unwrap(),
822                Message::text("held")
823            );
824            replayed_tx.send(()).unwrap();
825            std::future::pending::<()>().await;
826        });
827
828        let mut handler = create_test_handler();
829        let tracker = handler.auth_tracker.clone();
830        let (message_handler, raw_rx) = channel_message_handler();
831        handler.raw_rx = raw_rx;
832        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
833        handler.cmd_rx = cmd_rx;
834        let config = WebSocketConfig::builder()
835            .url(format!("ws://{address}"))
836            .writer_capacity(1)
837            .reconnect_delay_initial_ms(1)
838            .reconnect_delay_max_ms(1)
839            .reconnect_jitter_ms(0)
840            .build()
841            .unwrap();
842        let client = WebSocketClient::builder()
843            .config(config)
844            .message_handler(message_handler)
845            .connect()
846            .await
847            .unwrap();
848        client.set_auth_tracker(tracker.clone(), true);
849
850        // Enqueue and request reconnect without yielding so the writer retains this message
851        client.send_text("held".to_string(), None).await.unwrap();
852        assert!(client.request_reconnect());
853        wait_until_async(
854            || async { client.is_active() && client.connection_epoch() == 1 },
855            Duration::from_secs(5),
856        )
857        .await;
858        assert!(matches!(
859            client.send_text("overflow".to_string(), None).await,
860            Err(SendError::BufferFull)
861        ));
862        handler.inner = Some(client);
863        let stale = tokio::time::timeout(
864            Duration::from_secs(5),
865            handler.send_secret_with_retry(SecretString::from("stale-auth".to_string()), Some(0)),
866        )
867        .await
868        .unwrap();
869        assert!(
870            matches!(stale, Err(BybitWsError::Authentication(message)) if message == "Connection changed before authentication")
871        );
872        cmd_tx
873            .send(HandlerCommand::Authenticate {
874                payload: SecretString::from("authenticate".to_string()),
875            })
876            .unwrap();
877
878        tokio::time::timeout(Duration::from_secs(5), async {
879            loop {
880                if let Some(BybitWsMessage::Auth(response)) = handler.next().await {
881                    assert_eq!(response.success, Some(true));
882                    break;
883                }
884            }
885        })
886        .await
887        .unwrap();
888
889        assert!(tracker.is_authenticated());
890        tokio::time::timeout(Duration::from_secs(5), replayed_rx)
891            .await
892            .unwrap()
893            .unwrap();
894        handler.inner.as_ref().unwrap().disconnect().await;
895        server.abort();
896    }
897
898    async fn connect_book_handler() -> (
899        BybitWsFeedHandler,
900        tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
901        tokio::sync::mpsc::UnboundedReceiver<Value>,
902    ) {
903        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
904        let address = listener.local_addr().unwrap();
905        let (requests_tx, requests_rx) = tokio::sync::mpsc::unbounded_channel();
906
907        // Forwards each request as it arrives, since a completed write may still be queued
908        tokio::spawn(async move {
909            let (stream, _) = listener.accept().await.unwrap();
910            let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
911
912            while let Some(Ok(Message::Text(text))) = socket.next().await {
913                let request = serde_json::from_str::<Value>(&text).unwrap();
914
915                if requests_tx.send(request).is_err() {
916                    break;
917                }
918            }
919        });
920
921        let mut handler = create_test_handler();
922        let (message_handler, raw_rx) = channel_message_handler();
923        handler.raw_rx = raw_rx;
924        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
925        handler.cmd_rx = cmd_rx;
926        let config = WebSocketConfig::builder()
927            .url(format!("ws://{address}"))
928            .build()
929            .unwrap();
930        let client = WebSocketClient::builder()
931            .config(config)
932            .message_handler(message_handler)
933            .connect()
934            .await
935            .unwrap();
936        handler.inner = Some(client);
937
938        (handler, cmd_tx, requests_rx)
939    }
940
941    async fn complete_book_command(
942        handler: &mut BybitWsFeedHandler,
943        receiver: tokio::sync::oneshot::Receiver<BybitWsResult<()>>,
944    ) -> Result<BybitWsResult<()>, tokio::sync::oneshot::error::RecvError> {
945        let drive = async {
946            loop {
947                handler.next().await;
948            }
949        };
950
951        tokio::time::timeout(Duration::from_secs(5), async {
952            tokio::select! {
953                result = receiver => result,
954                () = drive => unreachable!("handler loop never ends"),
955            }
956        })
957        .await
958        .unwrap()
959    }
960
961    async fn next_request(requests: &mut tokio::sync::mpsc::UnboundedReceiver<Value>) -> Value {
962        tokio::time::timeout(Duration::from_secs(5), requests.recv())
963            .await
964            .unwrap()
965            .unwrap()
966    }
967
968    fn subscription_request(op: &str, topic: &str) -> Value {
969        serde_json::json!({"op": op, "args": [topic], "req_id": topic})
970    }
971
972    fn subscribe_book_command(
973        topic: &str,
974        gate: SnapshotGate,
975    ) -> (
976        HandlerCommand,
977        tokio::sync::oneshot::Receiver<BybitWsResult<()>>,
978    ) {
979        let payload = subscription_request("subscribe", topic).to_string();
980        let (completion, receiver) = tokio::sync::oneshot::channel();
981
982        let command = HandlerCommand::SubscribeBook {
983            payload,
984            gate,
985            completion,
986        };
987
988        (command, receiver)
989    }
990
991    #[tokio::test]
992    async fn test_subscribe_book_opens_gate_after_write() {
993        let (mut handler, cmd_tx, mut requests) = connect_book_handler().await;
994        let topic = "orderbook.50.BTCUSDT";
995        let gate = SnapshotGate::default();
996        gate.lock().close();
997        let (command, receiver) = subscribe_book_command(topic, gate.clone());
998
999        cmd_tx.send(command).unwrap();
1000        let result = complete_book_command(&mut handler, receiver).await;
1001        let request = next_request(&mut requests).await;
1002
1003        assert!(matches!(result, Ok(Ok(()))));
1004        assert!(!gate.lock().is_closed());
1005        assert_eq!(request, subscription_request("subscribe", topic));
1006        handler.inner.as_ref().unwrap().disconnect().await;
1007    }
1008
1009    #[tokio::test]
1010    async fn test_resubscribe_book_replaces_subscription_and_opens_gate() {
1011        let (mut handler, cmd_tx, mut requests) = connect_book_handler().await;
1012        let topic = "orderbook.50.BTCUSDT";
1013        handler.subscriptions.mark_subscribe(topic);
1014        handler.subscriptions.confirm_subscribe(topic);
1015        let gate = SnapshotGate::default();
1016        gate.lock().close();
1017        let (completion, receiver) = tokio::sync::oneshot::channel();
1018
1019        cmd_tx
1020            .send(HandlerCommand::ResubscribeBook {
1021                topic: topic.to_string(),
1022                cancel: CancellationToken::new(),
1023                gate: gate.clone(),
1024                completion,
1025            })
1026            .unwrap();
1027
1028        let result = complete_book_command(&mut handler, receiver).await;
1029        let pending = handler.subscriptions.pending_subscribe_topics();
1030        let unsubscribe = next_request(&mut requests).await;
1031        let subscribe = next_request(&mut requests).await;
1032
1033        assert!(matches!(result, Ok(Ok(()))));
1034        assert!(!gate.lock().is_closed());
1035        assert_eq!(pending, [topic]);
1036        assert_eq!(unsubscribe, subscription_request("unsubscribe", topic));
1037        assert_eq!(subscribe, subscription_request("subscribe", topic));
1038        handler.inner.as_ref().unwrap().disconnect().await;
1039    }
1040
1041    #[tokio::test]
1042    async fn test_subscribe_book_write_failure_keeps_gate_closed() {
1043        let (mut handler, cmd_tx, _requests) = connect_book_handler().await;
1044        handler.inner.as_ref().unwrap().disconnect().await;
1045        let gate = SnapshotGate::default();
1046        gate.lock().close();
1047        let (command, receiver) = subscribe_book_command("orderbook.50.BTCUSDT", gate.clone());
1048
1049        cmd_tx.send(command).unwrap();
1050        let result = complete_book_command(&mut handler, receiver).await;
1051
1052        assert!(matches!(result, Ok(Err(BybitWsError::Transport(_)))));
1053        assert!(gate.lock().is_closed());
1054    }
1055
1056    // A later subscribe arrives first; any replacement write would complete before its completion
1057    #[tokio::test]
1058    async fn test_resubscribe_book_cancelled_before_write_sends_nothing() {
1059        let (mut handler, cmd_tx, mut requests) = connect_book_handler().await;
1060        let topic = "orderbook.50.BTCUSDT";
1061        handler.subscriptions.mark_subscribe(topic);
1062        handler.subscriptions.confirm_subscribe(topic);
1063        let gate = SnapshotGate::default();
1064        gate.lock().close();
1065        let cancel = CancellationToken::new();
1066        cancel.cancel();
1067        let (completion, receiver) = tokio::sync::oneshot::channel();
1068        let sentinel = "orderbook.50.ETHUSDT";
1069        let (sentinel_command, sentinel_receiver) =
1070            subscribe_book_command(sentinel, SnapshotGate::default());
1071
1072        cmd_tx
1073            .send(HandlerCommand::ResubscribeBook {
1074                topic: topic.to_string(),
1075                cancel,
1076                gate: gate.clone(),
1077                completion,
1078            })
1079            .unwrap();
1080
1081        let result = complete_book_command(&mut handler, receiver).await;
1082        cmd_tx.send(sentinel_command).unwrap();
1083        let sentinel_result = complete_book_command(&mut handler, sentinel_receiver).await;
1084        let pending = handler.subscriptions.pending_subscribe_topics();
1085        let request = next_request(&mut requests).await;
1086
1087        assert!(result.is_err());
1088        assert!(matches!(sentinel_result, Ok(Ok(()))));
1089        assert!(gate.lock().is_closed());
1090        assert!(pending.is_empty());
1091        assert_eq!(request, subscription_request("subscribe", sentinel));
1092        handler.inner.as_ref().unwrap().disconnect().await;
1093    }
1094
1095    #[rstest]
1096    fn test_authenticate_command_debug_redacts_payload() {
1097        let payload = "authentication-secret";
1098        let command = HandlerCommand::Authenticate {
1099            payload: SecretString::from(payload.to_string()),
1100        };
1101
1102        let debug = format!("{command:?}");
1103
1104        assert!(debug.contains(REDACTED));
1105        assert!(!debug.contains(payload));
1106    }
1107
1108    fn load_value(fixture: &str) -> serde_json::Value {
1109        let json = load_test_json(fixture);
1110        serde_json::from_str(&json).unwrap()
1111    }
1112
1113    #[rstest]
1114    fn test_handler_initializes() {
1115        let _handler = create_test_handler();
1116    }
1117
1118    #[tokio::test]
1119    async fn order_without_writer_produces_correlated_terminal_response() {
1120        let handler = create_test_handler();
1121        handler.auth_tracker.succeed();
1122        let command = BybitWsOrderCommand {
1123            req_id: "not-sent-request".to_string(),
1124            op: BybitWsOrderRequestOp::Create,
1125            category: BybitProductType::Linear,
1126            weight: 1,
1127            referer: None,
1128            args: vec![serde_json::json!({"category": "linear"})],
1129        };
1130
1131        let failure = handler.send_order(&command).await.unwrap_err();
1132        let OrderSendFailure::NotSent(error) = failure else {
1133            panic!("Expected definitive not-sent failure, was {failure:?}");
1134        };
1135
1136        let BybitWsMessage::OrderNotSent { request_id, reason } =
1137            order_not_sent_message(&command, &error)
1138        else {
1139            panic!("Expected order response");
1140        };
1141
1142        assert_eq!(request_id, "not-sent-request");
1143        assert_eq!(reason, "Client error: No active WebSocket client");
1144    }
1145
1146    #[rstest]
1147    fn connection_change_invalidates_authentication_before_requeue() {
1148        let handler = create_test_handler();
1149        handler.auth_tracker.succeed();
1150        handler.pending_rates.insert(
1151            "reconnect-request".to_string(),
1152            PendingRate {
1153                endpoint: "/v5/order/create",
1154                category: BybitProductType::Linear,
1155            },
1156        );
1157
1158        let result = handler
1159            .classify_order_send_error("reconnect-request", SendError::ConnectionChanged)
1160            .unwrap();
1161
1162        assert!(!result);
1163        assert!(!handler.auth_tracker.is_authenticated());
1164        assert!(!handler.pending_rates.contains_key("reconnect-request"));
1165    }
1166
1167    #[rstest]
1168    fn pre_active_timeout_is_terminal_not_sent() {
1169        let handler = create_test_handler();
1170        handler.auth_tracker.succeed();
1171        handler.pending_rates.insert(
1172            "timeout-request".to_string(),
1173            PendingRate {
1174                endpoint: "/v5/order/create",
1175                category: BybitProductType::Linear,
1176            },
1177        );
1178
1179        let failure = handler
1180            .classify_order_send_error("timeout-request", SendError::Timeout)
1181            .unwrap_err();
1182
1183        assert!(matches!(failure, OrderSendFailure::NotSent(_)));
1184        assert!(!handler.auth_tracker.is_authenticated());
1185        assert!(!handler.pending_rates.contains_key("timeout-request"));
1186    }
1187
1188    #[rstest]
1189    fn buffer_full_is_not_sent_and_preserves_authentication() {
1190        let handler = create_test_handler();
1191        handler.auth_tracker.succeed();
1192        handler.pending_rates.insert(
1193            "full-request".to_string(),
1194            PendingRate {
1195                endpoint: "/v5/order/create",
1196                category: BybitProductType::Linear,
1197            },
1198        );
1199
1200        let failure = handler
1201            .classify_order_send_error("full-request", SendError::BufferFull)
1202            .unwrap_err();
1203
1204        assert!(matches!(failure, OrderSendFailure::NotSent(_)));
1205        assert!(handler.auth_tracker.is_authenticated());
1206        assert!(!handler.pending_rates.contains_key("full-request"));
1207    }
1208
1209    #[rstest]
1210    fn test_parse_frame_auth_success() {
1211        let value = load_value("ws_auth_success.json");
1212        let frame = parse_bybit_ws_frame(value);
1213        match frame {
1214            BybitWsFrame::Auth(auth) => {
1215                assert_eq!(auth.conn_id.as_deref(), Some("cejreaspqfm9se7usbrg-2xh"));
1216                assert_eq!(auth.ret_code, Some(0));
1217                assert_eq!(auth.success, Some(true));
1218            }
1219            other => panic!("Expected Auth, was {other:?}"),
1220        }
1221    }
1222
1223    #[rstest]
1224    fn test_parse_frame_auth_failure() {
1225        let value = load_value("ws_auth_failure.json");
1226        let frame = parse_bybit_ws_frame(value);
1227        match frame {
1228            BybitWsFrame::ErrorResponse(resp) => {
1229                assert_eq!(resp.ret_code, Some(10003));
1230                assert_eq!(resp.ret_msg.as_deref(), Some("Invalid apikey"));
1231            }
1232            other => panic!("Expected ErrorResponse, was {other:?}"),
1233        }
1234    }
1235
1236    #[rstest]
1237    fn test_parse_frame_subscription_ack() {
1238        let value = load_value("ws_subscription_ack.json");
1239        let frame = parse_bybit_ws_frame(value);
1240        match frame {
1241            BybitWsFrame::Subscription(sub) => {
1242                assert!(sub.success);
1243                assert_eq!(sub.op, BybitWsOperation::Subscribe);
1244                assert_eq!(sub.req_id.as_deref(), Some("sub-orderbook-1"));
1245            }
1246            other => panic!("Expected Subscription, was {other:?}"),
1247        }
1248    }
1249
1250    #[rstest]
1251    fn test_parse_frame_subscription_failure() {
1252        let value = load_value("ws_subscription_failure.json");
1253        let frame = parse_bybit_ws_frame(value);
1254        match frame {
1255            BybitWsFrame::ErrorResponse(resp) => {
1256                assert_eq!(
1257                    resp.ret_msg.as_deref(),
1258                    Some("Invalid topic: invalid.topic.BTCUSDT")
1259                );
1260            }
1261            other => panic!("Expected ErrorResponse, was {other:?}"),
1262        }
1263    }
1264
1265    #[rstest]
1266    fn test_parse_frame_order_response() {
1267        let value = load_value("ws_order_response.json");
1268        let frame = parse_bybit_ws_frame(value);
1269        match frame {
1270            BybitWsFrame::OrderResponse(resp) => {
1271                assert_eq!(resp.op, "order.create");
1272                assert_eq!(resp.ret_code, 0);
1273                assert_eq!(resp.ret_msg, "OK");
1274            }
1275            other => panic!("Expected OrderResponse, was {other:?}"),
1276        }
1277    }
1278
1279    #[rstest]
1280    fn test_parse_frame_orderbook() {
1281        let value = load_value("ws_orderbook_snapshot.json");
1282        let frame = parse_bybit_ws_frame(value);
1283        assert!(
1284            matches!(frame, BybitWsFrame::Orderbook(_)),
1285            "Expected Orderbook, was {frame:?}"
1286        );
1287    }
1288
1289    #[rstest]
1290    fn test_parse_frame_trade() {
1291        let value = load_value("ws_public_trade.json");
1292        let frame = parse_bybit_ws_frame(value);
1293        assert!(
1294            matches!(frame, BybitWsFrame::Trade(_)),
1295            "Expected Trade, was {frame:?}"
1296        );
1297    }
1298
1299    #[rstest]
1300    fn test_parse_frame_kline() {
1301        let value = load_value("ws_kline.json");
1302        let frame = parse_bybit_ws_frame(value);
1303        assert!(
1304            matches!(frame, BybitWsFrame::Kline(_)),
1305            "Expected Kline, was {frame:?}"
1306        );
1307    }
1308
1309    #[rstest]
1310    fn test_parse_frame_ticker_linear() {
1311        let value = load_value("ws_ticker_linear.json");
1312        let frame = parse_bybit_ws_frame(value);
1313        assert!(
1314            matches!(frame, BybitWsFrame::TickerLinear(_)),
1315            "Expected TickerLinear, was {frame:?}"
1316        );
1317    }
1318
1319    #[rstest]
1320    fn test_parse_frame_ticker_option() {
1321        let value = load_value("ws_ticker_option.json");
1322        let frame = parse_bybit_ws_frame(value);
1323        assert!(
1324            matches!(frame, BybitWsFrame::TickerOption(_)),
1325            "Expected TickerOption, was {frame:?}"
1326        );
1327    }
1328
1329    #[rstest]
1330    fn test_parse_frame_account_order() {
1331        let value = load_value("ws_account_order.json");
1332        let frame = parse_bybit_ws_frame(value);
1333        assert!(
1334            matches!(frame, BybitWsFrame::AccountOrder(_)),
1335            "Expected AccountOrder, was {frame:?}"
1336        );
1337    }
1338
1339    #[rstest]
1340    fn test_parse_frame_account_execution() {
1341        let value = load_value("ws_account_execution.json");
1342        let frame = parse_bybit_ws_frame(value);
1343        assert!(
1344            matches!(frame, BybitWsFrame::AccountExecution(_)),
1345            "Expected AccountExecution, was {frame:?}"
1346        );
1347    }
1348
1349    #[rstest]
1350    fn test_parse_frame_account_wallet() {
1351        let value = load_value("ws_account_wallet.json");
1352        let frame = parse_bybit_ws_frame(value);
1353        assert!(
1354            matches!(frame, BybitWsFrame::AccountWallet(_)),
1355            "Expected AccountWallet, was {frame:?}"
1356        );
1357    }
1358
1359    #[rstest]
1360    fn test_parse_frame_account_position() {
1361        let value = load_value("ws_account_position.json");
1362        let frame = parse_bybit_ws_frame(value);
1363        assert!(
1364            matches!(frame, BybitWsFrame::AccountPosition(_)),
1365            "Expected AccountPosition, was {frame:?}"
1366        );
1367    }
1368
1369    #[rstest]
1370    fn test_parse_frame_unknown_message() {
1371        let value: serde_json::Value = serde_json::json!({"foo": "bar"});
1372        let frame = parse_bybit_ws_frame(value);
1373        assert!(
1374            matches!(frame, BybitWsFrame::Unknown(_)),
1375            "Expected Unknown, was {frame:?}"
1376        );
1377    }
1378
1379    #[rstest]
1380    fn test_parse_raw_reconnected_signal() {
1381        let msg = Message::Text(nautilus_network::RECONNECTED.to_string().into());
1382        let result = BybitWsFeedHandler::parse_raw_frame(msg);
1383        assert!(
1384            matches!(result, Some(BybitWsFrame::Reconnected)),
1385            "Expected Some(Reconnected), was {result:?}"
1386        );
1387    }
1388
1389    #[rstest]
1390    fn test_parse_raw_pong_text() {
1391        let msg = Message::Text("pong".into());
1392        let result = BybitWsFeedHandler::parse_raw_frame(msg);
1393        assert!(result.is_none(), "Expected None for pong, was {result:?}");
1394    }
1395
1396    #[rstest]
1397    fn test_parse_raw_json_pong_message() {
1398        let msg = Message::Text(
1399            r#"{"args":["1777226678908"],"conn_id":"yzr7jz02gws1vh60mk5m-hxqdp","op":"pong"}"#
1400                .into(),
1401        );
1402        let result = BybitWsFeedHandler::parse_raw_frame(msg);
1403        assert!(
1404            result.is_none(),
1405            "Expected None for JSON pong, was {result:?}"
1406        );
1407    }
1408
1409    #[rstest]
1410    fn test_parse_raw_valid_json() {
1411        let json = load_test_json("ws_public_trade.json");
1412        let msg = Message::Text(json.into());
1413        let result = BybitWsFeedHandler::parse_raw_frame(msg);
1414        assert!(
1415            matches!(result, Some(BybitWsFrame::Trade(_))),
1416            "Expected Some(Trade), was {result:?}"
1417        );
1418    }
1419
1420    #[rstest]
1421    fn test_parse_raw_invalid_json() {
1422        let msg = Message::Text("not valid json".into());
1423        let result = BybitWsFeedHandler::parse_raw_frame(msg);
1424        assert!(
1425            result.is_none(),
1426            "Expected None for invalid JSON, was {result:?}"
1427        );
1428    }
1429
1430    #[rstest]
1431    fn test_parse_raw_binary_message() {
1432        let msg = Message::Binary(vec![0x01, 0x02].into());
1433        let result = BybitWsFeedHandler::parse_raw_frame(msg);
1434        assert!(result.is_none(), "Expected None for binary, was {result:?}");
1435    }
1436
1437    #[rstest]
1438    fn test_subscription_ack_with_req_id_confirms_only_that_topic() {
1439        let handler = create_test_handler();
1440        handler.subscriptions.mark_subscribe("orderbook.50.BTCUSDT");
1441        handler.subscriptions.mark_subscribe("publicTrade.BTCUSDT");
1442
1443        let ack = BybitWsSubscriptionMsg {
1444            success: true,
1445            op: BybitWsOperation::Subscribe,
1446            conn_id: None,
1447            req_id: Some("orderbook.50.BTCUSDT".to_string()),
1448            ret_msg: None,
1449        };
1450
1451        handler.handle_subscription_ack(&ack);
1452
1453        // Only orderbook should be confirmed, trade stays pending
1454        assert!(
1455            handler
1456                .subscriptions
1457                .pending_subscribe_topics()
1458                .contains(&"publicTrade.BTCUSDT".to_string())
1459        );
1460        assert!(
1461            !handler
1462                .subscriptions
1463                .pending_subscribe_topics()
1464                .contains(&"orderbook.50.BTCUSDT".to_string())
1465        );
1466    }
1467
1468    #[rstest]
1469    fn test_subscription_failure_with_req_id_marks_only_that_topic() {
1470        let handler = create_test_handler();
1471        handler.subscriptions.mark_subscribe("orderbook.50.BTCUSDT");
1472        handler.subscriptions.mark_subscribe("publicTrade.BTCUSDT");
1473
1474        let ack = BybitWsSubscriptionMsg {
1475            success: false,
1476            op: BybitWsOperation::Subscribe,
1477            conn_id: None,
1478            req_id: Some("orderbook.50.BTCUSDT".to_string()),
1479            ret_msg: Some("Invalid topic".to_string()),
1480        };
1481
1482        handler.handle_subscription_ack(&ack);
1483
1484        // Orderbook should be marked as failed (back to pending for retry)
1485        // Trade should remain pending (unaffected)
1486        let pending = handler.subscriptions.pending_subscribe_topics();
1487        assert!(pending.contains(&"orderbook.50.BTCUSDT".to_string()));
1488        assert!(pending.contains(&"publicTrade.BTCUSDT".to_string()));
1489    }
1490
1491    #[rstest]
1492    fn test_error_response_with_subscribe_op_triggers_mark_failure() {
1493        let handler = create_test_handler();
1494        handler
1495            .subscriptions
1496            .mark_subscribe("invalid.topic.BTCUSDT");
1497
1498        let resp = BybitWsResponse {
1499            op: Some(BybitWsOperation::Subscribe),
1500            topic: None,
1501            success: Some(false),
1502            conn_id: None,
1503            req_id: Some("invalid.topic.BTCUSDT".to_string()),
1504            ret_code: Some(10001),
1505            ret_msg: Some("Invalid topic".to_string()),
1506        };
1507
1508        handler.handle_subscription_error(&resp);
1509
1510        // Topic should still be in pending (mark_failure moves confirmed -> pending)
1511        let pending = handler.subscriptions.pending_subscribe_topics();
1512        assert!(pending.contains(&"invalid.topic.BTCUSDT".to_string()));
1513    }
1514
1515    #[rstest]
1516    fn test_already_subscribed_error_confirms_topic() {
1517        let handler = create_test_handler();
1518        handler.subscriptions.mark_subscribe("tickers.ETHUSDT");
1519
1520        let resp = BybitWsResponse {
1521            op: Some(BybitWsOperation::Subscribe),
1522            topic: None,
1523            success: Some(false),
1524            conn_id: None,
1525            req_id: Some("tickers.ETHUSDT".to_string()),
1526            ret_code: Some(10001),
1527            ret_msg: Some("error:already subscribed,topic:tickers.ETHUSDT".to_string()),
1528        };
1529
1530        handler.handle_subscription_error(&resp);
1531
1532        let pending = handler.subscriptions.pending_subscribe_topics();
1533        assert!(!pending.contains(&"tickers.ETHUSDT".to_string()));
1534        let symbols = handler.subscriptions.confirmed();
1535        let entry = symbols
1536            .get(&Ustr::from("tickers"))
1537            .expect("channel present");
1538        assert!(entry.contains(&Ustr::from("ETHUSDT")));
1539    }
1540
1541    #[rstest]
1542    fn test_subscription_ack_without_req_id_confirms_all_pending() {
1543        let handler = create_test_handler();
1544        handler.subscriptions.mark_subscribe("orderbook.50.BTCUSDT");
1545        handler.subscriptions.mark_subscribe("publicTrade.BTCUSDT");
1546
1547        let ack = BybitWsSubscriptionMsg {
1548            success: true,
1549            op: BybitWsOperation::Subscribe,
1550            conn_id: None,
1551            req_id: None,
1552            ret_msg: None,
1553        };
1554
1555        handler.handle_subscription_ack(&ack);
1556
1557        // Both should be confirmed when no req_id
1558        assert!(handler.subscriptions.pending_subscribe_topics().is_empty());
1559    }
1560}