Skip to main content

ccdata_api/
backend.rs

1use std::{env::var, collections::HashMap};
2use dotenv::dotenv;
3use crate::error::Error;
4use crate::{CCUnit, CCAPIEndpoint};
5use crate::schemas::{self as sh, CCDataResponse};
6use crate::schemas::min_api;
7use crate::schemas::data_api::indices_and_reference_rates::{CCIndicesMarket, CCIndicesOHLCV};
8use crate::schemas::data_api::spot::{CCSpotMarket, CCSpotInstrumentStatus, CCSpotOHLCV, CCSpotInstrumentMetdata, CCSpotMarkets,
9                                     CCSpotMarketsInstruments};
10use crate::schemas::data_api::futures::{CCFuturesMarket, CCFuturesOHLCV, CCFuturesMarkets};
11use crate::schemas::data_api::options::{CCOptionsMarket, CCOptionsOHLCV, CCOptionsMarkets};
12use crate::schemas::data_api::derivatives_indices::{CCDerIndicesMarket, CCDerIndicesOHLCV, CCDerIndicesMarkets};
13use crate::schemas::data_api::on_chain_dex::{CCOCDEXMarket, CCOCDEXOHLCV, CCOCDEXMarkets};
14use crate::schemas::data_api::on_chain_core::{CCOCCoreETHBlock, CCOCCoreAssetByChain, CCOCCoreAssetByAddress, CCOCCoreSupply};
15use crate::schemas::data_api::asset::{CCAssetMetadata, CCAssetEvent, CCAssetCodeRepoMetrics, CCAssetDiscord, CCAssetReddit, CCAssetTelegram, CCAssetTwitter};
16use crate::schemas::data_api::news::{CCNewsStatus, CCNewsLang, CCNewsSourceID, CCNewsLatestArticle, CCNewsSourceType, CCNewsSource, CCNewsCategory};
17use crate::schemas::data_api::overview::CCOverviewMktCapOHLCV;
18use crate::utils::{Market, Param, call_api_endpoint};
19
20
21/// API data collection backend.
22pub struct CCData {
23    /// CoinDesk API key
24    api_key: Option<String>,
25}
26
27impl CCData {
28    /// Creates a new backend for data collection.
29    pub fn new() -> Self {
30        Self { api_key: None }
31    }
32
33    /// Returns the refernce to the defined API key.
34    ///
35    /// # Examples
36    ///
37    /// ```rust
38    /// use ccdata_api::CCData;
39    ///
40    /// let mut backend: CCData = CCData::new();
41    /// // Provide API key as the environment variable called API_KEY
42    /// backend.build(&"API_KEY").unwrap();
43    ///
44    /// println!("{}", backend.api_key().unwrap());
45    /// ```
46    pub fn api_key(&self) -> Result<&str, Error> {
47        match &self.api_key {
48            Some(v) => Ok(v),
49            None => Err(Error::NoAPIKey),
50        }
51    }
52
53    /// Updates the API key.
54    ///
55    /// # Input
56    /// - `new_api_key`: New API key that will be used by the backend to send requests to CoinDesk API endpoints
57    ///
58    /// # Examples
59    ///
60    /// ```rust
61    /// use ccdata_api::CCData;
62    ///
63    /// let mut backend: CCData = CCData::new();
64    ///
65    /// let new_api_key: String = String::from("xxxxxxx");
66    /// backend.update_api_key(new_api_key);
67    ///
68    /// assert_eq!(backend.api_key().unwrap(), "xxxxxxx");
69    /// ```
70    pub fn update_api_key(&mut self, new_api_key: String) -> () {
71        self.api_key = Some(new_api_key);
72    }
73
74    /// Initiates the API data collection backend with the API key stored in the environment variable.
75    ///
76    /// # Input
77    /// -`api_key_env_var`: Name of the environment variable in the local `.env` file that stores the CoinDesk API key
78    ///
79    /// # Examples
80    ///
81    /// ```rust
82    /// use ccdata_api::CCData;
83    ///
84    /// let mut backend: CCData = CCData::new();
85    /// // Provide API key as the environment variable called API_KEY
86    /// backend.build(&"API_KEY").unwrap();
87    ///
88    /// println!("{}", backend.api_key().unwrap());
89    /// ```
90    pub fn build(&mut self, api_key_env_var: &str) -> Result<(), Error> {
91        dotenv()?;
92        Ok(self.update_api_key(var(api_key_env_var)?))
93    }
94
95    #[deprecated(since="1.0.6", note="Deprecated by CoinDesk")]
96    /// # Available Coin List (Blockchain Data)
97    /// Returns a list of all coins that CoinDesk have data for.
98    ///
99    /// # Description (CoinDesk Documentation)
100    /// Powered by IntoTheBlock, an intelligence company that leverages machine learning and advanced statistics to extract intelligent signals for crypto-assets.
101    ///
102    /// You can only use this endpoint with a valid api_key. Returns a list of all coins for which we currently get blockchain data from IntoTheBlock.
103    ///
104    /// # Examples
105    ///
106    /// ```rust
107    ///
108    /// use ccdata_api::CCData;
109    ///
110    /// #[tokio::main]
111    /// async fn main() -> () {
112    ///
113    ///     let mut backend: CCData = CCData::new();
114    ///     // Provide API key as the environment variable called API_KEY
115    ///     backend.build(&"API_KEY").unwrap();
116    ///
117    ///     let available_coin_list = backend.get_available_coin_list().await.unwrap();
118    ///     assert!(0 < available_coin_list.data.unwrap().len());
119    ///
120    /// }
121    /// ```
122    pub async fn get_available_coin_list(&self) -> Result<sh::CCMinResponse<HashMap<String, min_api::CCAvailableCoinList>>, Error> {
123        call_api_endpoint::<sh::CCMinResponse<HashMap<String, min_api::CCAvailableCoinList>>>(
124            self.api_key()?,
125            CCAPIEndpoint::AvailableCoinList, CCUnit::NA,
126            vec![], None
127        ).await
128    }
129
130    #[deprecated(since="1.0.6", note="Deprecated by CoinDesk")]
131    /// # Historical Daily (Blockchain Data)
132    /// Returns the historical data for a given symbol.
133    ///
134    /// # Description (CoinDesk Documentation)
135    /// Powered by IntoTheBlock, an intelligence company that leverages machine learning and advanced statistics to extract intelligent signals for crypto-assets.
136    /// Full description of the return fields available here.
137    ///
138    /// You can only use this endpoint with a valid api_key. Retrieve the daily aggregated blockchain data for the requested coin,
139    /// back through time for the number of points as specifed by the limit. Timestamp values are based on 00:00 GMT time.
140    ///
141    /// # Input
142    /// - `symbol`: Asset symbol
143    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
144    /// - `limit`: Maximum number of datapoints per API endpoint call
145    ///
146    /// # Examples
147    ///
148    /// ```rust
149    ///
150    /// use ccdata_api::CCData;
151    ///
152    /// #[tokio::main]
153    /// async fn main() -> () {
154    ///
155    ///     let mut backend: CCData = CCData::new();
156    ///     // Provide API key as the environment variable called API_KEY
157    ///     backend.build(&"API_KEY").unwrap();
158    ///
159    ///     let limit: usize = 2000;
160    ///     let historical_daily = backend.get_historical_daily("ETH", None, Some(limit)).await.unwrap();
161    ///     assert!(historical_daily.data.unwrap().data.unwrap().len() <= limit);
162    ///
163    /// }
164    /// ```
165    pub async fn get_historical_daily(&self, symbol: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<sh::CCMinResponse<sh::CCMinWrapper<Vec<min_api::CCHistoricalDaily>>>, Error> {
166        call_api_endpoint::<sh::CCMinResponse<sh::CCMinWrapper<Vec<min_api::CCHistoricalDaily>>>>(
167            self.api_key()?,
168            CCAPIEndpoint::HistoricalDaily, CCUnit::NA,
169            vec![Param::Symbol{v: symbol}, Param::Limit{v: limit}, Param::ToTs{v: to_timestamp}], None
170        ).await
171    }
172
173    #[deprecated(since="1.0.6", note="Deprecated by CoinDesk")]
174    /// # Balance Distribution Daily (Blockchain Data)
175    /// Returns the daily balance distribution history for Bitcoin.
176    ///
177    /// # Description (CoinDesk Documentation)
178    /// Powered by IntoTheBlock, an intelligence company that leverages machine learning and advanced statistics to extract intelligent signals for crypto-assets.
179    /// 
180    /// Retrieves the balance distribution for a specified asset over a specified time range at a daily interval.
181    /// Only data for BTC (Bitcoin) is currently available.
182    ///
183    /// You can only use this endpoint with a valid api_key. Retrieve the daily wallet balance distribution data for the requested coin,
184    /// back through time for the number of points as specifed by the limit. Timestamp values are based on 00:00 GMT time.
185    ///
186    /// # Input
187    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
188    /// - `limit`: Maximum number of datapoints per API endpoint call
189    ///
190    /// # Examples
191    ///
192    /// ```rust
193    ///
194    /// use ccdata_api::CCData;
195    ///
196    /// #[tokio::main]
197    /// async fn main() -> () {
198    ///
199    ///     let mut backend: CCData = CCData::new();
200    ///     // Provide API key as the environment variable called API_KEY
201    ///     backend.build(&"API_KEY").unwrap();
202    ///
203    ///     let limit: usize = 2000;
204    ///     let balance_distribution = backend.get_balance_distribution(None, Some(limit)).await.unwrap();
205    ///     assert!(balance_distribution.data.unwrap().data.unwrap().len() <= limit);
206    ///
207    /// }
208    /// ```
209    pub async fn get_balance_distribution(&self, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<sh::CCMinResponse<sh::CCMinWrapper<Vec<min_api::CCBalanceDistribution>>>, Error> {
210        call_api_endpoint::<sh::CCMinResponse<sh::CCMinWrapper<Vec<min_api::CCBalanceDistribution>>>>(
211            self.api_key()?,
212            CCAPIEndpoint::BalanceDistribution, CCUnit::NA,
213            vec![Param::Symbol{v: "BTC"}, Param::Limit{v: limit}, Param::ToTs{v: to_timestamp}], None
214        ).await
215    }
216
217    /// # Historical OHLCV+ \[Day, Hour, Minute\] (Indices & Ref. Rates)
218    /// Returns historical OHLCV data for a given instrument.
219    ///
220    /// # Description (CoinDesk Documentation)
221    /// This endpoint is meticulously designed to provide historical candlestick data for various indices, captured at one-day intervals.
222    /// The data encompasses crucial metrics such as OPEN, HIGH, LOW, CLOSE, VOLUME and additional trading-derived values (OHLCV+),
223    /// offering a comprehensive view of an index's historical performance. This information is essential for conducting in-depth market analyses and making
224    /// informed decisions based on past trends.
225    ///
226    /// # Input
227    /// - `instument`: Instrument symbol
228    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
229    /// - `limit`: Maximum number of datapoints per API endpoint call
230    /// - `market`: Market name
231    /// - `unit`: Unit of the interval between successive data points
232    ///
233    /// # Examples
234    ///
235    /// ```rust
236    ///
237    /// use ccdata_api::{CCData, CCUnit, CCIndicesMarket};
238    ///
239    /// #[tokio::main]
240    /// async fn main() -> () {
241    ///
242    ///     let mut backend: CCData = CCData::new();
243    ///     // Provide API key as the environment variable called API_KEY
244    ///     backend.build(&"API_KEY").unwrap();
245    ///
246    ///     let market: CCIndicesMarket = CCIndicesMarket::CADLI;
247    ///     let limit: usize = 2000;
248    ///     let ohlcv = backend.get_indices_ohlcv("BTC-USD", None, Some(limit), market, CCUnit::Day).await.unwrap();
249    ///     assert_eq!(ohlcv.data.unwrap().len(), limit);
250    ///
251    /// }
252    /// ```
253    pub async fn get_indices_ohlcv(&self, instrument: &str, to_timestamp: Option<i64>, limit: Option<usize>, market: CCIndicesMarket, unit: CCUnit) -> Result<CCDataResponse<Vec<CCIndicesOHLCV>>, Error> {
254        call_api_endpoint::<CCDataResponse<Vec<CCIndicesOHLCV>>>(
255            self.api_key()?,
256            CCAPIEndpoint::IndicesOHLCV, unit,
257            vec![Param::Instrument{v: instrument}, Param::Limit{v: limit}, Param::ToTimestamp{v: to_timestamp}, Param::Market{v: market.to_string()}], None
258        ).await
259    }
260
261    /// # Historical OHLCV+ \[Day, Hour, Minute\] (Spot)
262    /// Returns historical OHLCV data for a given instrument.
263    ///
264    /// # Description (CoinDesk Documentation)
265    /// This endpoint delivers daily aggregated candlestick data for specific cryptocurrency instruments across selected exchanges.
266    /// It offers vital trading metrics, including open, high, low, close (OHLC) prices, and trading volumes, both in base and quote currencies.
267    /// This data is key for understanding historical price movements and market behavior, allowing for detailed analysis of trading patterns and trends over time.
268    ///
269    /// # Input
270    /// - `instument`: Instrument symbol
271    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
272    /// - `limit`: Maximum number of datapoints per API endpoint call
273    /// - `market`: Market name
274    /// - `unit`: Unit of the interval between successive data points
275    ///
276    /// # Examples
277    ///
278    /// ```rust
279    ///
280    /// use ccdata_api::{CCData, CCUnit, CCSpotMarket};
281    ///
282    /// #[tokio::main]
283    /// async fn main() -> () {
284    ///
285    ///     let mut backend: CCData = CCData::new();
286    ///     // Provide API key as the environment variable called API_KEY
287    ///     backend.build(&"API_KEY").unwrap();
288    ///
289    ///     let market: CCSpotMarket = CCSpotMarket::KRAKEN;
290    ///     let limit: usize = 2000;
291    ///     let ohlcv = backend.get_spot_ohlcv("BTC-USD", None, Some(limit), market, CCUnit::Day).await.unwrap();
292    ///     assert_eq!(ohlcv.data.unwrap().len(), limit);
293    ///
294    /// }
295    /// ```
296    pub async fn get_spot_ohlcv(&self, instrument: &str, to_timestamp: Option<i64>, limit: Option<usize>, market: CCSpotMarket, unit: CCUnit) -> Result<CCDataResponse<Vec<CCSpotOHLCV>>, Error> {
297        call_api_endpoint::<CCDataResponse<Vec<CCSpotOHLCV>>>(
298            self.api_key()?,
299            CCAPIEndpoint::SpotOHLCV, unit,
300            vec![Param::Instrument{v: instrument}, Param::Limit{v: limit}, Param::ToTimestamp{v: to_timestamp}, Param::Market{v: market.to_string()}], None
301        ).await
302    }
303
304    /// # Instrument Metadata (Spot)
305    /// Returns metadata for a given instrument.
306    ///
307    /// # Description (CoinDesk Documentation)
308    /// This endpoint, specific to the Spot segment of the API, delivers vital metadata about financial instruments traded on specified exchanges,
309    /// focusing solely on non-price related information. This endpoint is crucial for internal use, offering a comprehensive dataset that includes mappings,
310    /// operational statuses, and historical data (first seen/last seen timestamps) about each instrument.
311    ///
312    /// # Input
313    /// - `instruments`: List of instrument symbols
314    /// - `market`: Market name
315    ///
316    /// # Examples
317    ///
318    /// ```rust
319    ///
320    /// use ccdata_api::{CCData, CCSpotMarket};
321    ///
322    /// #[tokio::main]
323    /// async fn main() -> () {
324    ///
325    ///     let mut backend: CCData = CCData::new();
326    ///     // Provide API key as the environment variable called API_KEY
327    ///     backend.build(&"API_KEY").unwrap();
328    ///
329    ///     let instruments: Vec<String> = vec![String::from("BTC-USD"), String::from("ETH-USD")];
330    ///     let market: CCSpotMarket = CCSpotMarket::KRAKEN;
331    ///     let instrument_metadata = backend.get_spot_instrument_metadata(&instruments, market).await.unwrap();
332    ///     assert_eq!(instrument_metadata.data.unwrap().len(), 2);
333    ///
334    /// }
335    /// ```
336    pub async fn get_spot_instrument_metadata(&self, instruments: &Vec<String>, market: CCSpotMarket) -> Result<CCDataResponse<HashMap<String, CCSpotInstrumentMetdata>>, Error> {
337        call_api_endpoint::<CCDataResponse<HashMap<String, CCSpotInstrumentMetdata>>>(
338            self.api_key()?,
339            CCAPIEndpoint::SpotInstrumentMetadata, CCUnit::NA,
340            vec![Param::Instruments{v: instruments}, Param::Market{v: market.to_string()}], None
341        ).await
342    }
343
344    /// # Markets (Spot)
345    /// Returns metadata about a given market.
346    ///
347    /// # Description (CoinDesk Documentation)
348    /// This endpoint provides comprehensive information about various cryptocurrency spot markets. By specifying a market through the "market" parameter,
349    /// users can retrieve details about a specific market, such as its trading pairs, volume, operational status, and other relevant metadata.
350    /// If no specific market is indicated, the endpoint delivers data on all available markets. This functionality is essential for users looking to explore
351    /// and compare the characteristics and trading conditions of different cryptocurrency exchanges or market segments, assisting in market analysis,
352    /// strategic planning, and decision-making.
353    ///
354    /// # Input
355    /// - `market`: Market name
356    ///
357    /// # Examples
358    ///
359    /// ```rust
360    ///
361    /// use ccdata_api::{CCData, CCSpotMarket};
362    ///
363    /// #[tokio::main]
364    /// async fn main() -> () {
365    ///
366    ///     let mut backend: CCData = CCData::new();
367    ///     // Provide API key as the environment variable called API_KEY
368    ///     backend.build(&"API_KEY").unwrap();
369    ///
370    ///     let market: CCSpotMarket = CCSpotMarket::KRAKEN;
371    ///     let markets = backend.get_spot_markets(market).await.unwrap();
372    ///     assert_eq!(markets.data.unwrap().get("kraken").unwrap().exchange_status, String::from("ACTIVE"));
373    ///
374    /// }
375    /// ```
376    pub async fn get_spot_markets(&self, market: CCSpotMarket) -> Result<CCDataResponse<HashMap<String, CCSpotMarkets>>, Error> {
377        call_api_endpoint::<CCDataResponse<HashMap<String, CCSpotMarkets>>>(
378            self.api_key()?,
379            CCAPIEndpoint::SpotMarkets, CCUnit::NA,
380            vec![Param::Market{v: market.to_string()}], None
381        ).await
382    }
383
384    /// # Markets + Instruments \[Mapped\] (Spot)
385    /// Returns a map of given instruments across a market.
386    ///
387    /// # Description (CoinDesk Documentation)
388    /// This endpoint retrieves a comprehensive dictionary of mapped instruments across one or more spot markets, filtered by a specified state or status.
389    /// Each entry in the dictionary uses the instrument ID—standardized by the mapping team—as the key, ensuring consistency and ease of reference.
390    /// This endpoint is particularly valuable for users needing precise and standardized information on trading instruments, facilitating the tracking,
391    // comparison, and analysis of different instruments within and across various spot markets. It is ideal for applications that depend on uniform identifiers
392    /// to integrate and interpret market data effectively.
393    ///
394    /// # Input
395    /// - `instruments`: List of instrument symbols
396    /// - `market`: Market name
397    /// - `instrument_status`: Status of the instrument (e.g., `ACTIVE`, `EXPIRED`)
398    ///
399    /// # Examples
400    ///
401    /// ```rust
402    ///
403    /// use ccdata_api::{CCData, CCSpotMarket, CCSpotInstrumentStatus};
404    ///
405    /// #[tokio::main]
406    /// async fn main() -> () {
407    ///
408    ///     let mut backend: CCData = CCData::new();
409    ///     // Provide API key as the environment variable called API_KEY
410    ///     backend.build(&"API_KEY").unwrap();
411    ///
412    ///     let instruments: Vec<String> = vec![String::from("BTC-USD"), String::from("ETH-USD")];
413    ///     let market: CCSpotMarket = CCSpotMarket::KRAKEN;
414    ///     let instrument_status: CCSpotInstrumentStatus = CCSpotInstrumentStatus::ACTIVE;
415    ///     let markets_instruments = backend.get_spot_markets_instruments(&instruments, market, instrument_status).await.unwrap();
416    ///     assert_eq!(markets_instruments.data.unwrap().get("kraken").unwrap().instruments.len(), 2);
417    ///
418    /// }
419    /// ```
420    pub async fn get_spot_markets_instruments(&self, instruments: &Vec<String>, market: CCSpotMarket, instrument_status: CCSpotInstrumentStatus) -> Result<CCDataResponse<HashMap<String, CCSpotMarketsInstruments>>, Error> {
421        call_api_endpoint::<CCDataResponse<HashMap<String, CCSpotMarketsInstruments>>>(
422            self.api_key()?,
423            CCAPIEndpoint::SpotMarketsInstruments, CCUnit::NA,
424            vec![Param::Instruments{v: instruments}, Param::Market{v: market.to_string()}, Param::InstrumentStatus {v: instrument_status}], None
425        ).await
426    }
427
428    /// # Historical OHLCV+ \[Day, Hour, Minute\] (Futures)
429    /// Returns historical OHLCV data for a given instrument.
430    ///
431    /// # Description (CoinDesk Documentation)
432    /// This endpoint offers daily aggregated candlestick data for specific futures instruments on designated exchanges.
433    /// It provides crucial trading data points such as open, high, low, close prices (OHLC), and volumes, vital for traders and analysts aiming to
434    /// understand historical price movements and market behavior over specific periods. The flexibility of this endpoint is enhanced by supporting a range
435    /// of parameters to tailor the data retrieval to specific needs, such as market selection, instrument details, and aggregation customization.
436    /// This makes it a highly adaptable tool for historical data analysis in the context of futures markets.
437    ///
438    /// # Input
439    /// - `instrument`: Instrument symbol
440    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
441    /// - `limit`: Maximum number of datapoints per API endpoint call
442    /// - `market`: Market name
443    /// - `unit`: Unit of the interval between successive data points
444    ///
445    /// # Examples
446    ///
447    /// ```rust
448    ///
449    /// use ccdata_api::{CCData, CCUnit, CCFuturesMarket};
450    ///
451    /// #[tokio::main]
452    /// async fn main() -> () {
453    ///
454    ///     let mut backend: CCData = CCData::new();
455    ///     // Provide API key as the environment variable called API_KEY
456    ///     backend.build(&"API_KEY").unwrap();
457    ///
458    ///     let market: CCFuturesMarket = CCFuturesMarket::BINANCE;
459    ///     let limit: usize = 2000;
460    ///     let ohlcv = backend.get_futures_ohlcv("BTC-USDT-VANILLA-PERPETUAL", None, Some(limit), market, CCUnit::Day).await.unwrap();
461    ///     assert!(ohlcv.data.unwrap().len() <= limit)
462    ///
463    /// }
464    /// ```
465    pub async fn get_futures_ohlcv(&self, instrument: &str, to_timestamp: Option<i64>, limit: Option<usize>, market: CCFuturesMarket, unit: CCUnit) -> Result<CCDataResponse<Vec<CCFuturesOHLCV>>, Error> {
466        call_api_endpoint::<CCDataResponse<Vec<CCFuturesOHLCV>>>(
467            self.api_key()?,
468            CCAPIEndpoint::FuturesOHLCV, unit,
469            vec![Param::Instrument{v: instrument}, Param::Limit{v: limit}, Param::ToTimestamp{v: to_timestamp}, Param::Market{v: market.to_string()}],
470            Some(String::from("&groups=ID,MAPPING,OHLC,TRADE,VOLUME,MAPPING_ADVANCED,OHLC_TRADE"))
471        ).await
472    }
473
474    /// # Markets (Futures)
475    /// Returns metadata about a given market.
476    ///
477    /// # Description (CoinDesk Documentation)
478    /// This endpoint provides comprehensive information about various cryptocurrency futures markets. By utilizing the "market" parameter,
479    /// users can access detailed data about specific futures markets, including trading pairs, volume, operational status, and additional relevant metadata.
480    /// If no specific market is specified, the endpoint returns information on all available futures markets. This capability is crucial for users who wish
481    /// to explore and analyze the characteristics and trading conditions of different cryptocurrency futures exchanges or market segments,
482    /// aiding in market analysis, strategic planning, and decision-making.
483    ///
484    /// # Input
485    /// - `market`: Market name
486    ///
487    /// # Examples
488    ///
489    /// ```rust
490    ///
491    /// use ccdata_api::{CCData, CCFuturesMarket};
492    ///
493    /// #[tokio::main]
494    /// async fn main() -> () {
495    ///
496    ///     let mut backend: CCData = CCData::new();
497    ///     // Provide API key as the environment variable called API_KEY
498    ///     backend.build(&"API_KEY").unwrap();
499    ///
500    ///     let market: CCFuturesMarket = CCFuturesMarket::BINANCE;
501    ///     let markets = backend.get_futures_markets(market).await.unwrap();
502    ///     assert_eq!(markets.data.unwrap().get("binance").unwrap().exchange_status, String::from("ACTIVE"));
503    ///
504    /// }
505    /// ```
506    pub async fn get_futures_markets(&self, market: CCFuturesMarket) -> Result<CCDataResponse<HashMap<String, CCFuturesMarkets>>, Error> {
507        call_api_endpoint::<CCDataResponse<HashMap<String, CCFuturesMarkets>>>(
508            self.api_key()?,
509            CCAPIEndpoint::FuturesMarkets, CCUnit::NA,
510            vec![Param::Market{v: market.to_string()}], None
511        ).await
512    }  
513
514    /// # Historical OHLCV+ \[Day, Hour, Minute\] (Options)
515    /// Returns historical OHLCV data for a given instrument.
516    ///
517    /// # Description (CoinDesk Documentation)
518    /// The Options Historical OHLCV+ Day endpoint provides historical OHLCV (open, high, low, close, volume) data for specified options instruments
519    /// on a chosen exchange, aggregated on a daily basis. This API endpoint delivers comprehensive historical data, enabling users to perform detailed
520    /// analysis of options market performance over time. It is essential for long-term market analysis, backtesting strategies, and informed
521    /// decision-making based on historical trends.
522    ///
523    /// # Input
524    /// - `instrument`: Instrument symbol
525    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
526    /// - `limit`: Maximum number of datapoints per API endpoint call
527    /// - `market`: Market name
528    /// - `unit`: Unit of the interval between successive data points
529    ///
530    /// # Examples
531    ///
532    /// ```rust
533    ///
534    /// use ccdata_api::{CCData, CCUnit, CCOptionsMarket};
535    ///
536    /// #[tokio::main]
537    /// async fn main() -> () {
538    ///
539    ///     let mut backend: CCData = CCData::new();
540    ///     // Provide API key as the environment variable called API_KEY
541    ///     backend.build(&"API_KEY").unwrap();
542    ///
543    ///     let market: CCOptionsMarket = CCOptionsMarket::OKEX;
544    ///     let limit: usize = 2000;
545    ///     let ohlcv = backend.get_options_ohlcv("BTC-USD-20241227-15000-P", None, Some(limit), market, CCUnit::Day).await.unwrap();
546    ///     assert!(ohlcv.data.unwrap().len() <= limit);
547    ///
548    /// }
549    /// ```
550    pub async fn get_options_ohlcv(&self, instrument: &str, to_timestamp: Option<i64>, limit: Option<usize>, market: CCOptionsMarket, unit: CCUnit) -> Result<CCDataResponse<Vec<CCOptionsOHLCV>>, Error> {
551        call_api_endpoint::<CCDataResponse<Vec<CCOptionsOHLCV>>>(
552            self.api_key()?,
553            CCAPIEndpoint::OptionsOHLCV, unit,
554            vec![Param::Instrument{v: instrument}, Param::Limit{v: limit}, Param::ToTimestamp{v: to_timestamp}, Param::Market{v: market.to_string()}],
555            Some(String::from("&groups=ID,MAPPING,OHLC,TRADE,VOLUME,MAPPING_ADVANCED,OHLC_TRADE"))
556        ).await
557    }
558
559    /// # Markets (Options)
560    /// Returns metadata about a given market.
561    ///
562    /// # Description (CoinDesk Documentation)
563    /// This endpoint provides comprehensive information about the various options markets integrated by our platform. By utilizing the "market" parameter,
564    /// users can access detailed data about specific options markets, including available instruments, trading volume, operational status, and additional
565    /// relevant metadata. If no specific market is specified, the endpoint returns information on all integrated options markets.
566    /// This capability is crucial for users who wish to explore and analyze the characteristics and trading conditions of different options exchanges
567    /// or market segments, aiding in market analysis, strategic planning, and decision-making.
568    ///
569    /// # Input
570    /// - `market`: Market name
571    ///
572    /// # Examples
573    ///
574    /// ```rust
575    ///
576    /// use ccdata_api::{CCData, CCOptionsMarket};
577    ///
578    /// #[tokio::main]
579    /// async fn main() -> () {
580    ///
581    ///     let mut backend: CCData = CCData::new();
582    ///     // Provide API key as the environment variable called API_KEY
583    ///     backend.build(&"API_KEY").unwrap();
584    ///
585    ///     let market: CCOptionsMarket = CCOptionsMarket::DERIBIT;
586    ///     let markets = backend.get_options_markets(market).await.unwrap();
587    ///     assert_eq!(markets.data.unwrap().get("deribit").unwrap().exchange_status, String::from("ACTIVE"));
588    ///
589    /// }
590    /// ```
591    pub async fn get_options_markets(&self, market: CCOptionsMarket) -> Result<CCDataResponse<HashMap<String, CCOptionsMarkets>>, Error> {
592        call_api_endpoint::<CCDataResponse<HashMap<String, CCOptionsMarkets>>>(
593            self.api_key()?,
594            CCAPIEndpoint::OptionsMarkets, CCUnit::NA,
595            vec![Param::Market{v: market.to_string()}], None
596        ).await
597    }
598
599    /// # Historical OHLCV+ \[Day, Hour, Minute\] (Derivatives Indices)
600    /// Returns historical OHLCV data for a given instrument.
601    ///
602    /// # Description (CoinDesk Documentation)
603    /// The Derivatives Index Historical OHLC+ Day endpoint provides historical OHLC (open, high, low, close) data for specified index instruments
604    /// on a selected market. This API endpoint delivers daily aggregated index metrics, offering a comprehensive view of historical performance.
605    /// Ideal for long-term analysis, it supports thorough market research and historical data examination, essential for informed decision-making
606    /// and strategic planning.
607    ///
608    /// # Input
609    /// - `instrument`: Instrument symbol
610    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
611    /// - `limit`: Maximum number of datapoints per API endpoint call
612    /// - `market`: Market name
613    /// - `unit`: Unit of the interval between successive data points
614    ///
615    /// # Examples
616    ///
617    /// ```rust
618    ///
619    /// use ccdata_api::{CCData, CCUnit, CCDerIndicesMarket};
620    ///
621    /// #[tokio::main]
622    /// async fn main() -> () {
623    ///
624    ///     let mut backend: CCData = CCData::new();
625    ///     // Provide API key as the environment variable called API_KEY
626    ///     backend.build(&"API_KEY").unwrap();
627    ///
628    ///     let market: CCDerIndicesMarket = CCDerIndicesMarket::BINANCE;
629    ///     let limit: usize = 2000;
630    ///     let ohlcv = backend.get_der_indices_ohlcv("BTCUSDT", None, Some(limit), market, CCUnit::Day).await.unwrap();
631    ///     assert!(ohlcv.data.unwrap().len() <= limit);
632    ///
633    /// }
634    /// ```
635    pub async fn get_der_indices_ohlcv(&self, instrument: &str, to_timestamp: Option<i64>, limit: Option<usize>, market: CCDerIndicesMarket, unit: CCUnit) -> Result<CCDataResponse<Vec<CCDerIndicesOHLCV>>, Error> {
636        call_api_endpoint::<CCDataResponse<Vec<CCDerIndicesOHLCV>>>(
637            self.api_key()?,
638            CCAPIEndpoint::DerIndicesOHLCV, unit,
639            vec![Param::Instrument{v: instrument}, Param::Limit{v: limit}, Param::ToTimestamp{v: to_timestamp}, Param::Market{v: market.to_string()}],
640            Some(String::from("&groups=ID,OHLC,OHLC_MESSAGE,MESSAGE,MAPPING,MAPPING_ADVANCED"))
641        ).await
642    }
643
644    /// # Markets (Derivatives Indices)
645    /// Returns metadata about a given market.
646    ///
647    /// # Description (CoinDesk Documentation)
648    /// This endpoint provides comprehensive information about various derivatives index markets. By specifying a market through the "market" parameter,
649    /// users can retrieve details about a specific derivatives market, such as its index instruments, volume, operational status, and other relevant metadata.
650    /// If no specific market is indicated, the endpoint delivers data on all available markets. This functionality is essential for users looking to explore
651    /// and compare the characteristics and trading conditions of different derivatives exchanges or market segments, assisting in market analysis,
652    /// strategic planning, and decision-making.
653    ///
654    /// # Input
655    /// - `market`: Market name
656    ///
657    /// # Examples
658    ///
659    /// ```rust
660    ///
661    /// use ccdata_api::{CCData, CCDerIndicesMarket};
662    ///
663    /// #[tokio::main]
664    /// async fn main() -> () {
665    ///
666    ///     let mut backend: CCData = CCData::new();
667    ///     // Provide API key as the environment variable called API_KEY
668    ///     backend.build(&"API_KEY").unwrap();
669    ///
670    ///     let market: CCDerIndicesMarket = CCDerIndicesMarket::KRAKEN;
671    ///     let markets = backend.get_der_indices_markets(market).await.unwrap();
672    ///     assert_eq!(markets.data.unwrap().get("kraken").unwrap().exchange_status, String::from("ACTIVE"));
673    ///
674    /// }
675    /// ```
676    pub async fn get_der_indices_markets(&self, market: CCDerIndicesMarket) -> Result<CCDataResponse<HashMap<String, CCDerIndicesMarkets>>, Error> {
677        call_api_endpoint::<CCDataResponse<HashMap<String, CCDerIndicesMarkets>>>(
678            self.api_key()?,
679            CCAPIEndpoint::DerIndicesMarkets, CCUnit::NA,
680            vec![Param::Market{v: market.to_string()}], None
681        ).await
682    }
683
684    /// # Historical OHLCV+ (Swap) \[Day, Hour, Minute\] (On-Chain DEX)
685    /// Returns historical OHLCV data for a given instrument.
686    ///
687    /// # Description (CoinDesk Documentation)
688    /// The On-Chain AMM Historical OHLCV+ (Swap) Day endpoint retrieves daily aggregated candlestick data for AMM swap transactions.
689    /// This data includes open, high, low, and close prices (OHLC), as well as trading volumes in both base and quote currencies for a selected instrument
690    /// on a specified exchange. This endpoint is essential for traders and analysts looking to understand historical price movements and market behavior
691    /// over specific periods.
692    ///
693    /// # Input
694    /// - `instrument`: Instrument symbol
695    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
696    /// - `limit`: Maximum number of datapoints per API endpoint call
697    /// - `market`: Market name
698    /// - `unit`: Unit of the interval between successive data points
699    ///
700    /// # Examples
701    ///
702    /// ```rust
703    ///
704    /// use ccdata_api::{CCData, CCUnit, CCOCDEXMarket};
705    ///
706    /// #[tokio::main]
707    /// async fn main() -> () {
708    ///
709    ///     let mut backend: CCData = CCData::new();
710    ///     // Provide API key as the environment variable called API_KEY
711    ///     backend.build(&"API_KEY").unwrap();
712    ///
713    ///     let market: CCOCDEXMarket = CCOCDEXMarket::UNISWAPV2;
714    ///     let limit: usize = 2000;
715    ///     let ohlcv = backend.get_ocdex_ohlcv("0x0d4a11d5eeaac28ec3f61d100daf4d40471f1852_2", None, Some(limit), market, CCUnit::Day).await.unwrap();
716    ///     assert!(ohlcv.data.unwrap().len() <= limit);
717    ///
718    /// }
719    /// ```
720    pub async fn get_ocdex_ohlcv(&self, instrument: &str, to_timestamp: Option<i64>, limit: Option<usize>, market: CCOCDEXMarket, unit: CCUnit) -> Result<CCDataResponse<Vec<CCOCDEXOHLCV>>, Error> {
721        call_api_endpoint::<CCDataResponse<Vec<CCOCDEXOHLCV>>>(
722            self.api_key()?,
723            CCAPIEndpoint::OCDEXOHLCV, unit,
724            vec![Param::Instrument{v: instrument}, Param::Limit{v: limit}, Param::ToTimestamp{v: to_timestamp}, Param::Market{v: market.to_string()}],
725            Some(String::from("&groups=ID,MAPPING,MAPPING_ADVANCED,OHLC,OHLC_SWAP,SWAP,VOLUME"))
726        ).await
727    }
728
729    /// # Markets (On-Chain DEX)
730    /// Returns metadata about a given market.
731    ///
732    /// # Description (CoinDesk Documentation)
733    /// The On-Chain Markets endpoint offers comprehensive information about various decentralized exchange (DEX) markets within the blockchain ecosystem.
734    /// By specifying a market through the "market" parameter, users can retrieve detailed information about a specific on-chain market, such as its trading pairs,
735    /// liquidity, operational status, and other relevant metadata. If no specific market is indicated, the endpoint delivers data on all available on-chain markets.
736    /// This functionality is essential for users looking to explore and compare the characteristics and trading conditions of different decentralized exchanges
737    /// or market segments, aiding in market analysis, strategic planning, and decision-making.
738    ///
739    /// # Input
740    /// - `market`: Market name
741    ///
742    /// # Examples
743    ///
744    /// ```rust
745    ///
746    /// use ccdata_api::{CCData, CCOCDEXMarket};
747    ///
748    /// #[tokio::main]
749    /// async fn main() -> () {
750    ///
751    ///     let mut backend: CCData = CCData::new();
752    ///     // Provide API key as the environment variable called API_KEY
753    ///     backend.build(&"API_KEY").unwrap();
754    ///
755    ///     let market: CCOCDEXMarket = CCOCDEXMarket::UNISWAPV2;
756    ///     let markets = backend.get_ocdex_markets(market).await.unwrap();
757    ///     assert_eq!(markets.data.unwrap().get("uniswapv2").unwrap().exchange_status, String::from("ACTIVE"));
758    ///
759    /// }
760    /// ```
761    pub async fn get_ocdex_markets(&self, market: CCOCDEXMarket) -> Result<CCDataResponse<HashMap<String, CCOCDEXMarkets>>, Error> {
762        call_api_endpoint::<CCDataResponse<HashMap<String, CCOCDEXMarkets>>>(
763            self.api_key()?,
764            CCAPIEndpoint::OCDEXMarkets, CCUnit::NA,
765            vec![Param::Market{v: market.to_string()}], None
766        ).await
767    }
768
769    /// # ETH Blocks \[Full Processed\] (On-Chain Core)
770    /// Returns the processed data for a given block.
771    ///
772    /// # Description (CoinDesk Documentation)
773    /// The On-Chain ETH: Block Full Processed endpoint delivers exhaustive details on a specific Ethereum block in a meticulously processed format,
774    /// complete with detailed explanations for each field. This endpoint is crucial for developers, researchers, and users seeking the most in-depth
775    /// and intelligible data concerning an Ethereum block. By utilizing the 'groups' parameter, users can unlock the full spectrum of data,
776    /// including general block information as well as detailed transaction data. This encompasses logs, traces, and blobs, offering a holistic view
777    /// of the block's activities. Access this wealth of information through the URL structure: /onchain/{version}/block/{asset_id}.
778    /// Passing -1 or leaving the block_number parameter empty will retrieve the latest available block. Alternatively, using a negative value for block_number
779    /// will return the data relative to the block that is currently being produce: -1 for the latest available block, -2 for the block before that, and so on,
780    /// allowing users to access past blocks with ease.
781    ///
782    /// # Input
783    /// - `block_number`: Block number on the blockchain
784    ///
785    /// # Examples
786    ///
787    /// ```rust
788    ///
789    /// use ccdata_api::CCData;
790    ///
791    /// #[tokio::main]
792    /// async fn main() -> () {
793    ///
794    ///     let mut backend: CCData = CCData::new();
795    ///     // Provide API key as the environment variable called API_KEY
796    ///     backend.build(&"API_KEY").unwrap();
797    ///
798    ///     let eth_block = backend.get_occore_eth_block(19501436).await.unwrap();
799    ///     assert_eq!(eth_block.data.unwrap().symbol, String::from("ETH"));;
800    ///
801    /// }
802    /// ```
803    pub async fn get_occore_eth_block(&self, block_number: i64) -> Result<CCDataResponse<CCOCCoreETHBlock>, Error> {
804        call_api_endpoint::<CCDataResponse<CCOCCoreETHBlock>>(
805            self.api_key()?,
806            CCAPIEndpoint::OCCoreETHBlocks, CCUnit::NA,
807            vec![Param::OCCoreBlockNumber{v: block_number}],
808            Some(String::from("&groups=ID,METADATA,TRANSACTIONS,ORPHAN_TRACES,UNCLES,WITHDRAWALS"))
809        ).await
810    }
811
812    /// # Assets Summary By Chain (On-Chain Core)
813    /// Returns a summary of assets on a given chain.
814    ///
815    /// # Description (CoinDesk Documentation)
816    /// The On-Chain Assets Summary By Chain endpoint retrieves a comprehensive summary of chain asset information for a specified blockchain,
817    /// identified by its chain symbol. This endpoint provides detailed summaries of the supported assets on the given chain,
818    /// including a complete list of all assets available. It is invaluable for users needing an overarching view of the asset landscape within a specific
819    /// blockchain, offering insights into the diversity and characteristics of the assets supported by that chain.
820    ///
821    /// # Input
822    /// - `chain_asset`: Chain asset symbol
823    ///
824    /// # Examples
825    ///
826    /// ```rust
827    ///
828    /// use ccdata_api::CCData;
829    ///
830    /// #[tokio::main]
831    /// async fn main() -> () {
832    ///
833    ///     let mut backend: CCData = CCData::new();
834    ///     // Provide API key as the environment variable called API_KEY
835    ///     backend.build(&"API_KEY").unwrap();
836    ///
837    ///     let assets_by_chain = backend.get_occore_assets_by_chain("ETH").await.unwrap();
838    ///     assert_eq!(assets_by_chain.data.unwrap().chain_asset_summary.symbol, String::from("ETH"));
839    ///
840    /// }
841    /// ```
842    pub async fn get_occore_assets_by_chain(&self, chain_asset: &str) -> Result<CCDataResponse<CCOCCoreAssetByChain>, Error> {
843        call_api_endpoint::<CCDataResponse<CCOCCoreAssetByChain>>(
844            self.api_key()?,
845            CCAPIEndpoint::OCCoreAssetsByChain, CCUnit::NA,
846            vec![Param::ChainAsset{v: chain_asset}],
847            Some(String::from("&asset_lookup_priority=SYMBOL"))
848        ).await
849    }
850
851    /// # Asset By Address Lookup (On-Chain Core)
852    /// Returns a summary of a smart contract on a given chain.
853    ///
854    /// # Description (CoinDesk Documentation)
855    /// The On-Chain Asset By Address Lookup endpoint retrieves comprehensive asset information for a specific asset identified by its smart contract address
856    /// and associated blockchain asset. This API endpoint is particularly useful for obtaining details about assets represented by tokens on various blockchain
857    /// platforms. By specifying the smart contract address and blockchain asset, users can access detailed metadata about the asset, including its name, symbol,
858    /// total supply, and other pertinent information. This endpoint is essential for developers, researchers, and users who need accurate and detailed asset
859    /// information for blockchain-based applications, analysis, or integration.
860    ///
861    /// # Input
862    /// - `chain_asset`: Chain asset symbol
863    /// - `address`: Blockchain address
864    /// - `quote_asset`: Asset to quote data in
865    ///
866    /// # Examples
867    ///
868    /// ```rust
869    ///
870    /// use ccdata_api::CCData;
871    ///
872    /// #[tokio::main]
873    /// async fn main() -> () {
874    ///
875    ///     let mut backend: CCData = CCData::new();
876    ///     // Provide API key as the environment variable called API_KEY
877    ///     backend.build(&"API_KEY").unwrap();
878    ///
879    ///     let address: String = String::from("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2");
880    ///     let quote_asset: String = String::from("USD");
881    ///     let asset_by_address = backend.get_occore_asset_by_address("ETH", &address, &quote_asset).await.unwrap();
882    ///     assert_eq!(asset_by_address.data.unwrap().parent_asset_symbol.unwrap(), String::from("ETH"));
883    ///
884    /// }
885    /// ```
886    pub async fn get_occore_asset_by_address(&self, chain_asset: &str, address: &str, quote_asset: &str) -> Result<CCDataResponse<CCOCCoreAssetByAddress>, Error> {
887        call_api_endpoint::<CCDataResponse<CCOCCoreAssetByAddress>>(
888            self.api_key()?,
889            CCAPIEndpoint::OCCoreAssetByAddress, CCUnit::NA,
890            vec![Param::ChainAsset{v: chain_asset}, Param::OCCoreAddress{v: address}, Param::OCCoreQuoteAsset{v: quote_asset}],
891            Some(String::from("&asset_lookup_priority=SYMBOL&groups=ID,BASIC,SUPPORTED_PLATFORMS,SECURITY_METRICS,SUPPLY,SUPPLY_ADDRESSES,ASSET_TYPE_SPECIFIC_METRICS,RESOURCE_LINKS,CLASSIFICATION,PRICE,MKT_CAP,VOLUME,CHANGE,TOPLIST_RANK,DESCRIPTION,DESCRIPTION_SUMMARY,CONTACT,SEO"))
892        ).await
893    }
894
895    /// # Historical Supply Day (On-Chain Core)
896    /// Returns supply history for a given asset.
897    ///
898    /// # Description (CoinDesk Documentation)
899    /// The On-Chain Historical Supply Day endpoint retrieves comprehensive historical supply data for various digital assets identified by either their
900    /// CoinDesk asset ID or unique asset symbol. This endpoint offers a detailed view of an asset's supply dynamics on a daily basis, providing insights
901    /// into circulating supply, total issued supply, staked supply, burnt tokens, and more.
902    ///
903    /// # Input
904    /// - `asset`: Asset symbol
905    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
906    /// - `limit`: Maximum number of datapoints per API endpoint call
907    ///
908    /// # Examples
909    ///
910    /// ```rust
911    ///
912    /// use ccdata_api::CCData;
913    ///
914    /// #[tokio::main]
915    /// async fn main() -> () {
916    ///
917    ///     let mut backend: CCData = CCData::new();
918    ///     // Provide API key as the environment variable called API_KEY
919    ///     backend.build(&"API_KEY").unwrap();
920    ///
921    ///     let limit: usize = 2000;
922    ///     let historical_supply = backend.get_occore_supply("BTC", None, Some(limit)).await.unwrap();
923    ///     assert!(historical_supply.data.unwrap().len() <= limit);
924    ///
925    /// }
926    /// ```
927    pub async fn get_occore_supply(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCOCCoreSupply>>, Error> {
928        call_api_endpoint::<CCDataResponse<Vec<CCOCCoreSupply>>>(
929            self.api_key()?,
930            CCAPIEndpoint::OCCoreSupply, CCUnit::NA,
931            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}], None
932        ).await
933    }
934
935    #[deprecated(since="1.0.6", note="Deprecated by CoinDesk")]
936    /// # Full Asset Metadata (Asset)
937    /// Returns a summary of metadata for a given asset.
938    ///
939    /// # Description (CoinDesk Documentation)
940    /// The Full Asset Metadata endpoint provides detailed and comprehensive information about any cryptocurrency asset identified by its CCData asset ID,
941    /// unique asset symbol, or asset URI. This includes extensive data on asset description, classification, blockchain properties, social metrics,
942    /// token sale information, and equity sale details—all consolidated into a single response to facilitate in-depth analysis, development, and research.
943    ///
944    /// # Input
945    /// - `asset`: Asset symbol
946    ///
947    /// # Examples
948    ///
949    /// ```rust
950    ///
951    /// use ccdata_api::CCData;
952    ///
953    /// #[tokio::main]
954    /// async fn main() -> () {
955    ///
956    ///     let mut backend: CCData = CCData::new();
957    ///     // Provide API key as the environment variable called API_KEY
958    ///     backend.build(&"API_KEY").unwrap();
959    ///
960    ///     let metadata = backend.get_asset_metadata("ETH").await.unwrap();
961    ///     assert_eq!(metadata.data.unwrap().name, String::from("Ethereum"));
962    ///
963    /// }
964    /// ```
965    pub async fn get_asset_metadata(&self, asset: &str) -> Result<CCDataResponse<CCAssetMetadata>, Error> {
966        call_api_endpoint::<CCDataResponse<CCAssetMetadata>>(
967            self.api_key()?,
968            CCAPIEndpoint::AssetMetadata, CCUnit::NA,
969            vec![Param::Asset{v: asset}],
970            Some(String::from("&asset_lookup_priority=SYMBOL&quote_asset=USD&groups=ID,BASIC,SUPPLY,SUPPLY_ADDRESSES,CLASSIFICATION"))
971        ).await
972    }
973
974    /// # Full Asset Metadata (Asset) - V2
975    /// 
976    /// # Description (CoinDesk Documentation)
977    /// The Full Asset Metadata endpoint returns an object that provides detailed and comprehensive information about multiple
978    /// cryptocurrency assets in response to a request. Each asset can be identified by its CoinDesk asset ID, unique asset symbol,
979    /// or asset URI, ensuring users receive a broad dataset covering all requested assets. This object consolidates extensive data related
980    /// to asset description, classification, blockchain properties, social metrics, token sale information, and equity sale details for each
981    /// asset—facilitating in-depth analysis, development, and research.
982    /// 
983    /// # Input
984    /// - `assets`: List of asset symbols
985    /// 
986    /// # Examples
987    /// 
988    /// ```rust
989    /// 
990    /// use ccdata_api::CCData;
991    ///
992    /// #[tokio::main]
993    /// async fn main() -> () {
994    /// 
995    ///     let mut backend: CCData = CCData::new();
996    ///     // Provide API key as the environment variable called API_KEY
997    ///     backend.build(&"API_KEY").unwrap();
998    /// 
999    ///     let assets: Vec<String> = vec![String::from("ETH"), String::from("BTC")];
1000    ///     let metadata = backend.get_asset_metadata_v2(assets).await.unwrap();
1001    ///     assert_eq!(metadata.data.as_ref().unwrap().get("ETH").unwrap().name, String::from("Ethereum"));
1002    ///     assert_eq!(metadata.data.unwrap().get("BTC").unwrap().name, String::from("Bitcoin"));
1003    /// 
1004    /// }
1005    /// ```
1006    pub async fn get_asset_metadata_v2(&self, assets: Vec<String>) -> Result<CCDataResponse<HashMap<String, CCAssetMetadata>>, Error> {
1007        call_api_endpoint::<CCDataResponse<HashMap<String, CCAssetMetadata>>>(
1008            self.api_key()?,
1009            CCAPIEndpoint::AssetMetadataV2, CCUnit::NA,
1010            vec![Param::Assets {v: assets}],
1011            Some(String::from("&asset_lookup_priority=SYMBOL&quote_asset=USD&groups=ID,BASIC,SUPPLY,SUPPLY_ADDRESSES,CLASSIFICATION"))
1012        ).await
1013    }
1014
1015    /// # Significant Asset Events (Asset)
1016    /// Returns a list of significant events for a given asset.
1017    ///
1018    /// # Description (CoinDesk Documentation)
1019    /// The Asset Events endpoint retrieves an array of significant events related to digital assets, such as security incidents, rebrandings, blockchain forks,
1020    /// and other impactful developments. Events are returned in chronological order, with the most recent events appearing first.
1021    ///
1022    /// # Input
1023    /// - `asset`: Asset symbol
1024    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1025    /// - `limit`: Maximum number of datapoints per API endpoint call
1026    ///
1027    /// # Examples
1028    ///
1029    /// ```rust
1030    ///
1031    /// use ccdata_api::CCData;
1032    ///
1033    /// #[tokio::main]
1034    /// async fn main() -> () {
1035    ///
1036    ///     let mut backend: CCData = CCData::new();
1037    ///     // Provide API key as the environment variable called API_KEY
1038    ///     backend.build(&"API_KEY").unwrap();
1039    ///
1040    ///     let limit: usize = 100;
1041    ///     let events = backend.get_asset_events("ETH", None, Some(limit)).await.unwrap();
1042    ///     assert!(events.data.unwrap().len() <= limit);
1043    ///
1044    /// }
1045    /// ```
1046    pub async fn get_asset_events(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCAssetEvent>>, Error> {
1047        call_api_endpoint::<CCDataResponse<Vec<CCAssetEvent>>>(
1048            self.api_key()?,
1049            CCAPIEndpoint::AssetEvents, CCUnit::NA,
1050            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}], None
1051        ).await
1052    }
1053
1054    /// # Historical Social \[Code Repository Day\] (Asset)
1055    /// Returns daily code repository metadata for a given asset.
1056    ///
1057    /// # Description (CoinDesk Documentation)
1058    /// The Historical Social Metrics Code Repository Day endpoint provides an in-depth, daily snapshot of a digital asset's code repositories.
1059    /// It is invaluable for gauging developer activity, community engagement, and the asset's overall health.
1060    ///
1061    /// # Input
1062    /// - `asset`: Asset symbol
1063    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1064    /// - `limit`: Maximum number of datapoints per API endpoint call
1065    ///
1066    /// # Examples
1067    ///
1068    /// ```rust
1069    ///
1070    /// use ccdata_api::CCData;
1071    ///
1072    /// #[tokio::main]
1073    /// async fn main() -> () {
1074    ///
1075    ///     let mut backend: CCData = CCData::new();
1076    ///     // Provide API key as the environment variable called API_KEY
1077    ///     backend.build(&"API_KEY").unwrap();
1078    ///
1079    ///     let limit: usize = 2000;
1080    ///     let code_repo = backend.get_asset_code_repo("ETH", None, Some(limit)).await.unwrap();
1081    ///     assert_eq!(code_repo.data.unwrap().len(), limit);
1082    ///
1083    /// }
1084    /// ```
1085    pub async fn get_asset_code_repo(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCAssetCodeRepoMetrics>>, Error> {
1086        call_api_endpoint::<CCDataResponse<Vec<CCAssetCodeRepoMetrics>>>(
1087            self.api_key()?,
1088            CCAPIEndpoint::AssetCodeRepo, CCUnit::NA,
1089            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}],
1090            Some(String::from("&groups=ID,GENERAL,ACTIVITY,SOURCE"))
1091        ).await
1092    }
1093
1094    /// # Historical Social \[Discord Day\] (Asset)
1095    /// Returns daily Discord metadata for a given asset.
1096    ///
1097    /// # Description (CoinDesk Documentation)
1098    /// The Historical Social Metrics Discord Days endpoint aggregates detailed daily metrics from all Discord servers related to a specific digital asset,
1099    /// offering a multifaceted view into community engagement and the asset's standing within Discord communities.
1100    ///
1101    /// # Input
1102    /// - `asset`: Asset symbol
1103    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1104    /// - `limit`: Maximum number of datapoints per API endpoint call
1105    ///
1106    /// # Examples
1107    ///
1108    /// ```rust
1109    ///
1110    /// use ccdata_api::CCData;
1111    ///
1112    /// #[tokio::main]
1113    /// async fn main() -> () {
1114    ///
1115    ///     let mut backend: CCData = CCData::new();
1116    ///     // Provide API key as the environment variable called API_KEY
1117    ///     backend.build(&"API_KEY").unwrap();
1118    ///
1119    ///     let limit: usize = 2000;
1120    ///     let discord = backend.get_asset_discord("ETH", None, Some(limit)).await.unwrap();
1121    ///     assert_eq!(discord.data.unwrap().len(), limit);
1122    ///
1123    /// }
1124    /// ```
1125    pub async fn get_asset_discord(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCAssetDiscord>>, Error> {
1126        call_api_endpoint::<CCDataResponse<Vec<CCAssetDiscord>>>(
1127            self.api_key()?,
1128            CCAPIEndpoint::AssetDiscord, CCUnit::NA,
1129            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}],
1130            Some(String::from("&groups=ID,GENERAL,ACTIVITY,SOURCE"))
1131        ).await
1132    }
1133
1134    /// # Historical Social \[Reddit Day\] (Asset)
1135    /// Returns daily Reddit metadata for a given asset.
1136    ///
1137    /// # Description (CoinDesk Documentation)
1138    /// The Reddit Historical Daily Metrics endpoint aggregates key performance indicators from all the subreddits related to a specific digital asset,
1139    /// providing a comprehensive understanding of the asset's footprint on Reddit—a critical channel for community engagement and public sentiment
1140    /// in the digital asset industry.
1141    ///
1142    /// # Input
1143    /// - `asset`: Asset symbol
1144    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1145    /// - `limit`: Maximum number of datapoints per API endpoint call
1146    ///
1147    /// # Examples
1148    ///
1149    /// ```rust
1150    ///
1151    /// use ccdata_api::CCData;
1152    ///
1153    /// #[tokio::main]
1154    /// async fn main() -> () {
1155    ///
1156    ///     let mut backend: CCData = CCData::new();
1157    ///     // Provide API key as the environment variable called API_KEY
1158    ///     backend.build(&"API_KEY").unwrap();
1159    ///
1160    ///     let limit: usize = 2000;
1161    ///     let reddit = backend.get_asset_reddit("ETH", None, Some(limit)).await.unwrap();
1162    ///     assert_eq!(reddit.data.unwrap().len(), limit);
1163    ///
1164    /// }
1165    /// ```
1166    pub async fn get_asset_reddit(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCAssetReddit>>, Error> {
1167        call_api_endpoint::<CCDataResponse<Vec<CCAssetReddit>>>(
1168            self.api_key()?,
1169            CCAPIEndpoint::AssetReddit, CCUnit::NA,
1170            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}],
1171            Some(String::from("&groups=ID,GENERAL,ACTIVITY,SOURCE"))
1172        ).await
1173    }
1174
1175    /// # Historical Social \[Telegram Day\] (Asset)
1176    /// Returns daily Telegram metadata for a given asset.
1177    ///
1178    /// # Description (CoinDesk Documentation)
1179    /// The Telegram Historical Daily Metrics endpoint collates essential data points across all Telegram groups affiliated with a particular cryptocurrency asset.
1180    /// Telegram often serves as a primary hub for real-time community engagement, announcements, and discussions in the crypto ecosystem.
1181    ///
1182    /// # Input
1183    /// - `asset`: Asset symbol
1184    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1185    /// - `limit`: Maximum number of datapoints per API endpoint call
1186    ///
1187    /// # Examples
1188    ///
1189    /// ```rust
1190    ///
1191    /// use ccdata_api::CCData;
1192    ///
1193    /// #[tokio::main]
1194    /// async fn main() -> () {
1195    ///
1196    ///     let mut backend: CCData = CCData::new();
1197    ///     // Provide API key as the environment variable called API_KEY
1198    ///     backend.build(&"API_KEY").unwrap();
1199    ///
1200    ///     let limit: usize = 2000;
1201    ///     let telegram = backend.get_asset_telegram("SOL", None, Some(limit)).await.unwrap();
1202    ///     assert_eq!(telegram.data.unwrap().len(), limit);
1203    ///
1204    /// }
1205    /// ```
1206    pub async fn get_asset_telegram(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCAssetTelegram>>, Error> {
1207        call_api_endpoint::<CCDataResponse<Vec<CCAssetTelegram>>>(
1208            self.api_key()?,
1209            CCAPIEndpoint::AssetTelegram, CCUnit::NA,
1210            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}],
1211            Some(String::from("&groups=ID,GENERAL,SOURCE"))
1212        ).await
1213    }
1214
1215    /// # Historical Social \[X (Twitter) Day\] (Asset)
1216    /// Returns daily X (Twitter) metadata for a given asset.
1217    ///
1218    /// # Description (CoinDesk Documentation)
1219    /// The X (Twitter) Historical Daily Metrics endpoint aggregates essential metrics from all X (Twitter) accounts associated with a specific cryptocurrency asset.
1220    /// X (Twitter) is a key platform for real-time updates, announcements, and community engagement in the digital asset industry.
1221    ///
1222    /// # Input
1223    /// - `asset`: Asset symbol
1224    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1225    /// - `limit`: Maximum number of datapoints per API endpoint call
1226    ///
1227    /// # Examples
1228    ///
1229    /// ```rust
1230    ///
1231    /// use ccdata_api::CCData;
1232    ///
1233    /// #[tokio::main]
1234    /// async fn main() -> () {
1235    ///
1236    ///     let mut backend: CCData = CCData::new();
1237    ///     // Provide API key as the environment variable called API_KEY
1238    ///     backend.build(&"API_KEY").unwrap();
1239    ///
1240    ///     let limit: usize = 2000;
1241    ///     let twitter = backend.get_asset_twitter("SOL", None, Some(limit)).await.unwrap();
1242    ///     assert_eq!(twitter.data.unwrap().len(), limit)
1243    ///
1244    /// }
1245    /// ```
1246    pub async fn get_asset_twitter(&self, asset: &str, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCAssetTwitter>>, Error> {
1247        call_api_endpoint::<CCDataResponse<Vec<CCAssetTwitter>>>(
1248            self.api_key()?,
1249            CCAPIEndpoint::AssetTwitter, CCUnit::NA,
1250            vec![Param::Asset{v: asset}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}],
1251            Some(String::from("&groups=ID,GENERAL,ACTIVITY,SOURCE"))
1252        ).await
1253    }
1254
1255    /// # Latest Articles (News)
1256    /// Returns a list of latest articles.
1257    ///
1258    /// # Description (CoinDesk Documentation)
1259    /// The Latest Articles endpoint serves as the pulse of the crypto news landscape, providing users with instant access to the most recent articles across
1260    /// the industry. By drawing from a wide array of reputable sources, this endpoint curates a fresh, real-time stream of information, insights,
1261    /// and developments, ensuring that users remain at the forefront of crypto news narratives. Whether you are an investor, enthusiast, or industry professional,
1262    /// this endpoint delivers a comprehensive and up-to-the-minute news digest, placing you at the heart of the ever-evolving crypto conversation.
1263    ///
1264    /// # Input
1265    /// - `language`: Language of the news
1266    /// - `source_id`: Source ID of the news stream
1267    /// - `categories`: List of news categories
1268    /// - `exclude_categories`: List of news categories to exclude
1269    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1270    /// - `limit`: Maximum number of datapoints per API endpoint call
1271    ///
1272    /// # Examples
1273    ///
1274    /// ```rust
1275    ///
1276    /// use ccdata_api::{CCData, CCNewsLang, CCNewsSourceID};
1277    ///
1278    /// #[tokio::main]
1279    /// async fn main() -> () {
1280    ///
1281    ///     let mut backend: CCData = CCData::new();
1282    ///     // Provide API key as the environment variable called API_KEY
1283    ///     backend.build(&"API_KEY").unwrap();
1284    ///
1285    ///     let language: CCNewsLang = CCNewsLang::EN;
1286    ///     let source_id: CCNewsSourceID = CCNewsSourceID::ForbesDigitalAssets;
1287    ///     let limit: usize = 100;
1288    ///     let articles = backend.get_news_latest_articles(language, source_id, None, None, None, Some(limit)).await.unwrap();
1289    ///     assert_eq!(articles.data.unwrap().len(), limit);
1290    ///
1291    /// }
1292    /// ```
1293    pub async fn get_news_latest_articles(&self, language: CCNewsLang, source_id: CCNewsSourceID, categories: Option<Vec<String>>,
1294                                          exclude_categories: Option<Vec<String>>, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCNewsLatestArticle>>, Error> {
1295        call_api_endpoint::<CCDataResponse<Vec<CCNewsLatestArticle>>>(
1296            self.api_key()?,
1297            CCAPIEndpoint::NewsLatestArticles, CCUnit::NA,
1298            vec![
1299                Param::NewsLanguage{v: language}, Param::NewsSourceID{v: source_id}, Param::NewsCategories{v: categories},
1300                Param::NewsExcludeCategories{v: exclude_categories}, Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit},
1301            ],
1302            None
1303        ).await
1304    }
1305
1306    /// # Sources (News)
1307    /// Returns a list of news sources.
1308    ///
1309    /// # Description (CoinDesk Documentation)
1310    /// The News Sources endpoint offers a comprehensive listing of all news sources available through our API. This endpoint is crucial for users who need
1311    /// to identify and access a diverse array of reputable news outlets, blogs, and information platforms. It ensures that users can explore and select from
1312    /// a curated list of trusted industry voices, supporting a variety of applications in research, news aggregation, and content curation.
1313    ///
1314    /// # Input
1315    /// - `language`: Language of the news
1316    /// - `source_type`: Type of news stream
1317    /// - `status`: Status of the news stream (e.g., ACTIVE, INACTIVE)
1318    ///
1319    /// # Examples
1320    ///
1321    /// ```rust
1322    ///
1323    /// use ccdata_api::{CCData, CCNewsLang, CCNewsSourceType, CCNewsStatus};
1324    ///
1325    /// #[tokio::main]
1326    /// async fn main() -> () {
1327    ///
1328    ///     let mut backend: CCData = CCData::new();
1329    ///     // Provide API key as the environment variable called API_KEY
1330    ///     backend.build(&"API_KEY").unwrap();
1331    ///
1332    ///     let language: CCNewsLang = CCNewsLang::EN;
1333    ///     let source_type: CCNewsSourceType = CCNewsSourceType::RSS;
1334    ///     let status: CCNewsStatus = CCNewsStatus::ACTIVE;
1335    ///     let sources = backend.get_news_sources(language, source_type, status).await.unwrap();
1336    ///     assert_eq!(sources.data.unwrap()[0].source_type, String::from("RSS"));
1337    ///
1338    /// }
1339    /// ```
1340    pub async fn get_news_sources(&self, language: CCNewsLang, source_type: CCNewsSourceType, status: CCNewsStatus) -> Result<CCDataResponse<Vec<CCNewsSource>>, Error> {
1341        call_api_endpoint::<CCDataResponse<Vec<CCNewsSource>>>(
1342            self.api_key()?,
1343            CCAPIEndpoint::NewsSources, CCUnit::NA,
1344            vec![Param::NewsLanguage{v: language}, Param::NewsSourceType{v: source_type}, Param::NewsStatus{v: status}],
1345            None
1346        ).await
1347    }
1348
1349    /// # Categories (News)
1350    /// Return  a list of news categories.
1351    ///
1352    /// # Description (CoinDesk Documentation)
1353    /// The News Categories List endpoint is designed to provide a straightforward listing of all news categories available through our API.
1354    /// This endpoint is essential for users looking to identify the broad spectrum of topics covered by our news sources, ranging from market trends
1355    /// and technological advances to regulatory changes and cultural events. By offering a clear overview of these categories, it facilitates users
1356    /// in understanding and navigating the thematic organization of news content.
1357    ///
1358    /// # Input
1359    /// - `status`: Status of the news stream (e.g., ACTIVE, INACTIVE)
1360    ///
1361    /// # Examples
1362    ///
1363    /// ```rust
1364    ///
1365    /// use ccdata_api::{CCData, CCNewsStatus};
1366    ///
1367    /// #[tokio::main]
1368    /// async fn main() -> () {
1369    ///
1370    ///     let mut backend: CCData = CCData::new();
1371    ///     // Provide API key as the environment variable called API_KEY
1372    ///     backend.build(&"API_KEY").unwrap();
1373    ///
1374    ///     let status: CCNewsStatus = CCNewsStatus::ACTIVE;
1375    ///     let categories = backend.get_news_categories(status).await.unwrap();
1376    ///     assert_eq!(categories.data.unwrap()[0].status, String::from("ACTIVE"));
1377    ///
1378    /// }
1379    /// ```
1380    pub async fn get_news_categories(&self, status: CCNewsStatus) -> Result<CCDataResponse<Vec<CCNewsCategory>>, Error> {
1381        call_api_endpoint::<CCDataResponse<Vec<CCNewsCategory>>>(
1382            self.api_key()?,
1383            CCAPIEndpoint::NewsCategories, CCUnit::NA,
1384            vec![Param::NewsStatus{v: status}],
1385            None
1386        ).await
1387    }
1388
1389    /// # MktCap Historical OHLCV \[All Assets Day\] (Overview)
1390    /// Returns daily historical OHLCV data for all assets.
1391    ///
1392    /// # Description (CoinDesk Documentation)
1393    /// Built as an overview for the digital asset industry, this endpoint presents a thorough historical daily overview of market capitalisation
1394    /// for digital assets that meet the volume and listing criteria. Users can explore day-by-day total market cap figures, along with daily open-high-low values
1395    /// and top-tier trading volumes, for the entire digital asset industry. It's a fundamental tool for analysts, researchers, and investors looking
1396    /// to understand market trends, trace asset performance over time, and make data-driven decisions rooted in historical contexts.
1397    ///
1398    /// # Input
1399    /// - `to_timestamp`: Final timestamp up to which the data will be extracted
1400    /// - `limit`: Maximum number of datapoints per API endpoint call
1401    ///
1402    /// # Examples
1403    ///
1404    /// ```rust
1405    ///
1406    /// use ccdata_api::CCData;
1407    ///
1408    /// #[tokio::main]
1409    /// async fn main() -> () {
1410    ///
1411    ///     let mut backend: CCData = CCData::new();
1412    ///     // Provide API key as the environment variable called API_KEY
1413    ///     backend.build(&"API_KEY").unwrap();
1414    ///
1415    ///     let limit: usize = 2000;
1416    ///     let mktcap = backend.get_overview_mktcap_ohlcv(None, Some(limit)).await.unwrap();
1417    ///     assert_eq!(mktcap.data.unwrap().len(), limit);
1418    ///
1419    /// }
1420    /// ```
1421    pub async fn get_overview_mktcap_ohlcv(&self, to_timestamp: Option<i64>, limit: Option<usize>) -> Result<CCDataResponse<Vec<CCOverviewMktCapOHLCV>>, Error> {
1422        call_api_endpoint::<CCDataResponse<Vec<CCOverviewMktCapOHLCV>>>(
1423            self.api_key()?,
1424            CCAPIEndpoint::OverviewMktCapOHLCV, CCUnit::NA,
1425            vec![Param::ToTimestamp{v: to_timestamp}, Param::Limit{v: limit}],
1426            Some(String::from("&groups=ID,OHLC,VOLUME"))
1427        ).await
1428    }
1429}
1430
1431
1432
1433#[cfg(test)]
1434mod tests {
1435    use crate::backend::CCData;
1436
1437    #[tokio::test]
1438    async fn unit_test_backend() -> () {
1439        let mut backend: CCData = CCData::new();
1440        backend.build(&"API_KEY").unwrap();
1441        assert!(backend.api_key != None);
1442    }
1443}