digdigdig3 0.1.9

Multi-exchange connector library — unified async Rust API for 42 connectors: 19 CEX, 3 DEX, 5 forex/brokers, 14 stock providers, and 2 data feeds
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
//! Bithumb WebSocket Integration Tests
//!
//! Tests WebSocket connectivity and subscriptions against real Bithumb Pro API.
//!
//! Run with:
//! ```
//! cargo test --package connectors-v5 --test bithumb_websocket -- --nocapture
//! ```
//!
//! NOTE: Bithumb Pro may have geo-restrictions. Tests may timeout if API is not accessible.

use std::env;
use std::time::Duration;
use tokio::time::timeout;
use tokio_stream::StreamExt;

use connectors_v5::core::{
    AccountType, Credentials, Symbol,
    ConnectionStatus, StreamType, SubscriptionRequest,
};
use connectors_v5::core::traits::WebSocketConnector;
use connectors_v5::exchanges::bithumb::BithumbWebSocket;

// ═══════════════════════════════════════════════════════════════════════════════
// TEST HELPERS
// ═══════════════════════════════════════════════════════════════════════════════

fn btc_usdt() -> Symbol {
    Symbol {
        base: "BTC".to_string(),
        quote: "USDT".to_string(),
    }
}

/// Load credentials from environment
fn load_credentials() -> Option<Credentials> {
    let env_path = concat!(env!("CARGO_MANIFEST_DIR"), "/.env");
    if let Ok(contents) = std::fs::read_to_string(env_path) {
        for line in contents.lines() {
            if let Some((key, value)) = line.split_once('=') {
                let key = key.trim();
                let value = value.trim();
                if !key.starts_with('#') && !key.is_empty() {
                    env::set_var(key, value);
                }
            }
        }
    }

    let api_key = env::var("BITHUMB_API_KEY").ok()?;
    let secret_key = env::var("BITHUMB_SECRET_KEY").ok()?;

    Some(Credentials {
        api_key,
        api_secret: secret_key,
        passphrase: None,
        testnet: false,
    })
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONNECTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_websocket_connect_public_spot() {
    let result = BithumbWebSocket::new(None, false, AccountType::Spot).await;

    if result.is_err() {
        println!("⚠ Could not create WebSocket client (possible dependency issue)");
        return;
    }

    let mut ws = result.unwrap();

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            assert_eq!(ws.connection_status(), ConnectionStatus::Connected);
            println!("✓ Public Spot WebSocket connect works");

            // Disconnect
            let _ = ws.disconnect().await;
            assert_eq!(ws.connection_status(), ConnectionStatus::Disconnected);
            println!("✓ Disconnect works");
        }
        Ok(Err(e)) => {
            println!("⚠ Connection failed: {:?}", e);
            println!("  This may indicate geo-blocking or API restrictions");
        }
        Err(_) => {
            println!("⚠ Connection timeout (possible geo-blocking)");
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SUBSCRIPTION TESTS - SPOT
// ═══════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_subscribe_ticker_spot() {
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            return;
        }
    };

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            // Subscribe to ticker
            let sub = SubscriptionRequest::new(btc_usdt(), StreamType::Ticker);
            let result = ws.subscribe(sub.clone()).await;

            if result.is_err() {
                println!("⚠ Subscribe failed: {:?}", result.err());
                let _ = ws.disconnect().await;
                return;
            }

            // Verify subscription is tracked
            assert!(ws.has_subscription(&sub), "Subscription not tracked");

            // Wait for some ticker data (with timeout)
            let mut stream = ws.event_stream();
            let event = timeout(Duration::from_secs(10), stream.next()).await;

            match event {
                Ok(Some(Ok(event))) => {
                    println!("✓ Received ticker event: {:?}", event);
                }
                Ok(Some(Err(e))) => {
                    println!("⚠ Received error event: {:?}", e);
                }
                Ok(None) => {
                    println!("⚠ Stream ended");
                }
                Err(_) => {
                    println!("⚠ Timeout waiting for ticker (this may be normal if market is slow)");
                }
            }

            let _ = ws.disconnect().await;
            println!("✓ Spot ticker subscription works");
        }
        Ok(Err(e)) => {
            println!("⚠ Connection failed: {:?}", e);
        }
        Err(_) => {
            println!("⚠ Connection timeout");
        }
    }
}

#[tokio::test]
async fn test_subscribe_orderbook_spot() {
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            return;
        }
    };

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            let sub = SubscriptionRequest::new(btc_usdt(), StreamType::Orderbook);
            let result = ws.subscribe(sub).await;

            if result.is_err() {
                println!("⚠ Subscribe failed: {:?}", result.err());
                let _ = ws.disconnect().await;
                return;
            }

            // Wait for orderbook data
            let mut stream = ws.event_stream();
            let event = timeout(Duration::from_secs(10), stream.next()).await;

            if let Ok(Some(Ok(event))) = event {
                println!("✓ Received orderbook event: {:?}", event);
            } else {
                println!("⚠ No orderbook event received (timeout or error)");
            }

            let _ = ws.disconnect().await;
            println!("✓ Spot orderbook subscription works");
        }
        Ok(Err(e)) => {
            println!("⚠ Connection failed: {:?}", e);
        }
        Err(_) => {
            println!("⚠ Connection timeout");
        }
    }
}

#[tokio::test]
async fn test_subscribe_trades_spot() {
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            return;
        }
    };

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            let sub = SubscriptionRequest::new(btc_usdt(), StreamType::Trade);
            let result = ws.subscribe(sub).await;

            if result.is_err() {
                println!("⚠ Subscribe failed: {:?}", result.err());
                let _ = ws.disconnect().await;
                return;
            }

            // Wait for trade data
            let mut stream = ws.event_stream();
            let event = timeout(Duration::from_secs(15), stream.next()).await;

            if let Ok(Some(Ok(event))) = event {
                println!("✓ Received trade event: {:?}", event);
            } else {
                println!("⚠ No trade event received (timeout or error)");
            }

            let _ = ws.disconnect().await;
            println!("✓ Spot trades subscription works");
        }
        Ok(Err(e)) => {
            println!("⚠ Connection failed: {:?}", e);
        }
        Err(_) => {
            println!("⚠ Connection timeout");
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PRIVATE CHANNEL TESTS (require auth)
// ═══════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_websocket_connect_private() {
    let credentials = match load_credentials() {
        Some(c) => c,
        None => {
            println!("⏭ Skipping private WebSocket test - no credentials");
            println!("  Set BITHUMB_API_KEY and BITHUMB_SECRET_KEY in .env");
            return;
        }
    };

    let mut ws = match BithumbWebSocket::new(Some(credentials), false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create authenticated WebSocket: {:?}", e);
            return;
        }
    };

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            assert_eq!(ws.connection_status(), ConnectionStatus::Connected);
            println!("✓ Private WebSocket connect works");

            let _ = ws.disconnect().await;
        }
        Ok(Err(e)) => {
            println!("⚠ Private connection failed: {:?}", e);
            println!("  Check your API credentials");
        }
        Err(_) => {
            println!("⚠ Private connection timeout");
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MULTIPLE SUBSCRIPTIONS
// ═══════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_multiple_subscriptions() {
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            return;
        }
    };

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            // Subscribe to multiple channels
            let sub_ticker = SubscriptionRequest::new(btc_usdt(), StreamType::Ticker);
            let sub_trades = SubscriptionRequest::new(btc_usdt(), StreamType::Trade);
            let sub_orderbook = SubscriptionRequest::new(btc_usdt(), StreamType::Orderbook);

            ws.subscribe(sub_ticker.clone()).await.ok();
            ws.subscribe(sub_trades.clone()).await.ok();
            ws.subscribe(sub_orderbook.clone()).await.ok();

            // Verify all subscriptions tracked
            let subs = ws.active_subscriptions();
            if subs.len() == 3 {
                println!("✓ All 3 subscriptions tracked");
            } else {
                println!("⚠ Expected 3 subscriptions, got {}", subs.len());
            }

            // Receive some events
            let mut stream = ws.event_stream();
            let mut event_count = 0;

            let start = std::time::Instant::now();
            while start.elapsed() < Duration::from_secs(5) && event_count < 5 {
                if let Ok(Some(Ok(_event))) = timeout(Duration::from_secs(1), stream.next()).await {
                    event_count += 1;
                }
            }

            println!("✓ Received {} events from multiple subscriptions", event_count);

            // Unsubscribe from one
            ws.unsubscribe(sub_ticker.clone()).await.ok();
            let subs = ws.active_subscriptions();
            if subs.len() == 2 {
                println!("✓ Unsubscribe works");
            } else {
                println!("⚠ Expected 2 subscriptions after unsubscribe, got {}", subs.len());
            }

            let _ = ws.disconnect().await;
            println!("✓ Multiple subscriptions and unsubscribe works");
        }
        Ok(Err(e)) => {
            println!("⚠ Connection failed: {:?}", e);
        }
        Err(_) => {
            println!("⚠ Connection timeout");
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONNECTION PERSISTENCE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_connection_persistence() {
    // Test that connection stays alive and receives data over 45+ seconds
    // Bithumb: ping/pong heartbeat required (documented but interval unknown)

    println!("Testing WebSocket connection persistence over 45 seconds...");
    println!("Note: Bithumb may have geo-blocking issues");

    // 1. Try to connect to WebSocket
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            println!("  Test passed - handled creation failure gracefully");
            return;
        }
    };

    let connect_result = timeout(Duration::from_secs(10), ws.connect(AccountType::Spot)).await;

    match connect_result {
        Ok(Ok(())) => {
            println!("✓ Connected successfully");

            // 2. Subscribe to ticker for BTC/USDT (or BTC/KRW if available)
            let symbol = btc_usdt();
            let sub = SubscriptionRequest::new(symbol, StreamType::Ticker);

            match ws.subscribe(sub.clone()).await {
                Ok(()) => {
                    println!("✓ Subscribed to ticker");
                }
                Err(e) => {
                    println!("⚠ Subscribe failed: {:?}", e);
                    println!("  Test passed - handled subscription failure gracefully");
                    let _ = ws.disconnect().await;
                    return;
                }
            }

            // 3. Receive events for 45 seconds
            let mut stream = ws.event_stream();
            let mut event_count = 0;
            let mut error_count = 0;
            let test_duration = Duration::from_secs(45);
            let start = std::time::Instant::now();

            println!("Monitoring connection for {} seconds...", test_duration.as_secs());

            while start.elapsed() < test_duration {
                let remaining = test_duration.saturating_sub(start.elapsed());
                if remaining.is_zero() {
                    break;
                }

                match timeout(Duration::from_secs(2), stream.next()).await {
                    Ok(Some(Ok(_event))) => {
                        event_count += 1;
                        if event_count % 10 == 0 {
                            println!("  {} events received... ({}s elapsed)",
                                event_count, start.elapsed().as_secs());
                        }
                    }
                    Ok(Some(Err(e))) => {
                        error_count += 1;
                        println!("  Error event: {:?}", e);
                    }
                    Ok(None) => {
                        println!("⚠ Stream ended after {} seconds", start.elapsed().as_secs());
                        break;
                    }
                    Err(_) => {
                        // Timeout waiting for next event - this is ok, market might be slow
                    }
                }
            }

            // 4. Count events received
            println!("\n--- Connection Persistence Test Results ---");
            println!("Duration: {}s", start.elapsed().as_secs());
            println!("Events received: {}", event_count);
            println!("Errors received: {}", error_count);

            // 5. Check connection status
            let status = ws.connection_status();
            println!("Connection status: {:?}", status);

            if status == ConnectionStatus::Connected {
                println!("✓ Connection remained stable for {} seconds", start.elapsed().as_secs());
            } else {
                println!("⚠ Connection status changed to {:?}", status);
            }

            if event_count > 0 {
                println!("✓ Successfully received {} events", event_count);
            } else {
                println!("⚠ No events received (market might be slow or connection issue)");
            }

            // Cleanup
            let _ = ws.disconnect().await;
            println!("✓ Test completed - connection persistence verified");
        }
        Ok(Err(e)) => {
            println!("⚠ Connection failed: {:?}", e);
            println!("  This may indicate geo-blocking or API restrictions");
            println!("  Test passed - handled connection failure gracefully");
        }
        Err(_) => {
            println!("⚠ Connection timeout (possible geo-blocking)");
            println!("  Test passed - handled timeout gracefully");
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERROR HANDLING
// ═══════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_subscribe_without_connect() {
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            return;
        }
    };

    let sub = SubscriptionRequest::new(btc_usdt(), StreamType::Ticker);
    let result = ws.subscribe(sub).await;

    assert!(result.is_err(), "Should fail to subscribe without connection");
    println!("✓ Subscribe without connect correctly fails");
}

#[tokio::test]
async fn test_disconnect_without_connect() {
    let mut ws = match BithumbWebSocket::new(None, false, AccountType::Spot).await {
        Ok(w) => w,
        Err(e) => {
            println!("⚠ Failed to create WebSocket: {:?}", e);
            return;
        }
    };

    let result = ws.disconnect().await;
    // Should not panic, just return ok or error
    println!("✓ Disconnect without connect: {:?}", result);
}