1use serde::Deserialize;
2use std::collections::HashMap;
3
4#[derive(Clone, Debug)]
5pub struct Config {
6 pub api_key: String,
7 pub api_secret: String,
8}
9
10#[derive(Clone, Debug)]
11pub struct Stock {
12 pub symbol: String,
13 pub config: Config,
14}
15
16#[derive(Deserialize, Debug)]
17pub struct StockLastTradeResponse {
18 status: String,
19 symbol: String,
20 last: LastTrade,
21}
22
23#[derive(Deserialize, Debug)]
24pub struct LastTrade {
25 price: f64,
26 size: f64,
27 exchange: u16,
28 cond1: u64,
29 cond2: u64,
30 cond3: u64,
31 cond4: u64,
32 timestamp: u64,
33}
34
35#[derive(Deserialize, Debug)]
36pub struct StockLastQuoteResponse {
37 status: String,
38 symbol: String,
39 last: LastQuote,
40}
41
42#[derive(Deserialize, Debug)]
43pub struct LastQuote {
44 askprice: f64,
45 asksize: u16,
46 askexchange: u16,
47 bidprice: f64,
48 bidsize: u16,
49 bidexchange: u16,
50 timestamp: u64,
51}
52
53#[derive(Deserialize, Debug)]
54pub struct Bar {
55 t: u64, o: f64, h: f64, l: f64, c: f64, v: u64, }
62
63pub type BarResponse = HashMap<String, Vec<Bar>>;
64
65#[allow(dead_code)]
66enum Duration {
67 Minute,
68 Min1,
69 Min5,
70 Min15,
71 Day,
72}
73
74impl Stock {
82 pub async fn bars(self) -> Result<BarResponse, Box<dyn std::error::Error>> {
83 let url = format!("{:}", "https://data.alpaca.markets/v1/bars/1D");
84
85 let client = reqwest::Client::new();
86 let res = client
87 .get(&url)
88 .header("APCA-API-KEY-ID", self.config.api_key)
89 .header("APCA-API-SECRET-KEY", self.config.api_secret)
90 .query(&[("symbols", self.symbol)])
91 .send()
92 .await?
93 .json::<BarResponse>()
94 .await?;
95
96 for item in res.iter() {
97 println!("{:?}", item);
98 }
99
100 Ok(res)
101 }
102
103 pub async fn last_trade(self) -> Result<StockLastTradeResponse, Box<dyn std::error::Error>> {
104 let url = format!(
105 "{:}/{:}",
106 "https://data.alpaca.markets/v1/last/stocks", self.symbol
107 );
108
109 let client = reqwest::Client::new();
110 let res = client
111 .get(&url)
112 .header("APCA-API-KEY-ID", self.config.api_key)
113 .header("APCA-API-SECRET-KEY", self.config.api_secret)
114 .send()
115 .await?
116 .json::<StockLastTradeResponse>()
117 .await?;
118
119 Ok(res)
120 }
121
122 pub async fn last_quote(self) -> Result<StockLastQuoteResponse, Box<dyn std::error::Error>> {
123 let url = format!(
124 "{:}/{:}",
125 "https://data.alpaca.markets/v1/last_quote/stocks", self.symbol
126 );
127
128 let client = reqwest::Client::new();
129 let res = client
130 .get(&url)
131 .header("APCA-API-KEY-ID", self.config.api_key)
132 .header("APCA-API-SECRET-KEY", self.config.api_secret)
133 .send()
134 .await?
135 .json::<StockLastQuoteResponse>()
136 .await?;
137
138 Ok(res)
139 }
140}