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
//! Binance-specific endpoint router trait.
//!
//! This module provides the `BinanceEndpointRouter` trait for routing API requests
//! to the correct Binance domain based on market characteristics.
//!
//! # Binance API Domains
//!
//! Binance has a complex multi-domain structure:
//! - **Spot**: `api.binance.com` - Spot trading and margin
//! - **Linear Futures (FAPI)**: `fapi.binance.com` - USDT-margined perpetuals/futures
//! - **Inverse Futures (DAPI)**: `dapi.binance.com` - Coin-margined perpetuals/futures
//! - **Options (EAPI)**: `eapi.binance.com` - Options trading
//! - **Portfolio Margin (PAPI)**: `papi.binance.com` - Portfolio margin API
//!
//! # Example
//!
//! ```rust,no_run
//! use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter};
//! use ccxt_core::types::{EndpointType, Market, MarketType};
//! use ccxt_core::ExchangeConfig;
//!
//! let binance = Binance::new(ExchangeConfig::default()).unwrap();
//!
//! // Get REST endpoint for a spot market
//! let spot_market = Market::new_spot(
//!     "BTCUSDT".to_string(),
//!     "BTC/USDT".to_string(),
//!     "BTC".to_string(),
//!     "USDT".to_string(),
//! );
//! let url = binance.rest_endpoint(&spot_market, EndpointType::Public);
//! assert!(url.contains("api.binance.com"));
//!
//! // Get default REST endpoint based on exchange options
//! let default_url = binance.default_rest_endpoint(EndpointType::Public);
//! ```

use ccxt_core::types::{EndpointType, Market, MarketType};

/// Binance-specific endpoint router trait.
///
/// This trait defines methods for obtaining the correct API endpoints based on
/// market characteristics. Binance has multiple API domains for different market
/// types (spot, linear futures, inverse futures, options).
///
/// # Implementation Notes
///
/// The routing logic follows these rules:
/// - **Spot markets**: Use `api.binance.com` endpoints
/// - **Linear Swap/Futures**: Use `fapi.binance.com` endpoints (USDT-margined)
/// - **Inverse Swap/Futures**: Use `dapi.binance.com` endpoints (Coin-margined)
/// - **Option markets**: Use `eapi.binance.com` endpoints
///
/// When sandbox mode is enabled, testnet URLs are returned instead.
pub trait BinanceEndpointRouter {
    /// Returns the REST API endpoint for a specific market.
    ///
    /// This method routes to the correct Binance domain based on the market's
    /// `market_type`, `linear`, and `inverse` fields.
    ///
    /// # Arguments
    ///
    /// * `market` - Reference to the market object containing type information
    /// * `endpoint_type` - Whether this is a public or private endpoint
    ///
    /// # Returns
    ///
    /// The REST API base URL string for the given market.
    ///
    /// # Routing Logic
    ///
    /// | Market Type | Linear | Inverse | Domain |
    /// |-------------|--------|---------|--------|
    /// | Spot | - | - | api.binance.com |
    /// | Swap/Futures | true | false | fapi.binance.com |
    /// | Swap/Futures | false | true | dapi.binance.com |
    /// | Option | - | - | eapi.binance.com |
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter};
    /// use ccxt_core::types::{EndpointType, Market, MarketType};
    /// use ccxt_core::ExchangeConfig;
    /// use rust_decimal_macros::dec;
    ///
    /// let binance = Binance::new(ExchangeConfig::default()).unwrap();
    ///
    /// // Linear futures market
    /// let linear_market = Market::new_swap(
    ///     "BTCUSDT".to_string(),
    ///     "BTC/USDT:USDT".to_string(),
    ///     "BTC".to_string(),
    ///     "USDT".to_string(),
    ///     "USDT".to_string(),
    ///     dec!(1.0),
    /// );
    /// let url = binance.rest_endpoint(&linear_market, EndpointType::Public);
    /// assert!(url.contains("fapi.binance.com"));
    /// ```
    fn rest_endpoint(&self, market: &Market, endpoint_type: EndpointType) -> String;

    /// Returns the WebSocket endpoint for a specific market.
    ///
    /// This method routes to the correct Binance WebSocket domain based on
    /// the market's type and settlement characteristics.
    ///
    /// # Arguments
    ///
    /// * `market` - Reference to the market object containing type information
    ///
    /// # Returns
    ///
    /// The WebSocket URL string for the given market.
    ///
    /// # Routing Logic
    ///
    /// | Market Type | Linear | Inverse | WebSocket Domain |
    /// |-------------|--------|---------|------------------|
    /// | Spot | - | - | stream.binance.com |
    /// | Swap/Futures | true | false | fstream.binance.com |
    /// | Swap/Futures | false | true | dstream.binance.com |
    /// | Option | - | - | nbstream.binance.com |
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter};
    /// use ccxt_core::types::Market;
    /// use ccxt_core::ExchangeConfig;
    ///
    /// let binance = Binance::new(ExchangeConfig::default()).unwrap();
    ///
    /// let spot_market = Market::new_spot(
    ///     "BTCUSDT".to_string(),
    ///     "BTC/USDT".to_string(),
    ///     "BTC".to_string(),
    ///     "USDT".to_string(),
    /// );
    /// let ws_url = binance.ws_endpoint(&spot_market);
    /// assert!(ws_url.contains("stream.binance.com"));
    /// ```
    fn ws_endpoint(&self, market: &Market) -> String;

    /// Returns the default REST endpoint when no specific market is provided.
    ///
    /// This method uses the exchange's `default_type` and `default_sub_type`
    /// options to determine which endpoint to return.
    ///
    /// # Arguments
    ///
    /// * `endpoint_type` - Whether this is a public or private endpoint
    ///
    /// # Returns
    ///
    /// The default REST API base URL string.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter, BinanceOptions};
    /// use ccxt_core::types::EndpointType;
    /// use ccxt_core::types::default_type::{DefaultType, DefaultSubType};
    /// use ccxt_core::ExchangeConfig;
    ///
    /// // Create a futures-focused Binance instance
    /// let options = BinanceOptions {
    ///     default_type: DefaultType::Swap,
    ///     default_sub_type: Some(DefaultSubType::Linear),
    ///     ..Default::default()
    /// };
    /// let binance = Binance::new_with_options(ExchangeConfig::default(), options).unwrap();
    ///
    /// let url = binance.default_rest_endpoint(EndpointType::Public);
    /// assert!(url.contains("fapi.binance.com"));
    /// ```
    fn default_rest_endpoint(&self, endpoint_type: EndpointType) -> String;

    /// Returns the default WebSocket endpoint when no specific market is provided.
    ///
    /// This method uses the exchange's `default_type` and `default_sub_type`
    /// options to determine which WebSocket endpoint to return.
    ///
    /// # Returns
    ///
    /// The default WebSocket URL string.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter};
    /// use ccxt_core::ExchangeConfig;
    ///
    /// let binance = Binance::new(ExchangeConfig::default()).unwrap();
    /// let ws_url = binance.default_ws_endpoint();
    /// // Default is spot, so should be stream.binance.com
    /// assert!(ws_url.contains("stream.binance.com"));
    /// ```
    fn default_ws_endpoint(&self) -> String;

    /// Returns the SAPI (Spot API) endpoint.
    ///
    /// SAPI is used for Binance-specific spot trading features like:
    /// - Margin trading operations
    /// - Savings and staking
    /// - Sub-account management
    /// - Asset transfers
    ///
    /// # Returns
    ///
    /// The SAPI base URL string.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter};
    /// use ccxt_core::ExchangeConfig;
    ///
    /// let binance = Binance::new(ExchangeConfig::default()).unwrap();
    /// let sapi_url = binance.sapi_endpoint();
    /// assert!(sapi_url.contains("sapi"));
    /// ```
    fn sapi_endpoint(&self) -> String;

    /// Returns the Portfolio Margin API (PAPI) endpoint.
    ///
    /// PAPI is used for portfolio margin trading which allows cross-margining
    /// across spot, futures, and options positions.
    ///
    /// # Returns
    ///
    /// The PAPI base URL string.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ccxt_exchanges::binance::{Binance, BinanceEndpointRouter};
    /// use ccxt_core::ExchangeConfig;
    ///
    /// let binance = Binance::new(ExchangeConfig::default()).unwrap();
    /// let papi_url = binance.papi_endpoint();
    /// assert!(papi_url.contains("papi"));
    /// ```
    fn papi_endpoint(&self) -> String;
}

use super::Binance;

use ccxt_core::types::default_type::{DefaultSubType, DefaultType};

impl BinanceEndpointRouter for Binance {
    fn rest_endpoint(&self, market: &Market, endpoint_type: EndpointType) -> String {
        let urls = self.urls();

        match market.market_type {
            MarketType::Spot => match endpoint_type {
                EndpointType::Public => urls.public.clone(),
                EndpointType::Private => urls.private.clone(),
            },
            MarketType::Swap | MarketType::Futures => {
                // Determine linear/inverse from market fields
                // Default to linear (true) if not specified
                let is_linear = market.linear.unwrap_or(true);

                if is_linear {
                    match endpoint_type {
                        EndpointType::Public => urls.fapi_public.clone(),
                        EndpointType::Private => urls.fapi_private.clone(),
                    }
                } else {
                    match endpoint_type {
                        EndpointType::Public => urls.dapi_public.clone(),
                        EndpointType::Private => urls.dapi_private.clone(),
                    }
                }
            }
            MarketType::Option => match endpoint_type {
                EndpointType::Public => urls.eapi_public.clone(),
                EndpointType::Private => urls.eapi_private.clone(),
            },
        }
    }

    fn ws_endpoint(&self, market: &Market) -> String {
        let urls = self.urls();

        match market.market_type {
            MarketType::Spot => urls.ws.clone(),
            MarketType::Swap | MarketType::Futures => {
                // Determine linear/inverse from market fields
                // Default to linear (true) if not specified
                let is_linear = market.linear.unwrap_or(true);

                if is_linear {
                    urls.ws_fapi.clone()
                } else {
                    urls.ws_dapi.clone()
                }
            }
            MarketType::Option => urls.ws_eapi.clone(),
        }
    }

    fn default_rest_endpoint(&self, endpoint_type: EndpointType) -> String {
        let urls = self.urls();
        let options = self.options();

        match options.default_type {
            DefaultType::Spot => match endpoint_type {
                EndpointType::Public => urls.public.clone(),
                EndpointType::Private => urls.private.clone(),
            },
            DefaultType::Margin => urls.sapi.clone(),
            DefaultType::Swap | DefaultType::Futures => {
                match options.default_sub_type {
                    Some(DefaultSubType::Inverse) => match endpoint_type {
                        EndpointType::Public => urls.dapi_public.clone(),
                        EndpointType::Private => urls.dapi_private.clone(),
                    },
                    _ => match endpoint_type {
                        // Default to FAPI (Linear)
                        EndpointType::Public => urls.fapi_public.clone(),
                        EndpointType::Private => urls.fapi_private.clone(),
                    },
                }
            }
            DefaultType::Option => match endpoint_type {
                EndpointType::Public => urls.eapi_public.clone(),
                EndpointType::Private => urls.eapi_private.clone(),
            },
        }
    }

    fn default_ws_endpoint(&self) -> String {
        let urls = self.urls();
        let options = self.options();

        match options.default_type {
            DefaultType::Swap | DefaultType::Futures => {
                // Check sub-type for FAPI vs DAPI selection
                match options.default_sub_type {
                    Some(DefaultSubType::Inverse) => urls.ws_dapi.clone(),
                    _ => urls.ws_fapi.clone(), // Default to FAPI (Linear) if not specified
                }
            }
            DefaultType::Option => urls.ws_eapi.clone(),
            _ => urls.ws.clone(), // Spot and Margin use standard WebSocket
        }
    }

    fn sapi_endpoint(&self) -> String {
        self.urls().sapi.clone()
    }

    fn papi_endpoint(&self) -> String {
        self.urls().papi.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ccxt_core::ExchangeConfig;
    use rust_decimal_macros::dec;

    fn create_test_binance() -> Binance {
        Binance::new(ExchangeConfig::default()).unwrap()
    }

    fn create_sandbox_binance() -> Binance {
        let config = ExchangeConfig {
            sandbox: true,
            ..Default::default()
        };
        Binance::new(config).unwrap()
    }

    // ==================== REST Endpoint Tests ====================

    #[test]
    fn test_rest_endpoint_spot_public() {
        let binance = create_test_binance();
        let market = Market::new_spot(
            "BTCUSDT".to_string(),
            "BTC/USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
        );

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        assert!(url.contains("api.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_spot_private() {
        let binance = create_test_binance();
        let market = Market::new_spot(
            "BTCUSDT".to_string(),
            "BTC/USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
        );

        let url = binance.rest_endpoint(&market, EndpointType::Private);
        assert!(url.contains("api.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_linear_swap_public() {
        let binance = create_test_binance();
        let market = Market::new_swap(
            "BTCUSDT".to_string(),
            "BTC/USDT:USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
            "USDT".to_string(),
            dec!(1.0),
        );

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        assert!(url.contains("fapi.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_linear_swap_private() {
        let binance = create_test_binance();
        let market = Market::new_swap(
            "BTCUSDT".to_string(),
            "BTC/USDT:USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
            "USDT".to_string(),
            dec!(1.0),
        );

        let url = binance.rest_endpoint(&market, EndpointType::Private);
        assert!(url.contains("fapi.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_inverse_swap_public() {
        let binance = create_test_binance();
        let mut market = Market::new_swap(
            "BTCUSD_PERP".to_string(),
            "BTC/USD:BTC".to_string(),
            "BTC".to_string(),
            "USD".to_string(),
            "BTC".to_string(),
            dec!(100.0),
        );
        // Ensure inverse is set correctly
        market.linear = Some(false);
        market.inverse = Some(true);

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        assert!(url.contains("dapi.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_inverse_swap_private() {
        let binance = create_test_binance();
        let mut market = Market::new_swap(
            "BTCUSD_PERP".to_string(),
            "BTC/USD:BTC".to_string(),
            "BTC".to_string(),
            "USD".to_string(),
            "BTC".to_string(),
            dec!(100.0),
        );
        market.linear = Some(false);
        market.inverse = Some(true);

        let url = binance.rest_endpoint(&market, EndpointType::Private);
        assert!(url.contains("dapi.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_option_public() {
        let binance = create_test_binance();
        let market = Market {
            id: "BTC-250328-100000-C".to_string(),
            symbol: "BTC/USDT:USDT-250328-100000-C".to_string(),
            market_type: MarketType::Option,
            ..Default::default()
        };

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        assert!(url.contains("eapi.binance.com"));
    }

    #[test]
    fn test_rest_endpoint_option_private() {
        let binance = create_test_binance();
        let market = Market {
            id: "BTC-250328-100000-C".to_string(),
            symbol: "BTC/USDT:USDT-250328-100000-C".to_string(),
            market_type: MarketType::Option,
            ..Default::default()
        };

        let url = binance.rest_endpoint(&market, EndpointType::Private);
        assert!(url.contains("eapi.binance.com"));
    }

    // ==================== WebSocket Endpoint Tests ====================

    #[test]
    fn test_ws_endpoint_spot() {
        let binance = create_test_binance();
        let market = Market::new_spot(
            "BTCUSDT".to_string(),
            "BTC/USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
        );

        let url = binance.ws_endpoint(&market);
        assert!(url.contains("stream.binance.com"));
    }

    #[test]
    fn test_ws_endpoint_linear_swap() {
        let binance = create_test_binance();
        let market = Market::new_swap(
            "BTCUSDT".to_string(),
            "BTC/USDT:USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
            "USDT".to_string(),
            dec!(1.0),
        );

        let url = binance.ws_endpoint(&market);
        assert!(url.contains("fstream.binance.com"));
    }

    #[test]
    fn test_ws_endpoint_inverse_swap() {
        let binance = create_test_binance();
        let mut market = Market::new_swap(
            "BTCUSD_PERP".to_string(),
            "BTC/USD:BTC".to_string(),
            "BTC".to_string(),
            "USD".to_string(),
            "BTC".to_string(),
            dec!(100.0),
        );
        market.linear = Some(false);
        market.inverse = Some(true);

        let url = binance.ws_endpoint(&market);
        assert!(url.contains("dstream.binance.com"));
    }

    #[test]
    fn test_ws_endpoint_option() {
        let binance = create_test_binance();
        let mut market = Market::default();
        market.market_type = MarketType::Option;

        let url = binance.ws_endpoint(&market);
        assert!(url.contains("nbstream.binance.com"));
    }

    // ==================== Default Endpoint Tests ====================

    #[test]
    fn test_default_rest_endpoint_spot() {
        let binance = create_test_binance();

        let url = binance.default_rest_endpoint(EndpointType::Public);
        assert!(url.contains("api.binance.com"));
    }

    #[test]
    fn test_default_ws_endpoint_spot() {
        let binance = create_test_binance();

        let url = binance.default_ws_endpoint();
        assert!(url.contains("stream.binance.com"));
    }

    // ==================== SAPI and PAPI Tests ====================

    #[test]
    fn test_sapi_endpoint() {
        let binance = create_test_binance();

        let url = binance.sapi_endpoint();
        assert!(url.contains("sapi"));
        assert!(url.contains("api.binance.com"));
    }

    #[test]
    fn test_papi_endpoint() {
        let binance = create_test_binance();

        let url = binance.papi_endpoint();
        assert!(url.contains("papi"));
    }

    // ==================== Sandbox Mode Tests ====================

    #[test]
    fn test_sandbox_rest_endpoint_spot() {
        let binance = create_sandbox_binance();
        let market = Market::new_spot(
            "BTCUSDT".to_string(),
            "BTC/USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
        );

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        assert!(url.contains("testnet"));
    }

    #[test]
    fn test_sandbox_ws_endpoint_spot() {
        let binance = create_sandbox_binance();
        let market = Market::new_spot(
            "BTCUSDT".to_string(),
            "BTC/USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
        );

        let url = binance.ws_endpoint(&market);
        assert!(url.contains("testnet"));
    }

    #[test]
    fn test_sandbox_rest_endpoint_linear_swap() {
        let binance = create_sandbox_binance();
        let market = Market::new_swap(
            "BTCUSDT".to_string(),
            "BTC/USDT:USDT".to_string(),
            "BTC".to_string(),
            "USDT".to_string(),
            "USDT".to_string(),
            dec!(1.0),
        );

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        assert!(url.contains("testnet"));
    }

    // ==================== Edge Case Tests ====================

    #[test]
    fn test_swap_defaults_to_linear_when_not_specified() {
        let binance = create_test_binance();
        let market = Market {
            market_type: MarketType::Swap,
            ..Default::default()
        };
        // linear and inverse are None

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        // Should default to linear (fapi)
        assert!(url.contains("fapi.binance.com"));
    }

    #[test]
    fn test_futures_defaults_to_linear_when_not_specified() {
        let binance = create_test_binance();
        let market = Market {
            market_type: MarketType::Futures,
            ..Default::default()
        };
        // linear and inverse are None

        let url = binance.rest_endpoint(&market, EndpointType::Public);
        // Should default to linear (fapi)
        assert!(url.contains("fapi.binance.com"));
    }
}