alpaca-sdk 0.0.0

Unofficial Rust SDK for the Alpaca trading, market data, and broker APIs
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
//! Request types for the market data API, ported from `alpaca/data/requests.py`.

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};

use crate::data::enums::{
    Adjustment, CorporateActionsType, DataFeed, MarketType, MostActivesBy, OptionsFeed,
};
use crate::data::timeframe::TimeFrame;

use crate::types::serde_util::comma_separated;
use crate::types::{ContractType, Sort, SupportedCurrencies};

/// One symbol or several.
///
/// alpaca-py types this `Union[str, List[str]]` and renames it to `symbols`,
/// comma-joined, in `NonEmptyRequest::to_request_fields`.
///
/// ```
/// # use alpaca_sdk::data::Symbols;
/// let one: Symbols = "AAPL".into();
/// let many: Symbols = vec!["AAPL", "SPY"].into();
///
/// assert_eq!(one.to_string(), "AAPL");
/// assert_eq!(many.to_string(), "AAPL,SPY");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Symbols(Vec<String>);

impl Symbols {
    /// The symbols as a slice.
    #[must_use]
    pub fn as_slice(&self) -> &[String] {
        &self.0
    }

    /// Whether no symbols were given.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl std::fmt::Display for Symbols {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0.join(","))
    }
}

impl From<&str> for Symbols {
    fn from(symbol: &str) -> Self {
        Self(vec![symbol.to_owned()])
    }
}

impl From<String> for Symbols {
    fn from(symbol: String) -> Self {
        Self(vec![symbol])
    }
}

impl From<Vec<String>> for Symbols {
    fn from(symbols: Vec<String>) -> Self {
        Self(symbols)
    }
}

impl From<Vec<&str>> for Symbols {
    fn from(symbols: Vec<&str>) -> Self {
        Self(symbols.into_iter().map(ToOwned::to_owned).collect())
    }
}

impl<const N: usize> From<[&str; N]> for Symbols {
    fn from(symbols: [&str; N]) -> Self {
        Self(symbols.iter().map(|s| (*s).to_owned()).collect())
    }
}

/// Fields shared by every historical time series request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeseriesRequest {
    /// The symbols to query, sent as one comma-separated `symbols` parameter.
    #[serde(rename = "symbols")]
    pub symbol_or_symbols: Symbols,
    /// The earliest timestamp to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<DateTime<Utc>>,
    /// The latest timestamp to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end: Option<DateTime<Utc>>,
    /// Maximum number of items across all pages.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// The currency to denominate prices in, for local currency trading.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<SupportedCurrencies>,
    /// Chronological ordering of the response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sort: Option<Sort>,
}

impl TimeseriesRequest {
    /// A request for `symbols` with no other filters.
    pub fn new(symbols: impl Into<Symbols>) -> Self {
        Self {
            symbol_or_symbols: symbols.into(),
            start: None,
            end: None,
            limit: None,
            currency: None,
            sort: None,
        }
    }

    /// Restricts the window to `start` onwards.
    #[must_use]
    pub fn start(mut self, start: DateTime<Utc>) -> Self {
        self.start = Some(start);
        self
    }

    /// Restricts the window to before `end`.
    #[must_use]
    pub fn end(mut self, end: DateTime<Utc>) -> Self {
        self.end = Some(end);
        self
    }

    /// Caps the total number of items returned across all pages.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the chronological ordering.
    #[must_use]
    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = Some(sort);
        self
    }

    /// Sets the denominating currency.
    #[must_use]
    pub fn currency(mut self, currency: SupportedCurrencies) -> Self {
        self.currency = Some(currency);
        self
    }
}

/// Historical bars for stocks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StockBarsRequest {
    /// The shared time series filters.
    #[serde(flatten)]
    pub base: TimeseriesRequest,
    /// The bar interval.
    pub timeframe: TimeFrame,
    /// How corporate actions are reflected in prices.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub adjustment: Option<Adjustment>,
    /// Which data feed to read from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feed: Option<DataFeed>,
    /// The as-of date for symbol mapping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asof: Option<String>,
}

impl StockBarsRequest {
    /// Bars for `symbols` at `timeframe`.
    pub fn new(symbols: impl Into<Symbols>, timeframe: TimeFrame) -> Self {
        Self {
            base: TimeseriesRequest::new(symbols),
            timeframe,
            adjustment: None,
            feed: None,
            asof: None,
        }
    }

    /// Sets the corporate action adjustment.
    #[must_use]
    pub fn adjustment(mut self, adjustment: Adjustment) -> Self {
        self.adjustment = Some(adjustment);
        self
    }

    /// Sets the data feed.
    #[must_use]
    pub fn feed(mut self, feed: DataFeed) -> Self {
        self.feed = Some(feed);
        self
    }
}

/// Historical bars for crypto.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CryptoBarsRequest {
    /// The shared time series filters.
    #[serde(flatten)]
    pub base: TimeseriesRequest,
    /// The bar interval.
    pub timeframe: TimeFrame,
}

impl CryptoBarsRequest {
    /// Bars for `symbols` at `timeframe`.
    pub fn new(symbols: impl Into<Symbols>, timeframe: TimeFrame) -> Self {
        Self {
            base: TimeseriesRequest::new(symbols),
            timeframe,
        }
    }
}

/// Historical bars for options.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OptionBarsRequest {
    /// The shared time series filters.
    #[serde(flatten)]
    pub base: TimeseriesRequest,
    /// The bar interval.
    pub timeframe: TimeFrame,
}

impl OptionBarsRequest {
    /// Bars for `symbols` at `timeframe`.
    pub fn new(symbols: impl Into<Symbols>, timeframe: TimeFrame) -> Self {
        Self {
            base: TimeseriesRequest::new(symbols),
            timeframe,
        }
    }
}

/// Historical quotes or trades for stocks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StockTimeseriesRequest {
    /// The shared time series filters.
    #[serde(flatten)]
    pub base: TimeseriesRequest,
    /// Which data feed to read from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feed: Option<DataFeed>,
    /// The as-of date for symbol mapping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asof: Option<String>,
}

impl StockTimeseriesRequest {
    /// A request for `symbols`.
    pub fn new(symbols: impl Into<Symbols>) -> Self {
        Self {
            base: TimeseriesRequest::new(symbols),
            feed: None,
            asof: None,
        }
    }

    /// Sets the data feed.
    #[must_use]
    pub fn feed(mut self, feed: DataFeed) -> Self {
        self.feed = Some(feed);
        self
    }
}

/// Generates delegating setters for requests that wrap [`TimeseriesRequest`],
/// so callers write `.limit(50)` rather than reaching into `.base`.
macro_rules! timeseries_delegates {
    ($ty:ty) => {
        impl $ty {
            /// Restricts the window to `start` onwards.
            #[must_use]
            pub fn start(mut self, start: DateTime<Utc>) -> Self {
                self.base = self.base.start(start);
                self
            }

            /// Restricts the window to before `end`.
            #[must_use]
            pub fn end(mut self, end: DateTime<Utc>) -> Self {
                self.base = self.base.end(end);
                self
            }

            /// Caps the total number of items returned across all pages.
            #[must_use]
            pub fn limit(mut self, limit: u32) -> Self {
                self.base = self.base.limit(limit);
                self
            }

            /// Sets the chronological ordering.
            #[must_use]
            pub fn sort(mut self, sort: Sort) -> Self {
                self.base = self.base.sort(sort);
                self
            }

            /// Sets the denominating currency.
            #[must_use]
            pub fn currency(mut self, currency: SupportedCurrencies) -> Self {
                self.base = self.base.currency(currency);
                self
            }
        }
    };
}

timeseries_delegates!(StockBarsRequest);
timeseries_delegates!(CryptoBarsRequest);
timeseries_delegates!(OptionBarsRequest);
timeseries_delegates!(StockTimeseriesRequest);

/// A request for the most recent stock data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StockLatestRequest {
    /// The symbols to query.
    #[serde(rename = "symbols")]
    pub symbol_or_symbols: Symbols,
    /// Which data feed to read from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feed: Option<DataFeed>,
    /// The currency to denominate prices in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<SupportedCurrencies>,
}

impl StockLatestRequest {
    /// The latest data for `symbols`.
    pub fn new(symbols: impl Into<Symbols>) -> Self {
        Self {
            symbol_or_symbols: symbols.into(),
            feed: None,
            currency: None,
        }
    }

    /// Sets the data feed.
    #[must_use]
    pub fn feed(mut self, feed: DataFeed) -> Self {
        self.feed = Some(feed);
        self
    }
}

/// A request for the most recent crypto data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CryptoLatestRequest {
    /// The symbols to query.
    #[serde(rename = "symbols")]
    pub symbol_or_symbols: Symbols,
}

impl CryptoLatestRequest {
    /// The latest data for `symbols`.
    pub fn new(symbols: impl Into<Symbols>) -> Self {
        Self {
            symbol_or_symbols: symbols.into(),
        }
    }
}

/// A request for the most recent option data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OptionLatestRequest {
    /// The symbols to query.
    #[serde(rename = "symbols")]
    pub symbol_or_symbols: Symbols,
    /// Which data feed to read from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feed: Option<OptionsFeed>,
}

impl OptionLatestRequest {
    /// The latest data for `symbols`.
    pub fn new(symbols: impl Into<Symbols>) -> Self {
        Self {
            symbol_or_symbols: symbols.into(),
            feed: None,
        }
    }

    /// Sets the data feed.
    #[must_use]
    pub fn feed(mut self, feed: OptionsFeed) -> Self {
        self.feed = Some(feed);
        self
    }
}

/// A request for stock snapshots.
pub type StockSnapshotRequest = StockLatestRequest;

/// A request for crypto snapshots.
pub type CryptoSnapshotRequest = CryptoLatestRequest;

/// A request for option snapshots.
pub type OptionSnapshotRequest = OptionLatestRequest;

/// A request for every contract in an underlying's option chain.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OptionChainRequest {
    /// The underlying symbol.
    ///
    /// Goes in the path rather than the query string, so it is skipped when
    /// serializing.
    #[serde(skip)]
    pub underlying_symbol: String,
    /// Which data feed to read from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feed: Option<OptionsFeed>,
    /// Only calls or only puts.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub contract_type: Option<ContractType>,
    /// Only contracts struck at or above this price.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strike_price_gte: Option<f64>,
    /// Only contracts struck at or below this price.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strike_price_lte: Option<f64>,
    /// Only contracts expiring on this date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date: Option<NaiveDate>,
    /// Only contracts expiring on or after this date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date_gte: Option<NaiveDate>,
    /// Only contracts expiring on or before this date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date_lte: Option<NaiveDate>,
    /// Only contracts with this root symbol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_symbol: Option<String>,
    /// Only contracts updated since this time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated_since: Option<DateTime<Utc>>,
}

impl OptionChainRequest {
    /// The chain for `underlying_symbol`.
    pub fn new(underlying_symbol: impl Into<String>) -> Self {
        Self {
            underlying_symbol: underlying_symbol.into(),
            feed: None,
            contract_type: None,
            strike_price_gte: None,
            strike_price_lte: None,
            expiration_date: None,
            expiration_date_gte: None,
            expiration_date_lte: None,
            root_symbol: None,
            updated_since: None,
        }
    }

    /// Restricts to calls or puts.
    #[must_use]
    pub fn contract_type(mut self, contract_type: ContractType) -> Self {
        self.contract_type = Some(contract_type);
        self
    }

    /// Sets the data feed.
    #[must_use]
    pub fn feed(mut self, feed: OptionsFeed) -> Self {
        self.feed = Some(feed);
        self
    }
}

/// A request for the most actively traded stocks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MostActivesRequest {
    /// How many to return.
    pub top: u32,
    /// What to rank by.
    pub by: MostActivesBy,
}

impl MostActivesRequest {
    /// The top `top` symbols ranked by `by`.
    #[must_use]
    pub fn new(top: u32, by: MostActivesBy) -> Self {
        Self { top, by }
    }
}

impl Default for MostActivesRequest {
    fn default() -> Self {
        // alpaca-py defaults to the top 10 by volume.
        Self {
            top: 10,
            by: MostActivesBy::Volume,
        }
    }
}

fn default_market_type() -> MarketType {
    MarketType::Stocks
}

/// A request for the day's biggest movers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MarketMoversRequest {
    /// How many of each direction to return.
    pub top: u32,
    /// Which market to rank.
    ///
    /// Goes in the path rather than the query string.
    #[serde(skip_serializing, default = "default_market_type")]
    pub market_type: MarketType,
}

impl MarketMoversRequest {
    /// The top `top` movers in `market_type`.
    #[must_use]
    pub fn new(top: u32, market_type: MarketType) -> Self {
        Self { top, market_type }
    }
}

impl Default for MarketMoversRequest {
    fn default() -> Self {
        Self {
            top: 10,
            market_type: MarketType::Stocks,
        }
    }
}

/// A request for news articles.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NewsRequest {
    /// The earliest article to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<DateTime<Utc>>,
    /// The latest article to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end: Option<DateTime<Utc>>,
    /// Chronological ordering of the response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sort: Option<Sort>,
    /// Only articles mentioning these symbols.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "comma_separated"
    )]
    pub symbols: Option<Vec<String>>,
    /// Maximum number of articles across all pages.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Whether to include the article body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_content: Option<bool>,
    /// Whether to drop articles with no body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exclude_contentless: Option<bool>,
    /// Token for resuming a manual pagination.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,
}

impl NewsRequest {
    /// A request with no filters.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Only articles mentioning these symbols.
    #[must_use]
    pub fn symbols(mut self, symbols: Vec<String>) -> Self {
        self.symbols = Some(symbols);
        self
    }

    /// Caps the total number of articles returned.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }
}

/// A request for corporate actions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CorporateActionsRequest {
    /// Only actions for these symbols.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "comma_separated"
    )]
    pub symbols: Option<Vec<String>>,
    /// Only actions for these CUSIPs.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "comma_separated"
    )]
    pub cusips: Option<Vec<String>>,
    /// Only actions of these kinds.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "comma_separated"
    )]
    pub types: Option<Vec<CorporateActionsType>>,
    /// The earliest date to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<NaiveDate>,
    /// The latest date to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end: Option<NaiveDate>,
    /// Only actions with these ids.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "comma_separated"
    )]
    pub ids: Option<Vec<String>>,
    /// Maximum number of actions across all pages.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Chronological ordering of the response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sort: Option<Sort>,
}

impl CorporateActionsRequest {
    /// A request with alpaca-py's defaults: 1,000 items, ascending.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Only actions for these symbols.
    #[must_use]
    pub fn symbols(mut self, symbols: Vec<String>) -> Self {
        self.symbols = Some(symbols);
        self
    }

    /// Only actions of these kinds.
    #[must_use]
    pub fn types(mut self, types: Vec<CorporateActionsType>) -> Self {
        self.types = Some(types);
        self
    }

    /// Restricts the date window.
    #[must_use]
    pub fn between(mut self, start: NaiveDate, end: NaiveDate) -> Self {
        self.start = Some(start);
        self.end = Some(end);
        self
    }
}

impl Default for CorporateActionsRequest {
    fn default() -> Self {
        Self {
            symbols: None,
            cusips: None,
            types: None,
            start: None,
            end: None,
            ids: None,
            limit: Some(1000),
            sort: Some(Sort::Asc),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::timeframe::TimeFrameUnit;

    #[test]
    fn symbols_render_as_one_comma_separated_parameter() {
        let request = TimeseriesRequest::new(["AAPL", "SPY"]);
        let json = serde_json::to_value(&request).unwrap();

        // symbol_or_symbols is renamed to `symbols` and joined, which is what
        // NonEmptyRequest::to_request_fields does in alpaca-py.
        assert_eq!(json["symbols"], serde_json::json!(["AAPL", "SPY"]));
        assert_eq!(request.symbol_or_symbols.to_string(), "AAPL,SPY");
    }

    #[test]
    fn a_single_symbol_is_accepted_without_a_vec() {
        let request = TimeseriesRequest::new("AAPL");
        assert_eq!(request.symbol_or_symbols.as_slice(), ["AAPL"]);
    }

    #[test]
    fn unset_filters_are_omitted() {
        let json = serde_json::to_value(TimeseriesRequest::new("AAPL")).unwrap();
        let object = json.as_object().unwrap();

        assert_eq!(object.len(), 1, "{object:?}");
        assert!(object.contains_key("symbols"));
    }

    #[test]
    fn bars_flatten_the_shared_filters_alongside_the_timeframe() {
        let request =
            StockBarsRequest::new("AAPL", TimeFrame::new(5, TimeFrameUnit::Minute).unwrap())
                .feed(DataFeed::Iex);
        let json = serde_json::to_value(&request).unwrap();

        assert_eq!(json["symbols"], serde_json::json!(["AAPL"]));
        assert_eq!(json["timeframe"], "5Min");
        assert_eq!(json["feed"], "iex");
    }

    #[test]
    fn option_chain_keeps_the_underlying_out_of_the_query() {
        // It goes in the path instead.
        let request = OptionChainRequest::new("AAPL").contract_type(ContractType::Call);
        let json = serde_json::to_value(&request).unwrap();

        assert!(json.get("underlying_symbol").is_none());
        assert_eq!(json["type"], "call");
    }

    #[test]
    fn market_movers_keeps_the_market_type_out_of_the_query() {
        let request = MarketMoversRequest::new(5, MarketType::Crypto);
        let json = serde_json::to_value(&request).unwrap();

        assert!(json.get("market_type").is_none());
        assert_eq!(json["top"], 5);
    }

    #[test]
    fn corporate_actions_defaults_match_alpaca_py() {
        let request = CorporateActionsRequest::new();
        assert_eq!(request.limit, Some(1000));
        assert_eq!(request.sort, Some(Sort::Asc));
    }

    #[test]
    fn most_actives_defaults_to_ten_by_volume() {
        let request = MostActivesRequest::default();
        assert_eq!(request.top, 10);
        assert_eq!(request.by, MostActivesBy::Volume);
    }
}