ccxt-exchanges 0.1.5

Exchange implementations for CCXT Rust
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
//! Binance delivery futures (DAPI) operations.
//!
//! This module provides DAPI (coin-margined delivery futures) specific methods
//! that either don't have direct equivalents in the unified `futures` module
//! or require DAPI-specific implementations.
//!
//! # Overview
//!
//! The DAPI (Delivery API) is Binance's API for coin-margined futures contracts,
//! where contracts are settled in the base currency (e.g., BTC/USD:BTC is settled in BTC).
//! This differs from FAPI (Futures API) which handles USDT-margined contracts.
//!
//! # DAPI vs FAPI Differences
//!
//! | Feature | FAPI (Linear) | DAPI (Inverse) |
//! |---------|---------------|----------------|
//! | Settlement | USDT | Base currency (BTC, ETH, etc.) |
//! | Symbol format | BTC/USDT:USDT | BTC/USD:BTC |
//! | Base URL | /fapi/v1/* | /dapi/v1/* |
//! | Margin type | Quote currency | Base currency |
//! | PnL calculation | In USDT | In base currency |
//!
//! # Automatic Routing
//!
//! Most DAPI operations are handled automatically by the methods in the `futures` module.
//! When you call methods like `fetch_position`, `set_leverage`, or `fetch_funding_rate`
//! with a coin-margined symbol (e.g., "BTC/USD:BTC"), the implementation automatically
//! routes to the appropriate DAPI endpoint based on the market's `inverse` flag.
//!
//! # Available Methods
//!
//! This module provides the following DAPI-specific methods:
//!
//! | Method | Description | Endpoint |
//! |--------|-------------|----------|
//! | [`set_position_mode_dapi`](Binance::set_position_mode_dapi) | Set hedge/one-way mode | `/dapi/v1/positionSide/dual` |
//! | [`fetch_position_mode_dapi`](Binance::fetch_position_mode_dapi) | Get current position mode | `/dapi/v1/positionSide/dual` |
//! | [`fetch_dapi_account`](Binance::fetch_dapi_account) | Get account information | `/dapi/v1/account` |
//! | [`fetch_dapi_income`](Binance::fetch_dapi_income) | Get income history | `/dapi/v1/income` |
//! | [`fetch_dapi_commission_rate`](Binance::fetch_dapi_commission_rate) | Get commission rates | `/dapi/v1/commissionRate` |
//! | [`fetch_dapi_adl_quantile`](Binance::fetch_dapi_adl_quantile) | Get ADL quantile | `/dapi/v1/adlQuantile` |
//! | [`fetch_dapi_force_orders`](Binance::fetch_dapi_force_orders) | Get force liquidation orders | `/dapi/v1/forceOrders` |
//!
//! # DAPI-Specific vs Unified Methods
//!
//! - **DAPI-specific**: Methods in this module (prefixed with `dapi_` or suffixed with `_dapi`)
//!   are exclusively for coin-margined futures and use DAPI endpoints directly.
//! - **Unified**: Methods in the `futures` module automatically route to FAPI or DAPI
//!   based on the symbol's market type (linear vs inverse).
//!
//! # Authentication
//!
//! All methods in this module require authentication. You must provide valid API credentials
//! when creating the Binance instance.
//!
//! # Example
//!
//! ```no_run
//! # use ccxt_exchanges::binance::Binance;
//! # use ccxt_core::ExchangeConfig;
//! # async fn example() -> ccxt_core::Result<()> {
//! let mut config = ExchangeConfig::default();
//! config.api_key = Some("your_api_key".to_string());
//! config.secret = Some("your_secret".to_string());
//! let binance = Binance::new_swap(config)?;
//!
//! // Fetch DAPI position mode
//! let is_hedge_mode = binance.fetch_position_mode_dapi(None).await?;
//! println!("DAPI Hedge mode: {}", is_hedge_mode);
//!
//! // Set DAPI position mode to hedge mode
//! let result = binance.set_position_mode_dapi(true, None).await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Error Handling
//!
//! All methods return `Result<T>` and can fail with the following error types:
//!
//! - **AuthenticationError**: Missing or invalid API credentials
//! - **ExchangeError**: API returned an error (e.g., invalid symbol, insufficient balance)
//! - **NetworkError**: Connection or timeout issues
//! - **ParseError**: Failed to parse API response
//!
//! ```no_run
//! # use ccxt_exchanges::binance::Binance;
//! # use ccxt_core::{ExchangeConfig, Error};
//! # async fn example() -> ccxt_core::Result<()> {
//! let config = ExchangeConfig::default(); // No credentials
//! let binance = Binance::new_swap(config)?;
//!
//! // This will fail with AuthenticationError
//! match binance.fetch_dapi_account(None).await {
//!     Ok(account) => println!("Account: {:?}", account),
//!     Err(e) => {
//!         eprintln!("Error fetching account: {}", e);
//!         // Handle specific error types
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use super::super::Binance;
use super::super::signed_request::HttpMethod;
use ccxt_core::{Error, ParseError, Result};
use serde_json::Value;

impl Binance {
    // ==================== DAPI Position Mode Methods ====================

    /// Set position mode for coin-margined futures (DAPI).
    ///
    /// This method sets the position mode (hedge mode or one-way mode) specifically
    /// for coin-margined (inverse) futures contracts using the DAPI endpoint.
    ///
    /// # Arguments
    ///
    /// * `dual_side` - `true` for hedge mode (dual-side position), `false` for one-way mode.
    /// * `params` - Optional additional parameters to include in the request.
    ///
    /// # Returns
    ///
    /// Returns the API response as a JSON `Value`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// // Enable hedge mode for DAPI
    /// let result = binance.set_position_mode_dapi(true, None).await?;
    /// println!("Result: {:?}", result);
    ///
    /// // Switch back to one-way mode for DAPI
    /// let result = binance.set_position_mode_dapi(false, None).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.set_position_mode_dapi(true, None).await {
    ///     Ok(result) => println!("Position mode set successfully: {:?}", result),
    ///     Err(e) => {
    ///         eprintln!("Failed to set position mode: {}", e);
    ///         // Handle error - could be auth error, network error, or exchange error
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_position_mode_dapi(
        &self,
        dual_side: bool,
        params: Option<Value>,
    ) -> Result<Value> {
        // Use DAPI endpoint for coin-margined futures
        let url = format!("{}/positionSide/dual", self.urls().dapi_private);

        self.signed_request(url)
            .method(HttpMethod::Post)
            .param("dualSidePosition", dual_side)
            .merge_json_params(params)
            .execute()
            .await
    }

    /// Fetch current position mode for coin-margined futures (DAPI).
    ///
    /// This method retrieves the current position mode (hedge mode or one-way mode)
    /// specifically for coin-margined (inverse) futures contracts using the DAPI endpoint.
    ///
    /// # Arguments
    ///
    /// * `params` - Optional additional parameters to include in the request.
    ///
    /// # Returns
    ///
    /// Returns the current position mode:
    /// - `true`: Hedge mode (dual-side position) is enabled.
    /// - `false`: One-way mode is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// let is_hedge_mode = binance.fetch_position_mode_dapi(None).await?;
    /// if is_hedge_mode {
    ///     println!("DAPI is in hedge mode (dual-side positions)");
    /// } else {
    ///     println!("DAPI is in one-way mode");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.fetch_position_mode_dapi(None).await {
    ///     Ok(is_hedge) => {
    ///         let mode = if is_hedge { "hedge" } else { "one-way" };
    ///         println!("Current DAPI position mode: {}", mode);
    ///     }
    ///     Err(e) => eprintln!("Failed to fetch position mode: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch_position_mode_dapi(&self, params: Option<Value>) -> Result<bool> {
        // Use DAPI endpoint for coin-margined futures
        let url = format!("{}/positionSide/dual", self.urls().dapi_private);

        let data = self
            .signed_request(url)
            .merge_json_params(params)
            .execute()
            .await?;

        // Parse the response to extract the dualSidePosition value
        if let Some(dual_side) = data.get("dualSidePosition") {
            if let Some(value) = dual_side.as_bool() {
                return Ok(value);
            }
            if let Some(value_str) = dual_side.as_str() {
                return Ok(value_str.to_lowercase() == "true");
            }
        }

        Err(Error::from(ParseError::invalid_format(
            "data",
            "Failed to parse DAPI position mode response: missing or invalid dualSidePosition field",
        )))
    }

    // ==================== DAPI Account Methods ====================

    /// Fetch coin-margined futures account information.
    ///
    /// This method retrieves account information specifically for coin-margined (inverse)
    /// futures contracts using the DAPI endpoint. The response includes wallet balance,
    /// unrealized profit, margin balance, available balance, and position information.
    ///
    /// # Arguments
    ///
    /// * `params` - Optional additional parameters to include in the request.
    ///
    /// # Returns
    ///
    /// Returns the account information as a raw JSON `Value`. The response includes:
    /// - `totalWalletBalance`: Total wallet balance
    /// - `totalUnrealizedProfit`: Total unrealized profit
    /// - `totalMarginBalance`: Total margin balance
    /// - `availableBalance`: Available balance for new positions
    /// - `maxWithdrawAmount`: Maximum withdraw amount
    /// - `assets`: List of asset balances
    /// - `positions`: List of positions
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// // Fetch DAPI account information
    /// let account = binance.fetch_dapi_account(None).await?;
    /// println!("Account: {:?}", account);
    ///
    /// // Access specific fields
    /// if let Some(balance) = account.get("totalWalletBalance") {
    ///     println!("Total wallet balance: {}", balance);
    /// }
    /// if let Some(positions) = account.get("positions") {
    ///     println!("Positions: {:?}", positions);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.fetch_dapi_account(None).await {
    ///     Ok(account) => {
    ///         // Process account data
    ///         if let Some(balance) = account.get("totalWalletBalance") {
    ///             println!("Wallet balance: {}", balance);
    ///         }
    ///     }
    ///     Err(e) => {
    ///         eprintln!("Failed to fetch DAPI account: {}", e);
    ///         // Could be authentication error, network error, or API error
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch_dapi_account(&self, params: Option<Value>) -> Result<Value> {
        // Use DAPI endpoint for coin-margined futures account
        let url = format!("{}/account", self.urls().dapi_private);

        let data = self
            .signed_request(url)
            .merge_json_params(params)
            .execute()
            .await?;

        // Check for API errors in response
        if let Some(code) = data.get("code") {
            if let Some(msg) = data.get("msg") {
                return Err(Error::exchange(
                    code.to_string(),
                    msg.as_str().unwrap_or("Unknown error").to_string(),
                ));
            }
        }

        Ok(data)
    }

    // ==================== DAPI Income History Methods ====================

    /// Fetch income history for coin-margined futures.
    ///
    /// This method retrieves income history specifically for coin-margined (inverse)
    /// futures contracts using the DAPI endpoint. Income types include realized PnL,
    /// funding fees, commissions, and other transaction types.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Optional symbol to filter by (e.g., "BTC/USD:BTC").
    /// * `income_type` - Optional income type to filter by. Valid values:
    ///   - `"TRANSFER"`: Transfer in/out
    ///   - `"WELCOME_BONUS"`: Welcome bonus
    ///   - `"REALIZED_PNL"`: Realized profit and loss
    ///   - `"FUNDING_FEE"`: Funding fee
    ///   - `"COMMISSION"`: Trading commission
    ///   - `"INSURANCE_CLEAR"`: Insurance fund clear
    ///   - `"REFERRAL_KICKBACK"`: Referral kickback
    ///   - `"COMMISSION_REBATE"`: Commission rebate
    ///   - `"DELIVERED_SETTELMENT"`: Delivered settlement
    /// * `since` - Optional start timestamp in milliseconds.
    /// * `limit` - Optional record limit (default 100, max 1000).
    /// * `params` - Optional additional parameters. Supports:
    ///   - `endTime`: End timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// Returns income history records as a raw JSON `Value` array. Each record includes:
    /// - `symbol`: Trading pair symbol
    /// - `incomeType`: Type of income
    /// - `income`: Income amount
    /// - `asset`: Asset currency
    /// - `info`: Additional information
    /// - `time`: Timestamp
    /// - `tranId`: Transaction ID
    /// - `tradeId`: Trade ID (if applicable)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # use serde_json::json;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// // Fetch all income history
    /// let income = binance.fetch_dapi_income(None, None, None, None, None).await?;
    /// println!("Income history: {:?}", income);
    ///
    /// // Fetch funding fees for a specific symbol
    /// let funding_fees = binance.fetch_dapi_income(
    ///     Some("BTC/USD:BTC"),
    ///     Some("FUNDING_FEE"),
    ///     None,
    ///     Some(100),
    ///     None,
    /// ).await?;
    ///
    /// // Fetch income with time range
    /// let params = json!({
    ///     "endTime": 1704067200000_i64
    /// });
    /// let income = binance.fetch_dapi_income(
    ///     None,
    ///     None,
    ///     Some(1703980800000),  // since
    ///     Some(50),             // limit
    ///     Some(params),
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.fetch_dapi_income(None, Some("FUNDING_FEE"), None, Some(100), None).await {
    ///     Ok(income) => {
    ///         if let Some(records) = income.as_array() {
    ///             println!("Found {} income records", records.len());
    ///             for record in records {
    ///                 println!("Income: {:?}", record.get("income"));
    ///             }
    ///         }
    ///     }
    ///     Err(e) => eprintln!("Failed to fetch income history: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch_dapi_income(
        &self,
        symbol: Option<&str>,
        income_type: Option<&str>,
        since: Option<i64>,
        limit: Option<u32>,
        params: Option<Value>,
    ) -> Result<Value> {
        // Use DAPI endpoint for coin-margined futures income
        let url = format!("{}/income", self.urls().dapi_private);

        let mut builder = self.signed_request(url);

        // Add symbol parameter if provided
        if let Some(sym) = symbol {
            // Load markets to convert unified symbol to exchange symbol
            self.load_markets(false).await?;
            let market = self.base().market(sym).await?;
            builder = builder.param("symbol", &market.id);
        }

        // Add income type filter if provided
        if let Some(income_t) = income_type {
            builder = builder.param("incomeType", income_t);
        }

        let data = builder
            .optional_param("startTime", since)
            .optional_param("limit", limit)
            .merge_json_params(params)
            .execute()
            .await?;

        // Check for API errors in response
        if let Some(code) = data.get("code") {
            if let Some(msg) = data.get("msg") {
                return Err(Error::exchange(
                    code.to_string(),
                    msg.as_str().unwrap_or("Unknown error").to_string(),
                ));
            }
        }

        Ok(data)
    }

    // ==================== DAPI Commission Rate Methods ====================

    /// Fetch commission rate for a coin-margined futures symbol.
    ///
    /// This method retrieves the maker and taker commission rates for a specific
    /// coin-margined (inverse) futures symbol using the DAPI endpoint.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Trading pair symbol (e.g., "BTC/USD:BTC"). This parameter is required.
    /// * `params` - Optional additional parameters to include in the request.
    ///
    /// # Returns
    ///
    /// Returns the commission rate information as a raw JSON `Value`. The response includes:
    /// - `symbol`: Trading pair symbol
    /// - `makerCommissionRate`: Maker commission rate (e.g., "0.0002")
    /// - `takerCommissionRate`: Taker commission rate (e.g., "0.0004")
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The symbol parameter is invalid or not found
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// // Fetch commission rate for BTC/USD:BTC
    /// let commission = binance.fetch_dapi_commission_rate("BTC/USD:BTC", None).await?;
    /// println!("Commission rate: {:?}", commission);
    ///
    /// // Access specific fields
    /// if let Some(maker_rate) = commission.get("makerCommissionRate") {
    ///     println!("Maker rate: {}", maker_rate);
    /// }
    /// if let Some(taker_rate) = commission.get("takerCommissionRate") {
    ///     println!("Taker rate: {}", taker_rate);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.fetch_dapi_commission_rate("BTC/USD:BTC", None).await {
    ///     Ok(commission) => {
    ///         let maker = commission.get("makerCommissionRate")
    ///             .and_then(serde_json::Value::as_str)
    ///             .unwrap_or("N/A");
    ///         let taker = commission.get("takerCommissionRate")
    ///             .and_then(serde_json::Value::as_str)
    ///             .unwrap_or("N/A");
    ///         println!("Maker: {}, Taker: {}", maker, taker);
    ///     }
    ///     Err(e) => eprintln!("Failed to fetch commission rate: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch_dapi_commission_rate(
        &self,
        symbol: &str,
        params: Option<Value>,
    ) -> Result<Value> {
        // Load markets to convert unified symbol to exchange symbol
        self.load_markets(false).await?;
        let market = self.base().market(symbol).await?;

        // Use DAPI endpoint for coin-margined futures commission rate
        let url = format!("{}/commissionRate", self.urls().dapi_private);

        let data = self
            .signed_request(url)
            .param("symbol", &market.id)
            .merge_json_params(params)
            .execute()
            .await?;

        // Check for API errors in response
        if let Some(code) = data.get("code") {
            if let Some(msg) = data.get("msg") {
                return Err(Error::exchange(
                    code.to_string(),
                    msg.as_str().unwrap_or("Unknown error").to_string(),
                ));
            }
        }

        Ok(data)
    }

    // ==================== DAPI ADL Quantile Methods ====================

    /// Fetch ADL (Auto-Deleveraging) quantile for coin-margined futures.
    ///
    /// This method retrieves the ADL quantile information for coin-margined (inverse)
    /// futures positions using the DAPI endpoint. The ADL quantile indicates the
    /// priority of a position for auto-deleveraging during extreme market conditions.
    ///
    /// A higher quantile means a higher priority for auto-deleveraging. Traders with
    /// profitable positions and high leverage are more likely to be auto-deleveraged
    /// when the insurance fund is insufficient to cover liquidation losses.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Optional symbol to filter by (e.g., "BTC/USD:BTC"). If not provided,
    ///   returns ADL quantile for all positions.
    /// * `params` - Optional additional parameters to include in the request.
    ///
    /// # Returns
    ///
    /// Returns the ADL quantile information as a raw JSON `Value`. The response includes:
    /// - `symbol`: Trading pair symbol
    /// - `adlQuantile`: ADL quantile object containing:
    ///   - `LONG`: Quantile for long positions (1-5, where 5 is highest priority)
    ///   - `SHORT`: Quantile for short positions (1-5, where 5 is highest priority)
    ///   - `HEDGE`: Quantile for hedge mode positions (if applicable)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The symbol parameter is invalid or not found (if provided)
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// // Fetch ADL quantile for all positions
    /// let adl = binance.fetch_dapi_adl_quantile(None, None).await?;
    /// println!("ADL quantile: {:?}", adl);
    ///
    /// // Fetch ADL quantile for a specific symbol
    /// let adl = binance.fetch_dapi_adl_quantile(Some("BTC/USD:BTC"), None).await?;
    /// println!("BTC ADL quantile: {:?}", adl);
    ///
    /// // Access specific fields from the response
    /// if let Some(arr) = adl.as_array() {
    ///     for item in arr {
    ///         if let Some(symbol) = item.get("symbol") {
    ///             println!("Symbol: {}", symbol);
    ///         }
    ///         if let Some(quantile) = item.get("adlQuantile") {
    ///             if let Some(long_q) = quantile.get("LONG") {
    ///                 println!("Long ADL quantile: {}", long_q);
    ///             }
    ///             if let Some(short_q) = quantile.get("SHORT") {
    ///                 println!("Short ADL quantile: {}", short_q);
    ///             }
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.fetch_dapi_adl_quantile(Some("BTC/USD:BTC"), None).await {
    ///     Ok(adl) => {
    ///         // Check ADL risk level
    ///         if let Some(arr) = adl.as_array() {
    ///             for item in arr {
    ///                 if let Some(quantile) = item.get("adlQuantile") {
    ///                     if let Some(long_q) = quantile.get("LONG").and_then(serde_json::Value::as_i64) {
    ///                         if long_q >= 4 {
    ///                             println!("Warning: High ADL risk for long position!");
    ///                         }
    ///                     }
    ///                 }
    ///             }
    ///         }
    ///     }
    ///     Err(e) => eprintln!("Failed to fetch ADL quantile: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch_dapi_adl_quantile(
        &self,
        symbol: Option<&str>,
        params: Option<Value>,
    ) -> Result<Value> {
        // Use DAPI endpoint for coin-margined futures ADL quantile
        let url = format!("{}/adlQuantile", self.urls().dapi_private);

        let mut builder = self.signed_request(url);

        // Add symbol parameter if provided
        if let Some(sym) = symbol {
            // Load markets to convert unified symbol to exchange symbol
            self.load_markets(false).await?;
            let market = self.base().market(sym).await?;
            builder = builder.param("symbol", &market.id);
        }

        let data = builder.merge_json_params(params).execute().await?;

        // Check for API errors in response
        if let Some(code) = data.get("code") {
            if let Some(msg) = data.get("msg") {
                return Err(Error::exchange(
                    code.to_string(),
                    msg.as_str().unwrap_or("Unknown error").to_string(),
                ));
            }
        }

        Ok(data)
    }

    // ==================== DAPI Force Orders Methods ====================

    /// Fetch force liquidation orders for coin-margined futures.
    ///
    /// This method retrieves force liquidation orders (liquidations and auto-deleveraging)
    /// for coin-margined (inverse) futures contracts using the DAPI endpoint.
    ///
    /// Force orders occur when:
    /// - **Liquidation**: A position is forcibly closed due to insufficient margin
    /// - **ADL (Auto-Deleveraging)**: A profitable position is reduced to cover losses
    ///   from liquidated positions when the insurance fund is insufficient
    ///
    /// # Arguments
    ///
    /// * `symbol` - Optional symbol to filter by (e.g., "BTC/USD:BTC").
    /// * `auto_close_type` - Optional auto-close type to filter by. Valid values:
    ///   - `"LIQUIDATION"`: Liquidation orders
    ///   - `"ADL"`: Auto-deleveraging orders
    /// * `since` - Optional start timestamp in milliseconds.
    /// * `limit` - Optional record limit (default 50, max 100).
    /// * `params` - Optional additional parameters. Supports:
    ///   - `endTime`: End timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// Returns force liquidation order records as a raw JSON `Value` array. Each record includes:
    /// - `orderId`: Order ID
    /// - `symbol`: Trading pair symbol
    /// - `status`: Order status
    /// - `clientOrderId`: Client order ID
    /// - `price`: Order price
    /// - `avgPrice`: Average fill price
    /// - `origQty`: Original quantity
    /// - `executedQty`: Executed quantity
    /// - `cumBase`: Cumulative base asset
    /// - `timeInForce`: Time in force
    /// - `type`: Order type
    /// - `reduceOnly`: Whether reduce-only
    /// - `side`: Order side (BUY/SELL)
    /// - `positionSide`: Position side (LONG/SHORT/BOTH)
    /// - `origType`: Original order type
    /// - `time`: Order time
    /// - `updateTime`: Last update time
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Authentication credentials are missing
    /// - The symbol parameter is invalid or not found (if provided)
    /// - The API request fails
    /// - The response cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # use serde_json::json;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// // Fetch all force orders
    /// let force_orders = binance.fetch_dapi_force_orders(None, None, None, None, None).await?;
    /// println!("Force orders: {:?}", force_orders);
    ///
    /// // Fetch liquidation orders for a specific symbol
    /// let liquidations = binance.fetch_dapi_force_orders(
    ///     Some("BTC/USD:BTC"),
    ///     Some("LIQUIDATION"),
    ///     None,
    ///     Some(50),
    ///     None,
    /// ).await?;
    ///
    /// // Fetch ADL orders with time range
    /// let params = json!({
    ///     "endTime": 1704067200000_i64
    /// });
    /// let adl_orders = binance.fetch_dapi_force_orders(
    ///     None,
    ///     Some("ADL"),
    ///     Some(1703980800000),  // since
    ///     Some(100),            // limit
    ///     Some(params),
    /// ).await?;
    ///
    /// // Process the results
    /// if let Some(orders) = force_orders.as_array() {
    ///     for order in orders {
    ///         if let Some(order_id) = order.get("orderId") {
    ///             println!("Order ID: {}", order_id);
    ///         }
    ///         if let Some(symbol) = order.get("symbol") {
    ///             println!("Symbol: {}", symbol);
    ///         }
    ///         if let Some(side) = order.get("side") {
    ///             println!("Side: {}", side);
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::binance::Binance;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let mut config = ExchangeConfig::default();
    /// config.api_key = Some("your_api_key".to_string());
    /// config.secret = Some("your_secret".to_string());
    /// let binance = Binance::new_swap(config)?;
    ///
    /// match binance.fetch_dapi_force_orders(None, Some("LIQUIDATION"), None, Some(50), None).await {
    ///     Ok(orders) => {
    ///         if let Some(arr) = orders.as_array() {
    ///             if arr.is_empty() {
    ///                 println!("No liquidation orders found");
    ///             } else {
    ///                 println!("Found {} liquidation orders", arr.len());
    ///                 for order in arr {
    ///                     println!("Order: {:?}", order.get("orderId"));
    ///                 }
    ///             }
    ///         }
    ///     }
    ///     Err(e) => eprintln!("Failed to fetch force orders: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch_dapi_force_orders(
        &self,
        symbol: Option<&str>,
        auto_close_type: Option<&str>,
        since: Option<i64>,
        limit: Option<u32>,
        params: Option<Value>,
    ) -> Result<Value> {
        // Use DAPI endpoint for coin-margined futures force orders
        let url = format!("{}/forceOrders", self.urls().dapi_private);

        let mut builder = self.signed_request(url);

        // Add symbol parameter if provided
        if let Some(sym) = symbol {
            // Load markets to convert unified symbol to exchange symbol
            self.load_markets(false).await?;
            let market = self.base().market(sym).await?;
            builder = builder.param("symbol", &market.id);
        }

        // Add auto close type filter if provided (LIQUIDATION or ADL)
        if let Some(close_type) = auto_close_type {
            builder = builder.param("autoCloseType", close_type);
        }

        let data = builder
            .optional_param("startTime", since)
            .optional_param("limit", limit)
            .merge_json_params(params)
            .execute()
            .await?;

        // Check for API errors in response
        if let Some(code) = data.get("code") {
            if let Some(msg) = data.get("msg") {
                return Err(Error::exchange(
                    code.to_string(),
                    msg.as_str().unwrap_or("Unknown error").to_string(),
                ));
            }
        }

        Ok(data)
    }
}