tokio_binance/client/
market.rs

1use reqwest::{Url, Client};
2use crate::param::{
3    Parameters, 
4    Interval,
5};
6use crate::builder::ParamBuilder;
7use crate::types::*;
8
9/// Client for dealing with market data.
10#[derive(Clone)]
11pub struct MarketDataClient {
12    pub(super) api_key: String,
13    pub(super) url: Url,
14    pub(super) client: Client,
15}
16
17impl MarketDataClient {
18    /// Creates new client instance
19    /// # Example
20    ///
21    /// ```no_run
22    /// use tokio_binance::{MarketDataClient, BINANCE_US_URL};
23    /// 
24    /// #[tokio::main]
25    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
26    ///     let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
27    ///     Ok(())
28    /// }
29    /// ```
30    pub fn connect<A, U>(api_key: A, url: U) -> crate::error::Result<Self> 
31    where
32        A: Into<String>,
33        U: Into<String>
34    {
35        Ok(Self {
36            api_key: api_key.into(),
37            url: url.into().parse::<Url>()?,
38            client: Client::new()
39        })
40    }
41    /// Get order book.
42    /// # Example
43    ///
44    /// ```no_run
45    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
46    /// use serde_json::Value;
47    /// 
48    /// # #[tokio::main]
49    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
50    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
51    /// let response = client
52    ///     .get_order_book("BNBUSDT")
53    ///     // optional: default 100; max 5000.
54    ///     .with_limit(5)
55    ///     //
56    ///     .json::<Value>()
57    ///     .await?;
58    /// # Ok(())
59    /// # }
60    /// ```
61    pub fn get_order_book<'a>(&self, symbol: &'a str) -> ParamBuilder<'a, '_, OrderBookParams>{
62        let Self { ref api_key, url, client } = self;
63        let url = url.join("/api/v3/depth").unwrap();
64
65        ParamBuilder::new(
66            Parameters { symbol: Some(symbol), ..Parameters::default() },
67            client.get(url),
68            Some(api_key),
69            None
70        )
71    }
72    /// Get recent trades (up to last 500).
73    /// # Example
74    ///
75    /// ```no_run
76    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
77    /// use serde_json::Value;
78    /// 
79    /// # #[tokio::main]
80    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
81    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
82    /// let response = client
83    ///     .get_trades("BNBUSDT")
84    ///     // optional: default 100; max 5000.
85    ///     .with_limit(5)
86    ///     //
87    ///     .json::<Value>()
88    ///     .await?;
89    /// # Ok(())
90    /// # }
91    /// ```
92    pub fn get_trades<'a>(&self, symbol: &'a str) -> ParamBuilder<'a, '_, TradesParams>{
93        let Self { ref api_key, url, client } = self;
94        let url = url.join("/api/v3/trades").unwrap();
95
96        ParamBuilder::new(
97            Parameters { symbol: Some(symbol), ..Parameters::default() },
98            client.get(url),
99            Some(api_key),
100            None
101        )
102    }
103    /// Get older trades.
104    /// # Example
105    ///
106    /// ```no_run
107    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
108    /// use serde_json::Value;
109    /// 
110    /// # #[tokio::main]
111    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
112    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
113    /// let response = client
114    ///     .get_historical_trades("BNBUSDT")
115    ///     // optional: trade id to fetch from; default gets most recent trades.
116    ///     .with_from_id(123049)
117    ///     // optional: default 100; max 5000.
118    ///     .with_limit(5)
119    ///     //
120    ///     .json::<Value>()
121    ///     .await?;
122    /// # Ok(())
123    /// # }
124    /// ```
125    pub fn get_historical_trades<'a>(&self, symbol: &'a str) -> ParamBuilder<'a, '_, HistoricalTradesParams>{
126        let Self { ref api_key, url, client } = self;
127        let url = url.join("/api/v3/historicalTrades").unwrap();
128
129        ParamBuilder::new(
130            Parameters { symbol: Some(symbol), ..Parameters::default() },
131            client.get(url),
132            Some(api_key),
133            None
134        )
135    }
136    /// Get compressed, aggregate trades. 
137    /// Trades that fill at the time, from the same order, 
138    /// with the same price will have the quantity aggregated.
139    /// # Example
140    ///
141    /// ```no_run
142    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
143    /// use chrono::{Utc, Duration};
144    /// use serde_json::Value;
145    /// 
146    /// # #[tokio::main]
147    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
148    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
149    /// let end = Utc::now();
150    /// let start = end - Duration::minutes(59);
151    /// 
152    /// let response = client
153    ///     .get_aggregate_trades("BNBUSDT")
154    ///     // optional: filter by orders greater than or equal to the provided id.
155    ///     .with_from_id(1230494)
156    ///     // optional: get agg trades from; pass 60 minutes of agg trades is the default.
157    ///     .with_start_time(start)
158    ///     // optional: get agg trades until; default is now.
159    ///     .with_end_time(end)
160    ///     // optional: limit the amount of agg trades; default 500; max 1000.
161    ///     .with_limit(100)
162    ///     //
163    ///     .json::<Value>()
164    ///     .await?;
165    /// # Ok(())
166    /// # }
167    /// ```
168    pub fn get_aggregate_trades<'a>(&self, symbol: &'a str) -> ParamBuilder<'a, '_, AggTradesParams>{
169        let Self { ref api_key, url, client } = self;
170        let url = url.join("/api/v3/aggTrades").unwrap();
171
172        ParamBuilder::new(
173            Parameters { symbol: Some(symbol), ..Parameters::default() },
174            client.get(url),
175            Some(api_key),
176            None
177        )
178    }
179    /// Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
180    /// # Example
181    ///
182    /// ```no_run
183    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
184    /// use tokio_binance::Interval;
185    /// use chrono::{Utc, Duration};
186    /// use serde_json::Value;
187    /// 
188    /// # #[tokio::main]
189    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
190    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
191    /// let end = Utc::now();
192    /// let start = end - Duration::minutes(499);
193    /// 
194    /// let response = client
195    ///     .get_candlestick_bars("BNBUSDT", Interval::OneMinute)
196    ///     // optional: get klines from; gets all recent klines by default
197    ///     .with_start_time(start)
198    ///     // optional: get klines until; default is now.
199    ///     .with_end_time(end)
200    ///     // optional: limit the amount of klines; default 500; max 1000.
201    ///     .with_limit(100)
202    ///     //
203    ///     .json::<Value>()
204    ///     .await?;
205    /// # Ok(())
206    /// # }
207    /// ```
208    pub fn get_candlestick_bars<'a>(&self, symbol: &'a str, interval: Interval) -> ParamBuilder<'a, '_, KlinesParams>{
209        let Self { ref api_key, url, client } = self;
210        let url = url.join("/api/v3/klines").unwrap();
211
212        ParamBuilder::new(
213            Parameters { symbol: Some(symbol), interval: Some(interval), ..Parameters::default() },
214            client.get(url),
215            Some(api_key),
216            None
217        )
218    }
219    /// Current average price for a symbol.
220    /// # Example
221    ///
222    /// ```no_run
223    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
224    /// use serde_json::Value;
225    /// 
226    /// # #[tokio::main]
227    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
228    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
229    /// let response = client
230    ///     .get_average_price("BNBUSDT")
231    ///     .json::<Value>()
232    ///     .await?;
233    /// # Ok(())
234    /// # }
235    /// ```
236    pub fn get_average_price<'a>(&self, symbol: &'a str) -> ParamBuilder<'a, '_, AveragePriceParams>{
237        let Self { ref api_key, url, client } = self;
238        let url = url.join("/api/v3/avgPrice").unwrap();
239
240        ParamBuilder::new(
241            Parameters { symbol: Some(symbol), ..Parameters::default() },
242            client.get(url),
243            Some(api_key),
244            None
245        )
246    }
247    /// 24 hour rolling window price change statistics. 
248    /// Careful when accessing this with no symbol.
249    /// # Example
250    ///
251    /// ```no_run
252    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
253    /// use serde_json::Value;
254    /// 
255    /// # #[tokio::main]
256    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
257    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
258    /// let response = client
259    ///     .get_24hr_ticker_price()
260    ///     // optional: filter by symbol; gets all symbols by default.
261    ///     .with_symbol("BNBUSDT")
262    ///     //
263    ///     .json::<Value>()
264    ///     .await?;
265    /// # Ok(())
266    /// # }
267    /// ```
268    pub fn get_24hr_ticker_price<'a>(&self) -> ParamBuilder<'a, '_, TwentyfourHourTickerPriceParams>{
269        let Self { ref api_key, url, client } = self;
270        let url = url.join("/api/v3/ticker/24hr").unwrap();
271
272        ParamBuilder::new(
273            Parameters::default(),
274            client.get(url),
275            Some(api_key),
276            None
277        )
278    }
279    /// Latest price for a symbol or symbols.
280    /// # Example
281    ///
282    /// ```no_run
283    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
284    /// use serde_json::Value;
285    /// 
286    /// # #[tokio::main]
287    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
288    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
289    /// let response = client
290    ///     .get_price_ticker()
291    ///     // optional: filter by symbol; gets all symbols by default.
292    ///     .with_symbol("BNBUSDT")
293    ///     //
294    ///     .json::<Value>()
295    ///     .await?;
296    /// # Ok(())
297    /// # }
298    /// ```
299    pub fn get_price_ticker<'a>(&self) -> ParamBuilder<'a, '_, TickerPriceParams>{
300        let Self { ref api_key, url, client } = self;
301        let url = url.join("/api/v3/ticker/price").unwrap();
302
303        ParamBuilder::new(
304            Parameters::default(),
305            client.get(url),
306            Some(api_key),
307            None
308        )
309    }
310    /// Best price/qty on the order book for a symbol or symbols.
311    /// # Example
312    ///
313    /// ```no_run
314    /// # use tokio_binance::{MarketDataClient, BINANCE_US_URL};
315    /// use serde_json::Value;
316    /// 
317    /// # #[tokio::main]
318    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
319    /// # let client = MarketDataClient::connect("<api-key>", BINANCE_US_URL)?;
320    /// let response = client
321    ///     .get_order_book_ticker()
322    ///     // optional: filter by symbol; gets all symbols by default.
323    ///     .with_symbol("BNBUSDT")
324    ///     //
325    ///     .json::<Value>()
326    ///     .await?;
327    /// # Ok(())
328    /// # }
329    /// ```
330    pub fn get_order_book_ticker<'a>(&self) -> ParamBuilder<'a, '_, OrderBookTickerParams>{
331        let Self { ref api_key, url, client } = self;
332        let url = url.join("/api/v3/ticker/bookTicker").unwrap();
333
334        ParamBuilder::new(
335            Parameters::default(),
336            client.get(url),
337            Some(api_key),
338            None
339        )
340    }
341}