Skip to main content

fauna_api/magpie/
quotes.rs

1use chrono::{DateTime, SecondsFormat, Utc};
2use serde::{Deserialize, Serialize};
3
4use super::portfolio::Asset;
5use crate::authentification::CredentialsOrApiKey;
6use crate::error::Result;
7use crate::http::{client, deserialize_date, encode, ok, serialize_date};
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct Quote {
12    pub symbol: String,
13    pub asset: Asset,
14    pub price: f64,
15    pub change: f64,
16    pub change_percent: f64,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub market_cap: Option<f64>,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub volume: Option<f64>,
21    #[serde(
22        deserialize_with = "deserialize_date",
23        serialize_with = "serialize_date"
24    )]
25    pub timestamp: DateTime<Utc>,
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct Price {
30    #[serde(
31        deserialize_with = "deserialize_date",
32        serialize_with = "serialize_date"
33    )]
34    pub date: DateTime<Utc>,
35    pub open: f64,
36    pub high: f64,
37    pub low: f64,
38    pub close: f64,
39    pub volume: f64,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct SearchResult {
44    pub symbol: String,
45    pub name: String,
46    pub asset: Asset,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub exchange: Option<String>,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52pub enum Interval {
53    #[serde(rename = "1d")]
54    Day,
55    #[serde(rename = "1h")]
56    Hour,
57    #[serde(rename = "1wk")]
58    Week,
59    #[serde(rename = "1mo")]
60    Month,
61}
62
63impl Interval {
64    fn as_str(self) -> &'static str {
65        match self {
66            Interval::Day => "1d",
67            Interval::Hour => "1h",
68            Interval::Week => "1wk",
69            Interval::Month => "1mo",
70        }
71    }
72}
73
74#[derive(Debug, Clone, Default)]
75pub struct SourceOpts {
76    pub source: Option<String>,
77}
78
79fn authorization_header(authorization: &CredentialsOrApiKey) -> String {
80    match authorization {
81        CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
82        CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
83    }
84}
85
86pub async fn quote_asset(
87    authorization: &CredentialsOrApiKey,
88    asset: Asset,
89    symbol: &str,
90    opts: SourceOpts,
91) -> Result<Quote> {
92    let mut request = client()
93        .get(format!(
94            "{}/magpie/quote/{}/{}",
95            super::get_url(),
96            encode(asset.as_str()),
97            encode(symbol)
98        ))
99        .header("Authorization", authorization_header(authorization));
100    if let Some(source) = opts.source.filter(|source| !source.is_empty()) {
101        request = request.query(&[("source", source)]);
102    }
103    let response = request.send().await?;
104    Ok(ok(response).await?.json().await?)
105}
106
107#[allow(clippy::too_many_arguments)]
108pub async fn price_asset(
109    authorization: &CredentialsOrApiKey,
110    asset: Asset,
111    symbol: &str,
112    start: DateTime<Utc>,
113    end: DateTime<Utc>,
114    interval: Interval,
115    opts: SourceOpts,
116) -> Result<Vec<Price>> {
117    let mut query = vec![
118        ("start", start.to_rfc3339_opts(SecondsFormat::Millis, true)),
119        ("end", end.to_rfc3339_opts(SecondsFormat::Millis, true)),
120        ("interval", interval.as_str().to_string()),
121    ];
122    if let Some(source) = opts.source.filter(|source| !source.is_empty()) {
123        query.push(("source", source));
124    }
125    let response = client()
126        .get(format!(
127            "{}/magpie/price/{}/{}",
128            super::get_url(),
129            encode(asset.as_str()),
130            encode(symbol)
131        ))
132        .query(&query)
133        .header("Authorization", authorization_header(authorization))
134        .send()
135        .await?;
136    Ok(ok(response).await?.json().await?)
137}
138
139pub async fn quote_source(authorization: &CredentialsOrApiKey, url: &str) -> Result<Quote> {
140    quote_asset(
141        authorization,
142        Asset::Other,
143        "_",
144        SourceOpts {
145            source: Some(url.to_string()),
146        },
147    )
148    .await
149}
150
151pub async fn price_source(
152    authorization: &CredentialsOrApiKey,
153    url: &str,
154    start: DateTime<Utc>,
155    end: DateTime<Utc>,
156    interval: Interval,
157) -> Result<Vec<Price>> {
158    price_asset(
159        authorization,
160        Asset::Other,
161        "_",
162        start,
163        end,
164        interval,
165        SourceOpts {
166            source: Some(url.to_string()),
167        },
168    )
169    .await
170}
171
172pub async fn search(
173    authorization: &CredentialsOrApiKey,
174    asset: Asset,
175    query: &str,
176) -> Result<Vec<SearchResult>> {
177    let response = client()
178        .get(format!(
179            "{}/magpie/search/{}?query={}",
180            super::get_url(),
181            encode(asset.as_str()),
182            encode(query)
183        ))
184        .header("Authorization", authorization_header(authorization))
185        .send()
186        .await?;
187    Ok(ok(response).await?.json().await?)
188}