nautilus-bybit 0.53.0

Bybit exchange integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! WebSocket message types for Bybit public and private channels.

use nautilus_model::{
    data::{Data, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate, OrderBookDeltas},
    events::{AccountState, OrderCancelRejected, OrderModifyRejected, OrderRejected},
    reports::{FillReport, OrderStatusReport, PositionStatusReport},
};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use ustr::Ustr;

use crate::{
    common::{
        enums::{
            BybitCancelType, BybitCreateType, BybitExecType, BybitOrderSide, BybitOrderStatus,
            BybitOrderType, BybitProductType, BybitStopOrderType, BybitTimeInForce, BybitTpSlMode,
            BybitTriggerDirection, BybitTriggerType, BybitWsOrderRequestOp,
        },
        parse::{
            deserialize_decimal_or_zero, deserialize_optional_decimal_or_zero,
            deserialize_optional_decimal_str,
        },
    },
    websocket::enums::BybitWsOperation,
};

/// Bybit WebSocket subscription message.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BybitSubscription {
    pub op: BybitWsOperation,
    pub args: Vec<String>,
}

/// Bybit WebSocket authentication message.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BybitAuthRequest {
    pub op: BybitWsOperation,
    pub args: Vec<serde_json::Value>,
}

/// High level message emitted by the Bybit WebSocket client.
#[derive(Debug, Clone)]
pub enum BybitWsMessage {
    /// Generic response (subscribe/auth acknowledgement).
    Response(BybitWsResponse),
    /// Authentication acknowledgement.
    Auth(BybitWsAuthResponse),
    /// Subscription acknowledgement.
    Subscription(BybitWsSubscriptionMsg),
    /// Order operation response (create/amend/cancel) from trade WebSocket.
    OrderResponse(BybitWsOrderResponse),
    /// Orderbook snapshot or delta.
    Orderbook(BybitWsOrderbookDepthMsg),
    /// Trade updates.
    Trade(BybitWsTradeMsg),
    /// Kline updates.
    Kline(BybitWsKlineMsg),
    /// Linear/inverse ticker update.
    TickerLinear(BybitWsTickerLinearMsg),
    /// Option ticker update.
    TickerOption(BybitWsTickerOptionMsg),
    /// Order updates from private channel.
    AccountOrder(BybitWsAccountOrderMsg),
    /// Execution/fill updates from private channel.
    AccountExecution(BybitWsAccountExecutionMsg),
    /// Wallet/balance updates from private channel.
    AccountWallet(BybitWsAccountWalletMsg),
    /// Position updates from private channel.
    AccountPosition(BybitWsAccountPositionMsg),
    /// Error received from the venue or client lifecycle.
    Error(BybitWebSocketError),
    /// Raw message payload that does not yet have a typed representation.
    Raw(Value),
    /// Notification that the underlying connection reconnected.
    Reconnected,
    /// Explicit pong event (text-based heartbeat acknowledgement).
    Pong,
}

/// Nautilus domain message emitted after parsing Bybit WebSocket events.
///
/// This enum contains fully-parsed Nautilus domain objects ready for consumption
/// by the Python layer without additional processing.
#[derive(Debug, Clone)]
pub enum NautilusWsMessage {
    /// Market data (trades, quotes, bars).
    Data(Vec<Data>),
    /// Order book deltas.
    Deltas(OrderBookDeltas),
    /// Mark price updates from ticker stream.
    MarkPrices(Vec<MarkPriceUpdate>),
    /// Index price updates from ticker stream.
    IndexPrices(Vec<IndexPriceUpdate>),
    /// Funding rate updates from ticker stream.
    FundingRates(Vec<FundingRateUpdate>),
    /// Order status reports from account stream or operation responses.
    OrderStatusReports(Vec<OrderStatusReport>),
    /// Fill reports from executions.
    FillReports(Vec<FillReport>),
    /// Position status report.
    PositionStatusReport(PositionStatusReport),
    /// Account state from wallet updates.
    AccountState(AccountState),
    /// Order rejected event (from failed order submission).
    OrderRejected(OrderRejected),
    /// Order cancel rejected event (from failed cancel operation).
    OrderCancelRejected(OrderCancelRejected),
    /// Order modify rejected event (from failed amend operation).
    OrderModifyRejected(OrderModifyRejected),
    /// Error from venue or client.
    Error(BybitWebSocketError),
    /// WebSocket reconnected notification.
    Reconnected,
    /// Authentication successful notification.
    Authenticated,
}

/// Represents an error event surfaced by the WebSocket client.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
pub struct BybitWebSocketError {
    /// Error/return code reported by Bybit.
    pub code: i64,
    /// Human readable message.
    pub message: String,
    /// Optional connection identifier.
    #[serde(default)]
    pub conn_id: Option<String>,
    /// Optional topic associated with the error (when applicable).
    #[serde(default)]
    pub topic: Option<String>,
    /// Optional request identifier related to the failure.
    #[serde(default)]
    pub req_id: Option<String>,
}

impl BybitWebSocketError {
    /// Creates a new error with the provided code/message.
    #[must_use]
    pub fn new(code: i64, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            conn_id: None,
            topic: None,
            req_id: None,
        }
    }

    /// Builds an error payload from a generic response frame.
    #[must_use]
    pub fn from_response(response: &BybitWsResponse) -> Self {
        // Build a more informative error message when ret_msg is missing
        let message = response.ret_msg.clone().unwrap_or_else(|| {
            let mut parts = vec![];

            if let Some(op) = &response.op {
                parts.push(format!("op={op}"));
            }
            if let Some(topic) = &response.topic {
                parts.push(format!("topic={topic}"));
            }
            if let Some(success) = response.success {
                parts.push(format!("success={success}"));
            }

            if parts.is_empty() {
                "Bybit websocket error (no error message provided)".to_string()
            } else {
                format!("Bybit websocket error: {}", parts.join(", "))
            }
        });

        Self {
            code: response.ret_code.unwrap_or_default(),
            message,
            conn_id: response.conn_id.clone(),
            topic: response.topic.map(|t| t.to_string()),
            req_id: response.req_id.clone(),
        }
    }

    /// Convenience constructor for client-side errors (e.g. parsing failures).
    #[must_use]
    pub fn from_message(message: impl Into<String>) -> Self {
        Self::new(-1, message)
    }
}

/// Generic WebSocket request for Bybit trading commands.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsRequest<T> {
    /// Request ID for correlation (will be echoed back in response).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub req_id: Option<String>,
    /// Operation type (order.create, order.amend, order.cancel, etc.).
    pub op: BybitWsOrderRequestOp,
    /// Request header containing timestamp and other metadata.
    pub header: BybitWsHeader,
    /// Arguments payload for the operation.
    pub args: Vec<T>,
}

/// Header for WebSocket trade requests.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
pub struct BybitWsHeader {
    /// Timestamp in milliseconds.
    pub x_bapi_timestamp: String,
    /// Optional referer ID.
    #[serde(rename = "Referer", skip_serializing_if = "Option::is_none")]
    pub referer: Option<String>,
}

impl BybitWsHeader {
    /// Creates a new header with the current timestamp.
    #[must_use]
    pub fn now() -> Self {
        Self::with_referer(None)
    }

    /// Creates a new header with the current timestamp and optional referer.
    #[must_use]
    pub fn with_referer(referer: Option<String>) -> Self {
        use nautilus_core::time::get_atomic_clock_realtime;
        Self {
            x_bapi_timestamp: get_atomic_clock_realtime().get_time_ms().to_string(),
            referer,
        }
    }
}

/// Parameters for placing an order via WebSocket.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsPlaceOrderParams {
    pub category: BybitProductType,
    pub symbol: Ustr,
    pub side: BybitOrderSide,
    pub order_type: BybitOrderType,
    pub qty: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_leverage: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_unit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<BybitTimeInForce>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_link_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_on_trigger: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_direction: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tpsl_mode: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub take_profit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_order_type: Option<BybitOrderType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_order_type: Option<BybitOrderType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_limit_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_limit_price: Option<String>,
}

/// Parameters for amending an order via WebSocket.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAmendOrderParams {
    pub category: BybitProductType,
    pub symbol: Ustr,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_link_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qty: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub take_profit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_by: Option<BybitTriggerType>,
}

/// Parameters for canceling an order via WebSocket.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsCancelOrderParams {
    pub category: BybitProductType,
    pub symbol: Ustr,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_link_id: Option<String>,
}

/// Item in a batch cancel request (without category field).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsBatchCancelItem {
    pub symbol: Ustr,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_link_id: Option<String>,
}

/// Arguments for batch cancel order operation via WebSocket.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BybitWsBatchCancelOrderArgs {
    pub category: BybitProductType,
    pub request: Vec<BybitWsBatchCancelItem>,
}

/// Item in a batch place request (same as BybitWsPlaceOrderParams but without category).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsBatchPlaceItem {
    pub symbol: Ustr,
    pub side: BybitOrderSide,
    pub order_type: BybitOrderType,
    pub qty: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_leverage: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_unit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<BybitTimeInForce>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_link_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_on_trigger: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_direction: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tpsl_mode: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub take_profit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_by: Option<BybitTriggerType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_order_type: Option<BybitOrderType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_order_type: Option<BybitOrderType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_limit_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_limit_price: Option<String>,
}

/// Arguments for batch place order operation via WebSocket.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BybitWsBatchPlaceOrderArgs {
    pub category: BybitProductType,
    pub request: Vec<BybitWsBatchPlaceItem>,
}

/// Subscription acknowledgement returned by Bybit.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitWsSubscriptionMsg {
    pub success: bool,
    pub op: BybitWsOperation,
    #[serde(default)]
    pub conn_id: Option<String>,
    #[serde(default)]
    pub req_id: Option<String>,
    #[serde(default)]
    pub ret_msg: Option<String>,
}

/// Generic response returned by the endpoint when subscribing or authenticating.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitWsResponse {
    #[serde(default)]
    pub op: Option<BybitWsOperation>,
    #[serde(default)]
    pub topic: Option<Ustr>,
    #[serde(default)]
    pub success: Option<bool>,
    #[serde(default)]
    pub conn_id: Option<String>,
    #[serde(default)]
    pub req_id: Option<String>,
    #[serde(default)]
    pub ret_code: Option<i64>,
    #[serde(default)]
    pub ret_msg: Option<String>,
}

/// Order operation response from WebSocket trade API.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsOrderResponse {
    /// Operation type (order.create, order.amend, order.cancel).
    pub op: Ustr,
    /// Connection ID.
    #[serde(default)]
    pub conn_id: Option<String>,
    /// Return code (0 = success, non-zero = error).
    pub ret_code: i64,
    /// Return message.
    pub ret_msg: String,
    /// Response data (usually empty for errors, may contain order details for success).
    #[serde(default)]
    pub data: Value,
    /// Request ID for correlation (echoed back if provided in request).
    #[serde(default)]
    pub req_id: Option<String>,
    /// Request header containing timestamp and rate limit info.
    #[serde(default)]
    pub header: Option<Value>,
    /// Extended info for errors.
    #[serde(default)]
    pub ret_ext_info: Option<Value>,
}

impl BybitWsOrderResponse {
    /// Extracts individual order errors from retExtInfo for batch operations.
    ///
    /// For batch operations, even when ret_code is 0, individual orders may fail.
    /// These failures are reported in retExtInfo.list as an array of {code, msg} objects.
    #[must_use]
    pub fn extract_batch_errors(&self) -> Vec<BybitBatchOrderError> {
        self.ret_ext_info
            .as_ref()
            .and_then(|ext| ext.get("list"))
            .and_then(|list| list.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|item| {
                        let code = item.get("code")?.as_i64()?;
                        let msg = item.get("msg")?.as_str()?.to_string();
                        Some(BybitBatchOrderError { code, msg })
                    })
                    .collect()
            })
            .unwrap_or_default()
    }
}

/// Error information for individual orders in a batch operation.
#[derive(Clone, Debug)]
pub struct BybitBatchOrderError {
    /// Error code (0 = success, non-zero = error).
    pub code: i64,
    /// Error message.
    pub msg: String,
}

/// Authentication acknowledgement for private channels.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAuthResponse {
    pub op: BybitWsOperation,
    #[serde(default)]
    pub conn_id: Option<String>,
    #[serde(default)]
    pub ret_code: Option<i64>,
    #[serde(default)]
    pub ret_msg: Option<String>,
    #[serde(default)]
    pub success: Option<bool>,
}

/// Representation of a kline/candlestick event on the public stream.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsKline {
    pub start: i64,
    pub end: i64,
    pub interval: Ustr,
    pub open: String,
    pub close: String,
    pub high: String,
    pub low: String,
    pub volume: String,
    pub turnover: String,
    pub confirm: bool,
    pub timestamp: i64,
}

/// Envelope for kline updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsKlineMsg {
    pub topic: Ustr,
    pub ts: i64,
    #[serde(rename = "type")]
    pub msg_type: Ustr,
    pub data: Vec<BybitWsKline>,
}

/// Orderbook depth payload consisting of raw ladder deltas.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitWsOrderbookDepth {
    /// Symbol.
    pub s: Ustr,
    /// Bid levels represented as `[price, size]` string pairs.
    pub b: Vec<Vec<String>>,
    /// Ask levels represented as `[price, size]` string pairs.
    pub a: Vec<Vec<String>>,
    /// Update identifier.
    pub u: i64,
    /// Cross sequence number.
    pub seq: i64,
}

/// Envelope for orderbook depth snapshots and updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsOrderbookDepthMsg {
    pub topic: Ustr,
    #[serde(rename = "type")]
    pub msg_type: Ustr,
    pub ts: i64,
    pub data: BybitWsOrderbookDepth,
    #[serde(default)]
    pub cts: Option<i64>,
}

/// Linear/Inverse ticker event payload.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsTickerLinear {
    pub symbol: Ustr,
    #[serde(default)]
    pub tick_direction: Option<String>,
    #[serde(default)]
    pub price24h_pcnt: Option<String>,
    #[serde(default)]
    pub last_price: Option<String>,
    #[serde(default)]
    pub prev_price24h: Option<String>,
    #[serde(default)]
    pub high_price24h: Option<String>,
    #[serde(default)]
    pub low_price24h: Option<String>,
    #[serde(default)]
    pub prev_price1h: Option<String>,
    #[serde(default)]
    pub mark_price: Option<String>,
    #[serde(default)]
    pub index_price: Option<String>,
    #[serde(default)]
    pub open_interest: Option<String>,
    #[serde(default)]
    pub open_interest_value: Option<String>,
    #[serde(default)]
    pub turnover24h: Option<String>,
    #[serde(default)]
    pub volume24h: Option<String>,
    #[serde(default)]
    pub next_funding_time: Option<String>,
    #[serde(default)]
    pub funding_rate: Option<String>,
    #[serde(default)]
    pub bid1_price: Option<String>,
    #[serde(default)]
    pub bid1_size: Option<String>,
    #[serde(default)]
    pub ask1_price: Option<String>,
    #[serde(default)]
    pub ask1_size: Option<String>,
}

/// Envelope for linear ticker updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsTickerLinearMsg {
    pub topic: Ustr,
    #[serde(rename = "type")]
    pub msg_type: Ustr,
    pub ts: i64,
    #[serde(default)]
    pub cs: Option<i64>,
    pub data: BybitWsTickerLinear,
}

/// Option ticker event payload.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsTickerOption {
    pub symbol: Ustr,
    pub bid_price: String,
    pub bid_size: String,
    pub bid_iv: String,
    pub ask_price: String,
    pub ask_size: String,
    pub ask_iv: String,
    pub last_price: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub mark_price: String,
    pub index_price: String,
    pub mark_price_iv: String,
    pub underlying_price: String,
    pub open_interest: String,
    pub turnover24h: String,
    pub volume24h: String,
    pub total_volume: String,
    pub total_turnover: String,
    pub delta: String,
    pub gamma: String,
    pub vega: String,
    pub theta: String,
    pub predicted_delivery_price: String,
    pub change24h: String,
}

/// Envelope for option ticker updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsTickerOptionMsg {
    #[serde(default)]
    pub id: Option<String>,
    pub topic: Ustr,
    #[serde(rename = "type")]
    pub msg_type: Ustr,
    pub ts: i64,
    pub data: BybitWsTickerOption,
}

/// Trade event payload containing trade executions on public feeds.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitWsTrade {
    #[serde(rename = "T")]
    pub t: i64,
    #[serde(rename = "s")]
    pub s: Ustr,
    #[serde(rename = "S")]
    pub taker_side: BybitOrderSide,
    #[serde(rename = "v")]
    pub v: String,
    #[serde(rename = "p")]
    pub p: String,
    #[serde(rename = "i")]
    pub i: String,
    #[serde(rename = "BT")]
    pub bt: bool,
    #[serde(rename = "L")]
    #[serde(default)]
    pub l: Option<String>,
    #[serde(rename = "id")]
    #[serde(default)]
    pub id: Option<Ustr>,
    #[serde(rename = "mP")]
    #[serde(default)]
    pub m_p: Option<String>,
    #[serde(rename = "iP")]
    #[serde(default)]
    pub i_p: Option<String>,
    #[serde(rename = "mIv")]
    #[serde(default)]
    pub m_iv: Option<String>,
    #[serde(rename = "iv")]
    #[serde(default)]
    pub iv: Option<String>,
}

/// Envelope for public trade updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsTradeMsg {
    pub topic: Ustr,
    #[serde(rename = "type")]
    pub msg_type: Ustr,
    pub ts: i64,
    pub data: Vec<BybitWsTrade>,
}

/// Private order stream payload.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountOrder {
    pub category: BybitProductType,
    pub symbol: Ustr,
    pub order_id: Ustr,
    pub side: BybitOrderSide,
    pub order_type: BybitOrderType,
    pub cancel_type: BybitCancelType,
    pub price: String,
    pub qty: String,
    pub order_iv: String,
    pub time_in_force: BybitTimeInForce,
    pub order_status: BybitOrderStatus,
    pub order_link_id: Ustr,
    pub last_price_on_created: Ustr,
    pub reduce_only: bool,
    pub leaves_qty: String,
    pub leaves_value: String,
    pub cum_exec_qty: String,
    pub cum_exec_value: String,
    pub avg_price: String,
    pub block_trade_id: Ustr,
    pub position_idx: i32,
    pub cum_exec_fee: String,
    pub created_time: String,
    pub updated_time: String,
    pub reject_reason: Ustr,
    pub trigger_price: String,
    pub take_profit: String,
    pub stop_loss: String,
    pub tp_trigger_by: BybitTriggerType,
    pub sl_trigger_by: BybitTriggerType,
    pub tp_limit_price: String,
    pub sl_limit_price: String,
    pub close_on_trigger: bool,
    pub place_type: Ustr,
    pub smp_type: Ustr,
    pub smp_group: i32,
    pub smp_order_id: Ustr,
    pub fee_currency: Ustr,
    pub trigger_by: BybitTriggerType,
    pub stop_order_type: BybitStopOrderType,
    pub trigger_direction: BybitTriggerDirection,
    #[serde(default)]
    pub tpsl_mode: Option<BybitTpSlMode>,
    #[serde(default)]
    pub create_type: Option<BybitCreateType>,
}

/// Envelope for account order updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountOrderMsg {
    pub topic: Ustr,
    pub id: String,
    pub creation_time: i64,
    pub data: Vec<BybitWsAccountOrder>,
}

/// Private execution (fill) stream payload.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountExecution {
    pub category: BybitProductType,
    pub symbol: Ustr,
    pub exec_fee: String,
    pub exec_id: String,
    pub exec_price: String,
    pub exec_qty: String,
    pub exec_type: BybitExecType,
    pub exec_value: String,
    pub is_maker: bool,
    pub fee_rate: String,
    pub trade_iv: String,
    pub mark_iv: String,
    pub block_trade_id: Ustr,
    pub mark_price: String,
    pub index_price: String,
    pub underlying_price: String,
    pub leaves_qty: String,
    pub order_id: Ustr,
    pub order_link_id: Ustr,
    pub order_price: String,
    pub order_qty: String,
    pub order_type: BybitOrderType,
    pub side: BybitOrderSide,
    pub exec_time: String,
    pub is_leverage: String,
    pub closed_size: String,
    pub seq: i64,
    pub stop_order_type: BybitStopOrderType,
}

/// Envelope for account execution updates.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountExecutionMsg {
    pub topic: Ustr,
    pub id: String,
    pub creation_time: i64,
    pub data: Vec<BybitWsAccountExecution>,
}

/// Coin level wallet update payload on private streams.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountWalletCoin {
    pub coin: Ustr,
    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
    pub wallet_balance: Decimal,
    pub available_to_withdraw: String,
    pub available_to_borrow: String,
    pub accrued_interest: String,
    #[serde(
        default,
        rename = "totalOrderIM",
        deserialize_with = "deserialize_optional_decimal_or_zero"
    )]
    pub total_order_im: Decimal,
    #[serde(
        default,
        rename = "totalPositionIM",
        deserialize_with = "deserialize_optional_decimal_or_zero"
    )]
    pub total_position_im: Decimal,
    #[serde(default, rename = "totalPositionMM")]
    pub total_position_mm: Option<String>,
    pub equity: String,
    #[serde(default, deserialize_with = "deserialize_optional_decimal_or_zero")]
    pub spot_borrow: Decimal,
}

/// Wallet summary payload covering all coins.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountWallet {
    pub total_wallet_balance: String,
    pub total_equity: String,
    pub total_available_balance: String,
    pub total_margin_balance: String,
    pub total_initial_margin: String,
    pub total_maintenance_margin: String,
    #[serde(rename = "accountIMRate")]
    pub account_im_rate: String,
    #[serde(rename = "accountMMRate")]
    pub account_mm_rate: String,
    #[serde(rename = "accountLTV")]
    pub account_ltv: String,
    pub coin: Vec<BybitWsAccountWalletCoin>,
}

/// Envelope for wallet updates on private streams.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountWalletMsg {
    pub topic: Ustr,
    pub id: String,
    pub creation_time: i64,
    pub data: Vec<BybitWsAccountWallet>,
}

/// Position data from private position stream.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountPosition {
    pub category: BybitProductType,
    pub symbol: Ustr,
    pub side: Ustr,
    pub size: String,
    pub position_idx: i32,
    pub trade_mode: i32,
    pub position_value: String,
    pub risk_id: i64,
    pub risk_limit_value: String,
    #[serde(deserialize_with = "deserialize_optional_decimal_str")]
    pub entry_price: Option<Decimal>,
    pub mark_price: String,
    pub leverage: String,
    pub position_balance: String,
    pub auto_add_margin: i32,
    #[serde(rename = "positionIM")]
    pub position_im: String,
    #[serde(rename = "positionIMByMp")]
    pub position_im_by_mp: String,
    #[serde(rename = "positionMM")]
    pub position_mm: String,
    #[serde(rename = "positionMMByMp")]
    pub position_mm_by_mp: String,
    pub liq_price: String,
    pub bust_price: String,
    pub tpsl_mode: Ustr,
    pub take_profit: String,
    pub stop_loss: String,
    pub trailing_stop: String,
    pub unrealised_pnl: String,
    pub session_avg_price: String,
    pub cur_realised_pnl: String,
    pub cum_realised_pnl: String,
    pub position_status: Ustr,
    pub adl_rank_indicator: i32,
    pub created_time: String,
    pub updated_time: String,
    pub seq: i64,
    pub is_reduce_only: bool,
    pub mmr_sys_updated_time: String,
    pub leverage_sys_updated_time: String,
}

/// Envelope for position updates on private streams.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWsAccountPositionMsg {
    pub topic: Ustr,
    pub id: String,
    pub creation_time: i64,
    pub data: Vec<BybitWsAccountPosition>,
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;
    use crate::common::testing::load_test_json;

    #[rstest]
    fn deserialize_account_order_frame_uses_enums() {
        let json = load_test_json("ws_account_order.json");
        let frame: BybitWsAccountOrderMsg = serde_json::from_str(&json).unwrap();
        let order = &frame.data[0];

        assert_eq!(order.cancel_type, BybitCancelType::CancelByUser);
        assert_eq!(order.tp_trigger_by, BybitTriggerType::MarkPrice);
        assert_eq!(order.sl_trigger_by, BybitTriggerType::LastPrice);
        assert_eq!(order.tpsl_mode, Some(BybitTpSlMode::Full));
        assert_eq!(order.create_type, Some(BybitCreateType::CreateByUser));
        assert_eq!(order.side, BybitOrderSide::Buy);
    }
}