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
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
//! Massive Market Data Integration Tests
//!
//! These tests verify connectivity and data reception from Massive (formerly Polygon) APIs.
//!
//! # Status
//!
//! **Partially tested.** We have a currencies subscription (crypto + forex) but not
//! stocks, options, indices, or futures subscriptions. The following are verified:
//!
//! | Category | Tested | Notes |
//! |----------|--------|-------|
//! | REST aggregates (crypto, forex) | ✅ | Free tier + currencies sub |
//! | REST aggregates (stocks) | ✅ | Free tier (minute aggs only) |
//! | REST aggregates (options, futures) | ✅ | Free tier (minute aggs only) |
//! | REST aggregates (indices) | ❌ | Requires indices subscription |
//! | REST tick trades (crypto) | ✅ | Currencies subscription |
//! | REST tick trades (stocks) | ❌ | Requires stocks subscription |
//! | REST quotes (forex) | ✅ | Currencies subscription |
//! | REST quotes (stocks) | ❌ | Requires stocks subscription |
//! | WebSocket (crypto) | ✅ | Currencies subscription |
//! | WebSocket (stocks) | ❌ | Requires stocks subscription |
//! | Reference data | ✅ | Free tier |
//! | Corporate actions (dividends, splits) | ✅ | Free tier |
//! | Options contracts (reference) | ✅ | Free tier |
//! | Options snapshots (Greeks) | ❌ | Requires Options Starter subscription |
//!
//! Transformation logic is tested via unit tests in `transformer.rs`. Network
//! integration for untested endpoints has not been verified against real data.
//!
//! # Prerequisites
//!
//! 1. Massive account with API key
//! 2. Environment variable set (see .env.template):
//!    - MASSIVE_API_KEY: API key from <https://massive.com/dashboard/api-keys>
//!
//! # Free Tier Limitations
//!
//! All asset classes have free Basic tiers with:
//! - 2 years historical data (1+ year for indices)
//! - 5 API calls/minute rate limit
//! - End of day + minute aggregates
//! - Reference data
//!
//! REST aggregates tests use data from ~1 month ago to stay within free tier limits.
//! Tick-level trades and quotes require paid subscriptions.
//!
//! # WebSocket Limitations
//!
//! - **Individual plan**: 1 concurrent WebSocket connection per product
//! - WebSocket tests are marked `#[serial]` to prevent connection conflicts
//! - Live streaming requires an active subscription for the asset class
//!
//! # Running
//!
//! ```bash
//! # Load env vars from .env
//! source .env
//!
//! # Run all Massive integration tests
//! cargo test --test massive_integration --features massive -- --ignored
//!
//! # Run specific test
//! cargo test --test massive_integration --features massive test_rest_aggregates_crypto -- --ignored
//!
//! # Run tests that should pass with currencies subscription
//! cargo test --test massive_integration --features massive -- --ignored \
//!     test_rest_aggregates_crypto test_rest_aggregates_forex \
//!     test_rest_trades_crypto test_rest_quotes_forex test_websocket_crypto
//! ```

#![cfg(feature = "massive")]
// Integration tests use unwrap/expect for concise failure messages; panics are the intended failure mode.
#![allow(clippy::unwrap_used, clippy::expect_used)]

use chrono::{Duration, Utc};
use futures_util::StreamExt;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use rustrade_data::exchange::massive::{
    ChannelType, DividendQuery, Market, MassiveLive, MassiveRestClient, OptionContractQuery,
    OptionSnapshotQuery, SplitQuery, TickerQuery,
};
use rustrade_instrument::exchange::ExchangeId;
use rustrade_instrument::instrument::kind::option::OptionKind;
use serial_test::serial;
use std::collections::HashMap;
use std::pin::pin;
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();
}

/// Get a time range from ~1 month ago (5 minutes of data).
/// This is well within the 2-year free tier limit for all asset classes.
fn historical_time_range() -> (chrono::DateTime<Utc>, chrono::DateTime<Utc>) {
    let end = Utc::now() - Duration::days(30);
    let start = end - Duration::minutes(5);
    (start, end)
}

// ============================================================================
// REST Client Tests
// ============================================================================

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

    let client = MassiveRestClient::from_env();
    assert!(
        client.is_ok(),
        "Failed to create REST client: {:?}",
        client.err()
    );
    tracing::info!("REST client created successfully");
}

// ============================================================================
// REST Aggregates Tests (12.5.2 - 12.5.4)
// ============================================================================

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching X:BTCUSD minute aggregates");

    let stream = client.fetch_aggregates("X:BTCUSD", 1, "minute", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let candle = result.expect("Failed to fetch candle");
        assert!(candle.open > Decimal::ZERO, "Open should be positive");
        assert!(candle.high >= candle.low, "High should be >= low");
        assert!(
            candle.volume >= Decimal::ZERO,
            "Volume should be non-negative"
        );
        count += 1;

        if count == 1 {
            tracing::info!(
                open = %candle.open,
                high = %candle.high,
                low = %candle.low,
                close = %candle.close,
                volume = %candle.volume,
                "First crypto candle"
            );
        }
    }

    tracing::info!(count, "Fetched crypto aggregates");
    assert!(count > 0, "Should have received at least one candle");
}

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching C:EURUSD minute aggregates");

    let stream = client.fetch_aggregates("C:EURUSD", 1, "minute", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let candle = result.expect("Failed to fetch candle");
        assert!(candle.open > Decimal::ZERO, "Open should be positive");
        assert!(candle.high >= candle.low, "High should be >= low");
        count += 1;

        if count == 1 {
            tracing::info!(
                open = %candle.open,
                high = %candle.high,
                low = %candle.low,
                close = %candle.close,
                "First forex candle"
            );
        }
    }

    tracing::info!(count, "Fetched forex aggregates");
    assert!(count > 0, "Should have received at least one candle");
}

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching AAPL minute aggregates");

    let stream = client.fetch_aggregates("AAPL", 1, "minute", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let candle = result.expect("Failed to fetch candle");
        assert!(candle.open > Decimal::ZERO, "Open should be positive");
        assert!(candle.high >= candle.low, "High should be >= low");
        count += 1;

        if count == 1 {
            tracing::info!(
                open = %candle.open,
                high = %candle.high,
                low = %candle.low,
                close = %candle.close,
                volume = %candle.volume,
                "First stock candle"
            );
        }
    }

    tracing::info!(count, "Fetched stock aggregates");
    // Note: May be 0 if the time range falls on a weekend/holiday
}

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

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

    // Use a historical AAPL option that was active ~1 month ago
    // Format: O:{underlying}{YYMMDD}{C/P}{strike*1000}
    // Using a strike near AAPL's price range
    let (from, to) = historical_time_range();

    // Find a valid option contract by querying tickers first
    let query = TickerQuery::new().market("options").search("AAPL").limit(1);

    let tickers: Vec<_> = client
        .fetch_tickers(&query)
        .take(1)
        .collect::<Vec<_>>()
        .await;

    if tickers.is_empty() {
        tracing::warn!("No AAPL options found, skipping test");
        return;
    }

    let ticker = match &tickers[0] {
        Ok(t) => &t.ticker,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to fetch options ticker");
            return;
        }
    };

    tracing::info!(%from, %to, %ticker, "Fetching options minute aggregates");

    let stream = client.fetch_aggregates(ticker, 1, "minute", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        match result {
            Ok(candle) => {
                assert!(candle.open >= Decimal::ZERO, "Open should be non-negative");
                count += 1;
                if count == 1 {
                    tracing::info!(
                        open = %candle.open,
                        volume = %candle.volume,
                        "First options candle"
                    );
                }
            }
            Err(e) => {
                tracing::warn!(error = %e, "Options fetch error");
                break;
            }
        }
    }

    tracing::info!(count, "Fetched options aggregates");
}

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching I:SPX minute aggregates");

    let stream = client.fetch_aggregates("I:SPX", 1, "minute", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let candle = result.expect("Failed to fetch candle");
        assert!(candle.open > Decimal::ZERO, "Open should be positive");
        assert!(candle.high >= candle.low, "High should be >= low");
        count += 1;

        if count == 1 {
            tracing::info!(
                open = %candle.open,
                high = %candle.high,
                low = %candle.low,
                close = %candle.close,
                "First index candle"
            );
        }
    }

    tracing::info!(count, "Fetched index aggregates");
}

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

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

    // Find an active futures contract
    let query = TickerQuery::new().market("futures").limit(1);

    let tickers: Vec<_> = client
        .fetch_tickers(&query)
        .take(1)
        .collect::<Vec<_>>()
        .await;

    if tickers.is_empty() {
        tracing::warn!("No futures tickers found, skipping test");
        return;
    }

    let ticker = match &tickers[0] {
        Ok(t) => &t.ticker,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to fetch futures ticker");
            return;
        }
    };

    let (from, to) = historical_time_range();
    tracing::info!(%from, %to, %ticker, "Fetching futures minute aggregates");

    let stream = client.fetch_aggregates(ticker, 1, "minute", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        match result {
            Ok(candle) => {
                assert!(candle.open > Decimal::ZERO, "Open should be positive");
                count += 1;
                if count == 1 {
                    tracing::info!(
                        open = %candle.open,
                        volume = %candle.volume,
                        "First futures candle"
                    );
                }
            }
            Err(e) => {
                tracing::warn!(error = %e, "Futures fetch error");
                break;
            }
        }
    }

    tracing::info!(count, "Fetched futures aggregates");
}

// ============================================================================
// REST Trades Tests (12.5.5)
// ============================================================================

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching X:BTCUSD trades");

    let stream = client.fetch_trades("X:BTCUSD", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let trade = result.expect("Failed to fetch trade");
        assert!(trade.price > Decimal::ZERO, "Price should be positive");
        assert!(trade.amount > Decimal::ZERO, "Amount should be positive");
        count += 1;

        if count == 1 {
            tracing::info!(
                price = %trade.price,
                amount = %trade.amount,
                "First crypto trade"
            );
        }

        // Limit to avoid rate limits
        if count >= 100 {
            break;
        }
    }

    tracing::info!(count, "Fetched crypto trades");
    assert!(count > 0, "Should have received at least one trade");
}

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching AAPL trades");

    let stream = client.fetch_trades("AAPL", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let trade = result.expect("Failed to fetch trade");
        assert!(trade.price > Decimal::ZERO, "Price should be positive");
        assert!(trade.amount > Decimal::ZERO, "Amount should be positive");
        count += 1;

        if count == 1 {
            tracing::info!(
                price = %trade.price,
                amount = %trade.amount,
                "First stock trade"
            );
        }

        if count >= 100 {
            break;
        }
    }

    tracing::info!(count, "Fetched stock trades");
}

// ============================================================================
// REST Quotes Tests (12.5.6)
// ============================================================================

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching C:EURUSD quotes");

    let stream = client.fetch_quotes("C:EURUSD", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let quote = result.expect("Failed to fetch quote");
        let bid = quote.best_bid.expect("Should have bid");
        let ask = quote.best_ask.expect("Should have ask");
        assert!(bid.price > Decimal::ZERO, "Bid should be positive");
        assert!(ask.price > Decimal::ZERO, "Ask should be positive");
        assert!(ask.price >= bid.price, "Ask should be >= bid");
        count += 1;

        if count == 1 {
            tracing::info!(
                bid = %bid.price,
                ask = %ask.price,
                "First forex quote"
            );
        }

        if count >= 100 {
            break;
        }
    }

    tracing::info!(count, "Fetched forex quotes");
    assert!(count > 0, "Should have received at least one quote");
}

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

    let client = MassiveRestClient::from_env().expect("Failed to create client");
    let (from, to) = historical_time_range();

    tracing::info!(%from, %to, "Fetching AAPL quotes (NBBO)");

    let stream = client.fetch_quotes("AAPL", from, to);
    let mut stream = pin!(stream);

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let quote = result.expect("Failed to fetch quote");
        let bid = quote.best_bid.expect("Should have bid");
        let ask = quote.best_ask.expect("Should have ask");
        assert!(bid.price > Decimal::ZERO, "Bid should be positive");
        assert!(ask.price > Decimal::ZERO, "Ask should be positive");
        assert!(ask.price >= bid.price, "Ask should be >= bid");
        count += 1;

        if count == 1 {
            tracing::info!(
                bid = %bid.price,
                ask = %ask.price,
                "First stock NBBO quote"
            );
        }

        if count >= 100 {
            break;
        }
    }

    tracing::info!(count, "Fetched stock quotes");
}

// ============================================================================
// WebSocket Tests (12.5.7 - 12.5.8)
// ============================================================================

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

    let instruments: HashMap<String, String> = [("BTC-USD".to_string(), "btc-usd".to_string())]
        .into_iter()
        .collect();

    let mut client = MassiveLive::from_env(Market::Crypto, ExchangeId::Massive, instruments)
        .expect("Failed to create WebSocket client");

    client.subscribe(&["BTC-USD"], ChannelType::Trade);
    tracing::info!("Subscribed to BTC-USD trades");

    let stream = client.start().await.expect("Failed to start stream");
    let mut stream = pin!(stream);

    let timeout = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut count = 0;
        while let Some(event) = stream.next().await {
            match event {
                Ok(market_event) => {
                    tracing::info!(?market_event, "Received market event");
                    count += 1;
                    if count >= 3 {
                        return Ok(count);
                    }
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Stream error");
                }
            }
        }
        Err("Stream ended without sufficient data")
    })
    .await;

    match timeout {
        Ok(Ok(count)) => tracing::info!(count, "WebSocket crypto test passed"),
        Ok(Err(e)) => panic!("Stream error: {}", e),
        Err(_) => panic!("Timeout waiting for crypto WebSocket data"),
    }
}

/// WebSocket test for stocks - requires stocks subscription
#[tokio::test]
#[ignore]
#[serial]
async fn test_websocket_stocks() {
    init_logging();

    let instruments: HashMap<String, String> = [("AAPL".to_string(), "aapl".to_string())]
        .into_iter()
        .collect();

    let mut client = MassiveLive::from_env(Market::Stocks, ExchangeId::Massive, instruments)
        .expect("Failed to create WebSocket client");

    client.subscribe(&["AAPL"], ChannelType::Trade);
    tracing::info!("Subscribed to AAPL trades");

    let stream = client.start().await.expect("Failed to start stream");
    let mut stream = pin!(stream);

    let timeout = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut count = 0;
        while let Some(event) = stream.next().await {
            match event {
                Ok(market_event) => {
                    tracing::info!(?market_event, "Received market event");
                    count += 1;
                    if count >= 3 {
                        return Ok(count);
                    }
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Stream error");
                }
            }
        }
        Err("Stream ended without sufficient data")
    })
    .await;

    match timeout {
        Ok(Ok(count)) => tracing::info!(count, "WebSocket stocks test passed"),
        Ok(Err(e)) => panic!("Stream error: {}", e),
        Err(_) => panic!("Timeout waiting for stock WebSocket data"),
    }
}

// ============================================================================
// Reference Data Tests (12.5.9)
// ============================================================================

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

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

    // Query crypto tickers
    let query = TickerQuery::new().market("crypto").limit(10);

    tracing::info!("Fetching crypto tickers");

    let tickers: Vec<_> = client
        .fetch_tickers(&query)
        .take(10)
        .collect::<Vec<_>>()
        .await;

    assert!(!tickers.is_empty(), "Should have received tickers");

    for result in &tickers {
        let ticker = result.as_ref().expect("Failed to fetch ticker");
        assert!(
            !ticker.ticker.is_empty(),
            "Ticker symbol should not be empty"
        );
        tracing::info!(
            ticker = %ticker.ticker,
            name = %ticker.name,
            market = %ticker.market,
            "Ticker"
        );
    }

    tracing::info!(count = tickers.len(), "Fetched tickers");
}

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

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

    tracing::info!("Fetching AAPL ticker details");

    let details = client.fetch_ticker_details("AAPL").await;
    let details = details.expect("Failed to fetch ticker details");

    assert_eq!(details.ticker.ticker, "AAPL");
    assert!(!details.ticker.name.is_empty(), "Name should not be empty");

    tracing::info!(
        ticker = %details.ticker.ticker,
        name = %details.ticker.name,
        market = %details.ticker.market,
        primary_exchange = ?details.ticker.primary_exchange,
        "Ticker details"
    );
}

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

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

    tracing::info!("Fetching exchanges");

    let exchanges = client.fetch_exchanges(None, None).await;
    let exchanges = exchanges.expect("Failed to fetch exchanges");

    assert!(!exchanges.is_empty(), "Should have received exchanges");

    for exchange in exchanges.iter().take(5) {
        tracing::info!(
            id = exchange.id,
            mic = ?exchange.mic,
            name = %exchange.name,
            exchange_type = ?exchange.exchange_type,
            "Exchange"
        );
    }

    tracing::info!(count = exchanges.len(), "Fetched exchanges");
}

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

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

    tracing::info!("Fetching market status");

    let status = client.fetch_market_status().await;
    let status = status.expect("Failed to fetch market status");

    tracing::info!(
        market = %status.market,
        server_time = %status.server_time,
        exchanges = ?status.exchanges,
        currencies = ?status.currencies,
        "Market status"
    );
}

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

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

    tracing::info!("Fetching market holidays");

    let holidays = client.fetch_market_holidays().await;
    let holidays = holidays.expect("Failed to fetch market holidays");

    assert!(!holidays.is_empty(), "Should have received holidays");

    for holiday in holidays.iter().take(5) {
        tracing::info!(
            date = %holiday.date,
            name = %holiday.name,
            exchange = %holiday.exchange,
            status = %holiday.status,
            "Holiday"
        );
    }

    tracing::info!(count = holidays.len(), "Fetched market holidays");
}

// ============================================================================
// Corporate Actions Tests (12.6.2)
// ============================================================================

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

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

    // Query AAPL dividends from the last 2 years (within free tier)
    let two_years_ago = (Utc::now() - Duration::days(730)).date_naive();
    let query = DividendQuery::new()
        .ticker("AAPL")
        .ex_dividend_date_gte(two_years_ago)
        .limit(10);

    tracing::info!(%two_years_ago, "Fetching AAPL dividends");

    let dividends: Vec<_> = client
        .fetch_dividends(&query)
        .take(10)
        .collect::<Vec<_>>()
        .await;

    assert!(!dividends.is_empty(), "Should have received dividends");

    for result in &dividends {
        let dividend = result.as_ref().expect("Failed to fetch dividend");
        assert_eq!(dividend.ticker, "AAPL");
        assert!(
            dividend.cash_amount > Decimal::ZERO,
            "Cash amount should be positive"
        );

        tracing::info!(
            ticker = %dividend.ticker,
            cash_amount = %dividend.cash_amount,
            ex_dividend_date = %dividend.ex_dividend_date,
            frequency = ?dividend.frequency,
            dividend_type = ?dividend.dividend_type,
            "Dividend"
        );
    }

    tracing::info!(count = dividends.len(), "Fetched dividends");
}

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

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

    // Query recent stock splits (within free tier data range)
    let two_years_ago = (Utc::now() - Duration::days(730)).date_naive();
    let query = SplitQuery::new()
        .execution_date_gte(two_years_ago)
        .limit(10);

    tracing::info!(%two_years_ago, "Fetching recent stock splits");

    let splits: Vec<_> = client
        .fetch_splits(&query)
        .take(10)
        .collect::<Vec<_>>()
        .await;

    // Note: May be empty if no splits occurred in the period
    for result in &splits {
        let split = result.as_ref().expect("Failed to fetch split");
        assert!(
            split.split_to > Decimal::ZERO,
            "split_to should be positive"
        );
        assert!(
            split.split_from > Decimal::ZERO,
            "split_from should be positive"
        );

        tracing::info!(
            ticker = %split.ticker,
            execution_date = %split.execution_date,
            split_to = %split.split_to,
            split_from = %split.split_from,
            "Split"
        );
    }

    tracing::info!(count = splits.len(), "Fetched splits");
}

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

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

    // Query NVDA splits - they had a 10:1 split in 2024
    let query = SplitQuery::new().ticker("NVDA").limit(5);

    tracing::info!("Fetching NVDA stock splits");

    let splits: Vec<_> = client
        .fetch_splits(&query)
        .take(5)
        .collect::<Vec<_>>()
        .await;

    for result in &splits {
        let split = result.as_ref().expect("Failed to fetch split");
        assert_eq!(split.ticker, "NVDA");

        tracing::info!(
            ticker = %split.ticker,
            execution_date = %split.execution_date,
            split_to = %split.split_to,
            split_from = %split.split_from,
            "NVDA Split"
        );
    }

    tracing::info!(count = splits.len(), "Fetched NVDA splits");
}

// ============================================================================
// Options Reference Data Tests
// ============================================================================

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

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

    // Query AAPL call options
    let query = OptionContractQuery::new()
        .underlying_ticker("AAPL")
        .limit(10);

    tracing::info!("Fetching AAPL option contracts");

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

    assert!(!contracts.is_empty(), "Should have received contracts");

    for contract in &contracts {
        assert_eq!(contract.underlying_ticker, "AAPL");
        assert!(
            contract.strike_price > Decimal::ZERO,
            "Strike should be positive"
        );

        tracing::info!(
            ticker = %contract.ticker,
            underlying = %contract.underlying_ticker,
            contract_type = %contract.contract_type,
            expiration = %contract.expiration_date,
            strike = %contract.strike_price,
            exercise = %contract.exercise_style,
            "Option contract"
        );
    }

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

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

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

    // Query AAPL call options with strike range
    let query = OptionContractQuery::new()
        .underlying_ticker("AAPL")
        .contract_type(OptionKind::Call)
        .strike_price_gte(dec!(150))
        .strike_price_lte(dec!(200))
        .limit(20);

    tracing::info!("Fetching filtered AAPL call options (strike 150-200)");

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

    for contract in &contracts {
        assert_eq!(contract.underlying_ticker, "AAPL");
        assert!(
            contract.strike_price >= dec!(150),
            "Strike should be >= 150"
        );
        assert!(
            contract.strike_price <= dec!(200),
            "Strike should be <= 200"
        );

        tracing::info!(
            ticker = %contract.ticker,
            strike = %contract.strike_price,
            expiration = %contract.expiration_date,
            "Filtered option contract"
        );
    }

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

/// Options chain snapshot test - requires Options Starter subscription
#[tokio::test]
#[ignore]
async fn test_options_chain_snapshot() {
    init_logging();

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

    let query = OptionSnapshotQuery::new().limit(5);

    tracing::info!("Fetching AAPL option chain snapshot");

    let snapshots = client
        .fetch_option_chain_snapshot("AAPL", &query)
        .await
        .expect("Failed to fetch chain snapshot");

    for snapshot in &snapshots {
        tracing::info!(
            ticker = %snapshot.contract.ticker,
            strike = %snapshot.contract.strike_price,
            iv = ?snapshot.implied_volatility,
            delta = ?snapshot.greeks.as_ref().and_then(|g| g.delta),
            gamma = ?snapshot.greeks.as_ref().and_then(|g| g.gamma),
            theta = ?snapshot.greeks.as_ref().and_then(|g| g.theta),
            vega = ?snapshot.greeks.as_ref().and_then(|g| g.vega),
            "Option snapshot"
        );
    }

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

/// Single option snapshot test - requires Options Starter subscription
#[tokio::test]
#[ignore]
async fn test_option_single_snapshot() {
    init_logging();

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

    // First, find a valid contract ticker
    let query = OptionContractQuery::new()
        .underlying_ticker("AAPL")
        .limit(1);

    let contracts = match client.fetch_option_contracts(&query).await {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to fetch contract ticker");
            return;
        }
    };

    if contracts.is_empty() {
        tracing::warn!("No AAPL options found, skipping test");
        return;
    }

    let contract_ticker = &contracts[0].ticker;

    tracing::info!(%contract_ticker, "Fetching single option snapshot");

    match client.fetch_option_snapshot("AAPL", contract_ticker).await {
        Ok(snapshot) => {
            tracing::info!(
                ticker = %snapshot.contract.ticker,
                strike = %snapshot.contract.strike_price,
                iv = ?snapshot.implied_volatility,
                open_interest = ?snapshot.open_interest,
                break_even = ?snapshot.break_even_price,
                delta = ?snapshot.greeks.as_ref().and_then(|g| g.delta),
                "Single option snapshot"
            );
        }
        Err(e) => {
            tracing::warn!(error = %e, "Failed to fetch option snapshot (may require subscription)");
        }
    }
}