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
//! Binance exchange builder pattern implementation.
//!
//! Provides a fluent API for constructing Binance exchange instances with
//! type-safe configuration options.

use super::{Binance, BinanceOptions};
use ccxt_core::config::{ProxyConfig, RetryPolicy};
use ccxt_core::types::default_type::{DefaultSubType, DefaultType};
use ccxt_core::{ExchangeConfig, Result};
use serde_json::Value;
use std::collections::HashMap;
use std::time::Duration;

/// Builder for creating Binance exchange instances.
///
/// Provides a fluent API for configuring all aspects of the Binance exchange,
/// including authentication, connection settings, and Binance-specific options.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::binance::BinanceBuilder;
///
/// let binance = BinanceBuilder::new()
///     .api_key("your-api-key")
///     .secret("your-secret")
///     .sandbox(true)
///     .timeout(30)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct BinanceBuilder {
    /// Exchange configuration
    config: ExchangeConfig,
    /// Binance-specific options
    options: BinanceOptions,
}

impl Default for BinanceBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl BinanceBuilder {
    /// Creates a new builder with default configuration.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            config: ExchangeConfig {
                id: "binance".to_string(),
                name: "Binance".to_string(),
                ..Default::default()
            },
            options: BinanceOptions::default(),
        }
    }

    /// Sets the API key for authentication.
    ///
    /// # Arguments
    ///
    /// * `key` - The API key string.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .api_key("your-api-key");
    /// ```
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.config.api_key = Some(ccxt_core::SecretString::new(key));
        self
    }

    /// Sets the API secret for authentication.
    ///
    /// # Arguments
    ///
    /// * `secret` - The API secret string.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .secret("your-secret");
    /// ```
    pub fn secret(mut self, secret: impl Into<String>) -> Self {
        self.config.secret = Some(ccxt_core::SecretString::new(secret));
        self
    }

    /// Enables or disables sandbox/testnet mode.
    ///
    /// When enabled, the exchange will connect to Binance's testnet
    /// instead of the production environment.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable sandbox mode.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .sandbox(true);
    /// ```
    pub fn sandbox(mut self, enabled: bool) -> Self {
        self.config.sandbox = enabled;
        self.options.test = enabled;
        self
    }

    /// Sets the request timeout.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout duration.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    /// use std::time::Duration;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .timeout(Duration::from_secs(60));
    /// ```
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout = timeout;
        self
    }

    /// Sets the request timeout in seconds (convenience method).
    ///
    /// # Arguments
    ///
    /// * `seconds` - Timeout duration in seconds.
    pub fn timeout_secs(mut self, seconds: u64) -> Self {
        self.config.timeout = Duration::from_secs(seconds);
        self
    }

    /// Sets the TCP connection timeout.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Connection timeout duration.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    /// use std::time::Duration;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .connect_timeout(Duration::from_secs(15));
    /// ```
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.config.connect_timeout = timeout;
        self
    }

    /// Sets the TCP connection timeout in seconds (convenience method).
    ///
    /// # Arguments
    ///
    /// * `seconds` - Connection timeout duration in seconds.
    pub fn connect_timeout_secs(mut self, seconds: u64) -> Self {
        self.config.connect_timeout = Duration::from_secs(seconds);
        self
    }

    /// Sets the retry policy.
    pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.config.retry_policy = Some(policy);
        self
    }

    /// Sets the receive window for signed requests.
    ///
    /// The receive window specifies how long a request is valid after
    /// the timestamp. Default is 5000 milliseconds.
    ///
    /// # Arguments
    ///
    /// * `millis` - Receive window in milliseconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .recv_window(10000);
    /// ```
    pub fn recv_window(mut self, millis: u64) -> Self {
        self.options.recv_window = millis;
        self
    }

    /// Sets the default trading type.
    ///
    /// Accepts both `DefaultType` enum values and string values for backward compatibility.
    /// Valid string values: "spot", "margin", "swap", "futures", "option".
    /// Legacy values "future" and "delivery" are also supported.
    ///
    /// # Arguments
    ///
    /// * `trading_type` - The default trading type (DefaultType or string).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    /// use ccxt_core::types::default_type::DefaultType;
    ///
    /// // Using DefaultType enum (recommended)
    /// let builder = BinanceBuilder::new()
    ///     .default_type(DefaultType::Swap);
    ///
    /// // Using string (backward compatible)
    /// let builder = BinanceBuilder::new()
    ///     .default_type("swap");
    /// ```
    pub fn default_type(mut self, trading_type: impl Into<DefaultType>) -> Self {
        self.options.default_type = trading_type.into();
        self
    }

    /// Sets the default sub-type for contract settlement.
    ///
    /// - `Linear`: USDT-margined contracts (FAPI)
    /// - `Inverse`: Coin-margined contracts (DAPI)
    ///
    /// Only applicable when `default_type` is `Swap`, `Futures`, or `Option`.
    ///
    /// # Arguments
    ///
    /// * `sub_type` - The default sub-type for contract settlement.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    /// use ccxt_core::types::default_type::{DefaultType, DefaultSubType};
    ///
    /// let builder = BinanceBuilder::new()
    ///     .default_type(DefaultType::Swap)
    ///     .default_sub_type(DefaultSubType::Linear);
    /// ```
    pub fn default_sub_type(mut self, sub_type: DefaultSubType) -> Self {
        self.options.default_sub_type = Some(sub_type);
        self
    }

    /// Enables or disables time synchronization adjustment.
    ///
    /// When enabled, the exchange will adjust for time differences
    /// between the local system and Binance servers.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable time adjustment.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .adjust_for_time_difference(true);
    /// ```
    pub fn adjust_for_time_difference(mut self, enabled: bool) -> Self {
        self.options.adjust_for_time_difference = enabled;
        self
    }

    /// Sets the time sync interval in seconds.
    ///
    /// Controls how often the time offset is refreshed when auto sync is enabled.
    /// Default is 30 seconds.
    ///
    /// # Arguments
    ///
    /// * `seconds` - Sync interval in seconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .time_sync_interval(60); // Sync every 60 seconds
    /// ```
    pub fn time_sync_interval(mut self, seconds: u64) -> Self {
        self.options.time_sync_interval_secs = seconds;
        self
    }

    /// Enables or disables automatic periodic time sync.
    ///
    /// When enabled, the time offset will be automatically refreshed
    /// based on the configured sync interval.
    /// Default is true.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable automatic time sync.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// // Disable automatic sync for manual control
    /// let builder = BinanceBuilder::new()
    ///     .auto_time_sync(false);
    /// ```
    pub fn auto_time_sync(mut self, enabled: bool) -> Self {
        self.options.auto_time_sync = enabled;
        self
    }

    /// Enables or disables rate limiting.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable rate limiting.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .enable_rate_limit(true);
    /// ```
    pub fn enable_rate_limit(mut self, enabled: bool) -> Self {
        self.config.enable_rate_limit = enabled;
        self
    }

    /// Sets the HTTP proxy configuration.
    ///
    /// # Arguments
    ///
    /// * `proxy` - The proxy configuration.
    pub fn proxy(mut self, proxy: ProxyConfig) -> Self {
        self.config.proxy = Some(proxy);
        self
    }

    /// Sets the HTTP proxy URL (convenience method).
    ///
    /// # Arguments
    ///
    /// * `url` - The proxy server URL.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .proxy_url("http://proxy.example.com:8080");
    /// ```
    pub fn proxy_url(mut self, url: impl Into<String>) -> Self {
        self.config.proxy = Some(ProxyConfig::new(url));
        self
    }

    /// Enables or disables verbose logging.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable verbose logging.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .verbose(true);
    /// ```
    pub fn verbose(mut self, enabled: bool) -> Self {
        self.config.verbose = enabled;
        self
    }

    /// Sets a custom option.
    ///
    /// # Arguments
    ///
    /// * `key` - Option key.
    /// * `value` - Option value as JSON.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    /// use serde_json::json;
    ///
    /// let builder = BinanceBuilder::new()
    ///     .option("customOption", json!("value"));
    /// ```
    pub fn option(mut self, key: impl Into<String>, value: Value) -> Self {
        self.config.options.insert(key.into(), value);
        self
    }

    /// Sets multiple custom options.
    ///
    /// # Arguments
    ///
    /// * `options` - HashMap of option key-value pairs.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut options = HashMap::new();
    /// options.insert("option1".to_string(), json!("value1"));
    /// options.insert("option2".to_string(), json!(42));
    ///
    /// let builder = BinanceBuilder::new()
    ///     .options(options);
    /// ```
    pub fn options(mut self, options: HashMap<String, Value>) -> Self {
        self.config.options.extend(options);
        self
    }

    /// Builds the Binance exchange instance.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the configured `Binance` instance.
    ///
    /// # Errors
    ///
    /// Returns an error if the exchange cannot be initialized.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ccxt_exchanges::binance::BinanceBuilder;
    ///
    /// let binance = BinanceBuilder::new()
    ///     .api_key("your-api-key")
    ///     .secret("your-secret")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn build(self) -> Result<Binance> {
        Binance::new_with_options(self.config, self.options)
    }
}

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

    #[test]
    fn test_builder_default() {
        let builder = BinanceBuilder::new();
        assert_eq!(builder.config.id, "binance");
        assert_eq!(builder.config.name, "Binance");
        assert!(!builder.config.sandbox);
        assert_eq!(builder.options.default_type, DefaultType::Spot);
    }

    #[test]
    fn test_builder_api_key() {
        let builder = BinanceBuilder::new().api_key("test-key");
        assert_eq!(
            builder
                .config
                .api_key
                .as_ref()
                .map(ccxt_core::SecretString::expose_secret),
            Some("test-key")
        );
    }

    #[test]
    fn test_builder_secret() {
        let builder = BinanceBuilder::new().secret("test-secret");
        assert_eq!(
            builder
                .config
                .secret
                .as_ref()
                .map(ccxt_core::SecretString::expose_secret),
            Some("test-secret")
        );
    }

    #[test]
    fn test_builder_sandbox() {
        let builder = BinanceBuilder::new().sandbox(true);
        assert!(builder.config.sandbox);
        assert!(builder.options.test);
    }

    #[test]
    fn test_builder_timeout() {
        let builder = BinanceBuilder::new().timeout(Duration::from_secs(60));
        assert_eq!(builder.config.timeout, Duration::from_secs(60));
    }

    #[test]
    fn test_builder_connect_timeout() {
        let builder = BinanceBuilder::new().connect_timeout(Duration::from_secs(15));
        assert_eq!(builder.config.connect_timeout, Duration::from_secs(15));
    }

    #[test]
    fn test_builder_connect_timeout_secs() {
        let builder = BinanceBuilder::new().connect_timeout_secs(20);
        assert_eq!(builder.config.connect_timeout, Duration::from_secs(20));
    }

    #[test]
    fn test_builder_recv_window() {
        let builder = BinanceBuilder::new().recv_window(10000);
        assert_eq!(builder.options.recv_window, 10000);
    }

    #[test]
    fn test_builder_default_type_with_enum() {
        let builder = BinanceBuilder::new().default_type(DefaultType::Swap);
        assert_eq!(builder.options.default_type, DefaultType::Swap);
    }

    #[test]
    fn test_builder_default_type_with_string() {
        // Test backward compatibility with string values
        let builder = BinanceBuilder::new().default_type("swap");
        assert_eq!(builder.options.default_type, DefaultType::Swap);
    }

    #[test]
    fn test_builder_default_type_legacy_future() {
        // Test backward compatibility with legacy "future" value
        let builder = BinanceBuilder::new().default_type("future");
        assert_eq!(builder.options.default_type, DefaultType::Swap);
    }

    #[test]
    fn test_builder_default_sub_type() {
        let builder = BinanceBuilder::new()
            .default_type(DefaultType::Swap)
            .default_sub_type(DefaultSubType::Linear);
        assert_eq!(builder.options.default_type, DefaultType::Swap);
        assert_eq!(
            builder.options.default_sub_type,
            Some(DefaultSubType::Linear)
        );
    }

    #[test]
    fn test_builder_chaining() {
        let builder = BinanceBuilder::new()
            .api_key("key")
            .secret("secret")
            .sandbox(true)
            .timeout(Duration::from_secs(30))
            .recv_window(5000)
            .default_type(DefaultType::Spot);

        assert_eq!(
            builder
                .config
                .api_key
                .as_ref()
                .map(ccxt_core::SecretString::expose_secret),
            Some("key")
        );
        assert_eq!(
            builder
                .config
                .secret
                .as_ref()
                .map(ccxt_core::SecretString::expose_secret),
            Some("secret")
        );
        assert!(builder.config.sandbox);
        assert_eq!(builder.config.timeout, Duration::from_secs(30));
        assert_eq!(builder.options.recv_window, 5000);
        assert_eq!(builder.options.default_type, DefaultType::Spot);
    }

    #[test]
    fn test_builder_build() {
        let result = BinanceBuilder::new().build();
        assert!(result.is_ok());

        let binance = result.expect("Failed to build Binance");
        assert_eq!(binance.id(), "binance");
        assert_eq!(binance.name(), "Binance");
    }

    #[test]
    fn test_builder_build_with_credentials() {
        let result = BinanceBuilder::new()
            .api_key("test-key")
            .secret("test-secret")
            .build();

        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_time_sync_interval() {
        let builder = BinanceBuilder::new().time_sync_interval(60);
        assert_eq!(builder.options.time_sync_interval_secs, 60);
    }

    #[test]
    fn test_builder_auto_time_sync() {
        let builder = BinanceBuilder::new().auto_time_sync(false);
        assert!(!builder.options.auto_time_sync);
    }

    #[test]
    fn test_builder_time_sync_chaining() {
        let builder = BinanceBuilder::new()
            .time_sync_interval(120)
            .auto_time_sync(false);

        assert_eq!(builder.options.time_sync_interval_secs, 120);
        assert!(!builder.options.auto_time_sync);
    }

    #[test]
    fn test_builder_build_with_time_sync_config() {
        let result = BinanceBuilder::new()
            .time_sync_interval(60)
            .auto_time_sync(true)
            .build();

        assert!(result.is_ok());
        let binance = result.expect("Failed to build Binance");

        // Verify the TimeSyncManager was created with correct config
        let time_sync = binance.time_sync();
        assert_eq!(
            time_sync.config().sync_interval,
            std::time::Duration::from_secs(60)
        );
        assert!(time_sync.config().auto_sync);
    }

    #[test]
    fn test_builder_build_time_sync_disabled() {
        let result = BinanceBuilder::new().auto_time_sync(false).build();

        assert!(result.is_ok());
        let binance = result.expect("Failed to build Binance");

        // Verify auto_sync is disabled
        let time_sync = binance.time_sync();
        assert!(!time_sync.config().auto_sync);
    }
}