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
use serde::de::DeserializeOwned;
use crate::client::HttpClient;
use crate::crypto::{CryptoBuilder, CryptoFunction};
use crate::custom::CustomBuilder;
use crate::earning::EarningBuilder;
use crate::economic_indicator::EconomicIndicatorBuilder;
use crate::error::{Error, ErrorHolder, Result};
use crate::exchange::ExchangeBuilder;
use crate::forex::{ForexBuilder, ForexFunction};
use crate::quote::QuoteBuilder;
use crate::search::SearchBuilder;
use crate::stock_time::{StockFunction, TimeSeriesBuilder};
use crate::technical_indicator::{TechnicalIndicatorBuilder, TechnicalIndicatorInterval};
const BASE_URL: &str = "https://www.alphavantage.co/";
const RAPID_API_BASE_URL: &str = "https://alpha-vantage.p.rapidapi.com/query";
/// Provider for alpha vantage API
pub enum Provider {
/// Use alphavantage API provider
AlphaVantage,
/// User `RapidAPI` as provider
RapidAPI,
}
/// Struct for initializing client which contains different method for API call
pub struct ApiClient {
api: String,
client: Box<dyn HttpClient + Send + Sync>,
provider: Provider,
}
impl ApiClient {
/// Method for initializing `ApiClient` struct using user
/// provided client and alphavantage.co provider
///
/// ```
/// use alpha_vantage::api::ApiClient;
/// let api = ApiClient::set_api("some_key", reqwest::Client::new());
/// ```
#[must_use]
pub fn set_api<S, T>(api: S, client: T) -> Self
where
S: Into<String>,
T: HttpClient + 'static + Send + Sync,
{
Self {
api: api.into(),
client: Box::new(client),
provider: Provider::AlphaVantage,
}
}
/// Method for initializing `ApiClient` struct using user
/// provided client and `RapidAPI` API provider
///
/// ```
/// use alpha_vantage::api::ApiClient;
/// let api = ApiClient::set_api("some_key", reqwest::Client::new());
/// ```
#[must_use]
pub fn set_rapid_api<S, T>(api: S, client: T) -> Self
where
S: Into<String>,
T: HttpClient + 'static + Send + Sync,
{
Self {
api: api.into(),
client: Box::new(client),
provider: Provider::RapidAPI,
}
}
/// Method to get api key
///
/// ```
/// use alpha_vantage::api::ApiClient;
/// let api = alpha_vantage::api::ApiClient::set_api("some_key", reqwest::Client::new());
/// assert_eq!(api.get_api_key(), "some_key");
/// ```
#[must_use]
pub fn get_api_key(&self) -> &str {
&self.api
}
// Get json from api endpoint and create struct
pub(crate) async fn get_json<T>(&self, path: &str) -> Result<T>
where
T: DeserializeOwned,
{
let string_output = match &self.provider {
Provider::AlphaVantage => {
self.client
.get_alpha_vantage_provider_output(&format!(
"{BASE_URL}{path}&apikey={}",
self.api
))
.await
}
Provider::RapidAPI => {
self.client
.get_rapid_api_provider_output(
&format!("{RAPID_API_BASE_URL}{path}"),
&self.api,
)
.await
}
}?;
let with_error: ErrorHolder<T> =
serde_json::from_str(&string_output).map_err(|_| Error::DecodeJsonToStruct)?;
with_error.handle_common_error()
}
/// Crypto method for calling cryptography function with help of
/// `CryptoBuilder`
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let crypto = api
/// .crypto(alpha_vantage::crypto::CryptoFunction::Daily, "BTC", "EUR")
/// .json()
/// .await
/// .unwrap();
/// assert_eq!(crypto.digital_code(), "BTC");
/// assert_eq!(crypto.digital_name(), "Bitcoin");
/// assert_eq!(crypto.market_code(), "EUR");
/// assert_eq!(crypto.market_name(), "Euro");
/// }
/// ```
#[must_use]
pub fn crypto<'a>(
&'a self,
function: CryptoFunction,
symbol: &'a str,
market: &'a str,
) -> CryptoBuilder<'a> {
CryptoBuilder::new(self, function, symbol, market)
}
/// Method for calling custom function not implemented currently in library
/// using `CustomBuilder`
#[must_use]
pub fn custom<'a>(&'a self, function: &'a str) -> CustomBuilder<'a> {
CustomBuilder::new(self, function)
}
/// Method for returning `EarningBuilder` for earning API
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let earning = api.earning("IBM").json().await.unwrap();
/// let symbol = earning.symbol();
/// assert_eq!(symbol, "IBM");
/// }
/// ```
#[must_use]
pub fn earning<'a>(&'a self, symbol: &'a str) -> EarningBuilder<'a> {
EarningBuilder::new(self, symbol)
}
/// Method for economic indicator builder
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let economic = api
/// .economic_indicator("REAL_GDP_PER_CAPITA")
/// .json()
/// .await
/// .unwrap();
/// assert_eq!(economic.interval(), "quarterly");
/// }
/// ```
#[must_use]
pub fn economic_indicator<'a>(&'a self, function: &'a str) -> EconomicIndicatorBuilder<'a> {
EconomicIndicatorBuilder::new(self, function)
}
/// Method for creating `ExchangeBuilder` for exchanging currency value from
/// one currency to another currency.
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let exchange = api.exchange("BTC", "EUR").json().await.unwrap();
/// assert_eq!(exchange.name_from(), "Bitcoin");
/// assert_eq!(exchange.code_from(), "BTC");
/// assert_eq!(exchange.name_to(), "Euro");
/// assert_eq!(exchange.code_to(), "EUR");
/// }
/// ```
#[must_use]
pub fn exchange<'a>(
&'a self,
from_currency: &'a str,
to_currency: &'a str,
) -> ExchangeBuilder<'a> {
ExchangeBuilder::new(self, from_currency, to_currency)
}
/// Method for creating `ForexBuilder` for `Forex` API
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let forex = api
/// .forex(alpha_vantage::forex::ForexFunction::Weekly, "EUR", "USD")
/// .json()
/// .await
/// .unwrap();
/// assert_eq!(forex.symbol_from(), "EUR");
/// assert_eq!(forex.symbol_to(), "USD");
/// assert!(forex.interval().is_none());
/// }
/// ```
#[must_use]
pub fn forex<'a>(
&'a self,
function: ForexFunction,
from_symbol: &'a str,
to_symbol: &'a str,
) -> ForexBuilder<'a> {
ForexBuilder::new(self, function, from_symbol, to_symbol)
}
/// Method for creating `QuoteBuilder` from `APIClient`
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let quote = api.quote("MSFT").json().await.unwrap();
/// let symbol = quote.symbol();
/// assert_eq!(symbol, "MSFT");
/// }
/// ```
#[must_use]
pub fn quote<'a>(&'a self, symbol: &'a str) -> QuoteBuilder<'a> {
QuoteBuilder::new(self, symbol)
}
/// Method for creating search builder
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let search = api.search("BA").json().await.unwrap();
/// let first_search_match = &search.matches()[0];
/// assert_eq!(first_search_match.symbol(), "BA");
/// assert_eq!(first_search_match.name(), "Boeing Company");
/// assert_eq!(first_search_match.stock_type(), "Equity");
/// assert_eq!(first_search_match.region(), "United States");
/// assert_eq!(first_search_match.currency(), "USD");
/// assert_eq!(first_search_match.match_score(), 1.0);
/// }
/// ```
#[must_use]
pub fn search<'a>(&'a self, keywords: &'a str) -> SearchBuilder<'a> {
SearchBuilder::new(self, keywords)
}
/// Method for creating Stock time Builder from `APIClient`
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let stock = api
/// .stock_time(alpha_vantage::stock_time::StockFunction::Weekly, "MSFT")
/// .json()
/// .await
/// .unwrap();
/// assert_eq!(stock.symbol(), "MSFT");
/// assert!(stock.interval().is_none());
/// }
/// ```
#[must_use]
pub fn stock_time<'a>(
&'a self,
function: StockFunction,
symbol: &'a str,
) -> TimeSeriesBuilder<'a> {
TimeSeriesBuilder::new(self, function, symbol)
}
/// Method for technical indicator builder
///
/// # Example
/// ```
/// #[tokio::main]
/// async fn main() {
/// let api = alpha_vantage::set_api("demo", reqwest::Client::new());
/// let technical = api
/// .technical_indicator(
/// "MAMA",
/// "IBM",
/// alpha_vantage::technical_indicator::TechnicalIndicatorInterval::Daily,
/// )
/// .series_type("close")
/// .extra_param("fastlimit", 0.02)
/// .json()
/// .await;
/// assert!(technical.is_ok());
/// }
/// ```
#[must_use]
pub fn technical_indicator<'a>(
&'a self,
function: &'a str,
symbol: &'a str,
interval: TechnicalIndicatorInterval,
) -> TechnicalIndicatorBuilder<'a> {
TechnicalIndicatorBuilder::new(self, function, symbol, interval)
}
}
/// Enum for declaring output size of API call
#[derive(Clone)]
pub enum OutputSize {
/// Return latest top 100 points recommended if no historical data is
/// required and decreases api json sizes
Compact,
/// Returns full api data points recommended if a full historical data is
/// required
Full,
}
/// Enum for declaring interval for intraday time series
#[derive(Clone)]
pub enum TimeSeriesInterval {
/// 1 min interval
OneMin,
/// 5 min interval
FiveMin,
/// 15 min interval
FifteenMin,
/// 30 min interval
ThirtyMin,
/// 60 min interval
SixtyMin,
}