rustrade-data 0.2.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
//! 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.

#![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 std::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]
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");
}

#[tokio::test]
#[ignore]
async fn test_crypto_trade_stream_receives_data() {
    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"));

    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;
        assert!(timeout.is_ok(), "Timeout waiting for crypto trade data");

        let event = timeout.unwrap();
        assert!(event.is_some(), "Stream ended without data");

        if let Event::Item(trade) = event.unwrap() {
            tracing::info!(?trade, "Received crypto trade");
            assert!(trade.kind.price > Decimal::ZERO, "Invalid trade price");
            assert!(trade.kind.amount > Decimal::ZERO, "Invalid trade amount");
            return;
        }
    }

    panic!("No crypto trade events received within timeout");
}

#[tokio::test]
#[ignore]
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]
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"));

    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;
        assert!(timeout.is_ok(), "Timeout waiting for crypto quote data");

        let event = timeout.unwrap();
        assert!(event.is_some(), "Stream ended without data");

        if let Event::Item(quote) = event.unwrap() {
            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;
        }
    }

    panic!("No crypto quote events received within timeout");
}

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

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

    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 mut btc_seen = false;
    let mut eth_seen = false;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(120);

    while !(btc_seen && eth_seen) && tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;
        if let Ok(Some(Event::Item(event))) = timeout {
            match event.instrument.base.as_ref() {
                "btc" => {
                    btc_seen = true;
                    tracing::info!("Received BTC trade");
                }
                "eth" => {
                    eth_seen = true;
                    tracing::info!("Received ETH trade");
                }
                _ => {}
            }
        }
    }

    assert!(btc_seen, "No BTC trades received within timeout");
    assert!(eth_seen, "No ETH trades received within timeout");
}

// ============================================================================
// 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);

    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");

    // Fetch snapshots for these contracts
    let symbols: Vec<String> = contracts.iter().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"
    );
}