bpx_api_client/routes/
markets.rs

1use std::collections::HashMap;
2
3use bpx_api_types::markets::{Kline, Market, OrderBookDepth, Ticker, Token};
4
5use crate::error::Result;
6use crate::BpxClient;
7
8const API_ASSETS: &str = "/api/v1/assets";
9const API_MARKETS: &str = "/api/v1/markets";
10const API_TICKER: &str = "/api/v1/ticker";
11const API_TICKERS: &str = "/api/v1/tickers";
12const API_DEPTH: &str = "/api/v1/depth";
13const API_KLINES: &str = "/api/v1/klines";
14
15impl BpxClient {
16    /// Fetches available assets and their associated tokens.
17    pub async fn get_assets(&self) -> Result<HashMap<String, Vec<Token>>> {
18        let url = format!("{}{}", self.base_url, API_ASSETS);
19        let res = self.get(url).await?;
20        res.json().await.map_err(Into::into)
21    }
22
23    /// Retrieves a list of available markets.
24    pub async fn get_markets(&self) -> Result<Vec<Market>> {
25        let url = format!("{}{}", self.base_url, API_MARKETS);
26        let res = self.get(url).await?;
27        res.json().await.map_err(Into::into)
28    }
29
30    /// Fetches the ticker information for a given symbol.
31    pub async fn get_ticker(&self, symbol: &str) -> Result<Ticker> {
32        let url = format!("{}{}&symbol={}", self.base_url, API_TICKER, symbol);
33        let res = self.get(url).await?;
34        res.json().await.map_err(Into::into)
35    }
36
37    /// Fetches the ticker information for all symbols.
38    pub async fn get_tickers(&self) -> Result<Vec<Ticker>> {
39        let url = format!("{}{}", self.base_url, API_TICKERS);
40        let res = self.get(url).await?;
41        res.json().await.map_err(Into::into)
42    }
43
44    /// Retrieves the order book depth for a given symbol.
45    pub async fn get_order_book_depth(&self, symbol: &str) -> Result<OrderBookDepth> {
46        let url = format!("{}{}&symbol={}", self.base_url, API_DEPTH, symbol);
47        let res = self.get(url).await?;
48        res.json().await.map_err(Into::into)
49    }
50
51    /// Fetches historical K-line (candlestick) data for a given symbol and interval.
52    pub async fn get_k_lines(
53        &self,
54        symbol: &str,
55        kline_interval: &str,
56        start_time: Option<i64>,
57        end_time: Option<i64>,
58    ) -> Result<Vec<Kline>> {
59        let mut url = format!(
60            "/{}{}?symbol={}&kline_interval={}",
61            self.base_url, API_KLINES, symbol, kline_interval
62        );
63        for (k, v) in [("start_time", start_time), ("end_time", end_time)] {
64            if let Some(v) = v {
65                url.push_str(&format!("&{}={}", k, v));
66            }
67        }
68        let res = self.get(url).await?;
69        res.json().await.map_err(Into::into)
70    }
71}