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