digdigdig3 0.1.27

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
//! # Bybit Parser
//!
//! Parsing Bybit V5 API responses to internal types.
//!
//! ## Response Structure
//!
//! Success response:
//! ```json
//! {
//!   "retCode": 0,
//!   "retMsg": "OK",
//!   "result": { ... },
//!   "time": 1702617474601
//! }
//! ```
//!
//! ## Key Differences from KuCoin
//!
//! - Success code: `retCode: 0` (integer) vs KuCoin `code: "200000"` (string)
//! - Data wrapper: `result` vs `data`
//! - Most data in `result.list` arrays
//! - Kline order: [time, open, high, low, close, volume, turnover]
//! - All timestamps in milliseconds

use serde_json::Value;
use crate::core::types::*;
use crate::core::types::{ExchangeResult, ExchangeError, CancelAllResponse, OrderResult};

pub struct BybitParser;

impl BybitParser {
    // ═══════════════════════════════════════════════════════════════════════════════
    // RESPONSE WRAPPER
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Extract result from Bybit response
    ///
    /// Checks retCode == 0 for success
    fn extract_result(json: &Value) -> ExchangeResult<&Value> {
        let ret_code = json["retCode"].as_i64().unwrap_or(-1);

        if ret_code != 0 {
            let ret_msg = json["retMsg"].as_str().unwrap_or("Unknown error");
            return Err(ExchangeError::Api {
                code: ret_code as i32,
                message: ret_msg.to_string(),
            });
        }

        Ok(&json["result"])
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // MARKET DATA PARSERS (REST)
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse ticker from REST response
    ///
    /// Endpoint: GET /v5/market/tickers
    /// Response: result.list[0] = { symbol, lastPrice, bid1Price, ask1Price, ... }
    pub fn parse_ticker(json: &Value) -> ExchangeResult<Ticker> {
        let result = Self::extract_result(json)?;
        let list = result["list"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing result.list".into()))?;

        let data = list.first()
            .ok_or_else(|| ExchangeError::Parse("Empty result.list".into()))?;

        let symbol = data["symbol"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing symbol".into()))?;

        let last_price = data["lastPrice"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .ok_or_else(|| ExchangeError::Parse("Invalid lastPrice".into()))?;

        let bid_price = data["bid1Price"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let ask_price = data["ask1Price"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let high_24h = data["highPrice24h"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let low_24h = data["lowPrice24h"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let volume_24h = data["volume24h"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let quote_volume_24h = data["turnover24h"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let timestamp = json["time"].as_i64().unwrap_or(0);

        Ok(Ticker {
            symbol: symbol.to_string(),
            last_price,
            bid_price,
            ask_price,
            high_24h,
            low_24h,
            volume_24h,
            quote_volume_24h,
            price_change_24h: {
                let last = data["lastPrice"].as_str().and_then(|s| s.parse::<f64>().ok());
                let prev = data["prevPrice24h"].as_str().and_then(|s| s.parse::<f64>().ok());
                match (last, prev) {
                    (Some(l), Some(p)) => Some(l - p),
                    _ => None,
                }
            },
            price_change_percent_24h: data["price24hPcnt"].as_str()
                .and_then(|s| s.parse::<f64>().ok())
                .map(|v| v * 100.0),
            timestamp,
        })
    }

    /// Parse orderbook from REST response
    ///
    /// Endpoint: GET /v5/market/orderbook
    /// Response: result = { s, b: [[price, size]], a: [[price, size]], ts, u }
    pub fn parse_orderbook(json: &Value) -> ExchangeResult<OrderBook> {
        let result = Self::extract_result(json)?;

        let bids: Vec<OrderBookLevel> = result["b"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing bids".into()))?
            .iter()
            .filter_map(|entry| {
                let arr = entry.as_array()?;
                let price = arr.first()?.as_str()?.parse::<f64>().ok()?;
                let size = arr.get(1)?.as_str()?.parse::<f64>().ok()?;
                Some(OrderBookLevel::new(price, size))
            })
            .collect();

        let asks: Vec<OrderBookLevel> = result["a"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing asks".into()))?
            .iter()
            .filter_map(|entry| {
                let arr = entry.as_array()?;
                let price = arr.first()?.as_str()?.parse::<f64>().ok()?;
                let size = arr.get(1)?.as_str()?.parse::<f64>().ok()?;
                Some(OrderBookLevel::new(price, size))
            })
            .collect();

        let timestamp = result["ts"].as_i64().unwrap_or(0);
        let last_update_id = result["u"].as_i64().map(|u| u as u64);
        let sequence = last_update_id.map(|u| u.to_string());

        Ok(OrderBook {
            bids,
            asks,
            timestamp,
            sequence,
            last_update_id,
            first_update_id: None,
            prev_update_id: None,
            event_time: None,
            transaction_time: None,
            checksum: None,
        })
    }

    /// Parse klines from REST response
    ///
    /// Endpoint: GET /v5/market/kline
    /// Response: result.list = [[time, open, high, low, close, volume, turnover], ...]
    ///
    /// CRITICAL: Array order is [time, open, high, low, close, volume, turnover]
    /// This differs from KuCoin: [time, open, close, high, low, volume, turnover]
    /// HIGH and CLOSE positions are SWAPPED!
    pub fn parse_klines(json: &Value) -> ExchangeResult<Vec<Kline>> {
        let result = Self::extract_result(json)?;
        let list = result["list"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing result.list".into()))?;

        let mut klines: Vec<Kline> = list.iter()
            .filter_map(|entry| {
                let arr = entry.as_array()?;

                // Bybit order: [time, open, high, low, close, volume, turnover]
                let open_time = arr.first()?.as_str()?.parse::<i64>().ok()?;
                let open = arr.get(1)?.as_str()?.parse::<f64>().ok()?;
                let high = arr.get(2)?.as_str()?.parse::<f64>().ok()?;
                let low = arr.get(3)?.as_str()?.parse::<f64>().ok()?;
                let close = arr.get(4)?.as_str()?.parse::<f64>().ok()?;
                let volume = arr.get(5)?.as_str()?.parse::<f64>().ok()?;
                let quote_volume = arr.get(6).and_then(|v| v.as_str())
                    .and_then(|s| s.parse::<f64>().ok());

                Some(Kline {
                    open_time,
                    open,
                    high,
                    low,
                    close,
                    volume,
                    quote_volume,
                    close_time: None,
                    trades: None,
                })
            })
            .collect();

        // Bybit returns newest first, reverse to oldest first
        klines.reverse();

        Ok(klines)
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // ACCOUNT PARSERS (REST)
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse balance from REST response
    ///
    /// Endpoint: GET /v5/account/wallet-balance
    /// Response: result.list[0].coin = [{ coin, walletBalance, locked, ... }]
    pub fn parse_balance(json: &Value) -> ExchangeResult<Vec<crate::core::Balance>> {
        let result = Self::extract_result(json)?;
        let list = result["list"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing result.list".into()))?;

        let account = list.first()
            .ok_or_else(|| ExchangeError::Parse("Empty result.list".into()))?;

        let coins = account["coin"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing coin array".into()))?;

        let balances = coins.iter()
            .filter_map(|coin_data| {
                let asset = coin_data["coin"].as_str()?.to_string();
                let free = coin_data["walletBalance"].as_str()?.parse::<f64>().ok()?;
                let locked = coin_data["locked"].as_str()?.parse::<f64>().ok().unwrap_or(0.0);
                let total = free + locked;

                Some(crate::core::Balance {
                    asset,
                    free,
                    locked,
                    total,
                })
            })
            .collect();

        Ok(balances)
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // TRADING PARSERS (REST)
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse order from REST response
    ///
    /// Endpoint: POST /v5/order/create OR GET /v5/order/realtime
    /// Response: result = { orderId, symbol, side, orderType, ... } OR result.list[0]
    pub fn parse_order(json: &Value) -> ExchangeResult<Order> {
        let result = Self::extract_result(json)?;

        // Handle both direct result and result.list[0]
        let data = if result.is_array() || result.get("list").is_some() {
            result["list"].as_array()
                .and_then(|list| list.first())
                .ok_or_else(|| ExchangeError::Parse("Empty order list".into()))?
        } else {
            result
        };

        let id = data["orderId"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing orderId".into()))?
            .to_string();

        let symbol = data["symbol"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing symbol".into()))?
            .to_string();

        let side = match data["side"].as_str() {
            Some("Buy") => OrderSide::Buy,
            Some("Sell") => OrderSide::Sell,
            _ => return Err(ExchangeError::Parse("Invalid side".into())),
        };

        let order_type = match data["orderType"].as_str() {
            Some("Market") => OrderType::Market,
            Some("Limit") => OrderType::Limit { price: 0.0 },
            _ => OrderType::Limit { price: 0.0 }, // default
        };

        let status = Self::parse_order_status(data["orderStatus"].as_str().unwrap_or(""));

        let price = data["price"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let quantity = data["qty"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let filled_quantity = data["cumExecQty"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let average_price = data["avgPrice"].as_str()
            .and_then(|s| s.parse::<f64>().ok());

        let created_at = data["createdTime"].as_str()
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);

        let updated_at = data["updatedTime"].as_str()
            .and_then(|s| s.parse::<i64>().ok());

        Ok(Order {
            id,
            client_order_id: data["orderLinkId"].as_str().map(String::from),
            symbol,
            side,
            order_type,
            status,
            price,
            stop_price: None,
            quantity,
            filled_quantity,
            average_price,
            time_in_force: TimeInForce::Gtc,
            commission: None,
            commission_asset: None,
            created_at,
            updated_at,
        })
    }

    /// Parse order status from string
    fn parse_order_status(status: &str) -> OrderStatus {
        match status {
            "Created" | "New" => OrderStatus::New,
            "PartiallyFilled" => OrderStatus::PartiallyFilled,
            "Filled" => OrderStatus::Filled,
            "Cancelled" => OrderStatus::Canceled,
            "Rejected" => OrderStatus::Rejected,
            _ => OrderStatus::New,
        }
    }

    /// Parse funding rate
    ///
    /// Endpoint: GET /v5/market/funding/history
    /// Response: result.list[0] = { symbol, fundingRate, fundingRateTimestamp }
    pub fn parse_funding_rate(json: &Value) -> ExchangeResult<FundingRate> {
        let result = Self::extract_result(json)?;
        let list = result["list"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing result.list".into()))?;

        let data = list.first()
            .ok_or_else(|| ExchangeError::Parse("Empty result.list".into()))?;

        let symbol = data["symbol"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing symbol".into()))?;

        let rate = data["fundingRate"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let timestamp = data["fundingRateTimestamp"].as_str()
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);

        Ok(FundingRate {
            symbol: symbol.to_string(),
            rate,
            next_funding_time: None,
            timestamp,
        })
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // EXCHANGE INFO PARSERS
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse exchange info (symbol list) from Bybit response
    ///
    /// Endpoint: GET /v5/market/instruments-info
    /// Response: result.list = [{ symbol, baseCoin, quoteCoin, status, lotSizeFilter, priceFilter }]
    ///
    /// Filters to active/trading symbols only (status == "Trading").
    pub fn parse_exchange_info(json: &Value, account_type: AccountType) -> ExchangeResult<Vec<crate::core::types::SymbolInfo>> {
        let result = Self::extract_result(json)?;
        let list = result["list"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing result.list".into()))?;

        let symbols = list.iter()
            .filter_map(|item| {
                let symbol = item["symbol"].as_str()?.to_string();
                let base_asset = item["baseCoin"].as_str().unwrap_or("").to_string();
                let quote_asset = item["quoteCoin"].as_str().unwrap_or("").to_string();
                let status = item["status"].as_str().unwrap_or("").to_string();

                // Filter to active symbols only
                if status != "Trading" {
                    return None;
                }

                // Parse lot size filter
                let lot_filter = item.get("lotSizeFilter");
                let min_quantity = lot_filter
                    .and_then(|f| f["minOrderQty"].as_str())
                    .and_then(|s| s.parse::<f64>().ok());
                let max_quantity = lot_filter
                    .and_then(|f| f["maxOrderQty"].as_str())
                    .and_then(|s| s.parse::<f64>().ok());
                let step_size = lot_filter
                    .and_then(|f| f["qtyStep"].as_str())
                    .and_then(|s| s.parse::<f64>().ok());

                // Parse price filter for precision
                let price_filter = item.get("priceFilter");
                let tick_size = price_filter
                    .and_then(|f| f["tickSize"].as_str())
                    .and_then(|s| s.parse::<f64>().ok());

                // Derive price precision from tick size (e.g. "0.01" -> 2)
                let price_precision = tick_size
                    .map(|t| {
                        let s = format!("{:.10}", t);
                        let trimmed = s.trim_end_matches('0');
                        if let Some(dot_pos) = trimmed.find('.') {
                            (trimmed.len() - dot_pos - 1) as u8
                        } else {
                            0u8
                        }
                    })
                    .unwrap_or(8);

                // Derive quantity precision from step size
                let quantity_precision = step_size
                    .map(|t| {
                        let s = format!("{:.10}", t);
                        let trimmed = s.trim_end_matches('0');
                        if let Some(dot_pos) = trimmed.find('.') {
                            (trimmed.len() - dot_pos - 1) as u8
                        } else {
                            0u8
                        }
                    })
                    .unwrap_or(8);

                Some(crate::core::types::SymbolInfo {
                    symbol,
                    base_asset,
                    quote_asset,
                    status,
                    price_precision,
                    quantity_precision,
                    min_quantity,
                    max_quantity,
                    tick_size,
                    step_size,
                    min_notional: None,
                    account_type,
                })
            })
            .collect();

        Ok(symbols)
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // OPTIONAL TRAIT PARSERS
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse cancel-all response.
    ///
    /// Bybit returns: `result.list = [{ orderId, orderLinkId }, ...]`
    /// Each item is a successfully cancelled order.
    pub fn parse_cancel_all_response(json: &Value) -> ExchangeResult<CancelAllResponse> {
        let result = Self::extract_result(json)?;

        let list = result["list"].as_array()
            .cloned()
            .unwrap_or_default();

        let details: Vec<OrderResult> = list.iter()
            .map(|item| OrderResult {
                order: None,
                client_order_id: item["orderLinkId"].as_str().map(String::from),
                success: true,
                error: None,
                error_code: None,
            })
            .collect();

        let cancelled_count = details.len() as u32;

        Ok(CancelAllResponse {
            cancelled_count,
            failed_count: 0,
            details,
        })
    }

    /// Parse amend order response.
    ///
    /// Bybit returns: `result = { orderId, orderLinkId }`
    /// The full updated order is not returned — re-use `parse_order` to wrap it.
    pub fn parse_amend_order_response(json: &Value) -> ExchangeResult<Order> {
        let result = Self::extract_result(json)?;

        // Bybit amend returns minimal info: orderId + orderLinkId
        // Build a minimal Order object from the available data.
        let id = result["orderId"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing orderId in amend response".to_string()))?
            .to_string();

        Ok(Order {
            id,
            client_order_id: result["orderLinkId"].as_str().map(String::from),
            symbol: String::new(),
            side: OrderSide::Buy,
            order_type: OrderType::Limit { price: 0.0 },
            status: OrderStatus::Open,
            price: None,
            stop_price: None,
            quantity: 0.0,
            filled_quantity: 0.0,
            average_price: None,
            commission: None,
            commission_asset: None,
            created_at: 0,
            updated_at: None,
            time_in_force: TimeInForce::Gtc,
        })
    }

    /// Parse batch orders response.
    ///
    /// Bybit batch response: `result.list = [{ orderId, orderLinkId, code, msg }, ...]`
    /// `code == "0"` indicates success for each item.
    pub fn parse_batch_orders_response(json: &Value) -> ExchangeResult<Vec<OrderResult>> {
        let result = Self::extract_result(json)?;

        let list = result["list"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing result.list in batch response".to_string()))?;

        let results = list.iter()
            .map(|item| {
                let code = item["code"].as_str().unwrap_or("0");
                let success = code == "0";
                if success {
                    OrderResult {
                        order: None,
                        client_order_id: item["orderLinkId"].as_str().map(String::from),
                        success: true,
                        error: None,
                        error_code: None,
                    }
                } else {
                    let msg = item["msg"].as_str().unwrap_or("Unknown error").to_string();
                    OrderResult {
                        order: None,
                        client_order_id: item["orderLinkId"].as_str().map(String::from),
                        success: false,
                        error: Some(msg),
                        error_code: code.parse().ok(),
                    }
                }
            })
            .collect();

        Ok(results)
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // ACCOUNT TRANSFERS PARSERS
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse inter-transfer response.
    ///
    /// Bybit returns: `result = { transferId }`
    pub fn parse_transfer_response(json: &Value) -> ExchangeResult<TransferResponse> {
        let result = Self::extract_result(json)?;

        let transfer_id = result["transferId"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing transferId".to_string()))?
            .to_string();

        Ok(TransferResponse {
            transfer_id,
            status: "SUCCESS".to_string(),
            asset: String::new(),
            amount: 0.0,
            timestamp: None,
        })
    }

    /// Parse transfer history response.
    ///
    /// Bybit returns: `result.list = [{ transferId, coin, amount, fromAccountType, toAccountType, status, timestamp }]`
    pub fn parse_transfer_history(json: &Value) -> ExchangeResult<Vec<TransferResponse>> {
        let result = Self::extract_result(json)?;
        let list = result["list"].as_array()
            .cloned()
            .unwrap_or_default();

        let records = list.iter()
            .map(|item| {
                let transfer_id = item["transferId"].as_str()
                    .unwrap_or("")
                    .to_string();
                let asset = item["coin"].as_str()
                    .unwrap_or("")
                    .to_string();
                let amount = item["amount"].as_str()
                    .and_then(|s| s.parse::<f64>().ok())
                    .unwrap_or(0.0);
                let status = item["status"].as_str()
                    .unwrap_or("UNKNOWN")
                    .to_string();
                let timestamp = item["timestamp"].as_str()
                    .and_then(|s| s.parse::<i64>().ok());

                TransferResponse {
                    transfer_id,
                    status,
                    asset,
                    amount,
                    timestamp,
                }
            })
            .collect();

        Ok(records)
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // CUSTODIAL FUNDS PARSERS
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse deposit address response.
    ///
    /// Bybit returns: `result = { coin, chains: [{ chainType, addressDeposit, tagDeposit, ... }] }`
    pub fn parse_deposit_address(json: &Value, asset: &str, network: Option<&str>) -> ExchangeResult<DepositAddress> {
        let result = Self::extract_result(json)?;

        let coin = result["coin"].as_str().unwrap_or(asset);

        let chains = result["chains"].as_array()
            .ok_or_else(|| ExchangeError::Parse("Missing chains array in deposit address".to_string()))?;

        // Pick the chain matching `network`, or the first one if network is None.
        let chain_data = if let Some(net) = network {
            chains.iter()
                .find(|c| {
                    c["chainType"].as_str().map(|s| s.eq_ignore_ascii_case(net)).unwrap_or(false)
                })
                .ok_or_else(|| ExchangeError::Parse(
                    format!("Network '{}' not found in deposit address chains", net)
                ))?
        } else {
            chains.first()
                .ok_or_else(|| ExchangeError::Parse("No chains in deposit address response".to_string()))?
        };

        let address = chain_data["addressDeposit"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing addressDeposit".to_string()))?
            .to_string();

        let tag = chain_data["tagDeposit"].as_str()
            .filter(|s| !s.is_empty())
            .map(String::from);

        let chain_type = chain_data["chainType"].as_str().map(String::from);

        Ok(DepositAddress {
            address,
            tag,
            network: chain_type,
            asset: coin.to_string(),
            created_at: None,
        })
    }

    /// Parse withdrawal response.
    ///
    /// Bybit returns: `result = { id }`
    pub fn parse_withdraw_response(json: &Value) -> ExchangeResult<WithdrawResponse> {
        let result = Self::extract_result(json)?;

        let withdraw_id = result["id"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing withdrawal id".to_string()))?
            .to_string();

        Ok(WithdrawResponse {
            withdraw_id,
            status: "PENDING".to_string(),
            tx_hash: None,
        })
    }

    /// Parse deposit history response.
    ///
    /// Bybit returns: `result.rows = [{ txID, coin, amount, chain, status, successAt }]`
    pub fn parse_deposit_history(json: &Value) -> ExchangeResult<Vec<FundsRecord>> {
        let result = Self::extract_result(json)?;

        // deposit history uses "rows" not "list"
        let rows = result["rows"].as_array()
            .cloned()
            .unwrap_or_default();

        let records = rows.iter()
            .map(|item| {
                let id = item["txID"].as_str().unwrap_or("").to_string();
                let asset = item["coin"].as_str().unwrap_or("").to_string();
                let amount = item["amount"].as_str()
                    .and_then(|s| s.parse::<f64>().ok())
                    .unwrap_or(0.0);
                let tx_hash = item["txID"].as_str()
                    .filter(|s| !s.is_empty())
                    .map(String::from);
                let network = item["chain"].as_str().map(String::from);
                let status = item["status"].as_str().unwrap_or("UNKNOWN").to_string();
                let timestamp = item["successAt"].as_str()
                    .and_then(|s| s.parse::<i64>().ok())
                    .unwrap_or(0);

                FundsRecord::Deposit {
                    id,
                    asset,
                    amount,
                    tx_hash,
                    network,
                    status,
                    timestamp,
                }
            })
            .collect();

        Ok(records)
    }

    /// Parse withdrawal history response.
    ///
    /// Bybit returns: `result.rows = [{ withdrawId, coin, amount, chain, address, tag, txID, status, createTime }]`
    pub fn parse_withdrawal_history(json: &Value) -> ExchangeResult<Vec<FundsRecord>> {
        let result = Self::extract_result(json)?;

        let rows = result["rows"].as_array()
            .cloned()
            .unwrap_or_default();

        let records = rows.iter()
            .map(|item| {
                let id = item["withdrawId"].as_str().unwrap_or("").to_string();
                let asset = item["coin"].as_str().unwrap_or("").to_string();
                let amount = item["amount"].as_str()
                    .and_then(|s| s.parse::<f64>().ok())
                    .unwrap_or(0.0);
                let fee = item["withdrawFee"].as_str()
                    .and_then(|s| s.parse::<f64>().ok());
                let address = item["address"].as_str().unwrap_or("").to_string();
                let tag = item["tag"].as_str()
                    .filter(|s| !s.is_empty())
                    .map(String::from);
                let tx_hash = item["txID"].as_str()
                    .filter(|s| !s.is_empty())
                    .map(String::from);
                let network = item["chain"].as_str().map(String::from);
                let status = item["status"].as_str().unwrap_or("UNKNOWN").to_string();
                let timestamp = item["createTime"].as_str()
                    .and_then(|s| s.parse::<i64>().ok())
                    .unwrap_or(0);

                FundsRecord::Withdrawal {
                    id,
                    asset,
                    amount,
                    fee,
                    address,
                    tag,
                    tx_hash,
                    network,
                    status,
                    timestamp,
                }
            })
            .collect();

        Ok(records)
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // SUB-ACCOUNT PARSERS
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse create sub-account response.
    ///
    /// Bybit returns: `result = { uid, username, memberType, status, remark }`
    pub fn parse_create_sub_member(json: &Value) -> ExchangeResult<SubAccountResult> {
        let result = Self::extract_result(json)?;

        let id = result["uid"].as_u64()
            .map(|u| u.to_string())
            .or_else(|| result["uid"].as_str().map(String::from));

        let name = result["username"].as_str().map(String::from);

        Ok(SubAccountResult {
            id,
            name,
            accounts: vec![],
            transaction_id: None,
        })
    }

    /// Parse list sub-members response.
    ///
    /// Bybit returns: `result.subMembers = [{ uid, username, memberType, status, remark }]`
    pub fn parse_list_sub_members(json: &Value) -> ExchangeResult<SubAccountResult> {
        let result = Self::extract_result(json)?;

        let sub_members = result["subMembers"].as_array()
            .cloned()
            .unwrap_or_default();

        let accounts: Vec<SubAccount> = sub_members.iter()
            .map(|item| {
                let id = item["uid"].as_u64()
                    .map(|u| u.to_string())
                    .or_else(|| item["uid"].as_str().map(String::from))
                    .unwrap_or_default();
                let name = item["username"].as_str().unwrap_or("").to_string();
                let status = match item["status"].as_u64() {
                    Some(1) => "Normal",
                    Some(2) => "Login Banned",
                    Some(4) => "Frozen",
                    _ => "Unknown",
                }.to_string();

                SubAccount { id, name, status }
            })
            .collect();

        Ok(SubAccountResult {
            id: None,
            name: None,
            accounts,
            transaction_id: None,
        })
    }

    /// Parse universal transfer response.
    ///
    /// Bybit returns: `result = { transferId }`
    pub fn parse_universal_transfer(json: &Value) -> ExchangeResult<SubAccountResult> {
        let result = Self::extract_result(json)?;

        let transfer_id = result["transferId"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing transferId in universal transfer response".to_string()))?
            .to_string();

        Ok(SubAccountResult {
            id: None,
            name: None,
            accounts: vec![],
            transaction_id: Some(transfer_id),
        })
    }

    /// Parse sub-account balance response.
    ///
    /// Bybit returns: `result = { memberId, accountType, balance: [{ coin, walletBalance, ... }] }`
    /// The balance list is returned as `transaction_id` is not applicable here.
    /// We store the coin balances as a JSON summary in `transaction_id`.
    pub fn parse_sub_account_balance(json: &Value) -> ExchangeResult<SubAccountResult> {
        let result = Self::extract_result(json)?;

        let member_id = result["memberId"].as_str()
            .or_else(|| result["memberId"].as_u64().map(|_| "").filter(|_| false))
            .map(String::from);

        // Summarize balance as "COIN:amount,COIN:amount,..."
        let balance_summary = result["balance"].as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|item| {
                        let coin = item["coin"].as_str()?;
                        let amount = item["walletBalance"].as_str().unwrap_or("0");
                        Some(format!("{}:{}", coin, amount))
                    })
                    .collect::<Vec<_>>()
                    .join(",")
            });

        Ok(SubAccountResult {
            id: member_id,
            name: None,
            accounts: vec![],
            transaction_id: balance_summary,
        })
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // USER TRADE PARSER
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse a single execution (fill) from `result.list[]` of GET /v5/execution/list
    ///
    /// Each list item:
    /// ```json
    /// {
    ///   "execId": "...",
    ///   "orderId": "...",
    ///   "symbol": "BTCUSDT",
    ///   "side": "Buy",
    ///   "execPrice": "50000",
    ///   "execQty": "0.001",
    ///   "execFee": "0.00001",
    ///   "feeCurrency": "USDT",
    ///   "isMaker": false,
    ///   "execTime": "1672531200000"
    /// }
    /// ```
    pub fn parse_user_trade(item: &Value) -> ExchangeResult<UserTrade> {
        let id = item["execId"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing execId".to_string()))?
            .to_string();

        let order_id = item["orderId"].as_str()
            .unwrap_or("")
            .to_string();

        let symbol = item["symbol"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing symbol".to_string()))?
            .to_string();

        let side = match item["side"].as_str().unwrap_or("Buy") {
            "Sell" => OrderSide::Sell,
            _ => OrderSide::Buy,
        };

        let price = item["execPrice"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let quantity = item["execQty"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let commission = item["execFee"].as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let commission_asset = item["feeCurrency"].as_str()
            .unwrap_or("")
            .to_string();

        let is_maker = item["isMaker"].as_bool().unwrap_or(false);

        // execTime is a string in milliseconds
        let timestamp = item["execTime"].as_str()
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);

        Ok(UserTrade {
            id,
            order_id,
            symbol,
            side,
            price,
            quantity,
            commission,
            commission_asset,
            is_maker,
            timestamp,
        })
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // WEBSOCKET PARSERS
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Parse WebSocket message
    ///
    /// Format: { "topic": "...", "type": "snapshot|delta", "ts": ..., "data": {...} }
    pub fn parse_ws_message(json: &Value) -> ExchangeResult<(String, String, &Value)> {
        let topic = json["topic"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing topic".into()))?;

        let msg_type = json["type"].as_str()
            .ok_or_else(|| ExchangeError::Parse("Missing type".into()))?;

        let data = &json["data"];

        Ok((topic.to_string(), msg_type.to_string(), data))
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // FUNDING HISTORY
    // ═══════════════════════════════════════════════════════════════════════════

    /// Parse funding payments from `GET /v5/account/transaction-log?type=SETTLEMENT`
    pub fn parse_funding_payments(response: &Value) -> ExchangeResult<Vec<FundingPayment>> {
        let result = Self::extract_result(response)?;
        let list = result.get("list")
            .and_then(|v| v.as_array())
            .ok_or_else(|| ExchangeError::Parse("Missing 'list' in transaction-log result".to_string()))?;

        let mut payments = Vec::with_capacity(list.len());
        for item in list {
            let symbol = item.get("symbol").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let payment: f64 = item.get("cashFlow")
                .and_then(|v| v.as_str()).and_then(|s| s.parse().ok()).unwrap_or(0.0);
            let position_size: f64 = item.get("qty")
                .and_then(|v| v.as_str()).and_then(|s| s.parse().ok()).unwrap_or(0.0);
            let asset = item.get("currency").and_then(|v| v.as_str()).unwrap_or("USDT").to_string();
            let timestamp: i64 = item.get("transactionTime")
                .and_then(|v| v.as_str()).and_then(|s| s.parse().ok()).unwrap_or(0);
            payments.push(FundingPayment {
                symbol,
                funding_rate: 0.0,
                position_size,
                payment,
                asset,
                timestamp,
            });
        }
        Ok(payments)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // ACCOUNT LEDGER
    // ═══════════════════════════════════════════════════════════════════════════

    /// Parse ledger from `GET /v5/account/transaction-log` (all types).
    ///
    /// Maps Bybit `type` field to `LedgerEntryType`.
    pub fn parse_ledger(response: &Value) -> ExchangeResult<Vec<LedgerEntry>> {
        let result = Self::extract_result(response)?;
        let list = result.get("list")
            .and_then(|v| v.as_array())
            .ok_or_else(|| ExchangeError::Parse("Missing 'list' in transaction-log result".to_string()))?;

        let mut entries = Vec::with_capacity(list.len());
        for item in list {
            let id = item.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let symbol = item.get("symbol").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let tx_type = item.get("type").and_then(|v| v.as_str()).unwrap_or("OTHER");
            let amount: f64 = item.get("cashFlow")
                .and_then(|v| v.as_str()).and_then(|s| s.parse().ok()).unwrap_or(0.0);
            let balance: Option<f64> = item.get("cashBalance")
                .and_then(|v| v.as_str()).and_then(|s| s.parse().ok());
            let asset = item.get("currency").and_then(|v| v.as_str()).unwrap_or("USDT").to_string();
            let timestamp: i64 = item.get("transactionTime")
                .and_then(|v| v.as_str()).and_then(|s| s.parse().ok()).unwrap_or(0);
            let entry_type = match tx_type {
                "TRADE" => LedgerEntryType::Trade,
                "SETTLEMENT" => LedgerEntryType::Funding,
                "DELIVERY" => LedgerEntryType::Settlement,
                "TRANSFER" | "AIRDROP" => LedgerEntryType::Transfer,
                "CASHBACK" | "REBATE" => LedgerEntryType::Rebate,
                "LIQUIDATION" => LedgerEntryType::Liquidation,
                "DEPOSIT" => LedgerEntryType::Deposit,
                "WITHDRAWAL" => LedgerEntryType::Withdrawal,
                other => LedgerEntryType::Other(other.to_string()),
            };
            entries.push(LedgerEntry {
                id,
                asset,
                amount,
                balance,
                entry_type,
                description: format!("{} {}", tx_type, symbol),
                ref_id: None,
                timestamp,
            });
        }
        Ok(entries)
    }
}

// Balance type conversion helper - removed, use core Balance directly

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_parse_ticker() {
        let json = json!({
            "retCode": 0,
            "retMsg": "OK",
            "result": {
                "list": [{
                    "symbol": "BTCUSDT",
                    "lastPrice": "40000.00",
                    "bid1Price": "39999.00",
                    "ask1Price": "40001.00",
                    "highPrice24h": "41000.00",
                    "lowPrice24h": "39000.00",
                    "volume24h": "1234.56",
                    "turnover24h": "49382000.00"
                }]
            },
            "time": 1702617474601i64
        });

        let ticker = BybitParser::parse_ticker(&json).unwrap();
        assert_eq!(ticker.symbol, "BTCUSDT");
        assert_eq!(ticker.last_price, 40000.0);
        assert_eq!(ticker.bid_price, Some(39999.0));
        assert_eq!(ticker.ask_price, Some(40001.0));
    }

    #[test]
    fn test_parse_klines() {
        let json = json!({
            "retCode": 0,
            "retMsg": "OK",
            "result": {
                "list": [
                    ["1670608800000", "40000.00", "40500.00", "39900.00", "40200.00", "123.456", "4960000.00"]
                ]
            },
            "time": 1702617474601i64
        });

        let klines = BybitParser::parse_klines(&json).unwrap();
        assert_eq!(klines.len(), 1);
        assert_eq!(klines[0].open_time, 1670608800000);
        assert_eq!(klines[0].open, 40000.0);
        assert_eq!(klines[0].high, 40500.0);
        assert_eq!(klines[0].low, 39900.0);
        assert_eq!(klines[0].close, 40200.0);
    }
}