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