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
//! Bitget exchange implementation.
//!
//! Supports spot trading and futures trading (USDT-M and Coin-M) with REST API and WebSocket support.
use ccxt_core::types::default_type::{DefaultSubType, DefaultType};
use ccxt_core::{BaseExchange, ExchangeConfig, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub mod auth;
pub mod builder;
pub mod endpoint_router;
pub mod error;
mod exchange_impl;
mod margin_impl;
pub mod parser;
pub mod rest;
pub mod signed_request;
pub mod symbol;
pub mod ws;
mod ws_exchange_impl;
pub use auth::BitgetAuth;
pub use builder::BitgetBuilder;
pub use endpoint_router::BitgetEndpointRouter;
pub use error::{BitgetErrorCode, is_error_response, parse_error};
pub use parser::{
datetime_to_timestamp, parse_balance, parse_market, parse_ohlcv, parse_order,
parse_order_status, parse_orderbook, parse_ticker, parse_trade, timestamp_to_datetime,
};
/// Bitget exchange structure.
#[derive(Debug)]
pub struct Bitget {
/// Base exchange instance.
base: BaseExchange,
/// Bitget-specific options.
options: BitgetOptions,
}
/// Bitget-specific options.
///
/// # Example
///
/// ```rust
/// use ccxt_exchanges::bitget::BitgetOptions;
/// use ccxt_core::types::default_type::{DefaultType, DefaultSubType};
///
/// let options = BitgetOptions {
/// default_type: DefaultType::Swap,
/// default_sub_type: Some(DefaultSubType::Linear),
/// ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BitgetOptions {
/// Product type: spot, umcbl (USDT-M), dmcbl (Coin-M).
///
/// This is kept for backward compatibility with existing configurations.
/// When using `default_type` and `default_sub_type`, this field is automatically
/// derived from those values.
pub product_type: String,
/// Default trading type (spot/swap/futures/option).
///
/// This determines which product type to use for API calls.
/// Bitget uses product_type-based filtering:
/// - `Spot` -> product_type=spot
/// - `Swap` + Linear -> product_type=umcbl (USDT-M)
/// - `Swap` + Inverse -> product_type=dmcbl (Coin-M)
/// - `Futures` + Linear -> product_type=umcbl (USDT-M futures)
/// - `Futures` + Inverse -> product_type=dmcbl (Coin-M futures)
#[serde(default)]
pub default_type: DefaultType,
/// Default sub-type for contract settlement (linear/inverse).
///
/// - `Linear`: USDT-margined contracts (product_type=umcbl)
/// - `Inverse`: Coin-margined contracts (product_type=dmcbl)
///
/// Only applicable when `default_type` is `Swap` or `Futures`.
/// Ignored for `Spot` type.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_sub_type: Option<DefaultSubType>,
/// Receive window in milliseconds.
pub recv_window: u64,
/// Enables testnet environment.
pub testnet: bool,
}
impl Default for BitgetOptions {
fn default() -> Self {
Self {
product_type: "spot".to_string(),
default_type: DefaultType::default(), // Defaults to Spot
default_sub_type: None,
recv_window: 5000,
testnet: false,
}
}
}
impl BitgetOptions {
/// Returns the effective product_type based on default_type and default_sub_type.
///
/// This method maps the DefaultType and DefaultSubType to Bitget's product_type:
/// - `Spot` -> "spot"
/// - `Swap` + Linear (or None) -> "umcbl" (USDT-M perpetuals)
/// - `Swap` + Inverse -> "dmcbl" (Coin-M perpetuals)
/// - `Futures` + Linear (or None) -> "umcbl" (USDT-M futures)
/// - `Futures` + Inverse -> "dmcbl" (Coin-M futures)
/// - `Margin` -> "spot" (margin uses spot markets)
/// - `Option` -> "spot" (options not fully supported, fallback to spot)
///
/// # Example
///
/// ```rust
/// use ccxt_exchanges::bitget::BitgetOptions;
/// use ccxt_core::types::default_type::{DefaultType, DefaultSubType};
///
/// let mut options = BitgetOptions::default();
/// options.default_type = DefaultType::Swap;
/// options.default_sub_type = Some(DefaultSubType::Linear);
/// assert_eq!(options.effective_product_type(), "umcbl");
///
/// options.default_sub_type = Some(DefaultSubType::Inverse);
/// assert_eq!(options.effective_product_type(), "dmcbl");
/// ```
pub fn effective_product_type(&self) -> &str {
match self.default_type {
DefaultType::Swap | DefaultType::Futures => {
match self.default_sub_type.unwrap_or(DefaultSubType::Linear) {
DefaultSubType::Linear => "umcbl", // USDT-M
DefaultSubType::Inverse => "dmcbl", // Coin-M
}
}
_ => "spot", // Margin, Spot and Option fallback to spot
}
}
}
impl Bitget {
/// Creates a new Bitget instance using the builder pattern.
///
/// This is the recommended way to create a Bitget instance.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::bitget::Bitget;
///
/// let bitget = Bitget::builder()
/// .api_key("your-api-key")
/// .secret("your-secret")
/// .passphrase("your-passphrase")
/// .sandbox(true)
/// .build()
/// .unwrap();
/// ```
pub fn builder() -> BitgetBuilder {
BitgetBuilder::new()
}
/// Creates a new Bitget instance.
///
/// # Arguments
///
/// * `config` - Exchange configuration.
pub fn new(config: ExchangeConfig) -> Result<Self> {
let base = BaseExchange::new(config)?;
let options = BitgetOptions::default();
Ok(Self { base, options })
}
/// Creates a new Bitget instance with custom options.
///
/// This is used internally by the builder pattern.
///
/// # Arguments
///
/// * `config` - Exchange configuration.
/// * `options` - Bitget-specific options.
pub fn new_with_options(config: ExchangeConfig, options: BitgetOptions) -> Result<Self> {
let base = BaseExchange::new(config)?;
Ok(Self { base, options })
}
/// Returns a reference to the base exchange.
pub fn base(&self) -> &BaseExchange {
&self.base
}
/// Returns a mutable reference to the base exchange.
pub fn base_mut(&mut self) -> &mut BaseExchange {
&mut self.base
}
/// Returns the Bitget options.
pub fn options(&self) -> &BitgetOptions {
&self.options
}
/// Sets the Bitget options.
pub fn set_options(&mut self, options: BitgetOptions) {
self.options = options;
}
/// Returns the exchange ID.
pub fn id(&self) -> &'static str {
"bitget"
}
/// Returns the exchange name.
pub fn name(&self) -> &'static str {
"Bitget"
}
/// Returns the API version.
pub fn version(&self) -> &'static str {
"v2"
}
/// Returns `true` if the exchange is CCXT-certified.
pub fn certified(&self) -> bool {
false
}
/// Returns `true` if Pro version (WebSocket) is supported.
pub fn pro(&self) -> bool {
true
}
/// Returns the rate limit in requests per second.
pub fn rate_limit(&self) -> u32 {
20
}
/// Returns `true` if sandbox/testnet mode is enabled.
///
/// Sandbox mode is enabled when either:
/// - `config.sandbox` is set to `true`
/// - `options.testnet` is set to `true`
///
/// # Returns
///
/// `true` if sandbox mode is enabled, `false` otherwise.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::bitget::Bitget;
/// use ccxt_core::ExchangeConfig;
///
/// let config = ExchangeConfig {
/// sandbox: true,
/// ..Default::default()
/// };
/// let bitget = Bitget::new(config).unwrap();
/// assert!(bitget.is_sandbox());
/// ```
pub fn is_sandbox(&self) -> bool {
self.base().config.sandbox || self.options.testnet
}
/// Returns the supported timeframes.
pub fn timeframes(&self) -> HashMap<String, String> {
let mut timeframes = HashMap::new();
timeframes.insert("1m".to_string(), "1m".to_string());
timeframes.insert("5m".to_string(), "5m".to_string());
timeframes.insert("15m".to_string(), "15m".to_string());
timeframes.insert("30m".to_string(), "30m".to_string());
timeframes.insert("1h".to_string(), "1H".to_string());
timeframes.insert("4h".to_string(), "4H".to_string());
timeframes.insert("6h".to_string(), "6H".to_string());
timeframes.insert("12h".to_string(), "12H".to_string());
timeframes.insert("1d".to_string(), "1D".to_string());
timeframes.insert("3d".to_string(), "3D".to_string());
timeframes.insert("1w".to_string(), "1W".to_string());
timeframes.insert("1M".to_string(), "1M".to_string());
timeframes
}
/// Returns the API URLs.
///
/// Returns testnet URLs when sandbox mode is enabled (via `config.sandbox` or `options.testnet`),
/// otherwise returns production URLs.
///
/// # Returns
///
/// - `BitgetUrls::testnet()` when sandbox mode is enabled
/// - `BitgetUrls::production()` when sandbox mode is disabled
pub fn urls(&self) -> BitgetUrls {
if self.base().config.sandbox || self.options.testnet {
BitgetUrls::testnet()
} else {
BitgetUrls::production()
}
}
/// Creates a public WebSocket client.
///
/// # Returns
///
/// Returns a `BitgetWs` instance for public data streams.
///
/// # Example
/// ```no_run
/// use ccxt_exchanges::bitget::Bitget;
/// use ccxt_core::ExchangeConfig;
///
/// # async fn example() -> ccxt_core::error::Result<()> {
/// let bitget = Bitget::new(ExchangeConfig::default())?;
/// let ws = bitget.create_ws();
/// ws.connect().await?;
/// # Ok(())
/// # }
/// ```
pub fn create_ws(&self) -> ws::BitgetWs {
let urls = self.urls();
ws::BitgetWs::new(urls.ws_public)
}
/// Creates a new private WebSocket client for Bitget.
///
/// Returns a `BitgetWs` instance configured with the private WebSocket URL.
/// The caller must call `login()` on the returned client before subscribing
/// to private channels.
pub fn create_private_ws(&self) -> ws::BitgetWs {
let urls = self.urls();
ws::BitgetWs::new(urls.ws_private)
}
/// Creates a signed request builder for authenticated API requests.
///
/// # Arguments
///
/// * `endpoint` - API endpoint path (e.g., "/api/v2/spot/account/assets")
///
/// # Returns
///
/// Returns a `BitgetSignedRequestBuilder` for fluent API construction.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::bitget::Bitget;
/// use ccxt_exchanges::bitget::signed_request::HttpMethod;
/// use ccxt_core::ExchangeConfig;
///
/// # async fn example() -> ccxt_core::Result<()> {
/// let bitget = Bitget::new(ExchangeConfig::default())?;
///
/// let data = bitget.signed_request("/api/v2/spot/account/assets")
/// .execute()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn signed_request(
&self,
endpoint: impl Into<String>,
) -> signed_request::BitgetSignedRequestBuilder<'_> {
signed_request::BitgetSignedRequestBuilder::new(self, endpoint)
}
}
/// Bitget API URLs.
#[derive(Debug, Clone)]
pub struct BitgetUrls {
/// REST API base URL.
pub rest: String,
/// Public WebSocket URL.
pub ws_public: String,
/// Private WebSocket URL.
pub ws_private: String,
}
impl BitgetUrls {
/// Returns production environment URLs.
pub fn production() -> Self {
Self {
rest: "https://api.bitget.com".to_string(),
ws_public: "wss://ws.bitget.com/v2/ws/public".to_string(),
ws_private: "wss://ws.bitget.com/v2/ws/private".to_string(),
}
}
/// Returns testnet environment URLs.
///
/// Testnet uses completely isolated domains for both REST and WebSocket APIs.
/// This is the recommended environment for testing without risking real funds.
///
/// # URLs
///
/// - REST: `https://api-testnet.bitget.com`
/// - WS Public: `wss://ws-testnet.bitget.com/v2/ws/public`
/// - WS Private: `wss://ws-testnet.bitget.com/v2/ws/private`
pub fn testnet() -> Self {
Self {
rest: "https://api-testnet.bitget.com".to_string(),
ws_public: "wss://ws-testnet.bitget.com/v2/ws/public".to_string(),
ws_private: "wss://ws-testnet.bitget.com/v2/ws/private".to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bitget_creation() {
let config = ExchangeConfig {
id: "bitget".to_string(),
name: "Bitget".to_string(),
..Default::default()
};
let bitget = Bitget::new(config);
assert!(bitget.is_ok());
let bitget = bitget.unwrap();
assert_eq!(bitget.id(), "bitget");
assert_eq!(bitget.name(), "Bitget");
assert_eq!(bitget.version(), "v2");
assert!(!bitget.certified());
assert!(bitget.pro());
}
#[test]
fn test_timeframes() {
let config = ExchangeConfig::default();
let bitget = Bitget::new(config).unwrap();
let timeframes = bitget.timeframes();
assert!(timeframes.contains_key("1m"));
assert!(timeframes.contains_key("1h"));
assert!(timeframes.contains_key("1d"));
assert_eq!(timeframes.len(), 12);
}
#[test]
fn test_urls() {
let config = ExchangeConfig::default();
let bitget = Bitget::new(config).unwrap();
let urls = bitget.urls();
assert!(urls.rest.contains("api.bitget.com"));
assert!(urls.ws_public.contains("ws.bitget.com"));
}
#[test]
fn test_sandbox_urls() {
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let bitget = Bitget::new(config).unwrap();
let urls = bitget.urls();
// Sandbox mode should use testnet URLs
assert_eq!(urls.rest, "https://api-testnet.bitget.com");
assert_eq!(urls.ws_public, "wss://ws-testnet.bitget.com/v2/ws/public");
assert_eq!(urls.ws_private, "wss://ws-testnet.bitget.com/v2/ws/private");
}
#[test]
fn test_bitget_urls_testnet() {
let urls = BitgetUrls::testnet();
assert_eq!(urls.rest, "https://api-testnet.bitget.com");
assert_eq!(urls.ws_public, "wss://ws-testnet.bitget.com/v2/ws/public");
assert_eq!(urls.ws_private, "wss://ws-testnet.bitget.com/v2/ws/private");
}
#[test]
fn test_sandbox_urls_with_testnet_option() {
let config = ExchangeConfig::default();
let options = BitgetOptions {
testnet: true,
..Default::default()
};
let bitget = Bitget::new_with_options(config, options).unwrap();
let urls = bitget.urls();
// Testnet option should also use testnet URLs
assert_eq!(urls.rest, "https://api-testnet.bitget.com");
assert_eq!(urls.ws_public, "wss://ws-testnet.bitget.com/v2/ws/public");
assert_eq!(urls.ws_private, "wss://ws-testnet.bitget.com/v2/ws/private");
}
#[test]
fn test_is_sandbox_with_config_sandbox() {
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let bitget = Bitget::new(config).unwrap();
assert!(bitget.is_sandbox());
}
#[test]
fn test_is_sandbox_with_options_testnet() {
let config = ExchangeConfig::default();
let options = BitgetOptions {
testnet: true,
..Default::default()
};
let bitget = Bitget::new_with_options(config, options).unwrap();
assert!(bitget.is_sandbox());
}
#[test]
fn test_is_sandbox_false_by_default() {
let config = ExchangeConfig::default();
let bitget = Bitget::new(config).unwrap();
assert!(!bitget.is_sandbox());
}
#[test]
fn test_default_options() {
let options = BitgetOptions::default();
assert_eq!(options.product_type, "spot");
assert_eq!(options.default_type, DefaultType::Spot);
assert_eq!(options.default_sub_type, None);
assert_eq!(options.recv_window, 5000);
assert!(!options.testnet);
}
#[test]
fn test_effective_product_type_spot() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Spot;
assert_eq!(options.effective_product_type(), "spot");
}
#[test]
fn test_effective_product_type_swap_linear() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Swap;
options.default_sub_type = Some(DefaultSubType::Linear);
assert_eq!(options.effective_product_type(), "umcbl");
}
#[test]
fn test_effective_product_type_swap_inverse() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Swap;
options.default_sub_type = Some(DefaultSubType::Inverse);
assert_eq!(options.effective_product_type(), "dmcbl");
}
#[test]
fn test_effective_product_type_swap_default_sub_type() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Swap;
// No sub_type specified, should default to Linear (umcbl)
assert_eq!(options.effective_product_type(), "umcbl");
}
#[test]
fn test_effective_product_type_futures_linear() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Futures;
options.default_sub_type = Some(DefaultSubType::Linear);
assert_eq!(options.effective_product_type(), "umcbl");
}
#[test]
fn test_effective_product_type_futures_inverse() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Futures;
options.default_sub_type = Some(DefaultSubType::Inverse);
assert_eq!(options.effective_product_type(), "dmcbl");
}
#[test]
fn test_effective_product_type_margin() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Margin;
assert_eq!(options.effective_product_type(), "spot");
}
#[test]
fn test_effective_product_type_option() {
let mut options = BitgetOptions::default();
options.default_type = DefaultType::Option;
assert_eq!(options.effective_product_type(), "spot");
}
}