RESTClient

Struct RESTClient 

Source
pub struct RESTClient {
    pub auth_key: String,
    pub api_url: String,
    /* private fields */
}

Fields§

§auth_key: String

The API key to use for requests.

§api_url: String

The API URL to use for requests.

The default API URL is https://api.polygon.io.

Implementations§

Source§

impl RESTClient

Source

pub fn new(auth_key: Option<&str>, timeout: Option<Duration>) -> Self

Returns a new REST client.

The auth_key parameter optionally provides the API key to use for authentication. If None is provided, then the API key specified in the POLYGON_AUTH_KEY environment variable is used.

The timeout parameter optionally provides the duration to wait for a response to a request.

§Panics

This function will panic if auth_key is None and the POLYGON_AUTH_KEY environment variable is not set.

Examples found in repository?
examples/dividends.rs (line 20)
10async fn main() {
11    let args: Vec<String> = env::args().collect();
12
13    if args.len() == 0 {
14        println!("Usage: dividends <ticker1> <ticker2> <ticker3> ...");
15        return;
16    }
17
18    let one_year_ago = (Local::now() - Duration::days(365)).date();
19
20    let client = RESTClient::new(None, None);
21
22    for ticker in args.iter() {
23        let query_params = HashMap::new();
24        let dividends = client
25            .reference_stock_dividends(ticker, &query_params)
26            .await;
27        if dividends.is_ok() {
28            let dividends_ref = &dividends.unwrap();
29            let res = dividends_ref
30                .results
31                .iter()
32                .filter_map(|x| {
33                    let ex_date = NaiveDate::parse_from_str(&x.ex_date, "%Y-%m-%d").unwrap();
34
35                    if ex_date > one_year_ago.naive_local() {
36                        Some(x)
37                    } else {
38                        None
39                    }
40                })
41                .collect::<Vec<_>>();
42
43            if res.len() > 0 {
44                let previous_close_res = client
45                    .stock_equities_previous_close(ticker, &query_params)
46                    .await
47                    .expect(&format!(
48                        "unable to find previous close for ticker {}",
49                        ticker
50                    ));
51
52                if previous_close_res.results.len() == 0 {
53                    panic!("no previous close found for ticker {}", ticker);
54                }
55
56                let close = previous_close_res.results.first().unwrap().c;
57                let sum: f64 = res.iter().map(|d| d.amount).sum();
58
59                println!("Yield for {} is {:.2}% [previous close = {}, sum of last {} dividends = {:.2}]",
60                    ticker,
61                    (sum / close) * 100f64,
62                    close,
63                    res.len(),
64                    sum);
65            }
66        }
67    }
68}
Source

pub async fn reference_tickers( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceTickersResponse, Error>

Query all ticker symbols supported by polygon.io using the /v3/reference/tickers API.

Source

pub async fn reference_ticker_types( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceTickerTypesResponse, Error>

Get a mapping of ticker types to their descriptive names using the /v2/reference/types API.

Source

pub async fn reference_ticker_details( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceTickerDetailsResponse, Error>

Get details for a ticker symbol’s company/entity using the /v1/meta/symbols/{stocks_ticker}/company API.

Source

pub async fn reference_ticker_details_vx( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceTickerDetailsResponseVX, Error>

Get details for a ticker symbol’s company/entity using the /vX/reference/tickers/{stocks_ticker} API.

Source

pub async fn reference_ticker_news( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceTickerNewsResponse, Error>

Get the most recent news articles related to a stock ticker symbol using the /v2/reference/news API.

Source

pub async fn reference_markets( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceMarketsResponse, Error>

Get a list of markets that are currently supported by polygon.io using the /v2/reference/markets API.

Source

pub async fn reference_locales( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceLocalesResponse, Error>

Get a list of locales currently supported by polygon.io using the /v2/reference/locales API.

Source

pub async fn reference_stock_splits( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceStockSplitsResponse, Error>

Get a list of historical stock splits for a ticker symbol using the /v2/reference/splits/{stocks_ticker} API.

Source

pub async fn reference_stock_dividends( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceStockDividendsResponse, Error>

Get a list of historical dividends for a stock using the /v2/reference/dividends/{stocks_ticker} API.

Examples found in repository?
examples/dividends.rs (line 25)
10async fn main() {
11    let args: Vec<String> = env::args().collect();
12
13    if args.len() == 0 {
14        println!("Usage: dividends <ticker1> <ticker2> <ticker3> ...");
15        return;
16    }
17
18    let one_year_ago = (Local::now() - Duration::days(365)).date();
19
20    let client = RESTClient::new(None, None);
21
22    for ticker in args.iter() {
23        let query_params = HashMap::new();
24        let dividends = client
25            .reference_stock_dividends(ticker, &query_params)
26            .await;
27        if dividends.is_ok() {
28            let dividends_ref = &dividends.unwrap();
29            let res = dividends_ref
30                .results
31                .iter()
32                .filter_map(|x| {
33                    let ex_date = NaiveDate::parse_from_str(&x.ex_date, "%Y-%m-%d").unwrap();
34
35                    if ex_date > one_year_ago.naive_local() {
36                        Some(x)
37                    } else {
38                        None
39                    }
40                })
41                .collect::<Vec<_>>();
42
43            if res.len() > 0 {
44                let previous_close_res = client
45                    .stock_equities_previous_close(ticker, &query_params)
46                    .await
47                    .expect(&format!(
48                        "unable to find previous close for ticker {}",
49                        ticker
50                    ));
51
52                if previous_close_res.results.len() == 0 {
53                    panic!("no previous close found for ticker {}", ticker);
54                }
55
56                let close = previous_close_res.results.first().unwrap().c;
57                let sum: f64 = res.iter().map(|d| d.amount).sum();
58
59                println!("Yield for {} is {:.2}% [previous close = {}, sum of last {} dividends = {:.2}]",
60                    ticker,
61                    (sum / close) * 100f64,
62                    close,
63                    res.len(),
64                    sum);
65            }
66        }
67    }
68}
Source

pub async fn reference_stock_financials( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceStockFinancialsResponse, Error>

Get historical financial data for a stock ticker using the /v2/reference/financials/{stocks_ticker} API.

Source

pub async fn reference_stock_financials_vx( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceStockFinancialsVXResponse, Error>

Get historical financial data for a stock ticker using the /vX/reference/financials API.

Source

pub async fn reference_market_holidays( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceMarketStatusUpcomingResponse, Error>

Get upcoming market holidays and their open/close items using the /v1/marketstatus/upcoming API.

Source

pub async fn reference_market_status( &self, query_params: &HashMap<&str, &str>, ) -> Result<ReferenceMarketStatusNowResponse, Error>

Get the current trading status of the exchanges and overall financial markets using the /v1/marketstatus/now API.

Source

pub async fn stock_equities_exchanges( &self, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesExchangesResponse, Error>

Get a list of stock exchanges which are supported by polygon.io using the /v1/meta/exchanges API.

Source

pub async fn stock_equities_condition_mappings( &self, tick_type: TickType, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesConditionMappingsResponse, Error>

Get a unified numerical mapping for conditions on trades and quotes using the /v1/meta/conditions/{tick_type} API.

Source

pub async fn stock_equities_historic_trades( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesHistoricTradesResponse, Error>

Get the most recent trade for a given stock using the /v2/last/trade/{stocks_ticker} API.

Source

pub async fn stock_equities_last_quote_for_a_symbol( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesLastQuoteForASymbolResponse, Error>

Get the most recent NBBO quote tick for a given stock using the /v2/last/nbbo/{stocks_ticker} API.

Source

pub async fn stock_equities_daily_open_close( &self, stocks_ticker: &str, date: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesDailyOpenCloseResponse, Error>

Get the open, close, and afterhours prices of a stock symbol on a certain date using the /v1/open-close/{stocks_ticker}/{date} API.

Source

pub async fn stock_equities_aggregates( &self, stocks_ticker: &str, multiplier: u32, timespan: &str, from: &str, to: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesAggregatesResponse, Error>

Get aggregate bars for a stock over a given date range in custom time window sizes using the /v2/aggs/ticker/{stocks_ticker}/range/{multiplier}/{timespan}/{from}/{to} API.

Source

pub async fn stock_equities_grouped_daily( &self, locale: &str, market: &str, date: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesGroupedDailyResponse, Error>

Get the daily open, high, low, and close for the entire stocks and equities market using the /v2/aggs/grouped/locale/{locale}/market/{market}/{date} API.

Source

pub async fn stock_equities_previous_close( &self, stocks_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesPreviousCloseResponse, Error>

Get the previous day’s open, high, low, and close for the specified stock ticker using the /v2/aggs/ticker/{stocks_ticker}/prev API.

Examples found in repository?
examples/dividends.rs (line 45)
10async fn main() {
11    let args: Vec<String> = env::args().collect();
12
13    if args.len() == 0 {
14        println!("Usage: dividends <ticker1> <ticker2> <ticker3> ...");
15        return;
16    }
17
18    let one_year_ago = (Local::now() - Duration::days(365)).date();
19
20    let client = RESTClient::new(None, None);
21
22    for ticker in args.iter() {
23        let query_params = HashMap::new();
24        let dividends = client
25            .reference_stock_dividends(ticker, &query_params)
26            .await;
27        if dividends.is_ok() {
28            let dividends_ref = &dividends.unwrap();
29            let res = dividends_ref
30                .results
31                .iter()
32                .filter_map(|x| {
33                    let ex_date = NaiveDate::parse_from_str(&x.ex_date, "%Y-%m-%d").unwrap();
34
35                    if ex_date > one_year_ago.naive_local() {
36                        Some(x)
37                    } else {
38                        None
39                    }
40                })
41                .collect::<Vec<_>>();
42
43            if res.len() > 0 {
44                let previous_close_res = client
45                    .stock_equities_previous_close(ticker, &query_params)
46                    .await
47                    .expect(&format!(
48                        "unable to find previous close for ticker {}",
49                        ticker
50                    ));
51
52                if previous_close_res.results.len() == 0 {
53                    panic!("no previous close found for ticker {}", ticker);
54                }
55
56                let close = previous_close_res.results.first().unwrap().c;
57                let sum: f64 = res.iter().map(|d| d.amount).sum();
58
59                println!("Yield for {} is {:.2}% [previous close = {}, sum of last {} dividends = {:.2}]",
60                    ticker,
61                    (sum / close) * 100f64,
62                    close,
63                    res.len(),
64                    sum);
65            }
66        }
67    }
68}
Source

pub async fn stock_equities_snapshot_all_tickers( &self, locale: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesSnapshotAllTickersResponse, Error>

Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded stock symbols using the /v2/snapshot/locale/{locale}/markets/{market}/tickers API.

Source

pub async fn stock_equities_snapshot_single_ticker( &self, locale: &str, ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesSnapshotAllTickersResponse, Error>

Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded stock ticker using the /v2/snapshot/locale/{locale}/markets/stocks/tickers/{ticker} API.

Source

pub async fn stock_equities_snapshot_gainers_losers( &self, locale: &str, direction: &str, query_params: &HashMap<&str, &str>, ) -> Result<StockEquitiesSnapshotGainersLosersResponse, Error>

Get the current top 20 gainers or losers of the day in the stocks/equities markets using the /v2/snapshot/locale/{locale}/markets/stocks/{direction} API.

Source

pub async fn forex_currencies_aggregates( &self, forex_ticker: &str, multiplier: u32, timespan: &str, from: &str, to: &str, query_params: &HashMap<&str, &str>, ) -> Result<ForexCurrenciesAggregatesResponse, Error>

Get aggregate bars for a forex pair over a given date range in custom time window sizes using the /v2/aggs/ticker/{forexTicker}/range/{multiplier}/{timespan}/{from}/{to} API.

Source

pub async fn forex_currencies_grouped_daily( &self, date: &str, query_params: &HashMap<&str, &str>, ) -> Result<ForexCurrenciesGroupedDailyResponse, Error>

Get the daily open, high, low, and close for the entire forex markets using the /v2/aggs/grouped/locale/global/market/fx/{date} API.

Source

pub async fn forex_currencies_previous_close( &self, forex_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<ForexCurrenciesPreviousCloseResponse, Error>

Get the previous day’s open, high, low, and close for the specified forex pair using the /v2/aggs/ticker/{forex_ticker}/prev API.

Source

pub async fn crypto_crypto_exchanges( &self, query_params: &HashMap<&str, &str>, ) -> Result<CryptoCryptoExchangesResponse, Error>

Get a list of cryptocurrency exchanges which are supported by polygon.io using the /v1/meta/crypto-exchanges API.

Source

pub async fn crypto_daily_open_close( &self, from: &str, to: &str, date: &str, query_params: &HashMap<&str, &str>, ) -> Result<CryptoDailyOpenCloseResponse, Error>

Get the open and close prices of a cryptocurrency symbol on a certain day using /v1/open-close/crypto/{from}/{to}/{date} API.

Source

pub async fn crypto_aggregates( &self, crypto_ticker: &str, multiplier: u32, timespan: &str, from: &str, to: &str, query_params: &HashMap<&str, &str>, ) -> Result<CryptoAggregatesResponse, Error>

Get aggregate bars for a cryptocurrency over a given date range in custom time window sizes using the /v2/aggs/ticker/{cryptoTicker}/range/{multiplier}/{timespan}/{from}/{to} API.

Source

pub async fn crypto_grouped_daily( &self, date: &str, query_params: &HashMap<&str, &str>, ) -> Result<CryptoGroupedDailyResponse, Error>

Get the daily open, high, low, and close for the entire crypto markets using the /v2/aggs/grouped/locale/global/market/crypto/{date} API.

Source

pub async fn crypto_previous_close( &self, crypto_ticker: &str, query_params: &HashMap<&str, &str>, ) -> Result<CryptoPreviousCloseResponse, Error>

Get the previous day’s open, high, low, and close for the specified cryptocurrency using the /v2/aggs/ticker/{crypto_ticker}/prev API.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V