fauna-api 1.0.858

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};

use super::portfolio::Asset;
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{client, deserialize_date, encode, ok, serialize_date};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Quote {
    pub symbol: String,
    pub asset: Asset,
    pub price: f64,
    pub change: f64,
    pub change_percent: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub market_cap: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub volume: Option<f64>,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub timestamp: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Price {
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub date: DateTime<Utc>,
    pub open: f64,
    pub high: f64,
    pub low: f64,
    pub close: f64,
    pub volume: f64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchResult {
    pub symbol: String,
    pub name: String,
    pub asset: Asset,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exchange: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Interval {
    #[serde(rename = "1d")]
    Day,
    #[serde(rename = "1h")]
    Hour,
    #[serde(rename = "1wk")]
    Week,
    #[serde(rename = "1mo")]
    Month,
}

impl Interval {
    fn as_str(self) -> &'static str {
        match self {
            Interval::Day => "1d",
            Interval::Hour => "1h",
            Interval::Week => "1wk",
            Interval::Month => "1mo",
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct SourceOpts {
    pub source: Option<String>,
}

fn authorization_header(authorization: &CredentialsOrApiKey) -> String {
    match authorization {
        CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
        CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
    }
}

pub async fn quote_asset(
    authorization: &CredentialsOrApiKey,
    asset: Asset,
    symbol: &str,
    opts: SourceOpts,
) -> Result<Quote> {
    let mut request = client()
        .get(format!(
            "{}/magpie/quote/{}/{}",
            super::get_url(),
            encode(asset.as_str()),
            encode(symbol)
        ))
        .header("Authorization", authorization_header(authorization));
    if let Some(source) = opts.source.filter(|source| !source.is_empty()) {
        request = request.query(&[("source", source)]);
    }
    let response = request.send().await?;
    Ok(ok(response).await?.json().await?)
}

#[allow(clippy::too_many_arguments)]
pub async fn price_asset(
    authorization: &CredentialsOrApiKey,
    asset: Asset,
    symbol: &str,
    start: DateTime<Utc>,
    end: DateTime<Utc>,
    interval: Interval,
    opts: SourceOpts,
) -> Result<Vec<Price>> {
    let mut query = vec![
        ("start", start.to_rfc3339_opts(SecondsFormat::Millis, true)),
        ("end", end.to_rfc3339_opts(SecondsFormat::Millis, true)),
        ("interval", interval.as_str().to_string()),
    ];
    if let Some(source) = opts.source.filter(|source| !source.is_empty()) {
        query.push(("source", source));
    }
    let response = client()
        .get(format!(
            "{}/magpie/price/{}/{}",
            super::get_url(),
            encode(asset.as_str()),
            encode(symbol)
        ))
        .query(&query)
        .header("Authorization", authorization_header(authorization))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn quote_source(authorization: &CredentialsOrApiKey, url: &str) -> Result<Quote> {
    quote_asset(
        authorization,
        Asset::Other,
        "_",
        SourceOpts {
            source: Some(url.to_string()),
        },
    )
    .await
}

pub async fn price_source(
    authorization: &CredentialsOrApiKey,
    url: &str,
    start: DateTime<Utc>,
    end: DateTime<Utc>,
    interval: Interval,
) -> Result<Vec<Price>> {
    price_asset(
        authorization,
        Asset::Other,
        "_",
        start,
        end,
        interval,
        SourceOpts {
            source: Some(url.to_string()),
        },
    )
    .await
}

pub async fn search(
    authorization: &CredentialsOrApiKey,
    asset: Asset,
    query: &str,
) -> Result<Vec<SearchResult>> {
    let response = client()
        .get(format!(
            "{}/magpie/search/{}?query={}",
            super::get_url(),
            encode(asset.as_str()),
            encode(query)
        ))
        .header("Authorization", authorization_header(authorization))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}