rustrade-data 0.1.0

High performance & normalised WebSocket intergration for leading cryptocurrency exchanges - batteries included.
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
//! IBKR Market Data & Historical Data Integration Tests
//!
//! These tests require IB Gateway or TWS running on localhost:4002 (paper account).
//!
//! # Prerequisites
//!
//! 1. IB Gateway or TWS running with API enabled
//! 2. Market data subscriptions for test instruments (AAPL)
//! 3. Port 4002 (Gateway paper) or 7497 (TWS paper)
//!
//! # Running
//!
//! ```bash
//! # Run all IBKR integration tests
//! cargo test --test ibkr_integration --features ibkr -- --ignored
//!
//! # Run specific test
//! cargo test --test ibkr_integration --features ibkr test_historical_daily_bars -- --ignored
//! ```
//!
//! Tests are marked `#[ignore]` to avoid CI failures without IB connectivity.

#![cfg(feature = "ibkr")]
#![allow(clippy::unwrap_used, clippy::expect_used)] // Integration tests: panics are the correct failure mode

use ibapi::{
    contracts::Contract,
    market_data::historical::{BarSize, WhatToShow},
};
use rustrade_data::{
    event::DataKind,
    exchange::ibkr::{
        IbkrMarketStream, IbkrStreamConfig,
        historical::{HistoricalRequest, IbkrHistoricalData, ToDuration},
        subscription::{IbkrSubscription, IbkrSubscriptionKind},
    },
};
use rustrade_instrument::ibkr::ContractRegistry;
use std::{sync::Arc, time::Duration};
use tokio_stream::StreamExt;
use tracing_subscriber::{EnvFilter, fmt};

fn init_logging() {
    let _ = fmt()
        .with_env_filter(
            EnvFilter::builder()
                .with_default_directive(tracing::Level::DEBUG.into())
                .from_env_lossy(),
        )
        .try_init();
}

fn test_port() -> u16 {
    std::env::var("IBKR_PORT")
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(4002)
}

fn test_client_id_base() -> i32 {
    std::env::var("IBKR_CLIENT_ID")
        .ok()
        .and_then(|id| id.parse().ok())
        .unwrap_or(300)
}

fn aapl_contract() -> Contract {
    Contract::stock("AAPL").build()
}

/// Connect to IB for historical data, wrapping the blocking call in spawn_blocking.
async fn connect_historical(url: &str, client_id: i32) -> Result<IbkrHistoricalData, String> {
    let url = url.to_string();
    tokio::task::spawn_blocking(move || {
        IbkrHistoricalData::connect(&url, client_id).map_err(|e| e.to_string())
    })
    .await
    .map_err(|e| format!("task join: {e}"))?
}

/// Connect raw ibapi client, wrapping the blocking call in spawn_blocking.
async fn connect_raw_client(
    url: &str,
    client_id: i32,
) -> Result<ibapi::client::blocking::Client, String> {
    let url = url.to_string();
    tokio::task::spawn_blocking(move || {
        ibapi::client::blocking::Client::connect(&url, client_id).map_err(|e| e.to_string())
    })
    .await
    .map_err(|e| format!("task join: {e}"))?
}

// ============================================================================
// Historical Data Tests (Task 3.3.5)
// ============================================================================

#[tokio::test]
#[ignore]
async fn test_historical_connection() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base();

    let result = connect_historical(&url, client_id).await;

    assert!(result.is_ok(), "Failed to connect: {:?}", result.err());
    println!("Connected to IB for historical data");
}

#[tokio::test]
#[ignore]
async fn test_historical_daily_bars() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base() + 1;

    let client = connect_historical(&url, client_id)
        .await
        .expect("connection failed");

    let contract = aapl_contract();
    let request = HistoricalRequest::daily_trades(contract, 30);

    println!("Fetching 30 days of AAPL daily bars...");

    let result = client.fetch_candles(request).await;

    assert!(result.is_ok(), "fetch_candles failed: {:?}", result.err());

    let candles = result.unwrap();

    println!("Received {} candles", candles.len());
    assert!(!candles.is_empty(), "Expected at least one candle");

    for candle in candles.iter().take(5) {
        println!(
            "  {} O:{:.2} H:{:.2} L:{:.2} C:{:.2} V:{:.0} T:{}",
            candle.close_time.format("%Y-%m-%d"),
            candle.open,
            candle.high,
            candle.low,
            candle.close,
            candle.volume,
            candle.trade_count
        );
    }

    let first = &candles[0];
    // M-6 fix: Include actual values in assertion messages for debugging
    assert!(
        first.high >= first.low,
        "High {:.4} should be >= Low {:.4}",
        first.high,
        first.low
    );
    assert!(
        first.high >= first.open,
        "High {:.4} should be >= Open {:.4}",
        first.high,
        first.open
    );
    assert!(
        first.high >= first.close,
        "High {:.4} should be >= Close {:.4}",
        first.high,
        first.close
    );
    assert!(
        first.low <= first.open,
        "Low {:.4} should be <= Open {:.4}",
        first.low,
        first.open
    );
    assert!(
        first.low <= first.close,
        "Low {:.4} should be <= Close {:.4}",
        first.low,
        first.close
    );
    assert!(
        first.volume >= 0.0,
        "Volume {:.2} should be non-negative",
        first.volume
    );
}

#[tokio::test]
#[ignore]
async fn test_historical_hourly_bars() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base() + 2;

    let client = connect_historical(&url, client_id)
        .await
        .expect("connection failed");

    let contract = aapl_contract();
    let request = HistoricalRequest {
        contract,
        end_date: None,
        duration: 5.days(),
        bar_size: BarSize::Hour,
        what_to_show: WhatToShow::Trades,
        regular_trading_hours_only: true,
    };

    println!("Fetching 5 days of AAPL hourly bars...");

    let result = client.fetch_candles(request).await;

    assert!(result.is_ok(), "fetch_candles failed: {:?}", result.err());

    let candles = result.unwrap();
    println!("Received {} hourly candles", candles.len());

    assert!(!candles.is_empty(), "Expected at least one hourly candle");

    if candles.len() > 1 {
        let first_time = candles[0].close_time;
        let second_time = candles[1].close_time;
        let diff = second_time - first_time;

        println!(
            "Time between first two bars: {} seconds",
            diff.num_seconds()
        );
        assert!(
            diff.num_seconds() > 0,
            "Candles should be chronologically ordered"
        );
    }
}

#[tokio::test]
#[ignore]
async fn test_historical_minute_bars() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base() + 3;

    let client = connect_historical(&url, client_id)
        .await
        .expect("connection failed");

    let contract = aapl_contract();
    let request = HistoricalRequest {
        contract,
        end_date: None,
        duration: 1.days(),
        bar_size: BarSize::Min,
        what_to_show: WhatToShow::Trades,
        regular_trading_hours_only: true,
    };

    println!("Fetching 1 day of AAPL 1-minute bars...");

    let result = client.fetch_candles(request).await;

    assert!(result.is_ok(), "fetch_candles failed: {:?}", result.err());

    let candles = result.unwrap();
    println!("Received {} minute candles", candles.len());

    assert!(!candles.is_empty(), "Expected at least one 1-minute candle");
}

#[tokio::test]
#[ignore]
async fn test_historical_midpoint_data() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base() + 4;

    let client = connect_historical(&url, client_id)
        .await
        .expect("connection failed");

    let contract = aapl_contract();
    let request = HistoricalRequest {
        contract,
        end_date: None,
        duration: 5.days(),
        bar_size: BarSize::Day,
        what_to_show: WhatToShow::MidPoint,
        regular_trading_hours_only: true,
    };

    println!("Fetching 5 days of AAPL midpoint data...");

    let result = client.fetch_candles(request).await;

    assert!(result.is_ok(), "fetch_candles failed: {:?}", result.err());

    let candles = result.unwrap();
    println!("Received {} midpoint candles", candles.len());

    // Midpoint data may be empty outside market hours or if no recent quotes
    if !candles.is_empty() {
        let first = &candles[0];
        println!(
            "  First midpoint: {} C:{:.2}",
            first.close_time.format("%Y-%m-%d"),
            first.close
        );
        assert_eq!(
            first.trade_count, 0,
            "Midpoint data should have no trade count"
        );
    }
}

#[tokio::test]
#[ignore]
async fn test_historical_from_shared_client() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base() + 5;

    let ib_client = connect_raw_client(&url, client_id)
        .await
        .expect("connection failed");
    let ib_client = Arc::new(ib_client);

    let historical = IbkrHistoricalData::from_client(ib_client);

    let contract = aapl_contract();
    let request = HistoricalRequest::daily_trades(contract, 10);

    let result = historical.fetch_candles(request).await;

    assert!(
        result.is_ok(),
        "fetch_candles from shared client failed: {:?}",
        result.err()
    );

    let candles = result.unwrap();
    assert!(
        !candles.is_empty(),
        "Expected at least one candle from shared client"
    );
    println!("Received {} candles from shared client", candles.len());
}

// ============================================================================
// Market Data Stream Tests (Task 3.2.7)
// ============================================================================

#[tokio::test]
#[ignore]
async fn test_market_stream_connection() {
    init_logging();

    let config = IbkrStreamConfig {
        host: "127.0.0.1".to_string(),
        port: test_port(),
        client_id: test_client_id_base() + 10,
    };

    let registry = ContractRegistry::new();
    registry.register("AAPL".into(), aapl_contract());
    let registry = Arc::new(registry);

    let subscriptions = vec![IbkrSubscription {
        instrument: "AAPL".into(),
        key: "AAPL".to_string(),
        kind: IbkrSubscriptionKind::Quotes,
    }];

    let result = IbkrMarketStream::init(config, registry, subscriptions);

    assert!(
        result.is_ok(),
        "Failed to initialize market stream: {:?}",
        result.err()
    );

    println!("Market stream initialized successfully");
}

#[tokio::test]
#[ignore]
async fn test_market_stream_quotes() {
    init_logging();

    let config = IbkrStreamConfig {
        host: "127.0.0.1".to_string(),
        port: test_port(),
        client_id: test_client_id_base() + 11,
    };

    let registry = ContractRegistry::new();
    registry.register("AAPL".into(), aapl_contract());
    let registry = Arc::new(registry);

    let subscriptions = vec![IbkrSubscription {
        instrument: "AAPL".into(),
        key: "AAPL".to_string(),
        kind: IbkrSubscriptionKind::Quotes,
    }];

    let mut stream =
        IbkrMarketStream::init(config, registry, subscriptions).expect("stream init failed");

    println!("Waiting for quote events (10 second timeout)...");
    println!("Note: No quotes will arrive outside US market hours (9:30 AM - 4:00 PM ET)");

    let timeout_result = tokio::time::timeout(Duration::from_secs(10), async {
        let mut quote_count = 0;
        while let Some(result) = stream.next().await {
            match result {
                Ok(event) => {
                    if let DataKind::OrderBookL1(l1) = &event.kind {
                        let bid_price = l1.best_bid.as_ref().map(|b| b.price);
                        let bid_amount = l1.best_bid.as_ref().map(|b| b.amount);
                        let ask_price = l1.best_ask.as_ref().map(|a| a.price);
                        let ask_amount = l1.best_ask.as_ref().map(|a| a.amount);
                        println!(
                            "Quote: bid={:?} @ {:?}, ask={:?} @ {:?}",
                            bid_price, bid_amount, ask_price, ask_amount
                        );
                        quote_count += 1;
                        if quote_count >= 5 {
                            break;
                        }
                    }
                }
                Err(e) => {
                    println!("Stream error: {:?}", e);
                    break;
                }
            }
        }
        quote_count
    })
    .await;

    match timeout_result {
        Ok(count) => println!("Received {} quotes", count),
        // Timeout is acceptable: quotes only flow during US market hours (9:30-16:00 ET)
        Err(_) => println!("Timeout (normal outside market hours)"),
    }
}

#[tokio::test]
#[ignore]
async fn test_market_stream_depth() {
    init_logging();

    let config = IbkrStreamConfig {
        host: "127.0.0.1".to_string(),
        port: test_port(),
        client_id: test_client_id_base() + 12,
    };

    let registry = ContractRegistry::new();
    registry.register("AAPL".into(), aapl_contract());
    let registry = Arc::new(registry);

    let subscriptions = vec![IbkrSubscription {
        instrument: "AAPL".into(),
        key: "AAPL".to_string(),
        kind: IbkrSubscriptionKind::Depth { rows: 5 },
    }];

    let mut stream =
        IbkrMarketStream::init(config, registry, subscriptions).expect("stream init failed");

    println!("Waiting for depth events (10 second timeout)...");
    println!("Note: Depth may not be available for all instruments or times");

    let timeout_result = tokio::time::timeout(Duration::from_secs(10), async {
        let mut depth_count = 0;
        while let Some(result) = stream.next().await {
            match result {
                Ok(event) => {
                    if let DataKind::OrderBook(book_event) = &event.kind {
                        println!("Depth event: {:?}", book_event);
                        depth_count += 1;
                        if depth_count >= 3 {
                            break;
                        }
                    }
                }
                Err(e) => {
                    println!("Stream error: {:?}", e);
                    break;
                }
            }
        }
        depth_count
    })
    .await;

    match timeout_result {
        Ok(count) => println!("Received {} depth updates", count),
        // Timeout is acceptable: depth only flows during market hours and requires L2 subscription
        Err(_) => println!("Timeout (depth may not be available)"),
    }
}

#[tokio::test]
#[ignore]
async fn test_market_stream_unregistered_contract() {
    init_logging();

    let config = IbkrStreamConfig {
        host: "127.0.0.1".to_string(),
        port: test_port(),
        client_id: test_client_id_base() + 13,
    };

    let registry = Arc::new(ContractRegistry::new());

    let subscriptions = vec![IbkrSubscription {
        instrument: "UNKNOWN_SYMBOL".into(),
        key: "UNKNOWN".to_string(),
        kind: IbkrSubscriptionKind::Quotes,
    }];

    let result = IbkrMarketStream::init(config, registry, subscriptions);

    // M-3: This test validates contract rejection, but connection errors also
    // cause is_err(). The test only confirms contract rejection when connected.
    assert!(result.is_err(), "Expected error for unregistered contract");

    println!(
        "Correctly rejected unregistered contract: {:?}",
        result.err()
    );
}

#[tokio::test]
#[ignore]
async fn test_market_stream_multiple_subscriptions() {
    init_logging();

    let config = IbkrStreamConfig {
        host: "127.0.0.1".to_string(),
        port: test_port(),
        client_id: test_client_id_base() + 14,
    };

    let registry = ContractRegistry::new();
    registry.register("AAPL".into(), aapl_contract());
    registry.register("MSFT".into(), Contract::stock("MSFT").build());
    let registry = Arc::new(registry);

    let subscriptions = vec![
        IbkrSubscription {
            instrument: "AAPL".into(),
            key: "AAPL".to_string(),
            kind: IbkrSubscriptionKind::Quotes,
        },
        IbkrSubscription {
            instrument: "MSFT".into(),
            key: "MSFT".to_string(),
            kind: IbkrSubscriptionKind::Quotes,
        },
    ];

    let result = IbkrMarketStream::init(config, registry, subscriptions);

    assert!(
        result.is_ok(),
        "Failed to initialize multi-subscription stream: {:?}",
        result.err()
    );

    println!("Multi-subscription stream initialized successfully");

    let mut stream = result.unwrap();

    let timeout_result = tokio::time::timeout(Duration::from_secs(10), async {
        let mut aapl_count = 0;
        let mut msft_count = 0;
        while let Some(result) = stream.next().await {
            if let Ok(event) = result {
                match event.instrument.as_str() {
                    "AAPL" => aapl_count += 1,
                    "MSFT" => msft_count += 1,
                    _ => {}
                }
                if aapl_count >= 2 && msft_count >= 2 {
                    break;
                }
            }
        }
        (aapl_count, msft_count)
    })
    .await;

    match timeout_result {
        Ok((aapl, msft)) => println!("Received {} AAPL, {} MSFT events", aapl, msft),
        Err(_) => println!("Timeout (normal outside market hours)"),
    }
}

// ============================================================================
// Contract Registry Integration
// ============================================================================

#[tokio::test]
#[ignore]
async fn test_contract_resolution() {
    init_logging();

    let url = format!("127.0.0.1:{}", test_port());
    let client_id = test_client_id_base() + 20;

    let client = connect_raw_client(&url, client_id)
        .await
        .expect("connection failed");

    let contract = aapl_contract();

    println!("Resolving AAPL contract details...");

    // M-5 fix: Wrap blocking call in spawn_blocking for consistency
    let details = tokio::task::spawn_blocking(move || client.contract_details(&contract))
        .await
        .expect("task join failed");

    assert!(
        details.is_ok(),
        "contract_details failed: {:?}",
        details.err()
    );

    let details = details.unwrap();

    assert!(!details.is_empty(), "Expected at least one contract detail");

    let first = &details[0];
    println!("Contract ID: {}", first.contract.contract_id);
    println!("Symbol: {}", first.contract.symbol);
    println!("Exchange: {}", first.contract.exchange);
    println!("Currency: {}", first.contract.currency);

    let registry = ContractRegistry::new();
    registry.register("AAPL".into(), first.contract.clone());

    assert_eq!(registry.len(), 1);
    assert!(registry.get_contract(&"AAPL".into()).is_some());
    assert!(
        registry
            .get_name_by_con_id(first.contract.contract_id)
            .is_some()
    );
}