Skip to main content

nautilus_bybit/websocket/
messages.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 obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
7//
8//  Unless required by applicable law or agreed to in writing, software
9//  distributed under the License is distributed on an "AS IS" BASIS,
10//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11//  See the License for the specific language governing permissions and
12//  limitations under the License.
13// -------------------------------------------------------------------------------------------------
14
15//! WebSocket message types for Bybit public and private channels.
16
17use std::fmt::Debug;
18
19use nautilus_core::string::secret::{REDACTED, zeroize_json_value};
20use rust_decimal::Decimal;
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23use ustr::Ustr;
24use zeroize::Zeroize;
25
26use crate::{
27    common::{
28        enums::{
29            BybitBboSideType, BybitCancelType, BybitCreateType, BybitExecType, BybitMarketUnit,
30            BybitOrderSide, BybitOrderSmpType, BybitOrderStatus, BybitOrderType, BybitPositionIdx,
31            BybitPositionSide, BybitPositionStatus, BybitProductType, BybitSmpType,
32            BybitStopOrderType, BybitTimeInForce, BybitTpSlMode, BybitTriggerDirection,
33            BybitTriggerType, BybitWsOrderRequestOp,
34        },
35        parse::{
36            deserialize_decimal_or_zero, deserialize_i32_or_string, deserialize_i64_or_string,
37            deserialize_optional_decimal_or_zero, deserialize_optional_decimal_str,
38        },
39    },
40    websocket::enums::BybitWsOperation,
41};
42
43/// Bybit WebSocket subscription message.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct BybitSubscription {
46    pub op: BybitWsOperation,
47    pub args: Vec<String>,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub req_id: Option<String>,
50}
51
52/// Bybit WebSocket authentication message.
53#[derive(Clone, Serialize, Deserialize)]
54pub struct BybitAuthRequest {
55    pub op: BybitWsOperation,
56    pub args: Vec<serde_json::Value>,
57}
58
59impl Debug for BybitAuthRequest {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.debug_struct(stringify!(BybitAuthRequest))
62            .field("op", &self.op)
63            .field("args", &REDACTED)
64            .finish()
65    }
66}
67
68impl Zeroize for BybitAuthRequest {
69    fn zeroize(&mut self) {
70        for arg in &mut self.args {
71            zeroize_json_value(arg);
72        }
73    }
74}
75
76/// Wire-level frame deserialized from a Bybit WebSocket message.
77///
78/// Represents the raw protocol layer before the handler converts data
79/// variants into the public [`BybitWsMessage`] API.
80#[derive(Debug, Clone)]
81pub enum BybitWsFrame {
82    /// Authentication acknowledgement.
83    Auth(BybitWsAuthResponse),
84    /// Subscription acknowledgement.
85    Subscription(BybitWsSubscriptionMsg),
86    /// Order operation response (create/amend/cancel) from trade WebSocket.
87    OrderResponse(BybitWsOrderResponse),
88    /// Error response from the venue.
89    ErrorResponse(BybitWsResponse),
90    /// Orderbook snapshot or delta.
91    Orderbook(BybitWsOrderbookDepthMsg),
92    /// Trade updates.
93    Trade(BybitWsTradeMsg),
94    /// Public liquidation updates.
95    Liquidation(BybitWsLiquidationMsg),
96    /// Kline updates.
97    Kline(BybitWsKlineMsg),
98    /// Linear/inverse ticker update.
99    TickerLinear(BybitWsTickerLinearMsg),
100    /// Option ticker update.
101    TickerOption(BybitWsTickerOptionMsg),
102    /// Order updates from private channel.
103    AccountOrder(BybitWsAccountOrderMsg),
104    /// Execution/fill updates from private channel.
105    AccountExecution(BybitWsAccountExecutionMsg),
106    /// Fast execution updates from private channel (slim payload).
107    AccountExecutionFast(BybitWsAccountExecutionFastMsg),
108    /// Wallet/balance updates from private channel.
109    AccountWallet(BybitWsAccountWalletMsg),
110    /// Position updates from private channel.
111    AccountPosition(BybitWsAccountPositionMsg),
112    /// Payload that does not match any known frame type.
113    Unknown(Value),
114    /// Notification that the underlying connection reconnected.
115    Reconnected,
116}
117
118/// High-level message emitted by the Bybit WebSocket client.
119#[derive(Debug, Clone)]
120pub enum BybitWsMessage {
121    /// Authentication acknowledgement.
122    Auth(BybitWsAuthResponse),
123    /// Order operation response (create/amend/cancel) from trade WebSocket.
124    OrderResponse(BybitWsOrderResponse),
125    /// An order command fails before the transport writes it.
126    OrderNotSent { request_id: String, reason: String },
127    /// Orderbook snapshot or delta.
128    Orderbook(BybitWsOrderbookDepthMsg),
129    /// Trade updates.
130    Trade(BybitWsTradeMsg),
131    /// Public liquidation updates.
132    Liquidation(BybitWsLiquidationMsg),
133    /// Kline updates.
134    Kline(BybitWsKlineMsg),
135    /// Linear/inverse ticker update.
136    TickerLinear(BybitWsTickerLinearMsg),
137    /// Option ticker update.
138    TickerOption(BybitWsTickerOptionMsg),
139    /// Order updates from private channel.
140    AccountOrder(BybitWsAccountOrderMsg),
141    /// Execution/fill updates from private channel.
142    AccountExecution(BybitWsAccountExecutionMsg),
143    /// Fast execution updates from private channel (slim payload).
144    AccountExecutionFast(BybitWsAccountExecutionFastMsg),
145    /// Wallet/balance updates from private channel.
146    AccountWallet(BybitWsAccountWalletMsg),
147    /// Position updates from private channel.
148    AccountPosition(BybitWsAccountPositionMsg),
149    /// Error received from the venue or client lifecycle.
150    Error(BybitWebSocketError),
151    /// Notification that the underlying connection reconnected.
152    Reconnected,
153}
154
155/// Represents an error event surfaced by the WebSocket client.
156#[derive(Debug, Clone, Serialize, Deserialize)]
157#[serde(rename_all = "camelCase")]
158pub struct BybitWebSocketError {
159    /// Error/return code reported by Bybit.
160    pub code: i64,
161    /// Human readable message.
162    pub message: String,
163    /// Optional connection identifier.
164    #[serde(default)]
165    pub conn_id: Option<String>,
166    /// Optional topic associated with the error (when applicable).
167    #[serde(default)]
168    pub topic: Option<String>,
169    /// Optional request identifier related to the failure.
170    #[serde(default)]
171    pub req_id: Option<String>,
172}
173
174impl BybitWebSocketError {
175    /// Creates a new error with the provided code/message.
176    #[must_use]
177    pub fn new(code: i64, message: impl Into<String>) -> Self {
178        Self {
179            code,
180            message: message.into(),
181            conn_id: None,
182            topic: None,
183            req_id: None,
184        }
185    }
186
187    /// Builds an error payload from a generic response frame.
188    #[must_use]
189    pub fn from_response(response: &BybitWsResponse) -> Self {
190        // Build a more informative error message when ret_msg is missing
191        let message = response.ret_msg.clone().unwrap_or_else(|| {
192            let mut parts = vec![];
193
194            if let Some(op) = &response.op {
195                parts.push(format!("op={op}"));
196            }
197
198            if let Some(topic) = &response.topic {
199                parts.push(format!("topic={topic}"));
200            }
201
202            if let Some(success) = response.success {
203                parts.push(format!("success={success}"));
204            }
205
206            if parts.is_empty() {
207                "Bybit websocket error (no error message provided)".to_string()
208            } else {
209                format!("Bybit websocket error: {}", parts.join(", "))
210            }
211        });
212
213        Self {
214            code: response.ret_code.unwrap_or_default(),
215            message,
216            conn_id: response.conn_id.clone(),
217            topic: response.topic.map(|t| t.to_string()),
218            req_id: response.req_id.clone(),
219        }
220    }
221
222    /// Convenience constructor for client-side errors (e.g. parsing failures).
223    #[must_use]
224    pub fn from_message(message: impl Into<String>) -> Self {
225        Self::new(-1, message)
226    }
227}
228
229/// Generic WebSocket request for Bybit trading commands.
230#[derive(Debug, Clone, Serialize)]
231#[serde(rename_all = "camelCase")]
232pub struct BybitWsRequest<T> {
233    /// Request ID for correlation (will be echoed back in response).
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub req_id: Option<String>,
236    /// Operation type (order.create, order.amend, order.cancel, etc.).
237    pub op: BybitWsOrderRequestOp,
238    /// Request header containing timestamp and other metadata.
239    pub header: BybitWsHeader,
240    /// Arguments payload for the operation.
241    pub args: Vec<T>,
242}
243
244/// Header for WebSocket trade requests.
245#[derive(Debug, Clone, Serialize)]
246#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
247pub struct BybitWsHeader {
248    /// Timestamp in milliseconds.
249    pub x_bapi_timestamp: String,
250    /// Optional referer ID.
251    #[serde(rename = "Referer", skip_serializing_if = "Option::is_none")]
252    pub referer: Option<String>,
253}
254
255impl BybitWsHeader {
256    /// Creates a new header with the current timestamp.
257    #[must_use]
258    pub fn now() -> Self {
259        Self::with_referer(None)
260    }
261
262    /// Creates a new header with the current timestamp and optional referer.
263    #[must_use]
264    pub fn with_referer(referer: Option<String>) -> Self {
265        use nautilus_core::time::get_atomic_clock_realtime;
266        Self {
267            x_bapi_timestamp: get_atomic_clock_realtime().get_time_ms().to_string(),
268            referer,
269        }
270    }
271}
272
273/// Parameters for placing an order via WebSocket.
274#[derive(Debug, Clone, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct BybitWsPlaceOrderParams {
277    pub category: BybitProductType,
278    pub symbol: Ustr,
279    pub side: BybitOrderSide,
280    pub order_type: BybitOrderType,
281    pub qty: String,
282    #[serde(skip_serializing_if = "Option::is_none")]
283    pub is_leverage: Option<i32>,
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub market_unit: Option<BybitMarketUnit>,
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub price: Option<String>,
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub time_in_force: Option<BybitTimeInForce>,
290    #[serde(skip_serializing_if = "Option::is_none")]
291    pub order_link_id: Option<String>,
292    #[serde(skip_serializing_if = "Option::is_none")]
293    pub reduce_only: Option<bool>,
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub close_on_trigger: Option<bool>,
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub trigger_price: Option<String>,
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub trigger_by: Option<BybitTriggerType>,
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub trigger_direction: Option<i32>,
302    #[serde(skip_serializing_if = "Option::is_none")]
303    pub tpsl_mode: Option<BybitTpSlMode>,
304    #[serde(skip_serializing_if = "Option::is_none")]
305    pub take_profit: Option<String>,
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub stop_loss: Option<String>,
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub tp_trigger_by: Option<BybitTriggerType>,
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub sl_trigger_by: Option<BybitTriggerType>,
312    #[serde(skip_serializing_if = "Option::is_none")]
313    pub sl_trigger_price: Option<String>,
314    #[serde(skip_serializing_if = "Option::is_none")]
315    pub tp_trigger_price: Option<String>,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub sl_order_type: Option<BybitOrderType>,
318    #[serde(skip_serializing_if = "Option::is_none")]
319    pub tp_order_type: Option<BybitOrderType>,
320    #[serde(skip_serializing_if = "Option::is_none")]
321    pub sl_limit_price: Option<String>,
322    #[serde(skip_serializing_if = "Option::is_none")]
323    pub tp_limit_price: Option<String>,
324    #[serde(skip_serializing_if = "Option::is_none")]
325    pub order_iv: Option<String>,
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub smp_type: Option<BybitOrderSmpType>,
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub mmp: Option<bool>,
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub position_idx: Option<BybitPositionIdx>,
332    #[serde(skip_serializing_if = "Option::is_none")]
333    pub bbo_side_type: Option<BybitBboSideType>,
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub bbo_level: Option<String>,
336}
337
338/// Parameters for amending an order via WebSocket.
339#[derive(Debug, Clone, Serialize, Deserialize)]
340#[serde(rename_all = "camelCase")]
341pub struct BybitWsAmendOrderParams {
342    pub category: BybitProductType,
343    pub symbol: Ustr,
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub order_id: Option<String>,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub order_link_id: Option<String>,
348    #[serde(skip_serializing_if = "Option::is_none")]
349    pub qty: Option<String>,
350    #[serde(skip_serializing_if = "Option::is_none")]
351    pub price: Option<String>,
352    #[serde(skip_serializing_if = "Option::is_none")]
353    pub trigger_price: Option<String>,
354    #[serde(skip_serializing_if = "Option::is_none")]
355    pub take_profit: Option<String>,
356    #[serde(skip_serializing_if = "Option::is_none")]
357    pub stop_loss: Option<String>,
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub tp_trigger_by: Option<BybitTriggerType>,
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub sl_trigger_by: Option<BybitTriggerType>,
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub order_iv: Option<String>,
364}
365
366/// Item in a batch amend request (without category field).
367#[derive(Debug, Clone, Serialize, Deserialize)]
368#[serde(rename_all = "camelCase")]
369pub struct BybitWsBatchAmendItem {
370    pub symbol: Ustr,
371    #[serde(skip_serializing_if = "Option::is_none")]
372    pub order_id: Option<String>,
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub order_link_id: Option<String>,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub qty: Option<String>,
377    #[serde(skip_serializing_if = "Option::is_none")]
378    pub price: Option<String>,
379    #[serde(skip_serializing_if = "Option::is_none")]
380    pub trigger_price: Option<String>,
381    #[serde(skip_serializing_if = "Option::is_none")]
382    pub take_profit: Option<String>,
383    #[serde(skip_serializing_if = "Option::is_none")]
384    pub stop_loss: Option<String>,
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub tp_trigger_by: Option<BybitTriggerType>,
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub sl_trigger_by: Option<BybitTriggerType>,
389    #[serde(skip_serializing_if = "Option::is_none")]
390    pub order_iv: Option<String>,
391}
392
393/// Arguments for batch amend order operation via WebSocket.
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct BybitWsBatchAmendOrderArgs {
396    pub category: BybitProductType,
397    pub request: Vec<BybitWsBatchAmendItem>,
398}
399
400/// Parameters for canceling an order via WebSocket.
401#[derive(Debug, Clone, Serialize, Deserialize)]
402#[serde(rename_all = "camelCase")]
403pub struct BybitWsCancelOrderParams {
404    pub category: BybitProductType,
405    pub symbol: Ustr,
406    #[serde(skip_serializing_if = "Option::is_none")]
407    pub order_id: Option<String>,
408    #[serde(skip_serializing_if = "Option::is_none")]
409    pub order_link_id: Option<String>,
410}
411
412/// Item in a batch cancel request (without category field).
413#[derive(Debug, Clone, Serialize, Deserialize)]
414#[serde(rename_all = "camelCase")]
415pub struct BybitWsBatchCancelItem {
416    pub symbol: Ustr,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub order_id: Option<String>,
419    #[serde(skip_serializing_if = "Option::is_none")]
420    pub order_link_id: Option<String>,
421}
422
423/// Arguments for batch cancel order operation via WebSocket.
424#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct BybitWsBatchCancelOrderArgs {
426    pub category: BybitProductType,
427    pub request: Vec<BybitWsBatchCancelItem>,
428}
429
430/// Item in a batch place request (same as BybitWsPlaceOrderParams but without category).
431#[derive(Debug, Clone, Serialize, Deserialize)]
432#[serde(rename_all = "camelCase")]
433pub struct BybitWsBatchPlaceItem {
434    pub symbol: Ustr,
435    pub side: BybitOrderSide,
436    pub order_type: BybitOrderType,
437    pub qty: String,
438    #[serde(skip_serializing_if = "Option::is_none")]
439    pub is_leverage: Option<i32>,
440    #[serde(skip_serializing_if = "Option::is_none")]
441    pub market_unit: Option<BybitMarketUnit>,
442    #[serde(skip_serializing_if = "Option::is_none")]
443    pub price: Option<String>,
444    #[serde(skip_serializing_if = "Option::is_none")]
445    pub time_in_force: Option<BybitTimeInForce>,
446    #[serde(skip_serializing_if = "Option::is_none")]
447    pub order_link_id: Option<String>,
448    #[serde(skip_serializing_if = "Option::is_none")]
449    pub reduce_only: Option<bool>,
450    #[serde(skip_serializing_if = "Option::is_none")]
451    pub close_on_trigger: Option<bool>,
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub trigger_price: Option<String>,
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub trigger_by: Option<BybitTriggerType>,
456    #[serde(skip_serializing_if = "Option::is_none")]
457    pub trigger_direction: Option<i32>,
458    #[serde(skip_serializing_if = "Option::is_none")]
459    pub tpsl_mode: Option<BybitTpSlMode>,
460    #[serde(skip_serializing_if = "Option::is_none")]
461    pub take_profit: Option<String>,
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub stop_loss: Option<String>,
464    #[serde(skip_serializing_if = "Option::is_none")]
465    pub tp_trigger_by: Option<BybitTriggerType>,
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub sl_trigger_by: Option<BybitTriggerType>,
468    #[serde(skip_serializing_if = "Option::is_none")]
469    pub sl_trigger_price: Option<String>,
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub tp_trigger_price: Option<String>,
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub sl_order_type: Option<BybitOrderType>,
474    #[serde(skip_serializing_if = "Option::is_none")]
475    pub tp_order_type: Option<BybitOrderType>,
476    #[serde(skip_serializing_if = "Option::is_none")]
477    pub sl_limit_price: Option<String>,
478    #[serde(skip_serializing_if = "Option::is_none")]
479    pub tp_limit_price: Option<String>,
480    #[serde(skip_serializing_if = "Option::is_none")]
481    pub order_iv: Option<String>,
482    #[serde(skip_serializing_if = "Option::is_none")]
483    pub smp_type: Option<BybitOrderSmpType>,
484    #[serde(skip_serializing_if = "Option::is_none")]
485    pub mmp: Option<bool>,
486    #[serde(skip_serializing_if = "Option::is_none")]
487    pub position_idx: Option<BybitPositionIdx>,
488    #[serde(skip_serializing_if = "Option::is_none")]
489    pub bbo_side_type: Option<BybitBboSideType>,
490    #[serde(skip_serializing_if = "Option::is_none")]
491    pub bbo_level: Option<String>,
492}
493
494/// Arguments for batch place order operation via WebSocket.
495#[derive(Debug, Clone, Serialize, Deserialize)]
496pub struct BybitWsBatchPlaceOrderArgs {
497    pub category: BybitProductType,
498    pub request: Vec<BybitWsBatchPlaceItem>,
499}
500
501/// Subscription acknowledgement returned by Bybit.
502#[derive(Clone, Debug, Serialize, Deserialize)]
503pub struct BybitWsSubscriptionMsg {
504    pub success: bool,
505    pub op: BybitWsOperation,
506    #[serde(default)]
507    pub conn_id: Option<String>,
508    #[serde(default)]
509    pub req_id: Option<String>,
510    #[serde(default)]
511    pub ret_msg: Option<String>,
512}
513
514/// Generic response returned by the endpoint when subscribing or authenticating.
515#[derive(Clone, Debug, Serialize, Deserialize)]
516pub struct BybitWsResponse {
517    #[serde(default)]
518    pub op: Option<BybitWsOperation>,
519    #[serde(default)]
520    pub topic: Option<Ustr>,
521    #[serde(default)]
522    pub success: Option<bool>,
523    #[serde(default)]
524    pub conn_id: Option<String>,
525    #[serde(default)]
526    pub req_id: Option<String>,
527    #[serde(default)]
528    pub ret_code: Option<i64>,
529    #[serde(default)]
530    pub ret_msg: Option<String>,
531}
532
533/// Order operation response from WebSocket trade API.
534#[derive(Clone, Debug, Serialize, Deserialize)]
535#[serde(rename_all = "camelCase")]
536pub struct BybitWsOrderResponse {
537    /// Operation type (order.create, order.amend, order.cancel).
538    pub op: Ustr,
539    /// Connection ID.
540    #[serde(default)]
541    pub conn_id: Option<String>,
542    /// Return code (0 = success, non-zero = error).
543    pub ret_code: i64,
544    /// Return message.
545    pub ret_msg: String,
546    /// Response data (usually empty for errors, may contain order details for success).
547    #[serde(default)]
548    pub data: Value,
549    /// Request ID for correlation (echoed back if provided in request).
550    #[serde(default)]
551    pub req_id: Option<String>,
552    /// Request header containing timestamp and rate limit info.
553    #[serde(default)]
554    pub header: Option<Value>,
555    /// Extended info for errors.
556    #[serde(default)]
557    pub ret_ext_info: Option<Value>,
558}
559
560impl BybitWsOrderResponse {
561    /// Extracts individual order errors from retExtInfo for batch operations.
562    ///
563    /// For batch operations, even when ret_code is 0, individual orders may fail.
564    /// These failures are reported in retExtInfo.list as an array of {code, msg} objects.
565    #[must_use]
566    pub fn extract_batch_errors(&self) -> Vec<BybitBatchOrderError> {
567        self.ret_ext_info
568            .as_ref()
569            .and_then(|ext| ext.get("list"))
570            .and_then(|list| list.as_array())
571            .map_or_default(|arr| {
572                arr.iter()
573                    .filter_map(|item| {
574                        let code = item.get("code")?.as_i64()?;
575                        let msg = item.get("msg")?.as_str()?.to_string();
576                        Some(BybitBatchOrderError { code, msg })
577                    })
578                    .collect()
579            })
580    }
581}
582
583/// Error information for individual orders in a batch operation.
584#[derive(Clone, Debug)]
585pub struct BybitBatchOrderError {
586    /// Error code (0 = success, non-zero = error).
587    pub code: i64,
588    /// Error message.
589    pub msg: String,
590}
591
592/// Authentication acknowledgement for private channels.
593#[derive(Clone, Debug, Serialize, Deserialize)]
594#[serde(rename_all = "camelCase")]
595pub struct BybitWsAuthResponse {
596    pub op: BybitWsOperation,
597    // The private stream sends snake_case names, the trade stream camelCase
598    #[serde(default, alias = "conn_id")]
599    pub conn_id: Option<String>,
600    #[serde(default)]
601    pub ret_code: Option<i64>,
602    #[serde(default, alias = "ret_msg")]
603    pub ret_msg: Option<String>,
604    #[serde(default)]
605    pub success: Option<bool>,
606}
607
608/// Representation of a kline/candlestick event on the public stream.
609#[derive(Clone, Debug, Serialize, Deserialize)]
610#[serde(rename_all = "camelCase")]
611pub struct BybitWsKline {
612    pub start: i64,
613    pub end: i64,
614    pub interval: Ustr,
615    pub open: String,
616    pub close: String,
617    pub high: String,
618    pub low: String,
619    pub volume: String,
620    pub turnover: String,
621    pub confirm: bool,
622    pub timestamp: i64,
623}
624
625/// Envelope for kline updates.
626#[derive(Clone, Debug, Serialize, Deserialize)]
627#[serde(rename_all = "camelCase")]
628pub struct BybitWsKlineMsg {
629    pub topic: Ustr,
630    pub ts: i64,
631    #[serde(rename = "type")]
632    pub msg_type: Ustr,
633    pub data: Vec<BybitWsKline>,
634}
635
636/// Orderbook depth payload consisting of raw ladder deltas.
637#[derive(Clone, Debug, Serialize, Deserialize)]
638pub struct BybitWsOrderbookDepth {
639    /// Symbol.
640    pub s: Ustr,
641    /// Bid levels represented as `[price, size]` string pairs.
642    pub b: Vec<Vec<String>>,
643    /// Ask levels represented as `[price, size]` string pairs.
644    pub a: Vec<Vec<String>>,
645    /// Update identifier.
646    pub u: i64,
647    /// Cross sequence number.
648    pub seq: i64,
649}
650
651/// Envelope for orderbook depth snapshots and updates.
652#[derive(Clone, Debug, Serialize, Deserialize)]
653#[serde(rename_all = "camelCase")]
654pub struct BybitWsOrderbookDepthMsg {
655    pub topic: Ustr,
656    #[serde(rename = "type")]
657    pub msg_type: Ustr,
658    pub ts: i64,
659    pub data: BybitWsOrderbookDepth,
660    #[serde(default)]
661    pub cts: Option<i64>,
662}
663
664/// Linear/Inverse ticker event payload.
665#[derive(Clone, Debug, Serialize, Deserialize)]
666#[serde(rename_all = "camelCase")]
667pub struct BybitWsTickerLinear {
668    pub symbol: Ustr,
669    #[serde(default)]
670    pub tick_direction: Option<String>,
671    #[serde(default)]
672    pub price24h_pcnt: Option<String>,
673    #[serde(default)]
674    pub last_price: Option<String>,
675    #[serde(default)]
676    pub prev_price24h: Option<String>,
677    #[serde(default)]
678    pub high_price24h: Option<String>,
679    #[serde(default)]
680    pub low_price24h: Option<String>,
681    #[serde(default)]
682    pub prev_price1h: Option<String>,
683    #[serde(default)]
684    pub mark_price: Option<String>,
685    #[serde(default)]
686    pub index_price: Option<String>,
687    #[serde(default)]
688    pub open_interest: Option<String>,
689    #[serde(default)]
690    pub open_interest_value: Option<String>,
691    #[serde(default)]
692    pub turnover24h: Option<String>,
693    #[serde(default)]
694    pub volume24h: Option<String>,
695    #[serde(default)]
696    pub next_funding_time: Option<String>,
697    #[serde(default)]
698    pub funding_rate: Option<String>,
699    #[serde(default)]
700    pub bid1_price: Option<String>,
701    #[serde(default)]
702    pub bid1_size: Option<String>,
703    #[serde(default)]
704    pub ask1_price: Option<String>,
705    #[serde(default)]
706    pub ask1_size: Option<String>,
707    #[serde(default)]
708    pub funding_interval_hour: Option<String>,
709}
710
711/// Envelope for linear ticker updates.
712#[derive(Clone, Debug, Serialize, Deserialize)]
713#[serde(rename_all = "camelCase")]
714pub struct BybitWsTickerLinearMsg {
715    pub topic: Ustr,
716    #[serde(rename = "type")]
717    pub msg_type: Ustr,
718    pub ts: i64,
719    #[serde(default)]
720    pub cs: Option<i64>,
721    pub data: BybitWsTickerLinear,
722}
723
724/// Option ticker event payload.
725#[derive(Clone, Debug, Serialize, Deserialize)]
726#[serde(rename_all = "camelCase")]
727pub struct BybitWsTickerOption {
728    pub symbol: Ustr,
729    pub bid_price: String,
730    pub bid_size: String,
731    pub bid_iv: String,
732    pub ask_price: String,
733    pub ask_size: String,
734    pub ask_iv: String,
735    pub last_price: String,
736    pub high_price24h: String,
737    pub low_price24h: String,
738    pub mark_price: String,
739    pub index_price: String,
740    pub mark_price_iv: String,
741    pub underlying_price: String,
742    pub open_interest: String,
743    pub turnover24h: String,
744    pub volume24h: String,
745    pub total_volume: String,
746    pub total_turnover: String,
747    pub delta: String,
748    pub gamma: String,
749    pub vega: String,
750    pub theta: String,
751    pub predicted_delivery_price: String,
752    pub change24h: String,
753}
754
755/// Envelope for option ticker updates.
756#[derive(Clone, Debug, Serialize, Deserialize)]
757#[serde(rename_all = "camelCase")]
758pub struct BybitWsTickerOptionMsg {
759    #[serde(default)]
760    pub id: Option<String>,
761    pub topic: Ustr,
762    #[serde(rename = "type")]
763    pub msg_type: Ustr,
764    pub ts: i64,
765    pub data: BybitWsTickerOption,
766}
767
768/// Trade event payload containing trade executions on public feeds.
769#[derive(Clone, Debug, Serialize, Deserialize)]
770pub struct BybitWsTrade {
771    #[serde(rename = "T")]
772    pub t: i64,
773    #[serde(rename = "s")]
774    pub s: Ustr,
775    #[serde(rename = "S")]
776    pub taker_side: BybitOrderSide,
777    #[serde(rename = "v")]
778    pub v: String,
779    #[serde(rename = "p")]
780    pub p: String,
781    #[serde(rename = "i")]
782    pub i: String,
783    #[serde(rename = "BT")]
784    pub bt: bool,
785    #[serde(rename = "L")]
786    #[serde(default)]
787    pub l: Option<String>,
788    #[serde(rename = "id")]
789    #[serde(default)]
790    pub id: Option<Ustr>,
791    #[serde(rename = "mP")]
792    #[serde(default)]
793    pub m_p: Option<String>,
794    #[serde(rename = "iP")]
795    #[serde(default)]
796    pub i_p: Option<String>,
797    #[serde(rename = "mIv")]
798    #[serde(default)]
799    pub m_iv: Option<String>,
800    #[serde(rename = "iv")]
801    #[serde(default)]
802    pub iv: Option<String>,
803}
804
805/// Envelope for public trade updates.
806#[derive(Clone, Debug, Serialize, Deserialize)]
807#[serde(rename_all = "camelCase")]
808pub struct BybitWsTradeMsg {
809    pub topic: Ustr,
810    #[serde(rename = "type")]
811    pub msg_type: Ustr,
812    pub ts: i64,
813    pub data: Vec<BybitWsTrade>,
814}
815
816/// Liquidation entry from the public `allLiquidation` stream.
817///
818/// `S` is the side of the liquidated position, where `Buy` means a long position was liquidated.
819#[derive(Clone, Debug, Serialize, Deserialize)]
820pub struct BybitWsLiquidation {
821    #[serde(rename = "T")]
822    pub t: i64,
823    #[serde(rename = "s")]
824    pub s: Ustr,
825    #[serde(rename = "S")]
826    pub side: BybitOrderSide,
827    #[serde(rename = "v")]
828    pub v: String,
829    #[serde(rename = "p")]
830    pub p: String,
831}
832
833/// Envelope for public liquidation updates.
834#[derive(Clone, Debug, Serialize, Deserialize)]
835#[serde(rename_all = "camelCase")]
836pub struct BybitWsLiquidationMsg {
837    pub topic: Ustr,
838    #[serde(rename = "type")]
839    pub msg_type: Ustr,
840    pub ts: i64,
841    pub data: Vec<BybitWsLiquidation>,
842}
843
844/// Private order stream payload.
845#[derive(Clone, Debug, Serialize, Deserialize)]
846#[serde(rename_all = "camelCase")]
847pub struct BybitWsAccountOrder {
848    pub category: BybitProductType,
849    pub symbol: Ustr,
850    pub order_id: Ustr,
851    pub side: BybitOrderSide,
852    pub order_type: BybitOrderType,
853    pub cancel_type: BybitCancelType,
854    pub price: String,
855    pub qty: String,
856    pub order_iv: String,
857    pub time_in_force: BybitTimeInForce,
858    pub order_status: BybitOrderStatus,
859    pub order_link_id: Ustr,
860    pub last_price_on_created: Ustr,
861    pub reduce_only: bool,
862    pub leaves_qty: String,
863    pub leaves_value: String,
864    pub cum_exec_qty: String,
865    pub cum_exec_value: String,
866    pub avg_price: String,
867    pub block_trade_id: Ustr,
868    #[serde(deserialize_with = "deserialize_i32_or_string")]
869    pub position_idx: i32,
870    pub cum_exec_fee: String,
871    pub created_time: String,
872    pub updated_time: String,
873    pub reject_reason: Ustr,
874    pub trigger_price: String,
875    pub take_profit: String,
876    pub stop_loss: String,
877    pub tp_trigger_by: BybitTriggerType,
878    pub sl_trigger_by: BybitTriggerType,
879    pub tp_limit_price: String,
880    pub sl_limit_price: String,
881    pub close_on_trigger: bool,
882    pub place_type: Ustr,
883    pub smp_type: BybitSmpType,
884    #[serde(deserialize_with = "deserialize_i32_or_string")]
885    pub smp_group: i32,
886    pub smp_order_id: Ustr,
887    pub fee_currency: Ustr,
888    pub trigger_by: BybitTriggerType,
889    pub stop_order_type: BybitStopOrderType,
890    pub trigger_direction: BybitTriggerDirection,
891    #[serde(default)]
892    pub tpsl_mode: Option<BybitTpSlMode>,
893    #[serde(default)]
894    pub create_type: Option<BybitCreateType>,
895}
896
897/// Envelope for account order updates.
898#[derive(Clone, Debug, Serialize, Deserialize)]
899#[serde(rename_all = "camelCase")]
900pub struct BybitWsAccountOrderMsg {
901    pub topic: Ustr,
902    pub id: String,
903    pub creation_time: i64,
904    pub data: Vec<BybitWsAccountOrder>,
905}
906
907/// Private execution (fill) stream payload.
908#[derive(Clone, Debug, Serialize, Deserialize)]
909#[serde(rename_all = "camelCase")]
910pub struct BybitWsAccountExecution {
911    pub category: BybitProductType,
912    pub symbol: Ustr,
913    pub exec_fee: String,
914    pub exec_id: String,
915    pub exec_price: String,
916    pub exec_qty: String,
917    pub exec_type: BybitExecType,
918    pub exec_value: String,
919    pub is_maker: bool,
920    pub fee_rate: String,
921    pub fee_currency: Ustr,
922    pub trade_iv: String,
923    pub mark_iv: String,
924    pub block_trade_id: Ustr,
925    pub mark_price: String,
926    pub index_price: String,
927    pub underlying_price: String,
928    pub leaves_qty: String,
929    pub order_id: Ustr,
930    pub order_link_id: Ustr,
931    pub order_price: String,
932    pub order_qty: String,
933    pub order_type: BybitOrderType,
934    pub side: BybitOrderSide,
935    pub exec_time: String,
936    pub is_leverage: String,
937    pub closed_size: String,
938    pub seq: i64,
939    pub stop_order_type: BybitStopOrderType,
940}
941
942/// Envelope for account execution updates.
943#[derive(Clone, Debug, Serialize, Deserialize)]
944#[serde(rename_all = "camelCase")]
945pub struct BybitWsAccountExecutionMsg {
946    pub topic: Ustr,
947    pub id: String,
948    pub creation_time: i64,
949    pub data: Vec<BybitWsAccountExecution>,
950}
951
952/// Slim execution payload delivered on the `execution.fast` private channel.
953///
954/// The fast stream omits fee/exec-type metadata that the standard `execution`
955/// channel provides. The execution client selects one stream; use the standard
956/// channel for venue-authoritative fees and all execution types.
957///
958/// Note: `orderLinkId` is documented as always empty for maker fills (and for
959/// option maker fills); identity correlation by `orderLinkId` works only for
960/// taker fast fills. The execution client correlates maker fills by venue order ID,
961/// deferring them until the corresponding order update arrives when necessary.
962///
963/// # References
964/// - <https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution>
965#[derive(Clone, Debug, Serialize, Deserialize)]
966#[serde(rename_all = "camelCase")]
967pub struct BybitWsAccountExecutionFast {
968    pub category: BybitProductType,
969    pub symbol: Ustr,
970    pub exec_id: String,
971    pub exec_price: String,
972    pub exec_qty: String,
973    pub order_id: Ustr,
974    pub order_link_id: Ustr,
975    pub side: BybitOrderSide,
976    pub exec_time: String,
977    pub is_maker: bool,
978    #[serde(default = "default_ws_execution_fast_seq")]
979    pub seq: i64,
980}
981
982const fn default_ws_execution_fast_seq() -> i64 {
983    -1
984}
985
986/// Envelope for account fast-execution updates.
987///
988/// The fast stream envelope omits the `id` field that the standard `execution`
989/// envelope includes.
990#[derive(Clone, Debug, Serialize, Deserialize)]
991#[serde(rename_all = "camelCase")]
992pub struct BybitWsAccountExecutionFastMsg {
993    pub topic: Ustr,
994    #[serde(default)]
995    pub id: String,
996    pub creation_time: i64,
997    pub data: Vec<BybitWsAccountExecutionFast>,
998}
999
1000/// Coin level wallet update payload on private streams.
1001#[derive(Clone, Debug, Serialize, Deserialize)]
1002#[serde(rename_all = "camelCase")]
1003pub struct BybitWsAccountWalletCoin {
1004    pub coin: Ustr,
1005    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1006    pub wallet_balance: Decimal,
1007    pub available_to_withdraw: String,
1008    pub available_to_borrow: String,
1009    pub accrued_interest: String,
1010    #[serde(
1011        default,
1012        rename = "totalOrderIM",
1013        deserialize_with = "deserialize_optional_decimal_or_zero"
1014    )]
1015    pub total_order_im: Decimal,
1016    #[serde(
1017        default,
1018        rename = "totalPositionIM",
1019        deserialize_with = "deserialize_optional_decimal_or_zero"
1020    )]
1021    pub total_position_im: Decimal,
1022    #[serde(default, rename = "totalPositionMM")]
1023    pub total_position_mm: Option<String>,
1024    pub equity: String,
1025    #[serde(default, deserialize_with = "deserialize_optional_decimal_or_zero")]
1026    pub spot_borrow: Decimal,
1027}
1028
1029/// Wallet summary payload covering all coins.
1030#[derive(Clone, Debug, Serialize, Deserialize)]
1031#[serde(rename_all = "camelCase")]
1032pub struct BybitWsAccountWallet {
1033    pub total_wallet_balance: String,
1034    pub total_equity: String,
1035    pub total_available_balance: String,
1036    pub total_margin_balance: String,
1037    pub total_initial_margin: String,
1038    pub total_maintenance_margin: String,
1039    #[serde(rename = "accountIMRate")]
1040    pub account_im_rate: String,
1041    #[serde(rename = "accountMMRate")]
1042    pub account_mm_rate: String,
1043    #[serde(rename = "accountLTV")]
1044    pub account_ltv: String,
1045    pub coin: Vec<BybitWsAccountWalletCoin>,
1046}
1047
1048/// Envelope for wallet updates on private streams.
1049#[derive(Clone, Debug, Serialize, Deserialize)]
1050#[serde(rename_all = "camelCase")]
1051pub struct BybitWsAccountWalletMsg {
1052    pub topic: Ustr,
1053    pub id: String,
1054    pub creation_time: i64,
1055    pub data: Vec<BybitWsAccountWallet>,
1056}
1057
1058/// Position data from private position stream.
1059#[derive(Clone, Debug, Serialize, Deserialize)]
1060#[serde(rename_all = "camelCase")]
1061pub struct BybitWsAccountPosition {
1062    pub category: BybitProductType,
1063    pub symbol: Ustr,
1064    pub side: BybitPositionSide,
1065    pub size: String,
1066    #[serde(deserialize_with = "deserialize_i32_or_string")]
1067    pub position_idx: i32,
1068    #[serde(deserialize_with = "deserialize_i32_or_string")]
1069    pub trade_mode: i32,
1070    pub position_value: String,
1071    #[serde(deserialize_with = "deserialize_i64_or_string")]
1072    pub risk_id: i64,
1073    pub risk_limit_value: String,
1074    #[serde(deserialize_with = "deserialize_optional_decimal_str")]
1075    pub entry_price: Option<Decimal>,
1076    pub mark_price: String,
1077    pub leverage: String,
1078    pub position_balance: String,
1079    #[serde(deserialize_with = "deserialize_i32_or_string")]
1080    pub auto_add_margin: i32,
1081    #[serde(rename = "positionIM")]
1082    pub position_im: String,
1083    #[serde(rename = "positionIMByMp")]
1084    pub position_im_by_mp: String,
1085    #[serde(rename = "positionMM")]
1086    pub position_mm: String,
1087    #[serde(rename = "positionMMByMp")]
1088    pub position_mm_by_mp: String,
1089    pub liq_price: String,
1090    pub bust_price: String,
1091    pub tpsl_mode: BybitTpSlMode,
1092    pub take_profit: String,
1093    pub stop_loss: String,
1094    pub trailing_stop: String,
1095    pub unrealised_pnl: String,
1096    pub session_avg_price: String,
1097    pub cur_realised_pnl: String,
1098    pub cum_realised_pnl: String,
1099    pub position_status: BybitPositionStatus,
1100    #[serde(deserialize_with = "deserialize_i32_or_string")]
1101    pub adl_rank_indicator: i32,
1102    pub created_time: String,
1103    pub updated_time: String,
1104    #[serde(default = "default_ws_position_seq")]
1105    pub seq: i64,
1106    #[serde(default)]
1107    pub is_reduce_only: bool,
1108    #[serde(default)]
1109    pub mmr_sys_updated_time: String,
1110    #[serde(default)]
1111    pub leverage_sys_updated_time: String,
1112    #[serde(default)]
1113    pub open_time: i64,
1114}
1115
1116const fn default_ws_position_seq() -> i64 {
1117    -1
1118}
1119
1120/// Envelope for position updates on private streams.
1121#[derive(Clone, Debug, Serialize, Deserialize)]
1122#[serde(rename_all = "camelCase")]
1123pub struct BybitWsAccountPositionMsg {
1124    pub topic: Ustr,
1125    pub id: String,
1126    pub creation_time: i64,
1127    pub data: Vec<BybitWsAccountPosition>,
1128}
1129
1130#[cfg(test)]
1131mod tests {
1132    use rstest::rstest;
1133
1134    use super::*;
1135
1136    #[rstest]
1137    fn auth_request_serializes_and_redacts_debug() {
1138        let request = BybitAuthRequest {
1139            op: BybitWsOperation::Auth,
1140            args: vec![
1141                serde_json::json!("api-key-value"),
1142                serde_json::json!(1_700_000_000_000_u64),
1143                serde_json::json!("signature-value"),
1144            ],
1145        };
1146
1147        let json = serde_json::to_value(&request).unwrap();
1148        let formatted = format!("{request:?}");
1149
1150        assert_eq!(json["args"][0], "api-key-value");
1151        assert_eq!(json["args"][1], 1_700_000_000_000_u64);
1152        assert_eq!(json["args"][2], "signature-value");
1153        assert!(formatted.contains(REDACTED));
1154        assert!(!formatted.contains("api-key-value"));
1155        assert!(!formatted.contains("signature-value"));
1156    }
1157    use crate::common::testing::load_test_json;
1158
1159    #[rstest]
1160    fn deserialize_account_execution_fast_msg() {
1161        // Sample payload from the venue docs: slim envelope without `id`,
1162        // includes `isMaker`, taker fill with populated `orderLinkId`.
1163        let json = load_test_json("ws_account_execution_fast.json");
1164        let msg: BybitWsAccountExecutionFastMsg = serde_json::from_str(&json).unwrap();
1165
1166        assert_eq!(msg.id, "");
1167        assert_eq!(msg.creation_time, 1_716_800_399_338);
1168        assert_eq!(msg.data.len(), 1);
1169        let exec = &msg.data[0];
1170        assert_eq!(exec.category, BybitProductType::Linear);
1171        assert_eq!(exec.symbol, Ustr::from("ICPUSDT"));
1172        assert_eq!(exec.exec_id, "3510f361-0add-5c7b-a2e7-9679810944fc");
1173        assert_eq!(exec.exec_price, "12.015");
1174        assert_eq!(exec.exec_qty, "3000");
1175        assert_eq!(
1176            exec.order_id,
1177            Ustr::from("443d63fa-b4c3-4297-b7b1-23bca88b04dc")
1178        );
1179        assert_eq!(exec.order_link_id, Ustr::from("test-order-link-001"));
1180        assert_eq!(exec.side, BybitOrderSide::Sell);
1181        assert!(!exec.is_maker);
1182        assert_eq!(exec.exec_time, "1716800399334");
1183        assert_eq!(exec.seq, 34_771_365_464);
1184    }
1185
1186    #[rstest]
1187    fn deserialize_account_execution_fast_msg_accepts_envelope_id() {
1188        // Forward-compat: if the venue adds an envelope `id` later, it must still parse.
1189        let json = load_test_json("ws_account_execution_fast_envelope_id.json");
1190        let msg: BybitWsAccountExecutionFastMsg = serde_json::from_str(&json).unwrap();
1191        assert_eq!(msg.id, "fast-1");
1192        assert!(msg.data.is_empty());
1193    }
1194
1195    #[rstest]
1196    fn deserialize_account_position_with_open_time() {
1197        let json = load_test_json("ws_account_position_with_open_time.json");
1198        let position: BybitWsAccountPosition = serde_json::from_str(&json).unwrap();
1199        assert_eq!(position.open_time, 1_700_000_000_123);
1200    }
1201
1202    #[rstest]
1203    fn serialize_place_params_includes_order_iv_when_set() {
1204        let params = BybitWsPlaceOrderParams {
1205            category: BybitProductType::Option,
1206            symbol: Ustr::from("BTC-30JUN25-100000-C"),
1207            side: BybitOrderSide::Buy,
1208            order_type: BybitOrderType::Limit,
1209            qty: "0.1".to_string(),
1210            is_leverage: None,
1211            market_unit: None,
1212            price: Some("500".to_string()),
1213            time_in_force: Some(BybitTimeInForce::Gtc),
1214            order_link_id: Some("test-1".to_string()),
1215            reduce_only: None,
1216            close_on_trigger: None,
1217            trigger_price: None,
1218            trigger_by: None,
1219            trigger_direction: None,
1220            tpsl_mode: None,
1221            take_profit: None,
1222            stop_loss: None,
1223            tp_trigger_by: None,
1224            sl_trigger_by: None,
1225            sl_trigger_price: None,
1226            tp_trigger_price: None,
1227            sl_order_type: None,
1228            tp_order_type: None,
1229            sl_limit_price: None,
1230            tp_limit_price: None,
1231            order_iv: Some("0.80".to_string()),
1232            smp_type: None,
1233            mmp: Some(true),
1234            position_idx: None,
1235            bbo_side_type: None,
1236            bbo_level: None,
1237        };
1238
1239        let json = serde_json::to_string(&params).unwrap();
1240        assert!(json.contains("\"orderIv\":\"0.80\""));
1241        assert!(json.contains("\"mmp\":true"));
1242    }
1243
1244    #[rstest]
1245    fn serialize_place_params_omits_order_iv_when_none() {
1246        let params = BybitWsPlaceOrderParams {
1247            category: BybitProductType::Linear,
1248            symbol: Ustr::from("BTCUSDT"),
1249            side: BybitOrderSide::Buy,
1250            order_type: BybitOrderType::Limit,
1251            qty: "0.01".to_string(),
1252            is_leverage: None,
1253            market_unit: None,
1254            price: Some("50000".to_string()),
1255            time_in_force: Some(BybitTimeInForce::Gtc),
1256            order_link_id: None,
1257            reduce_only: None,
1258            close_on_trigger: None,
1259            trigger_price: None,
1260            trigger_by: None,
1261            trigger_direction: None,
1262            tpsl_mode: None,
1263            take_profit: None,
1264            stop_loss: None,
1265            tp_trigger_by: None,
1266            sl_trigger_by: None,
1267            sl_trigger_price: None,
1268            tp_trigger_price: None,
1269            sl_order_type: None,
1270            tp_order_type: None,
1271            sl_limit_price: None,
1272            tp_limit_price: None,
1273            order_iv: None,
1274            smp_type: None,
1275            mmp: None,
1276            position_idx: None,
1277            bbo_side_type: None,
1278            bbo_level: None,
1279        };
1280
1281        let json = serde_json::to_string(&params).unwrap();
1282        assert!(!json.contains("orderIv"));
1283        assert!(!json.contains("smpType"));
1284        assert!(!json.contains("mmp"));
1285        assert!(!json.contains("positionIdx"));
1286    }
1287
1288    #[rstest]
1289    #[case(BybitOrderSmpType::None, "None")]
1290    #[case(BybitOrderSmpType::CancelMaker, "CancelMaker")]
1291    #[case(BybitOrderSmpType::CancelTaker, "CancelTaker")]
1292    #[case(BybitOrderSmpType::CancelBoth, "CancelBoth")]
1293    fn serialize_place_params_includes_smp_type_when_set(
1294        #[case] smp_type: BybitOrderSmpType,
1295        #[case] expected: &str,
1296    ) {
1297        let params = BybitWsPlaceOrderParams {
1298            category: BybitProductType::Linear,
1299            symbol: Ustr::from("BTCUSDT"),
1300            side: BybitOrderSide::Buy,
1301            order_type: BybitOrderType::Limit,
1302            qty: "0.01".to_string(),
1303            is_leverage: None,
1304            market_unit: None,
1305            price: Some("50000".to_string()),
1306            time_in_force: Some(BybitTimeInForce::Gtc),
1307            order_link_id: Some("smp-1".to_string()),
1308            reduce_only: None,
1309            close_on_trigger: None,
1310            trigger_price: None,
1311            trigger_by: None,
1312            trigger_direction: None,
1313            tpsl_mode: None,
1314            take_profit: None,
1315            stop_loss: None,
1316            tp_trigger_by: None,
1317            sl_trigger_by: None,
1318            sl_trigger_price: None,
1319            tp_trigger_price: None,
1320            sl_order_type: None,
1321            tp_order_type: None,
1322            sl_limit_price: None,
1323            tp_limit_price: None,
1324            order_iv: None,
1325            smp_type: Some(smp_type),
1326            mmp: None,
1327            position_idx: None,
1328            bbo_side_type: None,
1329            bbo_level: None,
1330        };
1331
1332        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
1333
1334        assert_eq!(json.get("smpType").and_then(Value::as_str), Some(expected));
1335    }
1336
1337    #[rstest]
1338    fn serialize_place_params_includes_bbo_when_set() {
1339        let params = BybitWsPlaceOrderParams {
1340            category: BybitProductType::Linear,
1341            symbol: Ustr::from("BTCUSDT"),
1342            side: BybitOrderSide::Buy,
1343            order_type: BybitOrderType::Limit,
1344            qty: "0.01".to_string(),
1345            is_leverage: None,
1346            market_unit: None,
1347            price: None,
1348            time_in_force: Some(BybitTimeInForce::Gtc),
1349            order_link_id: None,
1350            reduce_only: None,
1351            close_on_trigger: None,
1352            trigger_price: None,
1353            trigger_by: None,
1354            trigger_direction: None,
1355            tpsl_mode: None,
1356            take_profit: None,
1357            stop_loss: None,
1358            tp_trigger_by: None,
1359            sl_trigger_by: None,
1360            sl_trigger_price: None,
1361            tp_trigger_price: None,
1362            sl_order_type: None,
1363            tp_order_type: None,
1364            sl_limit_price: None,
1365            tp_limit_price: None,
1366            order_iv: None,
1367            smp_type: None,
1368            mmp: None,
1369            position_idx: None,
1370            bbo_side_type: Some(BybitBboSideType::Queue),
1371            bbo_level: Some("2".to_string()),
1372        };
1373
1374        let json = serde_json::to_string(&params).unwrap();
1375        assert!(json.contains("\"bboSideType\":\"Queue\""));
1376        assert!(json.contains("\"bboLevel\":\"2\""));
1377        assert!(!json.contains("\"price\""));
1378    }
1379
1380    #[rstest]
1381    #[case(BybitPositionIdx::BuyHedge, 1)]
1382    #[case(BybitPositionIdx::SellHedge, 2)]
1383    fn serialize_place_params_includes_position_idx_when_set(
1384        #[case] idx: BybitPositionIdx,
1385        #[case] expected: i32,
1386    ) {
1387        let params = BybitWsPlaceOrderParams {
1388            category: BybitProductType::Linear,
1389            symbol: Ustr::from("BTCUSDT"),
1390            side: BybitOrderSide::Buy,
1391            order_type: BybitOrderType::Limit,
1392            qty: "0.01".to_string(),
1393            is_leverage: None,
1394            market_unit: None,
1395            price: Some("50000".to_string()),
1396            time_in_force: Some(BybitTimeInForce::Gtc),
1397            order_link_id: None,
1398            reduce_only: None,
1399            close_on_trigger: None,
1400            trigger_price: None,
1401            trigger_by: None,
1402            trigger_direction: None,
1403            tpsl_mode: None,
1404            take_profit: None,
1405            stop_loss: None,
1406            tp_trigger_by: None,
1407            sl_trigger_by: None,
1408            sl_trigger_price: None,
1409            tp_trigger_price: None,
1410            sl_order_type: None,
1411            tp_order_type: None,
1412            sl_limit_price: None,
1413            tp_limit_price: None,
1414            order_iv: None,
1415            smp_type: None,
1416            mmp: None,
1417            position_idx: Some(idx),
1418            bbo_side_type: None,
1419            bbo_level: None,
1420        };
1421
1422        let json = serde_json::to_string(&params).unwrap();
1423        assert!(json.contains(&format!("\"positionIdx\":{expected}")));
1424    }
1425
1426    #[rstest]
1427    #[case(None)]
1428    #[case(Some(BybitPositionIdx::OneWay))]
1429    #[case(Some(BybitPositionIdx::BuyHedge))]
1430    #[case(Some(BybitPositionIdx::SellHedge))]
1431    fn place_params_position_idx_roundtrip(#[case] idx: Option<BybitPositionIdx>) {
1432        let params = BybitWsPlaceOrderParams {
1433            category: BybitProductType::Linear,
1434            symbol: Ustr::from("BTCUSDT"),
1435            side: BybitOrderSide::Buy,
1436            order_type: BybitOrderType::Limit,
1437            qty: "0.01".to_string(),
1438            is_leverage: None,
1439            market_unit: None,
1440            price: Some("50000".to_string()),
1441            time_in_force: Some(BybitTimeInForce::Gtc),
1442            order_link_id: None,
1443            reduce_only: None,
1444            close_on_trigger: None,
1445            trigger_price: None,
1446            trigger_by: None,
1447            trigger_direction: None,
1448            tpsl_mode: None,
1449            take_profit: None,
1450            stop_loss: None,
1451            tp_trigger_by: None,
1452            sl_trigger_by: None,
1453            sl_trigger_price: None,
1454            tp_trigger_price: None,
1455            sl_order_type: None,
1456            tp_order_type: None,
1457            sl_limit_price: None,
1458            tp_limit_price: None,
1459            order_iv: None,
1460            smp_type: None,
1461            mmp: None,
1462            position_idx: idx,
1463            bbo_side_type: None,
1464            bbo_level: None,
1465        };
1466
1467        let json = serde_json::to_string(&params).unwrap();
1468        let decoded: BybitWsPlaceOrderParams = serde_json::from_str(&json).unwrap();
1469        assert_eq!(decoded.position_idx, idx);
1470    }
1471
1472    #[rstest]
1473    fn serialize_amend_params_includes_order_iv_when_set() {
1474        let params = BybitWsAmendOrderParams {
1475            category: BybitProductType::Option,
1476            symbol: Ustr::from("BTC-30JUN25-100000-C"),
1477            order_id: None,
1478            order_link_id: Some("test-1".to_string()),
1479            qty: None,
1480            price: None,
1481            trigger_price: None,
1482            take_profit: None,
1483            stop_loss: None,
1484            tp_trigger_by: None,
1485            sl_trigger_by: None,
1486            order_iv: Some("0.90".to_string()),
1487        };
1488
1489        let json = serde_json::to_string(&params).unwrap();
1490        assert!(json.contains("\"orderIv\":\"0.90\""));
1491    }
1492
1493    #[rstest]
1494    fn deserialize_account_order_frame_uses_enums() {
1495        let json = load_test_json("ws_account_order.json");
1496        let frame: BybitWsAccountOrderMsg = serde_json::from_str(&json).unwrap();
1497        let order = &frame.data[0];
1498
1499        assert_eq!(order.cancel_type, BybitCancelType::CancelByUser);
1500        assert_eq!(order.tp_trigger_by, BybitTriggerType::MarkPrice);
1501        assert_eq!(order.sl_trigger_by, BybitTriggerType::LastPrice);
1502        assert_eq!(order.tpsl_mode, Some(BybitTpSlMode::Full));
1503        assert_eq!(order.create_type, Some(BybitCreateType::CreateByUser));
1504        assert_eq!(order.side, BybitOrderSide::Buy);
1505        assert_eq!(order.smp_group, 0);
1506    }
1507
1508    #[rstest]
1509    fn deserialize_account_order_frame_accepts_string_smp_group() {
1510        let mut json: Value =
1511            serde_json::from_str(&load_test_json("ws_account_order.json")).unwrap();
1512        json["data"][0]["smpGroup"] = Value::String("123456789".to_string());
1513
1514        let frame: BybitWsAccountOrderMsg = serde_json::from_value(json).unwrap();
1515
1516        assert_eq!(frame.data[0].smp_group, 123_456_789);
1517    }
1518
1519    #[rstest]
1520    fn deserialize_account_order_frame_accepts_string_position_idx() {
1521        let mut json: Value =
1522            serde_json::from_str(&load_test_json("ws_account_order.json")).unwrap();
1523        json["data"][0]["positionIdx"] = Value::String("1".to_string());
1524
1525        let frame: BybitWsAccountOrderMsg = serde_json::from_value(json).unwrap();
1526
1527        assert_eq!(frame.data[0].position_idx, 1);
1528    }
1529
1530    #[rstest]
1531    fn deserialize_account_position_frame_accepts_string_integer_fields() {
1532        let mut json: Value =
1533            serde_json::from_str(&load_test_json("ws_account_position.json")).unwrap();
1534        let position = &mut json["data"][0];
1535        position["positionIdx"] = Value::String("2".to_string());
1536        position["tradeMode"] = Value::String("1".to_string());
1537        position["autoAddMargin"] = Value::String("3".to_string());
1538        position["riskId"] = Value::String("1234".to_string());
1539        position["adlRankIndicator"] = Value::String("35".to_string());
1540
1541        let frame: BybitWsAccountPositionMsg = serde_json::from_value(json).unwrap();
1542
1543        let position = &frame.data[0];
1544        assert_eq!(position.position_idx, 2);
1545        assert_eq!(position.trade_mode, 1);
1546        assert_eq!(position.auto_add_margin, 3);
1547        assert_eq!(position.risk_id, 1234);
1548        assert_eq!(position.adl_rank_indicator, 35);
1549    }
1550
1551    #[rstest]
1552    fn deserialize_ws_account_position_without_conditional_fields() {
1553        // Bybit v5 docs mark `isReduceOnly`, `mmrSysUpdatedTime`, `leverageSysUpdatedTime`
1554        // and `seq` as conditional fields that may be absent from position snapshots,
1555        // e.g. once a position has been closed through the UI (see issue #3836).
1556        let json = r#"{
1557            "topic": "position",
1558            "id": "1",
1559            "creationTime": 1697673900000,
1560            "data": [{
1561                "category": "linear",
1562                "symbol": "LTCUSDT",
1563                "side": "",
1564                "size": "0",
1565                "positionIdx": 0,
1566                "tradeMode": 0,
1567                "positionValue": "0",
1568                "riskId": 1,
1569                "riskLimitValue": "150",
1570                "entryPrice": "",
1571                "markPrice": "70.00",
1572                "leverage": "10",
1573                "positionBalance": "0",
1574                "autoAddMargin": 0,
1575                "positionIM": "0",
1576                "positionIMByMp": "0",
1577                "positionMM": "0",
1578                "positionMMByMp": "0",
1579                "liqPrice": "",
1580                "bustPrice": "",
1581                "tpslMode": "Full",
1582                "takeProfit": "0",
1583                "stopLoss": "0",
1584                "trailingStop": "0",
1585                "unrealisedPnl": "0",
1586                "sessionAvgPrice": "0",
1587                "curRealisedPnl": "0",
1588                "cumRealisedPnl": "0",
1589                "positionStatus": "Normal",
1590                "adlRankIndicator": 0,
1591                "createdTime": "1676538056258",
1592                "updatedTime": "1697673600012"
1593            }]
1594        }"#;
1595
1596        let msg: BybitWsAccountPositionMsg = serde_json::from_str(json)
1597            .expect("Failed to parse WS account position with missing conditional fields");
1598        let position = &msg.data[0];
1599
1600        assert!(!position.is_reduce_only);
1601        assert_eq!(position.seq, -1);
1602        assert_eq!(position.mmr_sys_updated_time, "");
1603        assert_eq!(position.leverage_sys_updated_time, "");
1604    }
1605}