schwab-sdk 0.4.1

Async Rust client for the Charles Schwab Trader API and real-time market-data streaming.
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
//! `/chains` - option chain for an optionable symbol.
//!
//! Returns the option contracts for a symbol, grouped by expiration and
//! then by strike. The contract grouping is two levels of map:
//!
//! - outer key is `"<expiration-date>:<days-to-expiration>"`, e.g.
//!   `"2024-01-19:5"`;
//! - inner key is the strike price as the string Schwab sends it, e.g.
//!   `"150.0"`;
//! - the value is the [`OptionContract`]s at that strike.
//!
//! The per-strike value is exposed as a `Vec<OptionContract>`. Schwab's
//! published schema types it as a single contract object; deserialization
//! also accepts an array at that position, normalizing either shape to the
//! list form.
//!
//! Reached through [`MarketData::chains`](super::MarketData::chains).
//!
//! # Examples
//!
//! Fetch the near-the-money calls for a symbol. Every filter is optional;
//! narrow the chain before sending. Contracts come back grouped by
//! expiration and then by strike (see the key format above).
//!
//! ```no_run
//! use schwab_sdk::{AuthToken, SchwabClient};
//! use schwab_sdk::market_data::ContractType;
//!
//! # async fn run() -> schwab_sdk::Result<()> {
//! let client = SchwabClient::new(AuthToken::new("token"));
//!
//! let chain = client
//!     .market_data()
//!     .chains()
//!     .get("AAPL")
//!     .contract_type(ContractType::Call)
//!     .strike_count(5)
//!     .send()
//!     .await?;
//!
//! // Outer key: "<expiration>:<days-to-expiration>". Inner key: strike.
//! for (expiration, strikes) in &chain.call_exp_date_map {
//!     for (strike, contracts) in strikes {
//!         for contract in contracts {
//!             println!(
//!                 "{expiration} {strike}: bid {:?} ask {:?}",
//!                 contract.bid_price, contract.ask_price,
//!             );
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use std::collections::HashMap;
use std::fmt;

use chrono::NaiveDate;
use rust_decimal::Decimal;
use rust_decimal::serde::float_option as decimal_opt;
use serde::de::value::MapAccessDeserializer;
use serde::de::{MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer};

use crate::client::SchwabClient;
use crate::error::Result;
use crate::macros::string_enum;

/// Accessor for `/chains`. Construct via
/// [`MarketData::chains`](super::MarketData::chains).
#[derive(Debug)]
pub struct Chains<'a> {
    client: &'a SchwabClient,
}

impl<'a> Chains<'a> {
    pub(crate) fn new(client: &'a SchwabClient) -> Self {
        Self { client }
    }

    /// Begin a `GET /chains` request for an optionable `symbol`. Every
    /// filter is optional; with none set Schwab returns the full
    /// `SINGLE`-strategy chain.
    pub fn get(&self, symbol: impl Into<String>) -> GetChainBuilder<'a> {
        GetChainBuilder {
            client: self.client,
            symbol: symbol.into(),
            contract_type: None,
            strike_count: None,
            include_underlying_quote: None,
            strategy: None,
            interval: None,
            strike: None,
            range: None,
            from_date: None,
            to_date: None,
            volatility: None,
            underlying_price: None,
            interest_rate: None,
            days_to_expiration: None,
            exp_month: None,
            option_type: None,
            entitlement: None,
        }
    }
}

/// In-flight request for `GET /chains`. Built via [`Chains::get`].
#[derive(Debug)]
#[must_use = "call .send() to execute the request"]
pub struct GetChainBuilder<'a> {
    client: &'a SchwabClient,
    symbol: String,
    contract_type: Option<ContractType>,
    strike_count: Option<i32>,
    include_underlying_quote: Option<bool>,
    strategy: Option<OptionStrategy>,
    interval: Option<Decimal>,
    strike: Option<Decimal>,
    range: Option<OptionRange>,
    from_date: Option<NaiveDate>,
    to_date: Option<NaiveDate>,
    volatility: Option<Decimal>,
    underlying_price: Option<Decimal>,
    interest_rate: Option<Decimal>,
    days_to_expiration: Option<i32>,
    exp_month: Option<ExpirationMonth>,
    option_type: Option<OptionType>,
    entitlement: Option<Entitlement>,
}

impl<'a> GetChainBuilder<'a> {
    /// Restrict the chain to calls, puts, or both.
    pub fn contract_type(mut self, value: ContractType) -> Self {
        self.contract_type = Some(value);
        self
    }

    /// Number of strikes to return above and below the at-the-money
    /// price.
    pub fn strike_count(mut self, value: i32) -> Self {
        self.strike_count = Some(value);
        self
    }

    /// Include the underlying's quote in [`OptionChain::underlying`].
    pub fn include_underlying_quote(mut self, value: bool) -> Self {
        self.include_underlying_quote = Some(value);
        self
    }

    /// Chain strategy. `ANALYTICAL` enables the theoretical-value
    /// parameters ([`Self::volatility`], [`Self::underlying_price`],
    /// [`Self::interest_rate`], [`Self::days_to_expiration`]).
    pub fn strategy(mut self, value: OptionStrategy) -> Self {
        self.strategy = Some(value);
        self
    }

    /// Strike interval for spread-strategy chains.
    pub fn interval(mut self, value: Decimal) -> Self {
        self.interval = Some(value);
        self
    }

    /// Restrict the chain to a single strike price.
    pub fn strike(mut self, value: Decimal) -> Self {
        self.strike = Some(value);
        self
    }

    /// Restrict the chain to a moneyness range (ITM/NTM/OTM etc.).
    pub fn range(mut self, value: OptionRange) -> Self {
        self.range = Some(value);
        self
    }

    /// Lower bound of the expiration window (`yyyy-MM-dd`).
    pub fn from_date(mut self, value: NaiveDate) -> Self {
        self.from_date = Some(value);
        self
    }

    /// Upper bound of the expiration window (`yyyy-MM-dd`).
    pub fn to_date(mut self, value: NaiveDate) -> Self {
        self.to_date = Some(value);
        self
    }

    /// Volatility for theoretical-value math. Applies only to the
    /// `ANALYTICAL` strategy.
    pub fn volatility(mut self, value: Decimal) -> Self {
        self.volatility = Some(value);
        self
    }

    /// Underlying price for theoretical-value math. Applies only to the
    /// `ANALYTICAL` strategy.
    pub fn underlying_price(mut self, value: Decimal) -> Self {
        self.underlying_price = Some(value);
        self
    }

    /// Interest rate for theoretical-value math. Applies only to the
    /// `ANALYTICAL` strategy.
    pub fn interest_rate(mut self, value: Decimal) -> Self {
        self.interest_rate = Some(value);
        self
    }

    /// Days to expiration for theoretical-value math. Applies only to
    /// the `ANALYTICAL` strategy.
    pub fn days_to_expiration(mut self, value: i32) -> Self {
        self.days_to_expiration = Some(value);
        self
    }

    /// Restrict the chain to a single expiration month.
    pub fn exp_month(mut self, value: ExpirationMonth) -> Self {
        self.exp_month = Some(value);
        self
    }

    /// Restrict the chain to standard or non-standard contracts.
    pub fn option_type(mut self, value: OptionType) -> Self {
        self.option_type = Some(value);
        self
    }

    /// Client entitlement; applies only when authenticated with a retail
    /// token.
    pub fn entitlement(mut self, value: Entitlement) -> Self {
        self.entitlement = Some(value);
        self
    }

    /// Execute the request.
    pub async fn send(self) -> Result<OptionChain> {
        let mut request = self
            .client
            .market_data_http()
            .get("/chains")
            .query(&[("symbol", self.symbol.as_str())]);
        if let Some(v) = &self.contract_type {
            let s = v.to_string();
            request = request.query(&[("contractType", s.as_str())]);
        }
        if let Some(v) = self.strike_count {
            let s = v.to_string();
            request = request.query(&[("strikeCount", s.as_str())]);
        }
        if let Some(v) = self.include_underlying_quote {
            let s = if v { "true" } else { "false" };
            request = request.query(&[("includeUnderlyingQuote", s)]);
        }
        if let Some(v) = &self.strategy {
            let s = v.to_string();
            request = request.query(&[("strategy", s.as_str())]);
        }
        if let Some(v) = self.interval {
            let s = v.to_string();
            request = request.query(&[("interval", s.as_str())]);
        }
        if let Some(v) = self.strike {
            let s = v.to_string();
            request = request.query(&[("strike", s.as_str())]);
        }
        if let Some(v) = &self.range {
            let s = v.to_string();
            request = request.query(&[("range", s.as_str())]);
        }
        if let Some(v) = self.from_date {
            let s = v.format("%Y-%m-%d").to_string();
            request = request.query(&[("fromDate", s.as_str())]);
        }
        if let Some(v) = self.to_date {
            let s = v.format("%Y-%m-%d").to_string();
            request = request.query(&[("toDate", s.as_str())]);
        }
        if let Some(v) = self.volatility {
            let s = v.to_string();
            request = request.query(&[("volatility", s.as_str())]);
        }
        if let Some(v) = self.underlying_price {
            let s = v.to_string();
            request = request.query(&[("underlyingPrice", s.as_str())]);
        }
        if let Some(v) = self.interest_rate {
            let s = v.to_string();
            request = request.query(&[("interestRate", s.as_str())]);
        }
        if let Some(v) = self.days_to_expiration {
            let s = v.to_string();
            request = request.query(&[("daysToExpiration", s.as_str())]);
        }
        if let Some(v) = &self.exp_month {
            let s = v.to_string();
            request = request.query(&[("expMonth", s.as_str())]);
        }
        if let Some(v) = &self.option_type {
            let s = v.to_string();
            request = request.query(&[("optionType", s.as_str())]);
        }
        if let Some(v) = &self.entitlement {
            let s = v.to_string();
            request = request.query(&[("entitlement", s.as_str())]);
        }
        request.send_json().await
    }
}

// --- Response shape ---

/// Per-strike option contracts for one expiration. Keyed by strike price
/// as the string Schwab sends (e.g. `"150.0"`); the value is the list of
/// contracts at that strike.
pub type OptionContractMap = HashMap<String, Vec<OptionContract>>;

/// Deserialize a `callExpDateMap`/`putExpDateMap`.
///
/// Schwab's published schema types the per-strike value as a single
/// [`OptionContract`]; an array of contracts can also appear at that
/// position. This accepts either shape and normalizes both to a `Vec`.
fn de_exp_date_map<'de, D>(
    deserializer: D,
) -> std::result::Result<HashMap<String, OptionContractMap>, D::Error>
where
    D: Deserializer<'de>,
{
    let raw: HashMap<String, HashMap<String, Contracts>> = HashMap::deserialize(deserializer)?;
    Ok(raw
        .into_iter()
        .map(|(expiration, strikes)| {
            let strikes = strikes
                .into_iter()
                .map(|(strike, contracts)| (strike, contracts.0))
                .collect();
            (expiration, strikes)
        })
        .collect())
}

/// One strike's contracts, tolerant of both the single-object and array
/// wire shapes. Private: callers see the normalized `Vec<OptionContract>`.
struct Contracts(Vec<OptionContract>);

impl<'de> Deserialize<'de> for Contracts {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer
            .deserialize_any(ContractsVisitor)
            .map(Contracts)
    }
}

struct ContractsVisitor;

impl<'de> Visitor<'de> for ContractsVisitor {
    type Value = Vec<OptionContract>;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("an option contract or an array of option contracts")
    }

    fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut contracts = Vec::new();
        while let Some(contract) = seq.next_element()? {
            contracts.push(contract);
        }
        Ok(contracts)
    }

    fn visit_map<A>(self, map: A) -> std::result::Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let contract = OptionContract::deserialize(MapAccessDeserializer::new(map))?;
        Ok(vec![contract])
    }
}

/// `/chains` response body.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct OptionChain {
    /// Underlying symbol the chain is for.
    #[serde(default)]
    pub symbol: Option<String>,
    /// Schwab response status string (typically `"SUCCESS"`).
    #[serde(default)]
    pub status: Option<String>,
    /// Underlying quote; populated when `include_underlying_quote` was
    /// set on the request.
    #[serde(default)]
    pub underlying: Option<Underlying>,
    /// Strategy Schwab used to assemble the chain.
    #[serde(default)]
    pub strategy: Option<OptionStrategy>,
    /// Strike interval used for spread-strategy chains.
    #[serde(default, with = "decimal_opt")]
    pub interval: Option<Decimal>,
    /// `true` if the chain is built from delayed quotes.
    #[serde(rename = "isDelayed", default)]
    pub is_delayed: Option<bool>,
    /// `true` if the underlying is an index.
    #[serde(rename = "isIndex", default)]
    pub is_index: Option<bool>,
    /// Days to expiration for `ANALYTICAL` strategy chains.
    #[serde(rename = "daysToExpiration", default, with = "decimal_opt")]
    pub days_to_expiration: Option<Decimal>,
    /// Interest rate used for `ANALYTICAL` theoretical-value math (fraction).
    #[serde(rename = "interestRate", default, with = "decimal_opt")]
    pub interest_rate: Option<Decimal>,
    /// Underlying price used for `ANALYTICAL` theoretical-value math.
    #[serde(rename = "underlyingPrice", default, with = "decimal_opt")]
    pub underlying_price: Option<Decimal>,
    /// Volatility used for `ANALYTICAL` theoretical-value math.
    #[serde(default, with = "decimal_opt")]
    pub volatility: Option<Decimal>,
    /// Call contracts, keyed by `"<expiration>:<days-to-expiration>"`.
    #[serde(
        rename = "callExpDateMap",
        default,
        deserialize_with = "de_exp_date_map"
    )]
    pub call_exp_date_map: HashMap<String, OptionContractMap>,
    /// Put contracts, keyed by `"<expiration>:<days-to-expiration>"`.
    #[serde(
        rename = "putExpDateMap",
        default,
        deserialize_with = "de_exp_date_map"
    )]
    pub put_exp_date_map: HashMap<String, OptionContractMap>,
}

/// Underlying-security snapshot attached to an [`OptionChain`].
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Underlying {
    /// Best ask, USD.
    #[serde(default, with = "decimal_opt")]
    pub ask: Option<Decimal>,
    /// Best ask size.
    #[serde(rename = "askSize", default)]
    pub ask_size: Option<i64>,
    /// Best bid, USD.
    #[serde(default, with = "decimal_opt")]
    pub bid: Option<Decimal>,
    /// Best bid size.
    #[serde(rename = "bidSize", default)]
    pub bid_size: Option<i64>,
    /// Net change since prior close, USD.
    #[serde(default, with = "decimal_opt")]
    pub change: Option<Decimal>,
    /// Prior session close, USD.
    #[serde(default, with = "decimal_opt")]
    pub close: Option<Decimal>,
    /// `true` if the quote is delayed.
    #[serde(default)]
    pub delayed: Option<bool>,
    /// Underlying description.
    #[serde(default)]
    pub description: Option<String>,
    /// Listing exchange (typed enum specific to chain responses).
    #[serde(rename = "exchangeName", default)]
    pub exchange_name: Option<UnderlyingExchange>,
    /// 52-week high, USD.
    #[serde(rename = "fiftyTwoWeekHigh", default, with = "decimal_opt")]
    pub fifty_two_week_high: Option<Decimal>,
    /// 52-week low, USD.
    #[serde(rename = "fiftyTwoWeekLow", default, with = "decimal_opt")]
    pub fifty_two_week_low: Option<Decimal>,
    /// Day high, USD.
    #[serde(rename = "highPrice", default, with = "decimal_opt")]
    pub high_price: Option<Decimal>,
    /// Last trade, USD.
    #[serde(default, with = "decimal_opt")]
    pub last: Option<Decimal>,
    /// Day low, USD.
    #[serde(rename = "lowPrice", default, with = "decimal_opt")]
    pub low_price: Option<Decimal>,
    /// Mark price, USD.
    #[serde(default, with = "decimal_opt")]
    pub mark: Option<Decimal>,
    /// Mark change since prior close, USD.
    #[serde(rename = "markChange", default, with = "decimal_opt")]
    pub mark_change: Option<Decimal>,
    /// Mark change since prior close as a fraction.
    #[serde(rename = "markPercentChange", default, with = "decimal_opt")]
    pub mark_percent_change: Option<Decimal>,
    /// Day open, USD.
    #[serde(rename = "openPrice", default, with = "decimal_opt")]
    pub open_price: Option<Decimal>,
    /// Net change since prior close as a fraction.
    #[serde(rename = "percentChange", default, with = "decimal_opt")]
    pub percent_change: Option<Decimal>,
    /// Last quote time, epoch milliseconds.
    #[serde(rename = "quoteTime", default)]
    pub quote_time: Option<i64>,
    /// Underlying symbol.
    #[serde(default)]
    pub symbol: Option<String>,
    /// Cumulative session volume.
    #[serde(rename = "totalVolume", default)]
    pub total_volume: Option<i64>,
    /// Last trade time, epoch milliseconds.
    #[serde(rename = "tradeTime", default)]
    pub trade_time: Option<i64>,
}

/// A single option contract within a [`OptionChain`].
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct OptionContract {
    /// Put/call discriminator.
    #[serde(rename = "putCall", default)]
    pub put_call: Option<PutCall>,
    /// OSI option symbol.
    #[serde(default)]
    pub symbol: Option<String>,
    /// Human-readable contract description.
    #[serde(default)]
    pub description: Option<String>,
    /// Exchange display name.
    #[serde(rename = "exchangeName", default)]
    pub exchange_name: Option<String>,
    /// Best bid premium, USD.
    #[serde(rename = "bidPrice", default, with = "decimal_opt")]
    pub bid_price: Option<Decimal>,
    /// Best ask premium, USD.
    #[serde(rename = "askPrice", default, with = "decimal_opt")]
    pub ask_price: Option<Decimal>,
    /// Last trade premium, USD.
    #[serde(rename = "lastPrice", default, with = "decimal_opt")]
    pub last_price: Option<Decimal>,
    /// Mark price, USD.
    #[serde(rename = "markPrice", default, with = "decimal_opt")]
    pub mark_price: Option<Decimal>,
    /// Best bid size (contracts).
    #[serde(rename = "bidSize", default)]
    pub bid_size: Option<i64>,
    /// Best ask size (contracts).
    #[serde(rename = "askSize", default)]
    pub ask_size: Option<i64>,
    /// Last trade size (contracts).
    #[serde(rename = "lastSize", default)]
    pub last_size: Option<i64>,
    /// Day high premium, USD.
    #[serde(rename = "highPrice", default, with = "decimal_opt")]
    pub high_price: Option<Decimal>,
    /// Day low premium, USD.
    #[serde(rename = "lowPrice", default, with = "decimal_opt")]
    pub low_price: Option<Decimal>,
    /// Day open premium, USD.
    #[serde(rename = "openPrice", default, with = "decimal_opt")]
    pub open_price: Option<Decimal>,
    /// Prior session close premium, USD.
    #[serde(rename = "closePrice", default, with = "decimal_opt")]
    pub close_price: Option<Decimal>,
    /// Cumulative session volume (contracts).
    #[serde(rename = "totalVolume", default)]
    pub total_volume: Option<i64>,
    /// Trade date, epoch milliseconds.
    #[serde(rename = "tradeDate", default)]
    pub trade_date: Option<i64>,
    /// Epoch milliseconds. Schwab's published schema mistypes this as a
    /// 32-bit integer; the live API sends a millisecond timestamp.
    #[serde(rename = "quoteTimeInLong", default)]
    pub quote_time_in_long: Option<i64>,
    /// Epoch milliseconds. Same schema mistype as
    /// [`Self::quote_time_in_long`].
    #[serde(rename = "tradeTimeInLong", default)]
    pub trade_time_in_long: Option<i64>,
    /// Net change since prior close, USD.
    #[serde(rename = "netChange", default, with = "decimal_opt")]
    pub net_change: Option<Decimal>,
    /// Implied volatility as a percentage.
    #[serde(default, with = "decimal_opt")]
    pub volatility: Option<Decimal>,
    /// Delta (Black-Scholes).
    #[serde(default, with = "decimal_opt")]
    pub delta: Option<Decimal>,
    /// Gamma (Black-Scholes).
    #[serde(default, with = "decimal_opt")]
    pub gamma: Option<Decimal>,
    /// Theta (Black-Scholes).
    #[serde(default, with = "decimal_opt")]
    pub theta: Option<Decimal>,
    /// Vega (Black-Scholes).
    #[serde(default, with = "decimal_opt")]
    pub vega: Option<Decimal>,
    /// Rho (Black-Scholes).
    #[serde(default, with = "decimal_opt")]
    pub rho: Option<Decimal>,
    /// Extrinsic (time) value, USD.
    #[serde(rename = "timeValue", default, with = "decimal_opt")]
    pub time_value: Option<Decimal>,
    /// Open interest (contracts).
    #[serde(rename = "openInterest", default, with = "decimal_opt")]
    pub open_interest: Option<Decimal>,
    /// `true` if the contract is in the money.
    #[serde(rename = "isInTheMoney", default)]
    pub is_in_the_money: Option<bool>,
    /// Theoretical fair value from Schwab's pricing model, USD.
    #[serde(rename = "theoreticalOptionValue", default, with = "decimal_opt")]
    pub theoretical_option_value: Option<Decimal>,
    /// Theoretical volatility used in the pricing model.
    #[serde(rename = "theoreticalVolatility", default, with = "decimal_opt")]
    pub theoretical_volatility: Option<Decimal>,
    /// `true` if the contract is a mini option (smaller deliverable).
    #[serde(rename = "isMini", default)]
    pub is_mini: Option<bool>,
    /// `true` for non-standard contracts (corporate-action-adjusted, etc.).
    #[serde(rename = "isNonStandard", default)]
    pub is_non_standard: Option<bool>,
    /// Deliverables backing the contract.
    #[serde(rename = "optionDeliverablesList", default)]
    pub option_deliverables_list: Vec<OptionDeliverables>,
    /// Strike price, USD.
    #[serde(rename = "strikePrice", default, with = "decimal_opt")]
    pub strike_price: Option<Decimal>,
    /// `yyyy-MM-dd'T'HH:mm:ss` expiration timestamp string.
    #[serde(rename = "expirationDate", default)]
    pub expiration_date: Option<String>,
    /// Calendar days until expiration.
    #[serde(rename = "daysToExpiration", default)]
    pub days_to_expiration: Option<i32>,
    /// Expiration classification (standard/weekly/quarterly/...).
    #[serde(rename = "expirationType", default)]
    pub expiration_type: Option<ExpirationType>,
    /// Last trading day, epoch milliseconds.
    #[serde(rename = "lastTradingDay", default)]
    pub last_trading_day: Option<i64>,
    /// Shares-per-contract multiplier (typically 100).
    #[serde(default, with = "decimal_opt")]
    pub multiplier: Option<Decimal>,
    /// AM/PM settlement.
    #[serde(rename = "settlementType", default)]
    pub settlement_type: Option<SettlementType>,
    /// Free-form note Schwab attaches to the deliverable.
    #[serde(rename = "deliverableNote", default)]
    pub deliverable_note: Option<String>,
    /// `true` for index options.
    #[serde(rename = "isIndexOption", default)]
    pub is_index_option: Option<bool>,
    /// Net change since prior close as a fraction.
    #[serde(rename = "percentChange", default, with = "decimal_opt")]
    pub percent_change: Option<Decimal>,
    /// Mark change since prior close, USD.
    #[serde(rename = "markChange", default, with = "decimal_opt")]
    pub mark_change: Option<Decimal>,
    /// Mark change since prior close as a fraction.
    #[serde(rename = "markPercentChange", default, with = "decimal_opt")]
    pub mark_percent_change: Option<Decimal>,
    /// `true` if the contract is in the SEC Penny Pilot program.
    #[serde(rename = "isPennyPilot", default)]
    pub is_penny_pilot: Option<bool>,
    /// Intrinsic value, USD.
    #[serde(rename = "intrinsicValue", default, with = "decimal_opt")]
    pub intrinsic_value: Option<Decimal>,
    /// Option root symbol (the underlying's OSI root).
    #[serde(rename = "optionRoot", default)]
    pub option_root: Option<String>,
}

/// One deliverable backing an option contract.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct OptionDeliverables {
    /// Symbol of the deliverable.
    #[serde(default)]
    pub symbol: Option<String>,
    /// Asset class of the deliverable (kept as a string here; the value
    /// space differs from [`crate::accounts::AssetType`]).
    #[serde(rename = "assetType", default)]
    pub asset_type: Option<String>,
    /// Number of units delivered.
    // Schwab's spec types this as a string, but the live API sends a number.
    // `float_option` accepts either form.
    #[serde(rename = "deliverableUnits", default, with = "decimal_opt")]
    pub deliverable_units: Option<Decimal>,
    /// Settlement currency code.
    #[serde(rename = "currencyType", default)]
    pub currency_type: Option<String>,
}

// --- Enums ---

string_enum! {
    /// `contractType` query value.
    ContractType {
        /// Calls only.
        Call = "CALL",
        /// Puts only.
        Put = "PUT",
        /// Both calls and puts.
        All = "ALL",
    }
}

string_enum! {
    /// Option chain `strategy`. Used both as a `strategy` query value and
    /// in the [`OptionChain::strategy`] response field.
    OptionStrategy {
        /// Standalone contracts (default).
        Single = "SINGLE",
        /// Theoretical pricing with caller-supplied vol/rate/underlying.
        Analytical = "ANALYTICAL",
        /// Covered (call/put + underlying) combinations.
        Covered = "COVERED",
        /// Vertical spreads.
        Vertical = "VERTICAL",
        /// Calendar (horizontal) spreads.
        Calendar = "CALENDAR",
        /// Strangles.
        Strangle = "STRANGLE",
        /// Straddles.
        Straddle = "STRADDLE",
        /// Butterflies.
        Butterfly = "BUTTERFLY",
        /// Condors.
        Condor = "CONDOR",
        /// Diagonal spreads.
        Diagonal = "DIAGONAL",
        /// Collars.
        Collar = "COLLAR",
        /// Roll combinations.
        Roll = "ROLL",
    }
}

string_enum! {
    /// `range` query value - the moneyness window of the chain.
    OptionRange {
        /// In the money.
        Itm = "ITM",
        /// Near the money.
        Ntm = "NTM",
        /// Out of the money.
        Otm = "OTM",
        /// Strikes above market.
        Sak = "SAK",
        /// Strikes below market.
        Sbk = "SBK",
        /// Strikes near market.
        Snk = "SNK",
        /// All strikes (no moneyness filter).
        All = "ALL",
    }
}

string_enum! {
    /// `expMonth` query value.
    ExpirationMonth {
        /// January.
        Jan = "JAN",
        /// February.
        Feb = "FEB",
        /// March.
        Mar = "MAR",
        /// April.
        Apr = "APR",
        /// May.
        May = "MAY",
        /// June.
        Jun = "JUN",
        /// July.
        Jul = "JUL",
        /// August.
        Aug = "AUG",
        /// September.
        Sep = "SEP",
        /// October.
        Oct = "OCT",
        /// November.
        Nov = "NOV",
        /// December.
        Dec = "DEC",
        /// All months (no month filter).
        All = "ALL",
    }
}

string_enum! {
    /// `optionType` query value.
    OptionType {
        /// Standard (non-adjusted) contracts only.
        Standard = "S",
        /// Non-standard (e.g. corporate-action-adjusted) contracts only.
        NonStandard = "NS",
    }
}

string_enum! {
    /// `entitlement` query value, applicable only to retail tokens.
    Entitlement {
        /// Paying professional.
        PayingPro = "PP",
        /// Non-professional.
        NonPro = "NP",
        /// Non-paying professional.
        NonPayingPro = "PN",
    }
}

string_enum! {
    /// Put/call discriminator on an [`OptionContract`].
    PutCall {
        /// Put.
        Put = "PUT",
        /// Call.
        Call = "CALL",
    }
}

string_enum! {
    /// Exchange of the [`Underlying`] security.
    UnderlyingExchange {
        /// Index (no listing exchange).
        Ind = "IND",
        /// NYSE American (formerly AMEX).
        Ase = "ASE",
        /// New York Stock Exchange.
        Nys = "NYS",
        /// Nasdaq.
        Nas = "NAS",
        /// Nasdaq Capital Market.
        Nap = "NAP",
        /// Pacific Stock Exchange / NYSE Arca.
        Pac = "PAC",
        /// OCC Options Price Reporting Authority.
        Opr = "OPR",
        /// BATS Global Markets.
        Bats = "BATS",
    }
}

string_enum! {
    /// Option expiration calendar cycle. `M` end-of-month, `Q` quarterly,
    /// `S` standard (3rd-Friday) and `W` weekly.
    ExpirationType {
        /// End-of-month expiration.
        EndOfMonth = "M",
        /// Quarterly expiration.
        Quarterly = "Q",
        /// Standard 3rd-Friday monthly expiration.
        Standard = "S",
        /// Weekly expiration.
        Weekly = "W",
    }
}

string_enum! {
    /// Option contract settlement time.
    SettlementType {
        /// AM settlement.
        Am = "A",
        /// PM settlement.
        Pm = "P",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn option_chain_parses() {
        // Shape modeled on Schwab's documented response: underlying
        // snapshot plus a callExpDateMap with one expiration and one
        // strike. The per-strike value is a list of contracts.
        let json = r#"{
            "symbol": "AAPL",
            "status": "SUCCESS",
            "strategy": "SINGLE",
            "isDelayed": false,
            "isIndex": false,
            "interestRate": 4.85,
            "underlyingPrice": 150.25,
            "volatility": 29.0,
            "underlying": {
                "symbol": "AAPL",
                "description": "Apple Inc",
                "bid": 150.20,
                "ask": 150.30,
                "last": 150.25,
                "exchangeName": "NAS",
                "totalVolume": 50000000,
                "quoteTime": 1710432000000
            },
            "callExpDateMap": {
                "2024-01-19:5": {
                    "150.0": [
                        {
                            "putCall": "CALL",
                            "symbol": "AAPL  240119C00150000",
                            "description": "AAPL 01/19/2024 150.00 C",
                            "bidPrice": 2.10,
                            "askPrice": 2.20,
                            "lastPrice": 2.15,
                            "delta": 0.52,
                            "gamma": 0.08,
                            "theta": -0.04,
                            "vega": 0.11,
                            "rho": 0.02,
                            "openInterest": 12000.0,
                            "strikePrice": 150.0,
                            "expirationDate": "2024-01-19T00:00:00.000+00:00",
                            "daysToExpiration": 5,
                            "expirationType": "W",
                            "settlementType": "P",
                            "lastTradingDay": 1705622400000,
                            "isInTheMoney": true,
                            "totalVolume": 3400
                        }
                    ]
                }
            },
            "putExpDateMap": {}
        }"#;
        let chain: OptionChain = serde_json::from_str(json).unwrap();
        assert_eq!(chain.symbol.as_deref(), Some("AAPL"));
        assert_eq!(chain.strategy, Some(OptionStrategy::Single));
        assert_eq!(chain.underlying_price, Some(dec!(150.25)));

        let underlying = chain.underlying.as_ref().unwrap();
        assert_eq!(underlying.exchange_name, Some(UnderlyingExchange::Nas));
        assert_eq!(underlying.total_volume, Some(50000000));

        let exp = chain.call_exp_date_map.get("2024-01-19:5").unwrap();
        let strike = exp.get("150.0").unwrap();
        assert_eq!(strike.len(), 1);

        let contract = &strike[0];
        assert_eq!(contract.put_call, Some(PutCall::Call));
        assert_eq!(contract.bid_price, Some(dec!(2.10)));
        assert_eq!(contract.delta, Some(dec!(0.52)));
        assert_eq!(contract.open_interest, Some(dec!(12000.0)));
        assert_eq!(contract.strike_price, Some(dec!(150.0)));
        assert_eq!(contract.days_to_expiration, Some(5));
        assert_eq!(contract.expiration_type, Some(ExpirationType::Weekly));
        assert_eq!(contract.settlement_type, Some(SettlementType::Pm));
        assert_eq!(contract.last_trading_day, Some(1705622400000));
        assert_eq!(contract.is_in_the_money, Some(true));

        assert!(chain.put_exp_date_map.is_empty());
    }

    #[test]
    fn per_strike_array_form_is_accepted() {
        // Array shape: the per-strike value is a list of contracts. This
        // fixture carries two contracts at one strike to confirm the full
        // list is retained.
        let json = r#"{
            "callExpDateMap": {
                "2024-01-19:5": {
                    "150.0": [
                        { "symbol": "AAPL  240119C00150000", "putCall": "CALL" },
                        { "symbol": "AAPL  240119C00150000-MINI", "putCall": "CALL", "isMini": true }
                    ]
                }
            }
        }"#;
        let chain: OptionChain = serde_json::from_str(json).unwrap();
        let strike = chain
            .call_exp_date_map
            .get("2024-01-19:5")
            .unwrap()
            .get("150.0")
            .unwrap();
        assert_eq!(strike.len(), 2);
        assert_eq!(strike[1].is_mini, Some(true));
    }

    #[test]
    fn per_strike_single_object_form_is_accepted() {
        // Single-object shape (Schwab's published schema): the per-strike
        // value is one contract rather than an array. It is normalized to
        // a one-element list. Both maps are exercised to confirm each
        // field uses the tolerant path.
        let json = r#"{
            "callExpDateMap": {
                "2024-01-19:5": {
                    "150.0": { "symbol": "AAPL  240119C00150000", "putCall": "CALL", "bidPrice": 2.10 }
                }
            },
            "putExpDateMap": {
                "2024-01-19:5": {
                    "150.0": { "symbol": "AAPL  240119P00150000", "putCall": "PUT" }
                }
            }
        }"#;
        let chain: OptionChain = serde_json::from_str(json).unwrap();

        let call = chain
            .call_exp_date_map
            .get("2024-01-19:5")
            .unwrap()
            .get("150.0")
            .unwrap();
        assert_eq!(call.len(), 1);
        assert_eq!(call[0].bid_price, Some(dec!(2.10)));

        let put = chain
            .put_exp_date_map
            .get("2024-01-19:5")
            .unwrap()
            .get("150.0")
            .unwrap();
        assert_eq!(put.len(), 1);
        assert_eq!(put[0].put_call, Some(PutCall::Put));
    }

    #[test]
    fn empty_option_chain_parses() {
        let chain: OptionChain = serde_json::from_str("{}").unwrap();
        assert!(chain.call_exp_date_map.is_empty());
        assert!(chain.put_exp_date_map.is_empty());
        assert!(chain.underlying.is_none());
    }

    #[test]
    fn contract_type_round_trips_known_variants() {
        for raw in ["CALL", "PUT", "ALL"] {
            let json = format!(r#""{raw}""#);
            let parsed: ContractType = serde_json::from_str(&json).unwrap();
            assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
        }
    }

    #[test]
    fn option_strategy_round_trips_known_variants() {
        for raw in [
            "SINGLE",
            "ANALYTICAL",
            "COVERED",
            "VERTICAL",
            "CALENDAR",
            "STRANGLE",
            "STRADDLE",
            "BUTTERFLY",
            "CONDOR",
            "DIAGONAL",
            "COLLAR",
            "ROLL",
        ] {
            let json = format!(r#""{raw}""#);
            let parsed: OptionStrategy = serde_json::from_str(&json).unwrap();
            assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
        }
    }

    #[test]
    fn expiration_type_round_trips_single_letter_codes() {
        for raw in ["M", "Q", "S", "W"] {
            let json = format!(r#""{raw}""#);
            let parsed: ExpirationType = serde_json::from_str(&json).unwrap();
            assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
        }
    }

    #[test]
    fn settlement_type_round_trips_single_letter_codes() {
        for raw in ["A", "P"] {
            let json = format!(r#""{raw}""#);
            let parsed: SettlementType = serde_json::from_str(&json).unwrap();
            assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
        }
    }

    #[test]
    fn unknown_option_strategy_preserves_raw_string() {
        let parsed: OptionStrategy = serde_json::from_str(r#""IRON_CONDOR""#).unwrap();
        assert!(matches!(parsed, OptionStrategy::Unknown(ref s) if s == "IRON_CONDOR"));
    }
}