rustrade-data 0.20.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
//! Alpaca Market Data Integration Tests
//!
//! These tests verify connectivity and data reception from Alpaca market data streams.
//!
//! # Status
//!
//! **Tested locally, CI planned (paper trading allowed by Alpaca):**
//! - Crypto streaming: trades and quotes (24/7, free)
//! - IEX equity streaming: trades and quotes (market hours, free)
//!
//! **NOT tested (requires Algo Trader Plus subscription):**
//! - SIP equity streaming (`test_sip_*`) — implemented but unverified
//!
//! Tests are marked `#[ignore]` to avoid CI failures without credentials.
//!
//! # Prerequisites
//!
//! 1. Alpaca paper trading account (https://app.alpaca.markets)
//! 2. Environment variables set (see .env.template):
//!    - ALPACA_API_KEY: API key
//!    - ALPACA_SECRET_KEY: Secret key
//!
//! # Running
//!
//! ```bash
//! # Load env vars from .env
//! source .env
//!
//! # Run all Alpaca data integration tests
//! cargo test --test alpaca_data --features alpaca -- --ignored
//!
//! # Run specific test
//! cargo test --test alpaca_data --features alpaca test_crypto_trade_stream -- --ignored
//! ```
//!
//! # Market Hours Note
//!
//! US equity market hours are 9:30 AM - 4:00 PM ET (9:30 PM - 4:00 AM SGT next day).
//! The IEX feed only provides trade data during market hours. Tests that wait for
//! trade events (`test_iex_*_receives_data`) may timeout outside market hours.
//! Connection and subscription tests work anytime.
//!
//! Crypto streams (BTC/USD, etc.) are available 24/7 and are the primary validation.
//!
//! - WebSocket tests are marked `#[serial]` to prevent connection conflicts. Alpaca allows one
//!   data-stream connection per feed and rejects another with "auth failed: connection limit
//!   exceeded". Clones of one `AlpacaSubscriber` share that connection, but each test builds its
//!   own subscriber, so running them in parallel fails every connection but the one that wins the
//!   race.

#![cfg(feature = "alpaca")]
// Test code: unwrap/expect panics are the correct failure mode for test assertions
#![allow(clippy::unwrap_used, clippy::expect_used)]

use futures_util::StreamExt;
use rust_decimal::Decimal;
use rustrade_data::{
    exchange::alpaca::{AlpacaCrypto, AlpacaIex, AlpacaSip, AlpacaSubscriber},
    streams::{
        Streams,
        reconnect::{Event, stream::ReconnectingStream},
    },
    subscription::{quote::Quotes, trade::PublicTrades},
};
use rustrade_instrument::instrument::market_data::kind::MarketDataInstrumentKind;
use serial_test::serial;
use std::{collections::BTreeSet, time::Duration};
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();
}

// ============================================================================
// Crypto Stream Tests (24/7 availability - primary validation)
// ============================================================================

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

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaCrypto::default(),
                "btc",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to connect to crypto trade stream: {:?}",
        streams.err()
    );
    tracing::info!("Crypto trade stream connected and subscribed");
}

/// Every trade the crypto stream delivers inside a bounded window is well formed and routed to the
/// subscribed instrument. Whether a trade arrives at all is not asserted.
///
/// Alpaca's crypto feed carries its own venue's fills, not a consolidated tape, and the delay
/// before the first BTC/USD trade is large and variable: within one half-hour window (2026-09-19)
/// it measured under 60s, ~136s, ~175s, and none at all in ~189s. No deadline separates "not
/// subscribed" from "not yet traded", so requiring a trade made the test fail on market activity.
/// The subscription itself is asserted deterministically by `init()`: the subscriber holds it open
/// until the venue names every requested symbol, as `test_crypto_trade_stream_connection` also
/// relies on.
#[tokio::test]
#[ignore]
#[serial]
async fn test_crypto_trade_stream_validates_delivered_trades() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaCrypto::default(),
                "btc",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await
        .expect("Failed to init crypto stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    // Polled in short slices so the closing summary can tell a quiet stream from an eventful one:
    // a slice with nothing in it counts as a quiet window, a reconnect or other non-item event as a
    // non-trade event. A stream that ends is the only outcome that fails without a trade.
    const WINDOW: Duration = Duration::from_secs(60);
    const SLICE: Duration = Duration::from_secs(10);
    let deadline = tokio::time::Instant::now() + WINDOW;
    let mut trades = 0usize;
    let mut non_trade_events = 0usize;
    let mut quiet_windows = 0usize;

    loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            break;
        }
        match tokio::time::timeout(remaining.min(SLICE), stream.next()).await {
            Err(_) => quiet_windows += 1,
            Ok(None) => panic!(
                "Stream ended inside the window (trades={trades}, non-trade events={non_trade_events}, \
                 quiet windows={quiet_windows})"
            ),
            Ok(Some(Event::Item(trade))) => {
                trades += 1;
                tracing::info!(?trade, "Received crypto trade");
                assert_eq!(
                    trade.instrument.base.as_ref(),
                    "btc",
                    "Trade routed to an instrument that was never subscribed"
                );
                assert!(trade.kind.price > Decimal::ZERO, "Invalid trade price");
                assert!(trade.kind.amount > Decimal::ZERO, "Invalid trade amount");
            }
            Ok(Some(_)) => non_trade_events += 1,
        }
    }

    // Deliberately not asserted: whether BTC/USD traded is market activity. Logged so a run that
    // saw nothing is still legible, and so the first-trade delay can be re-measured.
    tracing::info!(
        trades,
        non_trade_events,
        quiet_windows,
        window = ?WINDOW,
        "crypto trade window closed"
    );
}

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

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaCrypto::default(),
                "btc",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to connect to crypto quote stream: {:?}",
        streams.err()
    );
    tracing::info!("Crypto quote stream connected and subscribed");
}

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

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaCrypto::default(),
                "btc",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await
        .expect("Failed to init crypto quote stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    // Same shape as the trade test above: a quiet window must not end the run early. Quotes tick
    // continuously and independently of trade flow, so 60 seconds is ample here.
    let deadline = tokio::time::Instant::now() + Duration::from_secs(60);
    let mut non_quote_events = 0usize;

    while tokio::time::Instant::now() < deadline {
        match tokio::time::timeout(Duration::from_secs(30), stream.next()).await {
            Err(_) => continue,
            Ok(None) => panic!("Stream ended without data (non-quote events={non_quote_events})"),
            Ok(Some(Event::Item(quote))) => {
                tracing::info!(?quote, "Received crypto quote");
                assert!(quote.kind.bid_price > Decimal::ZERO, "Invalid bid price");
                assert!(quote.kind.ask_price > Decimal::ZERO, "Invalid ask price");
                assert!(
                    quote.kind.ask_price >= quote.kind.bid_price,
                    "Ask < Bid (crossed market)"
                );
                return;
            }
            Ok(Some(_)) => non_quote_events += 1,
        }
    }

    panic!("No crypto quotes received within 60s (non-quote events={non_quote_events})");
}

/// Verifies that two instruments subscribe over a single connection, and that any event which
/// does arrive routes to one of them.
///
/// ### Why this no longer waits for both symbols to tick
///
/// It used to: it required a quote for BTC/USD *and* ETH/USD within 60s, and failed about a
/// quarter of CI runs. The subscription was never at fault. On every failing run Alpaca was sent
/// `{"action":"subscribe","quotes":["BTC/USD","ETH/USD"]}` and confirmed
/// `quotes: ["BTC/USD", "ETH/USD"]`, and no event was dropped, misrouted or failed to
/// deserialise -- the second symbol simply had not ticked yet.
///
/// Alpaca's crypto feed publishes a quote when top-of-book changes, and the delay before a given
/// symbol *first* ticks is both large and highly variable. A single 300s window over four symbols
/// confirmed on one connection measured first-quote delays of 1s (BTC), 15s (LTC), 96s (SOL) and
/// 132s (ETH); ETH then delivered 76 quotes in the remaining 168s. No deadline distinguishes "not
/// subscribed" from "not yet ticked", so waiting on both symbols asserted market activity rather
/// than library behaviour.
///
/// What carries the subscription assertion instead is
/// [`AlpacaSubscriber`]'s subscribe:
/// `init()` now succeeds only once Alpaca has confirmed every requested symbol *by name*, so the
/// `streams.is_ok()` assertion below is the multi-instrument check this test previously
/// approximated by waiting for data -- and it is deterministic.
///
/// The window that follows is a bonus: it cannot require data, but any event it does see must
/// belong to a subscribed instrument, which is what catches misrouting.
#[tokio::test]
#[ignore]
#[serial]
async fn test_crypto_multiple_symbols() {
    init_logging();

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [
                (
                    AlpacaCrypto::default(),
                    "btc",
                    "usd",
                    MarketDataInstrumentKind::Spot,
                    Quotes,
                ),
                (
                    AlpacaCrypto::default(),
                    "eth",
                    "usd",
                    MarketDataInstrumentKind::Spot,
                    Quotes,
                ),
            ],
        )
        .init()
        .await;

    // Alpaca confirms the symbols it holds, and the subscriber holds `init()` open until every
    // requested one is named. Reaching here therefore means both were subscribed -- a partial
    // subscription fails above, reporting which symbol was missing.
    assert!(
        streams.is_ok(),
        "Failed to subscribe to multiple crypto symbols: {:?}",
        streams.err()
    );

    let mut stream = streams
        .unwrap()
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    let subscribed = BTreeSet::from(["btc".to_string(), "eth".to_string()]);
    let mut seen = BTreeSet::<String>::new();
    let mut events = 0usize;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(30);

    while seen.len() < subscribed.len() && tokio::time::Instant::now() < deadline {
        let remaining = deadline - tokio::time::Instant::now();
        match tokio::time::timeout(remaining, stream.next()).await {
            Ok(Some(Event::Item(event))) => {
                events += 1;
                let base = event.instrument.base.as_ref().to_string();
                // A quote can only reach here by matching a SubscriptionId this test registered,
                // so an unknown base means the instrument map routed an event to the wrong
                // instrument -- the one failure a quiet market cannot explain away.
                assert!(
                    subscribed.contains(&base),
                    "Quote routed to an instrument that was never subscribed: \
                     base={base}, subscribed={subscribed:?}"
                );
                seen.insert(base);
            }
            Ok(Some(_)) => {}
            Ok(None) => break,
            Err(_) => break,
        }
    }

    // Deliberately not asserted: which symbols ticked is market activity. Logged so a run that
    // saw nothing is still legible, and so the first-tick delays above can be re-measured.
    tracing::info!(events, ?seen, "crypto multi-symbol quote window closed");
}

/// Trades and quotes from one feed at once, through clones of one subscriber.
///
/// Alpaca allows one connection per feed, and each kind is its own `subscribe`, so this needs the
/// two streams to share a socket: opened on separate sockets, the second `init()` fails with
/// `connection limit exceeded`. Both `init()`s succeeding is therefore the assertion.
///
/// The window that follows cannot require data -- see `test_crypto_multiple_symbols` for how long
/// a crypto symbol can stay quiet -- but any event it does see must be well formed. The shared
/// connection splits frames that mix trades and quotes between the two streams, and a message
/// routed to the wrong one would surface here as an error.
#[tokio::test]
#[ignore]
#[serial]
async fn test_crypto_trades_and_quotes_share_one_connection() {
    init_logging();

    let subscriber = AlpacaSubscriber::from_env().unwrap();

    let trades = Streams::<PublicTrades>::builder()
        .subscribe(
            subscriber.clone(),
            [(
                AlpacaCrypto::default(),
                "btc",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await
        .expect("trades on the crypto feed");

    let quotes = Streams::<Quotes>::builder()
        .subscribe(
            subscriber,
            [(
                AlpacaCrypto::default(),
                "btc",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await
        .expect("quotes on the crypto feed, on the connection the trades already hold");

    let mut trades = trades.select_all();
    let mut quotes = quotes.select_all();

    let (mut trade_events, mut quote_events) = (0usize, 0usize);
    let deadline = tokio::time::sleep(Duration::from_secs(20));
    tokio::pin!(deadline);

    loop {
        tokio::select! {
            () = &mut deadline => break,
            Some(event) = trades.next() => match event {
                Event::Item(Ok(_)) => trade_events += 1,
                Event::Item(Err(error)) => panic!("trade stream error: {error:?}"),
                Event::Reconnecting(exchange) => panic!("trade stream reconnecting: {exchange}"),
            },
            Some(event) = quotes.next() => match event {
                Event::Item(Ok(_)) => quote_events += 1,
                Event::Item(Err(error)) => panic!("quote stream error: {error:?}"),
                Event::Reconnecting(exchange) => panic!("quote stream reconnecting: {exchange}"),
            },
        }
    }

    tracing::info!(
        trade_events,
        quote_events,
        "crypto trades and quotes shared one connection"
    );
}

// ============================================================================
// IEX Equity Stream Tests (market hours only for data reception)
// ============================================================================

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

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaIex::default(),
                "spy",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to connect to IEX trade stream: {:?}",
        streams.err()
    );
    tracing::info!("IEX trade stream connected and subscribed");
}

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

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaIex::default(),
                "aapl",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to connect to IEX quote stream: {:?}",
        streams.err()
    );
    tracing::info!("IEX quote stream connected and subscribed");
}

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

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [
                (
                    AlpacaIex::default(),
                    "spy",
                    "usd",
                    MarketDataInstrumentKind::Spot,
                    PublicTrades,
                ),
                (
                    AlpacaIex::default(),
                    "aapl",
                    "usd",
                    MarketDataInstrumentKind::Spot,
                    PublicTrades,
                ),
            ],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to subscribe to multiple IEX symbols: {:?}",
        streams.err()
    );
    tracing::info!("IEX multi-symbol subscription confirmed");
}

/// Test receiving trade data from IEX.
///
/// NOTE: This test may timeout outside US market hours (9:30 AM - 4:00 PM ET).
/// The IEX feed only provides trade data during market hours.
#[tokio::test]
#[ignore]
async fn test_iex_trade_stream_receives_data() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaIex::default(),
                "spy",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await
        .expect("Failed to init IEX stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    tracing::info!("Waiting for IEX trade data (may timeout outside market hours)...");

    let deadline = tokio::time::Instant::now() + Duration::from_secs(60);

    while tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;

        match timeout {
            Ok(Some(Event::Item(trade))) => {
                tracing::info!(?trade, "Received IEX trade");
                assert!(trade.kind.price > Decimal::ZERO, "Invalid trade price");
                assert!(trade.kind.amount > Decimal::ZERO, "Invalid trade amount");
                return;
            }
            Ok(Some(_)) => continue,
            Ok(None) => panic!("Stream ended unexpectedly"),
            Err(_) => {
                tracing::warn!("Timeout waiting for IEX data - may be outside market hours");
                continue;
            }
        }
    }

    panic!(
        "No IEX trade events received within timeout. \
         If outside US market hours (9:30 AM - 4:00 PM ET), this is expected."
    );
}

/// Test receiving quote data from IEX.
///
/// NOTE: This test may timeout outside US market hours.
#[tokio::test]
#[ignore]
async fn test_iex_quote_stream_receives_data() {
    init_logging();

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaIex::default(),
                "spy",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await
        .expect("Failed to init IEX quote stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    tracing::info!("Waiting for IEX quote data (may timeout outside market hours)...");

    let deadline = tokio::time::Instant::now() + Duration::from_secs(60);

    while tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;

        match timeout {
            Ok(Some(Event::Item(quote))) => {
                tracing::info!(?quote, "Received IEX quote");
                assert!(quote.kind.bid_price > Decimal::ZERO, "Invalid bid price");
                assert!(quote.kind.ask_price > Decimal::ZERO, "Invalid ask price");
                return;
            }
            Ok(Some(_)) => continue,
            Ok(None) => panic!("Stream ended unexpectedly"),
            Err(_) => {
                tracing::warn!("Timeout waiting for IEX quote - may be outside market hours");
                continue;
            }
        }
    }

    panic!(
        "No IEX quote events received within timeout. \
         If outside US market hours (9:30 AM - 4:00 PM ET), this is expected."
    );
}

// ============================================================================
// SIP Equity Stream Tests (requires SIP subscription)
// ============================================================================

/// Test SIP trade stream connection.
///
/// NOTE: Requires SIP subscription. Will fail with auth error without subscription.
#[tokio::test]
#[ignore]
async fn test_sip_trade_stream_connection() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaSip::default(),
                "spy",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to connect to SIP trade stream: {:?}",
        streams.err()
    );
    tracing::info!("SIP trade stream connected and subscribed");
}

/// Test SIP quote stream connection.
///
/// NOTE: Requires SIP subscription.
#[tokio::test]
#[ignore]
async fn test_sip_quote_stream_connection() {
    init_logging();

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaSip::default(),
                "aapl",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to connect to SIP quote stream: {:?}",
        streams.err()
    );
    tracing::info!("SIP quote stream connected and subscribed");
}

/// Test receiving trade data from SIP (consolidated tape).
///
/// NOTE: Requires SIP subscription. May timeout outside US market hours.
#[tokio::test]
#[ignore]
async fn test_sip_trade_stream_receives_data() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaSip::default(),
                "spy",
                "usd",
                MarketDataInstrumentKind::Spot,
                PublicTrades,
            )],
        )
        .init()
        .await
        .expect("Failed to init SIP stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    tracing::info!("Waiting for SIP trade data (consolidated tape)...");

    let deadline = tokio::time::Instant::now() + Duration::from_secs(60);

    while tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;

        match timeout {
            Ok(Some(Event::Item(trade))) => {
                tracing::info!(?trade, "Received SIP trade");
                assert!(trade.kind.price > Decimal::ZERO, "Invalid trade price");
                assert!(trade.kind.amount > Decimal::ZERO, "Invalid trade amount");
                return;
            }
            Ok(Some(_)) => continue,
            Ok(None) => panic!("Stream ended unexpectedly"),
            Err(_) => {
                tracing::warn!("Timeout waiting for SIP data - may be outside market hours");
                continue;
            }
        }
    }

    panic!(
        "No SIP trade events received within timeout. \
         If outside US market hours (9:30 AM - 4:00 PM ET), this is expected."
    );
}

/// Test receiving quote data from SIP (consolidated NBBO).
///
/// NOTE: Requires SIP subscription. May timeout outside US market hours.
#[tokio::test]
#[ignore]
async fn test_sip_quote_stream_receives_data() {
    init_logging();

    let streams = Streams::<Quotes>::builder()
        .subscribe(
            AlpacaSubscriber::from_env().unwrap(),
            [(
                AlpacaSip::default(),
                "spy",
                "usd",
                MarketDataInstrumentKind::Spot,
                Quotes,
            )],
        )
        .init()
        .await
        .expect("Failed to init SIP quote stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    tracing::info!("Waiting for SIP quote data (consolidated NBBO)...");

    let deadline = tokio::time::Instant::now() + Duration::from_secs(60);

    while tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;

        match timeout {
            Ok(Some(Event::Item(quote))) => {
                tracing::info!(?quote, "Received SIP quote (NBBO)");
                assert!(quote.kind.bid_price > Decimal::ZERO, "Invalid bid price");
                assert!(quote.kind.ask_price > Decimal::ZERO, "Invalid ask price");
                return;
            }
            Ok(Some(_)) => continue,
            Ok(None) => panic!("Stream ended unexpectedly"),
            Err(_) => {
                tracing::warn!("Timeout waiting for SIP quote - may be outside market hours");
                continue;
            }
        }
    }

    panic!(
        "No SIP quote events received within timeout. \
         If outside US market hours (9:30 AM - 4:00 PM ET), this is expected."
    );
}

// ============================================================================
// Options Market Data Tests (REST API - available 24/7)
// ============================================================================

use chrono::Utc;
use rustrade_data::exchange::alpaca::options::{
    AlpacaOptionContractQuery, AlpacaOptionFeed, AlpacaOptionsClient,
};

/// Test fetching AAPL option contracts.
///
/// Verifies that we can discover option contracts with various filters.
#[tokio::test]
#[ignore]
async fn test_fetch_aapl_option_contracts() {
    init_logging();

    let client = AlpacaOptionsClient::from_env().expect("Failed to create options client");

    // Query AAPL options expiring in the next 60 days
    let today = Utc::now().date_naive();
    let sixty_days = today + chrono::Duration::days(60);

    let query = AlpacaOptionContractQuery::new(vec!["AAPL".into()])
        .expiration_gte(today)
        .expiration_lte(sixty_days)
        .limit(100);

    let contracts = client
        .fetch_contracts(&query)
        .await
        .expect("Failed to fetch contracts");

    tracing::info!(count = contracts.len(), "Fetched AAPL option contracts");

    assert!(!contracts.is_empty(), "No AAPL options found");

    // Verify contract data quality
    for contract in contracts.iter().take(5) {
        tracing::info!(
            symbol = %contract.symbol,
            expiration = %contract.expiration_date,
            strike = %contract.strike_price,
            option_type = %contract.option_type,
            style = %contract.style,
            "Contract"
        );

        assert!(
            contract.symbol.starts_with("AAPL"),
            "Symbol should start with AAPL"
        );
        assert!(
            contract.expiration_date >= today,
            "Expiration should be >= today"
        );
        assert!(
            contract.expiration_date <= sixty_days,
            "Expiration should be <= 60 days out"
        );
        assert!(
            contract.strike_price > Decimal::ZERO,
            "Strike should be positive"
        );
        assert!(
            contract.option_type == "call" || contract.option_type == "put",
            "Option type should be call or put"
        );
        assert!(
            contract.style == "american" || contract.style == "european",
            "Style should be american or european"
        );
    }
}

/// Test fetching option contracts with call-only filter.
#[tokio::test]
#[ignore]
async fn test_fetch_call_options_only() {
    init_logging();

    let client = AlpacaOptionsClient::from_env().expect("Failed to create options client");

    let today = Utc::now().date_naive();
    let thirty_days = today + chrono::Duration::days(30);

    let query = AlpacaOptionContractQuery::new(vec!["AAPL".into()])
        .expiration_gte(today)
        .expiration_lte(thirty_days)
        .call_only()
        .limit(50);

    let contracts = client
        .fetch_contracts(&query)
        .await
        .expect("Failed to fetch call options");

    tracing::info!(count = contracts.len(), "Fetched AAPL call options");

    assert!(!contracts.is_empty(), "No AAPL call options found");

    // Verify all are calls
    for contract in &contracts {
        assert_eq!(
            contract.option_type, "call",
            "Expected call option, got {}",
            contract.option_type
        );
    }
}

/// Test fetching option chain snapshots with Greeks.
///
/// Uses the indicative (delayed) feed which is free.
#[tokio::test]
#[ignore]
async fn test_fetch_aapl_chain_snapshot_with_greeks() {
    init_logging();

    let client = AlpacaOptionsClient::from_env().expect("Failed to create options client");

    // First get some contracts
    let today = Utc::now().date_naive();
    let thirty_days = today + chrono::Duration::days(30);

    // `limit` is the PAGE SIZE, not a cap on results: `fetch_contracts` pages until the
    // chain is exhausted. A page size of 10 walks the whole 30-day AAPL chain ten contracts
    // at a time and trips the client's 100-page runaway guard with
    // `PaginationLimitExceeded { pages: 101, limit: 100 }`. Use the same page size as
    // `test_fetch_aapl_option_contracts`, which covers a wider window without tripping it.
    let query = AlpacaOptionContractQuery::new(vec!["AAPL".into()])
        .expiration_gte(today)
        .expiration_lte(thirty_days)
        .limit(100);

    let contracts = client
        .fetch_contracts(&query)
        .await
        .expect("Failed to fetch contracts");

    assert!(!contracts.is_empty(), "No contracts to fetch snapshots for");

    // Snapshot only a small slice. The snapshot endpoint takes an explicit symbol list and
    // the full 30-day AAPL chain runs to thousands of contracts, which is both needlessly
    // slow and far more than this test needs to verify Greeks come back populated.
    let symbols: Vec<String> = contracts
        .iter()
        .take(10)
        .map(|c| c.symbol.clone())
        .collect();

    let snapshots = client
        .fetch_snapshots(&symbols, AlpacaOptionFeed::Indicative)
        .await
        .expect("Failed to fetch snapshots");

    tracing::info!(
        requested = symbols.len(),
        received = snapshots.len(),
        "Fetched option snapshots"
    );

    // We might not get snapshots for all symbols (some may not have recent activity)
    // but we should get at least some
    assert!(!snapshots.is_empty(), "No snapshots received");

    // Log snapshot details
    let mut greeks_count = 0;
    for snapshot in &snapshots {
        if snapshot.has_greeks() {
            greeks_count += 1;
            let greeks = snapshot.greeks();
            tracing::info!(
                symbol = %snapshot.symbol,
                delta = ?greeks.delta,
                gamma = ?greeks.gamma,
                theta = ?greeks.theta,
                vega = ?greeks.vega,
                iv = ?greeks.implied_volatility,
                "Snapshot with Greeks"
            );
        }

        if let Some(ref quote) = snapshot.latest_quote {
            tracing::info!(
                symbol = %snapshot.symbol,
                bid = %quote.bid_price,
                ask = %quote.ask_price,
                "Snapshot quote"
            );
            assert!(
                quote.bid_price >= Decimal::ZERO,
                "Bid should be non-negative"
            );
            assert!(
                quote.ask_price >= Decimal::ZERO,
                "Ask should be non-negative"
            );
        }
    }

    tracing::info!(
        total = snapshots.len(),
        with_greeks = greeks_count,
        "Snapshot summary"
    );
}

/// Test the convenience method for fetching entire chain snapshots.
#[tokio::test]
#[ignore]
async fn test_fetch_chain_snapshots_convenience() {
    init_logging();

    let client = AlpacaOptionsClient::from_env().expect("Failed to create options client");

    // SPY has a large active option chain (50k+ contracts) — a good stress test
    // for pagination and the 100-symbol batch limit.
    let snapshots = client
        .fetch_chain_snapshots("SPY", AlpacaOptionFeed::Indicative)
        .await
        .expect("Failed to fetch chain snapshots");

    tracing::info!(count = snapshots.len(), "Fetched SPY chain snapshots");

    // SPY has many options, we should get a substantial number
    assert!(!snapshots.is_empty(), "No SPY chain snapshots received");
}

// ============================================================================
// OPRA Options Tests (requires OPRA subscription)
// ============================================================================

/// Test fetching option snapshots with real-time OPRA feed.
///
/// NOTE: Requires OPRA subscription. Will return empty or error without subscription.
#[tokio::test]
#[ignore]
async fn test_fetch_opra_snapshots() {
    init_logging();

    let client = AlpacaOptionsClient::from_env().expect("Failed to create options client");

    // Get some AAPL contracts
    let today = Utc::now().date_naive();
    let thirty_days = today + chrono::Duration::days(30);

    let query = AlpacaOptionContractQuery::new(vec!["AAPL".into()])
        .expiration_gte(today)
        .expiration_lte(thirty_days)
        .limit(10);

    let contracts = client
        .fetch_contracts(&query)
        .await
        .expect("Failed to fetch contracts");

    assert!(!contracts.is_empty(), "No contracts to fetch snapshots for");

    let symbols: Vec<String> = contracts.iter().map(|c| c.symbol.clone()).collect();

    // Fetch with OPRA (real-time) feed
    let snapshots = client
        .fetch_snapshots(&symbols, AlpacaOptionFeed::Opra)
        .await
        .expect("Failed to fetch OPRA snapshots");

    tracing::info!(
        requested = symbols.len(),
        received = snapshots.len(),
        "Fetched OPRA option snapshots"
    );

    assert!(!snapshots.is_empty(), "No OPRA snapshots received");

    // Verify we got real-time data with Greeks
    let mut greeks_count = 0;
    for snapshot in &snapshots {
        if snapshot.has_greeks() {
            greeks_count += 1;
            let greeks = snapshot.greeks();
            tracing::info!(
                symbol = %snapshot.symbol,
                delta = ?greeks.delta,
                gamma = ?greeks.gamma,
                theta = ?greeks.theta,
                vega = ?greeks.vega,
                iv = ?greeks.implied_volatility,
                "OPRA snapshot with Greeks"
            );
        }
    }

    tracing::info!(
        total = snapshots.len(),
        with_greeks = greeks_count,
        "OPRA snapshot summary"
    );
}

/// Test fetching entire chain with OPRA feed.
///
/// NOTE: Requires OPRA subscription.
#[tokio::test]
#[ignore]
async fn test_fetch_opra_chain_snapshots() {
    init_logging();

    let client = AlpacaOptionsClient::from_env().expect("Failed to create options client");

    let snapshots = client
        .fetch_chain_snapshots("AAPL", AlpacaOptionFeed::Opra)
        .await
        .expect("Failed to fetch OPRA chain snapshots");

    tracing::info!(count = snapshots.len(), "Fetched AAPL OPRA chain snapshots");

    assert!(
        !snapshots.is_empty(),
        "No AAPL OPRA chain snapshots received"
    );
}