schwab 0.2.3

Unofficial Rust client library for the Schwab API, unaffiliated with Schwab brokerage or thinkorswim
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
use std::collections::HashMap;

use reqwest::Method;
use tracing::instrument;

use crate::client::ApiBase;
use crate::models::market_data::{
    CandleList, ExpirationChain, Hours, InstrumentResponse, InstrumentsResponse, OptionChain,
    ScreenerResponse,
};
use crate::query::{
    comma_separated_required, comma_separated_symbols, push_optional, required_text,
};
use crate::{
    Client, MoverOptions, OptionChainOptions, PriceHistoryOptions, QuoteOptions, Quotes, Result,
};

impl Client {
    /// Fetches quotes for a list of symbols.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::EmptySymbols`] if all provided symbols are empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let quotes = client.get_quotes(["AAPL", "MSFT"]).await?;
    /// for (symbol, quote) in &quotes {
    ///     println!("{symbol}: {quote:?}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_quotes<S>(&self, symbols: impl IntoIterator<Item = S>) -> Result<Quotes>
    where
        S: AsRef<str>,
    {
        self.get_quotes_with_options(symbols, QuoteOptions::default())
            .await
    }

    /// Fetches quotes with optional OpenAPI query parameters.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::EmptySymbols`] if all provided symbols are empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config, QuoteOptions};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let quotes = client
    ///     .get_quotes_with_options(
    ///         ["AAPL"],
    ///         QuoteOptions::new().fields("quote,reference").indicative(true),
    ///     )
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_quotes_with_options<S>(
        &self,
        symbols: impl IntoIterator<Item = S>,
        options: QuoteOptions,
    ) -> Result<Quotes>
    where
        S: AsRef<str>,
    {
        let symbols = comma_separated_symbols(symbols)?;
        let url = self.endpoint_url(ApiBase::MarketData, &["quotes"])?;
        let mut query = vec![("symbols", symbols)];
        push_optional(&mut query, "fields", options.fields);
        if options.indicative {
            query.push(("indicative", options.indicative.to_string()));
        }
        self.send_json(Method::GET, url, &query, None).await
    }

    /// Fetches the single-symbol quote endpoint from `GET /{symbol_id}/quotes`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `symbol_id` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let quotes = client.get_quote("AAPL", Some("quote,reference")).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_quote(
        &self,
        symbol_id: impl AsRef<str>,
        fields: Option<&str>,
    ) -> Result<Quotes> {
        let symbol_id = required_text("symbol_id", symbol_id.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &[&symbol_id, "quotes"])?;
        let mut query = Vec::new();
        push_optional(&mut query, "fields", fields);
        self.send_json(Method::GET, url, &query, None).await
    }

    /// Fetches an option chain from `GET /chains`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if the symbol is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config, OptionChainOptions};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let chain = client
    ///     .get_option_chain(
    ///         OptionChainOptions::new("AAPL")
    ///             .parameter("contractType", "CALL")
    ///             .integer_parameter("strikeCount", 5),
    ///     )
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_option_chain(&self, options: OptionChainOptions) -> Result<OptionChain> {
        required_text("symbol", &options.symbol)?;
        let url = self.endpoint_url(ApiBase::MarketData, &["chains"])?;
        self.send_json(Method::GET, url, &options.into_query(), None)
            .await
    }

    /// Fetches option expirations from `GET /expirationchain`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `symbol` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let expirations = client.get_expiration_chain("AAPL").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_expiration_chain(&self, symbol: impl AsRef<str>) -> Result<ExpirationChain> {
        let symbol = required_text("symbol", symbol.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &["expirationchain"])?;
        self.send_json(Method::GET, url, &[("symbol", symbol.to_owned())], None)
            .await
    }

    /// Searches instruments from `GET /instruments`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `symbol` or `projection` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let results = client.get_instruments("AAPL", "symbol-search").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_instruments(
        &self,
        symbol: impl AsRef<str>,
        projection: impl AsRef<str>,
    ) -> Result<InstrumentsResponse> {
        let symbol = required_text("symbol", symbol.as_ref())?;
        let projection = required_text("projection", projection.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &["instruments"])?;
        self.send_json(
            Method::GET,
            url,
            &[
                ("symbol", symbol.to_owned()),
                ("projection", projection.to_owned()),
            ],
            None,
        )
        .await
    }

    /// Fetches a single instrument from `GET /instruments/{cusip_id}`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `cusip_id` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let instrument = client.get_instrument_by_cusip("037833100").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_instrument_by_cusip(
        &self,
        cusip_id: impl AsRef<str>,
    ) -> Result<InstrumentResponse> {
        let cusip_id = required_text("cusip_id", cusip_id.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &["instruments", &cusip_id])?;
        self.send_json(Method::GET, url, &[], None).await
    }

    /// Fetches market hours from `GET /markets`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if all market values are empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let hours = client
    ///     .get_market_hours(["equity", "option"], Some("2024-01-02"))
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_market_hours<S>(
        &self,
        markets: impl IntoIterator<Item = S>,
        date: Option<&str>,
    ) -> Result<HashMap<String, HashMap<String, Hours>>>
    where
        S: AsRef<str>,
    {
        let markets = comma_separated_required("markets", markets)?;
        let url = self.endpoint_url(ApiBase::MarketData, &["markets"])?;
        let mut query = vec![("markets", markets)];
        push_optional(&mut query, "date", date);
        self.send_json(Method::GET, url, &query, None).await
    }

    /// Fetches market hours from `GET /markets/{market_id}`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `market_id` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let hours = client.get_market_hour("equity", Some("2024-01-02")).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_market_hour(
        &self,
        market_id: impl AsRef<str>,
        date: Option<&str>,
    ) -> Result<HashMap<String, HashMap<String, Hours>>> {
        let market_id = required_text("market_id", market_id.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &["markets", &market_id])?;
        let mut query = Vec::new();
        push_optional(&mut query, "date", date);
        self.send_json(Method::GET, url, &query, None).await
    }

    /// Fetches market movers from `GET /movers/{symbol_id}`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `symbol_id` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config, MoverOptions};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let movers = client
    ///     .get_movers("$DJI", MoverOptions::new().sort("VOLUME").frequency(5))
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_movers(
        &self,
        symbol_id: impl AsRef<str>,
        options: MoverOptions,
    ) -> Result<ScreenerResponse> {
        let symbol_id = required_text("symbol_id", symbol_id.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &["movers", &symbol_id])?;
        self.send_json(Method::GET, url, &options.into_query(), None)
            .await
    }

    /// Fetches price history from `GET /pricehistory`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::MissingRequiredParameter`] if `symbol` is empty.
    /// Returns an [`Error`](crate::Error) if the request fails or the response cannot be decoded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> schwab::Result<()> {
    /// use schwab::{Client, Config, PriceHistoryOptions};
    ///
    /// let client = Client::new(Config::new().bearer_token("my-token"));
    /// let candles = client
    ///     .get_price_history(
    ///         "AAPL",
    ///         PriceHistoryOptions::new()
    ///             .parameter("periodType", "day")
    ///             .integer_parameter("period", 5),
    ///     )
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all)]
    pub async fn get_price_history(
        &self,
        symbol: impl AsRef<str>,
        options: PriceHistoryOptions,
    ) -> Result<CandleList> {
        let symbol = required_text("symbol", symbol.as_ref())?;
        let url = self.endpoint_url(ApiBase::MarketData, &["pricehistory"])?;
        let mut query = vec![("symbol", symbol.to_owned())];
        query.extend(options.into_query());
        self.send_json(Method::GET, url, &query, None).await
    }
}

#[cfg(test)]
mod tests {
    use mockito::Matcher;

    use crate::test_support::fixture;
    use crate::*;

    #[tokio::test]
    async fn get_quotes_sends_expected_no_auth_request() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/quotes")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("symbols".into(), "AAPL,MSFT".into()),
                Matcher::UrlEncoded("fields".into(), "quote,reference".into()),
                Matcher::UrlEncoded("indicative".into(), "true".into()),
            ]))
            .match_header("authorization", Matcher::Missing)
            .with_status(200)
            .with_body(fixture("quote_equity.json"))
            .create_async()
            .await;

        let url = server.url();
        let client = Client::new(Config::new().base_url(&url).unwrap());
        let quotes = client
            .get_quotes_with_options(
                ["AAPL", "MSFT"],
                QuoteOptions::new()
                    .fields("quote,reference")
                    .indicative(true),
            )
            .await
            .unwrap();

        mock.assert_async().await;
        assert!(quotes.contains_key("AAPL"));
    }

    #[tokio::test]
    async fn get_quotes_returns_http_status_errors() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", Matcher::Any)
            .with_status(400)
            .with_body(r#"{"message":"bad symbols"}"#)
            .create_async()
            .await;

        let url = server.url();
        let client = Client::new(Config::new().base_url(&url).unwrap());
        let error = client.get_quotes(["AAPL"]).await.unwrap_err();

        assert!(matches!(
            error,
            Error::HttpStatus { status: 400, body } if body.contains("bad symbols")
        ));
    }

    #[tokio::test]
    async fn get_option_chain_sends_documented_query_parameters() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/chains")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("symbol".into(), "AAPL".into()),
                Matcher::UrlEncoded("contractType".into(), "CALL".into()),
                Matcher::UrlEncoded("strikeCount".into(), "5".into()),
                Matcher::UrlEncoded("includeUnderlyingQuote".into(), "true".into()),
            ]))
            .with_status(200)
            .with_body(r#"{"status":"SUCCESS"}"#)
            .create_async()
            .await;

        let url = server.url();
        let client = Client::new(Config::new().base_url(&url).unwrap());
        client
            .get_option_chain(
                OptionChainOptions::new("AAPL")
                    .parameter("contractType", "CALL")
                    .integer_parameter("strikeCount", 5)
                    .include_underlying_quote(true),
            )
            .await
            .unwrap();

        mock.assert_async().await;
    }

    #[tokio::test]
    async fn numeric_option_helpers_preserve_explicit_zero_values() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/chains")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("symbol".into(), "AAPL".into()),
                Matcher::UrlEncoded("strikeCount".into(), "0".into()),
                Matcher::UrlEncoded("volatility".into(), "0".into()),
            ]))
            .with_status(200)
            .with_body(r#"{"status":"SUCCESS"}"#)
            .create_async()
            .await;

        let url = server.url();
        let client = Client::new(Config::new().base_url(&url).unwrap());
        client
            .get_option_chain(
                OptionChainOptions::new("AAPL")
                    .integer_parameter("strikeCount", 0)
                    .number_parameter("volatility", 0.0),
            )
            .await
            .unwrap();

        mock.assert_async().await;
    }

    #[tokio::test]
    async fn endpoint_request_shapes_are_covered() {
        let mut server = mockito::Server::new_async().await;
        let url = server.url();
        let client = Client::new(Config::new().base_url(&url).unwrap());

        // get_quote with path-encoded symbol
        let m = server
            .mock("GET", "/AAPL%2FPR/quotes")
            .match_query(Matcher::UrlEncoded("fields".into(), "quote".into()))
            .with_status(200)
            .with_body(r#"{"AAPL":{"assetMainType":"EQUITY"}}"#)
            .create_async()
            .await;
        client.get_quote("AAPL/PR", Some("quote")).await.unwrap();
        m.assert_async().await;

        // get_expiration_chain
        let m = server
            .mock("GET", "/expirationchain")
            .match_query(Matcher::UrlEncoded("symbol".into(), "AAPL".into()))
            .with_status(200)
            .with_body(r#"{"expirationList":[]}"#)
            .create_async()
            .await;
        client.get_expiration_chain("AAPL").await.unwrap();
        m.assert_async().await;

        // get_instruments
        let m = server
            .mock("GET", "/instruments")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("symbol".into(), "AAPL".into()),
                Matcher::UrlEncoded("projection".into(), "symbol-search".into()),
            ]))
            .with_status(200)
            .with_body(r#"{"instruments":[]}"#)
            .create_async()
            .await;
        client
            .get_instruments("AAPL", "symbol-search")
            .await
            .unwrap();
        m.assert_async().await;

        // get_instrument_by_cusip with path encoding
        let m = server
            .mock("GET", "/instruments/CUSIP%2F1")
            .with_status(200)
            .with_body(r#"{"cusip":"037833100"}"#)
            .create_async()
            .await;
        client.get_instrument_by_cusip("CUSIP/1").await.unwrap();
        m.assert_async().await;

        // get_market_hours
        let m = server
            .mock("GET", "/markets")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("markets".into(), "equity,option".into()),
                Matcher::UrlEncoded("date".into(), "2024-01-02".into()),
            ]))
            .with_status(200)
            .with_body(r#"{"equity":{}}"#)
            .create_async()
            .await;
        client
            .get_market_hours(["equity", "option"], Some("2024-01-02"))
            .await
            .unwrap();
        m.assert_async().await;

        // get_market_hour
        let m = server
            .mock("GET", "/markets/equity")
            .match_query(Matcher::UrlEncoded("date".into(), "2024-01-02".into()))
            .with_status(200)
            .with_body(r#"{"equity":{"EQ":{}}}"#)
            .create_async()
            .await;
        client
            .get_market_hour("equity", Some("2024-01-02"))
            .await
            .unwrap();
        m.assert_async().await;

        // get_movers
        let m = server
            .mock("GET", "/movers/$DJI")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("sort".into(), "VOLUME".into()),
                Matcher::UrlEncoded("frequency".into(), "5".into()),
            ]))
            .with_status(200)
            .with_body(r#"{"screeners":[]}"#)
            .create_async()
            .await;
        client
            .get_movers("$DJI", MoverOptions::new().sort("VOLUME").frequency(5))
            .await
            .unwrap();
        m.assert_async().await;

        // get_price_history
        let m = server
            .mock("GET", "/pricehistory")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("symbol".into(), "AAPL".into()),
                Matcher::UrlEncoded("periodType".into(), "day".into()),
                Matcher::UrlEncoded("period".into(), "0".into()),
                Matcher::UrlEncoded("needExtendedHoursData".into(), "false".into()),
            ]))
            .with_status(200)
            .with_body(r#"{"candles":[]}"#)
            .create_async()
            .await;
        client
            .get_price_history(
                "AAPL",
                PriceHistoryOptions::new()
                    .parameter("periodType", "day")
                    .integer_parameter("period", 0)
                    .bool_parameter("needExtendedHoursData", false),
            )
            .await
            .unwrap();
        m.assert_async().await;
    }

    #[tokio::test]
    async fn required_list_rejects_empty_values() {
        let client = Client::new(Config::new());

        let result = client.get_market_hours([" "], None).await;
        assert!(matches!(
            result,
            Err(Error::MissingRequiredParameter("markets"))
        ));
    }
}