crypto_rest_client/exchanges/
deribit.rs

1use super::utils::http_get;
2use crate::error::Result;
3use std::collections::BTreeMap;
4
5const BASE_URL: &str = "https://www.deribit.com/api/v2";
6
7/// The RESTful client for Deribit.
8///
9/// Deribit has InverseFuture, InverseSwap and Option markets.
10///
11/// * WebSocket API doc: <https://docs.deribit.com/?shell#market-data>
12/// * Trading at:
13///     * Future <https://www.deribit.com/main#/futures>
14///     * Option <https://www.deribit.com/main#/options>
15/// * Rate Limits: <https://www.deribit.com/pages/information/rate-limits>
16///   * Each sub-account has a rate limit of 20 requests per second
17pub struct DeribitRestClient {
18    _api_key: Option<String>,
19    _api_secret: Option<String>,
20}
21
22impl DeribitRestClient {
23    pub fn new(api_key: Option<String>, api_secret: Option<String>) -> Self {
24        DeribitRestClient { _api_key: api_key, _api_secret: api_secret }
25    }
26
27    /// Get most recent trades.
28    ///
29    /// 100 trades are returned.
30    ///
31    /// For example: <https://www.deribit.com/api/v2/public/get_last_trades_by_instrument?count=100&instrument_name=BTC-PERPETUAL>
32    pub fn fetch_trades(symbol: &str) -> Result<String> {
33        gen_api!(format!(
34            "/public/get_last_trades_by_instrument?count=100&instrument_name={symbol}"
35        ))
36    }
37
38    /// Get the latest Level2 snapshot of orderbook.
39    ///
40    /// Top 2000 bids and asks are returned.
41    ///
42    /// For example: <https://www.deribit.com/api/v2/public/get_order_book?depth=2000&instrument_name=BTC-PERPETUAL>,
43    pub fn fetch_l2_snapshot(symbol: &str) -> Result<String> {
44        gen_api!(format!("/public/get_order_book?depth=2000&instrument_name={symbol}",))
45    }
46
47    /// Get open interest.
48    ///
49    /// For example:
50    /// - <https://www.deribit.com/api/v2/public/get_book_summary_by_currency?currency=BTC>
51    /// - <https://www.deribit.com/api/v2/public/get_book_summary_by_instrument?instrument_name=BTC-PERPETUAL>
52    pub fn fetch_open_interest(symbol: Option<&str>) -> Result<String> {
53        if let Some(symbol) = symbol {
54            gen_api!(format!("/public/get_book_summary_by_instrument?instrument_name={symbol}"))
55        } else {
56            let btc = gen_api!("/public/get_book_summary_by_currency?currency=BTC")?;
57            let eth = gen_api!("/public/get_book_summary_by_currency?currency=ETH")?;
58            let sol = gen_api!("/public/get_book_summary_by_currency?currency=SOL")?;
59            let usdc = gen_api!("/public/get_book_summary_by_currency?currency=USDC")?;
60            Ok(format!("{btc}\n{eth}\n{sol}\n{usdc}"))
61        }
62    }
63}