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
//! Bitget-specific error handling.
//!
//! This module provides error parsing for Bitget API responses,
//! mapping Bitget error codes to ccxt-core Error types.

use ccxt_core::error::Error;
use serde_json::Value;
use std::time::Duration;

/// Bitget error codes and their meanings.
///
/// Reference: https://www.bitget.com/api-doc/common/error-code
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitgetErrorCode {
    /// Invalid API key (40001)
    InvalidApiKey,
    /// Invalid signature (40002)
    InvalidSignature,
    /// Rate limit exceeded (40003)
    RateLimitExceeded,
    /// Invalid request parameters (40004)
    InvalidRequest,
    /// Insufficient funds (40005)
    InsufficientFunds,
    /// Bad symbol / Invalid trading pair (40006)
    BadSymbol,
    /// Order not found (40007)
    OrderNotFound,
    /// Unknown error code
    Unknown(i64),
}

impl BitgetErrorCode {
    /// Parses a Bitget error code string into a BitgetErrorCode.
    pub fn from_code(code: &str) -> Self {
        match code.parse::<i64>() {
            Ok(40001) => BitgetErrorCode::InvalidApiKey,
            Ok(40002) => BitgetErrorCode::InvalidSignature,
            Ok(40003) => BitgetErrorCode::RateLimitExceeded,
            Ok(40004) => BitgetErrorCode::InvalidRequest,
            Ok(40005) => BitgetErrorCode::InsufficientFunds,
            Ok(40006) => BitgetErrorCode::BadSymbol,
            Ok(40007) => BitgetErrorCode::OrderNotFound,
            Ok(n) => BitgetErrorCode::Unknown(n),
            Err(_) => BitgetErrorCode::Unknown(0),
        }
    }

    /// Returns the numeric code for this error.
    pub fn code(&self) -> i64 {
        match self {
            BitgetErrorCode::InvalidApiKey => 40001,
            BitgetErrorCode::InvalidSignature => 40002,
            BitgetErrorCode::RateLimitExceeded => 40003,
            BitgetErrorCode::InvalidRequest => 40004,
            BitgetErrorCode::InsufficientFunds => 40005,
            BitgetErrorCode::BadSymbol => 40006,
            BitgetErrorCode::OrderNotFound => 40007,
            BitgetErrorCode::Unknown(n) => *n,
        }
    }
}

/// Parses a Bitget API error response and converts it to a ccxt-core Error.
///
/// Bitget API responses follow this format:
/// ```json
/// {
///     "code": "40001",
///     "msg": "Invalid API key",
///     "data": null
/// }
/// ```
///
/// # Arguments
///
/// * `response` - The JSON response from Bitget API
///
/// # Returns
///
/// A ccxt-core Error mapped from the Bitget error code.
///
/// # Example
///
/// ```rust
/// use ccxt_exchanges::bitget::error::parse_error;
/// use serde_json::json;
///
/// let response = json!({
///     "code": "40001",
///     "msg": "Invalid API key"
/// });
///
/// let error = parse_error(&response);
/// assert!(error.as_authentication().is_some());
/// ```
pub fn parse_error(response: &Value) -> Error {
    let code = response
        .get("code")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("unknown");

    let msg = response
        .get("msg")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("Unknown error");

    let error_code = BitgetErrorCode::from_code(code);

    match error_code {
        BitgetErrorCode::InvalidApiKey | BitgetErrorCode::InvalidSignature => {
            Error::authentication(msg.to_string())
        }
        BitgetErrorCode::RateLimitExceeded => {
            // Bitget typically suggests waiting 1 second on rate limit
            Error::rate_limit(msg.to_string(), Some(Duration::from_secs(1)))
        }
        BitgetErrorCode::InvalidRequest => Error::invalid_request(msg.to_string()),
        BitgetErrorCode::InsufficientFunds => Error::insufficient_balance(msg.to_string()),
        BitgetErrorCode::BadSymbol => Error::bad_symbol(msg.to_string()),
        BitgetErrorCode::OrderNotFound | BitgetErrorCode::Unknown(_) => Error::exchange(code, msg),
    }
}

/// Checks if a Bitget API response indicates an error.
///
/// Bitget uses "00000" as the success code. Any other code indicates an error.
///
/// # Arguments
///
/// * `response` - The JSON response from Bitget API
///
/// # Returns
///
/// `true` if the response indicates an error, `false` otherwise.
pub fn is_error_response(response: &Value) -> bool {
    response.get("code").and_then(serde_json::Value::as_str) != Some("00000")
}

/// Extracts the error code from a Bitget API response.
///
/// # Arguments
///
/// * `response` - The JSON response from Bitget API
///
/// # Returns
///
/// The error code as a string, or "unknown" if not found.
pub fn extract_error_code(response: &Value) -> &str {
    response
        .get("code")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("unknown")
}

/// Extracts the error message from a Bitget API response.
///
/// # Arguments
///
/// * `response` - The JSON response from Bitget API
///
/// # Returns
///
/// The error message as a string, or "Unknown error" if not found.
pub fn extract_error_message(response: &Value) -> &str {
    response
        .get("msg")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("Unknown error")
}

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

    #[test]
    fn test_parse_authentication_error_invalid_api_key() {
        let response = json!({
            "code": "40001",
            "msg": "Invalid API key"
        });

        let error = parse_error(&response);
        assert!(error.as_authentication().is_some());
        assert!(error.to_string().contains("Invalid API key"));
    }

    #[test]
    fn test_parse_authentication_error_invalid_signature() {
        let response = json!({
            "code": "40002",
            "msg": "Invalid signature"
        });

        let error = parse_error(&response);
        assert!(error.as_authentication().is_some());
        assert!(error.to_string().contains("Invalid signature"));
    }

    #[test]
    fn test_parse_rate_limit_error() {
        let response = json!({
            "code": "40003",
            "msg": "Rate limit exceeded"
        });

        let error = parse_error(&response);
        assert!(error.as_rate_limit().is_some());
        let (msg, retry_after) = error.as_rate_limit().unwrap();
        assert!(msg.contains("Rate limit"));
        assert!(retry_after.is_some());
    }

    #[test]
    fn test_parse_invalid_request_error() {
        let response = json!({
            "code": "40004",
            "msg": "Invalid request parameters"
        });

        let error = parse_error(&response);
        let display = error.to_string();
        assert!(display.contains("Invalid request"));
    }

    #[test]
    fn test_parse_insufficient_funds_error() {
        let response = json!({
            "code": "40005",
            "msg": "Insufficient balance"
        });

        let error = parse_error(&response);
        let display = error.to_string();
        assert!(display.contains("Insufficient balance"));
    }

    #[test]
    fn test_parse_bad_symbol_error() {
        let response = json!({
            "code": "40006",
            "msg": "Invalid trading pair"
        });

        let error = parse_error(&response);
        let display = error.to_string();
        assert!(display.contains("Bad symbol"));
    }

    #[test]
    fn test_parse_order_not_found_error() {
        let response = json!({
            "code": "40007",
            "msg": "Order not found"
        });

        let error = parse_error(&response);
        let display = error.to_string();
        assert!(display.contains("Order not found"));
    }

    #[test]
    fn test_parse_unknown_error() {
        let response = json!({
            "code": "99999",
            "msg": "Some unknown error"
        });

        let error = parse_error(&response);
        let display = error.to_string();
        assert!(display.contains("Some unknown error"));
    }

    #[test]
    fn test_parse_error_missing_code() {
        let response = json!({
            "msg": "Error without code"
        });

        let error = parse_error(&response);
        // Should default to exchange error with "unknown" code
        let display = error.to_string();
        assert!(display.contains("Error without code"));
    }

    #[test]
    fn test_parse_error_missing_message() {
        let response = json!({
            "code": "40001"
        });

        let error = parse_error(&response);
        // Should default to "Unknown error" message
        let display = error.to_string();
        assert!(display.contains("Unknown error"));
    }

    #[test]
    fn test_is_error_response_success() {
        let response = json!({
            "code": "00000",
            "msg": "success",
            "data": {}
        });

        assert!(!is_error_response(&response));
    }

    #[test]
    fn test_is_error_response_error() {
        let response = json!({
            "code": "40001",
            "msg": "Invalid API key"
        });

        assert!(is_error_response(&response));
    }

    #[test]
    fn test_is_error_response_missing_code() {
        let response = json!({
            "msg": "No code field"
        });

        // Missing code should be treated as error
        assert!(is_error_response(&response));
    }

    #[test]
    fn test_extract_error_code() {
        let response = json!({
            "code": "40001",
            "msg": "Invalid API key"
        });

        assert_eq!(extract_error_code(&response), "40001");
    }

    #[test]
    fn test_extract_error_code_missing() {
        let response = json!({
            "msg": "No code"
        });

        assert_eq!(extract_error_code(&response), "unknown");
    }

    #[test]
    fn test_extract_error_message() {
        let response = json!({
            "code": "40001",
            "msg": "Invalid API key"
        });

        assert_eq!(extract_error_message(&response), "Invalid API key");
    }

    #[test]
    fn test_extract_error_message_missing() {
        let response = json!({
            "code": "40001"
        });

        assert_eq!(extract_error_message(&response), "Unknown error");
    }

    #[test]
    fn test_bitget_error_code_from_code() {
        assert_eq!(
            BitgetErrorCode::from_code("40001"),
            BitgetErrorCode::InvalidApiKey
        );
        assert_eq!(
            BitgetErrorCode::from_code("40002"),
            BitgetErrorCode::InvalidSignature
        );
        assert_eq!(
            BitgetErrorCode::from_code("40003"),
            BitgetErrorCode::RateLimitExceeded
        );
        assert_eq!(
            BitgetErrorCode::from_code("40004"),
            BitgetErrorCode::InvalidRequest
        );
        assert_eq!(
            BitgetErrorCode::from_code("40005"),
            BitgetErrorCode::InsufficientFunds
        );
        assert_eq!(
            BitgetErrorCode::from_code("40006"),
            BitgetErrorCode::BadSymbol
        );
        assert_eq!(
            BitgetErrorCode::from_code("40007"),
            BitgetErrorCode::OrderNotFound
        );
        assert_eq!(
            BitgetErrorCode::from_code("99999"),
            BitgetErrorCode::Unknown(99999)
        );
        assert_eq!(
            BitgetErrorCode::from_code("invalid"),
            BitgetErrorCode::Unknown(0)
        );
    }

    #[test]
    fn test_bitget_error_code_code() {
        assert_eq!(BitgetErrorCode::InvalidApiKey.code(), 40001);
        assert_eq!(BitgetErrorCode::InvalidSignature.code(), 40002);
        assert_eq!(BitgetErrorCode::RateLimitExceeded.code(), 40003);
        assert_eq!(BitgetErrorCode::InvalidRequest.code(), 40004);
        assert_eq!(BitgetErrorCode::InsufficientFunds.code(), 40005);
        assert_eq!(BitgetErrorCode::BadSymbol.code(), 40006);
        assert_eq!(BitgetErrorCode::OrderNotFound.code(), 40007);
        assert_eq!(BitgetErrorCode::Unknown(12345).code(), 12345);
    }
}