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
#![allow(clippy::disallowed_methods)]
//! Stress test suite
//!
//! Tests concurrent performance, connection pool management, and memory leak detection.

use ccxt_core::ExchangeConfig;
use ccxt_exchanges::binance::Binance;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::task::JoinSet;

#[tokio::test]
#[ignore] // Requires network; run with: cargo test --test stress_test --ignored
async fn test_concurrent_ticker_fetches() {
    println!("🚀 Starting concurrent ticker test (100 concurrent requests)...");

    let config = ExchangeConfig::default();
    let exchange = Arc::new(Binance::new(config).unwrap());
    let symbols = vec![
        "BTC/USDT",
        "ETH/USDT",
        "BNB/USDT",
        "XRP/USDT",
        "ADA/USDT",
        "SOL/USDT",
        "DOT/USDT",
        "DOGE/USDT",
        "AVAX/USDT",
        "MATIC/USDT",
    ];

    let start = Instant::now();
    let mut tasks = JoinSet::new();

    // 100 concurrent tasks (10 per symbol)
    for i in 0..100 {
        let exchange_clone = Arc::clone(&exchange);
        let symbol = symbols[i % symbols.len()].to_string();

        tasks.spawn(async move {
            exchange_clone
                .fetch_ticker(&symbol, ccxt_core::types::TickerParams::default())
                .await
        });
    }

    let mut success_count = 0;
    let mut error_count = 0;

    while let Some(result) = tasks.join_next().await {
        match result {
            Ok(Ok(_)) => success_count += 1,
            Ok(Err(e)) => {
                error_count += 1;
                eprintln!("❌ Request failed: {:?}", e);
            }
            Err(e) => {
                error_count += 1;
                eprintln!("❌ Task failed: {:?}", e);
            }
        }
    }

    let duration = start.elapsed();

    println!("✅ Concurrent test completed:");
    println!("   - Total requests: 100");
    println!("   - Success: {}", success_count);
    println!("   - Failed: {}", error_count);
    println!("   - Total time: {:?}", duration);
    println!("   - Avg latency: {:?}", duration / 100);

    assert!(
        success_count >= 80,
        "Success rate too low: {}/100",
        success_count
    );
    assert!(
        duration < Duration::from_secs(5),
        "Avg latency too high: {:?}",
        duration
    );
}

#[tokio::test]
#[ignore]
async fn test_concurrent_orderbook_fetches() {
    println!("🚀 Starting concurrent orderbook test (50 concurrent requests)...");

    let config = ExchangeConfig::default();
    let exchange = Arc::new(Binance::new(config).unwrap());
    let symbols = vec!["BTC/USDT", "ETH/USDT", "BNB/USDT", "XRP/USDT", "ADA/USDT"];

    let start = Instant::now();
    let mut tasks = JoinSet::new();

    for i in 0..50 {
        let exchange_clone = Arc::clone(&exchange);
        let symbol = symbols[i % symbols.len()].to_string();

        tasks.spawn(async move { exchange_clone.fetch_order_book(&symbol, Some(10)).await });
    }

    let mut success_count = 0;
    let mut error_count = 0;

    while let Some(result) = tasks.join_next().await {
        match result {
            Ok(Ok(orderbook)) => {
                success_count += 1;
                assert!(
                    !orderbook.bids.is_empty(),
                    "Orderbook bids should not be empty"
                );
                assert!(
                    !orderbook.asks.is_empty(),
                    "Orderbook asks should not be empty"
                );
            }
            Ok(Err(e)) => {
                error_count += 1;
                eprintln!("❌ Request failed: {:?}", e);
            }
            Err(e) => {
                error_count += 1;
                eprintln!("❌ Task failed: {:?}", e);
            }
        }
    }

    let duration = start.elapsed();

    println!("✅ Concurrent orderbook test completed:");
    println!("   - Total requests: 50");
    println!("   - Success: {}", success_count);
    println!("   - Failed: {}", error_count);
    println!("   - Total time: {:?}", duration);
    println!("   - Avg latency: {:?}", duration / 50);

    assert!(
        success_count >= 40,
        "Success rate too low: {}/50",
        success_count
    );
}

#[tokio::test]
#[ignore]
async fn test_rate_limiter_enforcement() {
    println!("🚀 Testing rate limiter enforcement...");

    let config = ExchangeConfig::default();
    let exchange = Arc::new(Binance::new(config).unwrap());
    let start = Instant::now();

    // Rapidly send 20 consecutive requests
    let mut tasks = JoinSet::new();
    for i in 0..20 {
        let exchange_clone = Arc::clone(&exchange);
        tasks.spawn(async move {
            let request_start = Instant::now();
            let result = exchange_clone
                .fetch_ticker("BTC/USDT", ccxt_core::types::TickerParams::default())
                .await;
            (i, request_start.elapsed(), result.is_ok())
        });
    }

    let mut results = Vec::new();
    while let Some(result) = tasks.join_next().await {
        if let Ok(data) = result {
            results.push(data);
        }
    }

    let total_duration = start.elapsed();

    println!("✅ Rate limiting test completed:");
    println!("   - Total requests: 20");
    println!("   - Total time: {:?}", total_duration);

    // Binance weight limit ~1200/min; 20 requests should complete quickly
    assert!(
        total_duration < Duration::from_secs(10),
        "Rate limiting may be too strict"
    );

    let success_count = results.iter().filter(|(_, _, success)| *success).count();
    println!("   - Success rate: {}/20", success_count);
    assert!(
        success_count >= 18,
        "Success rate too low; rate limit may be triggered"
    );
}

#[tokio::test]
#[ignore]
async fn test_connection_pool() {
    println!("🚀 Testing connection pool management...");

    let config = ExchangeConfig::default();
    let exchange = Arc::new(Binance::new(config).unwrap());

    // First round: establish connections
    println!("   📝 First round (establishing connections)...");
    let start = Instant::now();
    let mut tasks = JoinSet::new();

    for _ in 0..10 {
        let exchange_clone = Arc::clone(&exchange);
        tasks.spawn(async move {
            exchange_clone
                .fetch_ticker("BTC/USDT", ccxt_core::types::TickerParams::default())
                .await
        });
    }

    let mut first_round_count = 0;
    while let Some(result) = tasks.join_next().await {
        if result.is_ok() {
            first_round_count += 1;
        }
    }
    let first_duration = start.elapsed();

    tokio::time::sleep(Duration::from_millis(100)).await;

    // Second round: reuse connections
    println!("   📝 Second round (reusing connections)...");
    let start = Instant::now();
    let mut tasks = JoinSet::new();

    for _ in 0..10 {
        let exchange_clone = Arc::clone(&exchange);
        tasks.spawn(async move {
            exchange_clone
                .fetch_ticker("ETH/USDT", ccxt_core::types::TickerParams::default())
                .await
        });
    }

    let mut second_round_count = 0;
    while let Some(result) = tasks.join_next().await {
        if result.is_ok() {
            second_round_count += 1;
        }
    }
    let second_duration = start.elapsed();

    println!("✅ Connection pool test completed:");
    println!(
        "   - First round: {} success, time {:?}",
        first_round_count, first_duration
    );
    println!(
        "   - Second round: {} success, time {:?}",
        second_round_count, second_duration
    );

    assert!(first_round_count >= 8, "First round success rate too low");
    assert!(second_round_count >= 8, "Second round success rate too low");

    // Second round typically faster (connections established)
    // Note: this may vary due to network conditions
    println!(
        "   - Speed improvement: {:?}",
        first_duration.saturating_sub(second_duration)
    );
}

#[tokio::test]
#[ignore]
async fn test_memory_leak() {
    println!("🚀 Starting memory leak detection (1000 iterations)...");

    let config = ExchangeConfig::default();
    let exchange = Arc::new(Binance::new(config).unwrap());

    // Get initial memory info (if available)
    #[cfg(target_os = "linux")]
    fn get_memory_usage() -> Option<usize> {
        use std::fs;
        let status = fs::read_to_string("/proc/self/status").ok()?;
        for line in status.lines() {
            if line.starts_with("VmRSS:") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                return parts.get(1)?.parse().ok();
            }
        }
        None
    }

    #[cfg(not(target_os = "linux"))]
    fn get_memory_usage() -> Option<usize> {
        None
    }

    let initial_memory = get_memory_usage();
    let start = Instant::now();

    // Execute 1000 requests
    for i in 0..1000 {
        let result = exchange
            .fetch_ticker("BTC/USDT", ccxt_core::types::TickerParams::default())
            .await;

        if result.is_err() && i % 100 == 0 {
            eprintln!("âš ī¸  Iteration {} failed", i);
        }

        // Report progress every 100 iterations
        if i % 100 == 0 && i > 0 {
            let progress = (i as f64 / 1000.0) * 100.0;
            println!("   📊 Progress: {:.1}% ({}/1000)", progress, i);
        }

        // Small delay to avoid excessive request rate
        if i % 10 == 0 {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    let duration = start.elapsed();
    let final_memory = get_memory_usage();

    println!("✅ Memory leak detection completed:");
    println!("   - Iterations: 1000");
    println!("   - Total time: {:?}", duration);
    println!("   - Avg latency: {:?}", duration / 1000);

    if let (Some(initial), Some(final_mem)) = (initial_memory, final_memory) {
        let memory_increase = final_mem.saturating_sub(initial);
        let memory_increase_mb = memory_increase as f64 / 1024.0;
        println!("   - Memory growth: {:.2} MB", memory_increase_mb);

        assert!(
            memory_increase_mb < 50.0,
            "Memory leak detected: excessive growth ({:.2} MB)",
            memory_increase_mb
        );
    } else {
        println!("   â„šī¸  Memory stats not available on current platform");
    }

    assert!(
        duration < Duration::from_secs(120),
        "Execution time too long: {:?}",
        duration
    );
}

#[tokio::test]
#[ignore]
async fn test_mixed_load() {
    println!("🚀 Starting mixed load test...");

    let config = ExchangeConfig::default();
    let exchange = Arc::new(Binance::new(config).unwrap());
    let start = Instant::now();
    let mut tasks = JoinSet::new();

    // 20 ticker requests
    for _ in 0..20 {
        let exchange_clone = Arc::clone(&exchange);
        tasks.spawn(async move {
            exchange_clone
                .fetch_ticker("BTC/USDT", ccxt_core::types::TickerParams::default())
                .await
                .map(|_| "ticker")
        });
    }

    // 10 orderbook requests
    for _ in 0..10 {
        let exchange_clone = Arc::clone(&exchange);
        tasks.spawn(async move {
            exchange_clone
                .fetch_order_book("ETH/USDT", Some(20))
                .await
                .map(|_| "orderbook")
        });
    }

    // 10 trade history requests
    for _ in 0..10 {
        let exchange_clone = Arc::clone(&exchange);
        tasks.spawn(async move {
            exchange_clone
                .fetch_trades("BNB/USDT", None)
                .await
                .map(|_| "trades")
        });
    }

    let mut results = std::collections::HashMap::new();
    results.insert("ticker", 0);
    results.insert("orderbook", 0);
    results.insert("trades", 0);

    while let Some(result) = tasks.join_next().await {
        if let Ok(Ok(op_type)) = result {
            *results.get_mut(op_type).unwrap() += 1;
        }
    }

    let duration = start.elapsed();

    println!("✅ Mixed load test completed:");
    println!("   - Ticker success: {}/20", results["ticker"]);
    println!("   - OrderBook success: {}/10", results["orderbook"]);
    println!("   - Trades success: {}/10", results["trades"]);
    println!("   - Total time: {:?}", duration);

    assert!(results["ticker"] >= 16, "Ticker success rate too low");
    assert!(results["orderbook"] >= 8, "OrderBook success rate too low");
    assert!(results["trades"] >= 8, "Trades success rate too low");
}