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
use super::{get_http, PriceFeed};
use crate::{config::CurrencyStore, currency::*, Error};
use async_trait::async_trait;
use clap::Parser;
use reqwest::Url;
use serde_json::Value;

#[derive(Parser, Debug, Clone)]
pub struct KrakenCli {
    /// Fetch the exchange rate from Kraken
    #[clap(long)]
    kraken_url: Option<Url>,
}

pub struct KrakenApi {
    url: Url,
}

impl Default for KrakenApi {
    fn default() -> Self {
        Self {
            url: Url::parse("https://api.kraken.com/0").unwrap(),
        }
    }
}

fn extract_response(value: &Value) -> Option<&'_ str> {
    value
        .get("result")?
        .as_object()?
        .iter()
        .last()? // we are only fetching one anyway
        .1
        .get("p")?
        .as_array()?
        .get(0)?
        .as_str()
}

impl KrakenApi {
    pub fn from_opts(opts: KrakenCli) -> Option<Self> {
        opts.kraken_url.map(Self::new)
    }

    pub fn new(url: Url) -> Self {
        Self { url }
    }

    async fn get_exchange_rate(
        &self,
        currency_pair: CurrencyPair<Currency>,
        _currency_store: &CurrencyStore<String>,
    ) -> Result<CurrencyPairAndPrice<Currency>, Error> {
        // NOTE: Kraken prefixes older cryptocurrencies with "X" and fiat with "Z"
        let asset_pair_name = format!(
            "{}{}",
            currency_pair.base.path().unwrap_or_else(|| currency_pair.base.symbol()),
            currency_pair
                .quote
                .path()
                .unwrap_or_else(|| currency_pair.quote.symbol()),
        );

        // https://docs.kraken.com/rest/
        let mut url = self.url.clone();
        url.set_path(&format!("{}/public/Ticker", url.path()));
        url.set_query(Some(&format!("pair={asset_pair_name}")));

        // get today's VWAP
        let data = get_http(url).await?;
        let exchange_rate = extract_response(&data).ok_or(Error::InvalidResponse)?.parse::<f64>()?;

        Ok(CurrencyPairAndPrice {
            pair: currency_pair,
            price: exchange_rate,
        })
    }
}

#[async_trait]
impl PriceFeed for KrakenApi {
    async fn get_price(
        &self,
        currency_pair: CurrencyPair<Currency>,
        currency_store: &CurrencyStore<String>,
    ) -> Result<CurrencyPairAndPrice<Currency>, Error> {
        self.get_exchange_rate(currency_pair, currency_store).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn should_extract_response() {
        assert_eq!(
            extract_response(&json!({
                "error":[],
                "result": {
                        "XXBTZUSD": {
                                "a":["19141.50000","3","3.000"],
                                "b":["19141.40000","7","7.000"],
                                "c":["19145.00000","0.01022591"],
                                "v":["647.22057875","2415.97751491"],
                                "p":["19105.89558","19068.90458"],
                                "t":[4359,13327],
                                "l":["19028.50000","18860.00000"],
                                "h":["19190.00000","19259.40000"],
                                "o":"19050.00000"
                        }
                    }
                }
            )),
            Some("19105.89558")
        )
    }
}