ccdata_api/lib.rs
1//! # CCData API Wrapper
2//!
3//! `ccdata-api` is a wrapper for CCData REST API endpoints. This crate supports non-exhausitve list of CCData endpoints,
4//! you can check what endpoints are supported by checking the variants of the enum `CCAPIEndpoint` - it contains all
5//! supported endpoint URLs.
6//!
7//! For documentation on CCData REST API endpoints visit CCData online documentation:
8//! - Min-API: <https://developers.ccdata.io/documentation/legacy/Price/SingleSymbolPriceEndpoint>
9//! - Data-API: <https://developers.ccdata.io/documentation/data-api/introduction>
10//!
11//! **Disclaimer:** This crate is an unofficial CCData REST API wrapper, the maintainers of the crate are independent developers.
12//! The developers of the crate do not accept any responsibility or liability for the accuracy, security, or completeness of the code,
13//! or the information provided within the crate.
14//!
15//! # Errors
16//!
17//! The REST API functions in the crate will error if the data received does not fit into the pre-defined schemas provided
18//! in the crate. If you encounter any errors, please open an issue on GitHub with the parameters that you have used (e.g., asset symbol,
19//! timestamp, limit, etc.). **Do not provide your API key or any personal data!**
20//!
21//! # Features
22//! - `debug`: If this feature is enabled, you can set `CCDATA_API_DEBUG` environment variable to `true`, which will print the response body
23//! for every request to the command line.
24//!
25//! # Examples
26//!
27//! To start making the REST API requests, define a data collection backend. This can be done by either directly passing an
28//! API key to the data collection backend, or by defining a `.env` file with an API key as an environment variable (Preferred
29//! method).
30//!
31//! ## Build Backend Explicitly Stating API Key (May expose API key)
32//!
33//! ```rust
34//! use ccdata_api::CCData;
35//!
36//! let mut backend: CCData = CCData::new();
37//!
38//! let api_key: String = String::from("xxxxxxx");
39//! backend.update_api_key(api_key);
40//!
41//! assert_eq!(backend.api_key().unwrap(), &String::from("xxxxxxx"));
42//! ```
43//!
44//! ## Build Backend Using .env File (Preferred method)
45//!
46//! ```rust
47//! use ccdata_api::CCData;
48//!
49//! let mut backend: CCData = CCData::new();
50//! // Provide API key as the environment variable called API_KEY
51//! backend.build(&"API_KEY").unwrap();
52//!
53//! println!("{}", backend.api_key().unwrap());
54//! ```
55//!
56//! ## Making First API Call
57//!
58//! After the backend has been build, you can make API requests using the methods provided in the backend. For example, to
59//! get a daily spot OHLCV data for Bitcoin you can do the following (note that the calls use Rust's `async` functionality):
60//!
61//! ```rust
62//!
63//! use ccdata_api::{CCData, CCUnit, CCSpotMarket};
64//!
65//! #[tokio::main]
66//! async fn main() -> () {
67//!
68//! let mut backend: CCData = CCData::new();
69//! // Provide API key as the environment variable called API_KEY
70//! backend.build(&"API_KEY").unwrap();
71//!
72//! // Define the API parameters
73//! let market: CCSpotMarket = CCSpotMarket::KRAKEN;
74//! let limit: usize = 2000;
75//! let to_timestamp: Option<i64> = Some(1728860400);
76//!
77//! // Make the API call
78//! let ohlcv = backend.get_spot_ohlcv(&String::from("BTC-USD"), to_timestamp, Some(limit), market, CCUnit::Day).await.unwrap();
79//! assert_eq!(ohlcv.data.unwrap().len(), limit);
80//!
81//! }
82//! ```
83//!
84//! # General information
85//! If you would like to add a commit or an issue, please do so using the GitHub link to the project:
86//! - <https://github.com/rsadykhov/ccdata-api>
87
88
89// Re-Exports
90pub use self::backend::CCData;
91// Min-API Re-Exports
92pub use self::schemas::{CCMinResponse, CCMinWrapper, CCRateLimit, CCMaxCalls, CCCallsMade};
93pub use self::schemas::min_api::{CCAvailableCoinList, CCHistoricalDaily, CCBalanceDistribution, CCSupplyBand};
94// Data-API Re-Exports
95pub use self::schemas::{CCDataResponse, CCError, CCErrorOtherInfo};
96pub use self::schemas::data_api::indices_and_reference_rates::{CCIndicesMarket, CCIndicesOHLCV};
97pub use self::schemas::data_api::spot::{CCSpotMarket, CCSpotInstrumentStatus, CCSpotOHLCV, CCSpotInstrumentMetdata, CCSpotMarkets, CCSpotMarketsInstruments};
98pub use self::schemas::data_api::futures::{CCFuturesMarket, CCFuturesOHLCV, CCFuturesMarkets};
99pub use self::schemas::data_api::options::{CCOptionsMarket, CCOptionsOHLCV, CCOptionsMarkets};
100pub use self::schemas::data_api::derivatives_indices::{CCDerIndicesMarket, CCDerIndicesOHLCV, CCDerIndicesMarkets};
101pub use self::schemas::data_api::on_chain_dex::{CCOCDEXMarket, CCOCDEXOHLCV, CCOCDEXMarkets};
102pub use self::schemas::data_api::on_chain_core::{CCOCCoreETHBlock, CCOCCoreAssetByChain, CCOCCoreAssetByAddress, CCOCCoreSupply};
103pub use self::schemas::data_api::asset::{CCAssetMetadata, CCAssetEvent, CCAssetCodeRepoMetrics, CCAssetDiscord, CCAssetReddit, CCAssetTelegram, CCAssetTwitter};
104pub use self::schemas::data_api::news::{CCNewsStatus, CCNewsLang, CCNewsSourceID, CCNewsLatestArticle, CCNewsSourceType, CCNewsSource, CCNewsCategory};
105pub use self::schemas::data_api::overview::CCOverviewMktCapOHLCV;
106
107
108pub mod error;
109pub mod schemas;
110pub mod utils;
111pub mod backend;
112
113
114/// Unit of the interval between successive data points.
115pub enum CCUnit {
116 /// Daily data interval
117 Day,
118 /// Hourly data interval
119 Hour,
120 /// Minutely data interval
121 Minute,
122 /// Used for API endpoints that do not have a specified unit for data or where unit is unapplicable
123 NA,
124}
125
126
127/// All supported API endpoints.
128pub enum CCAPIEndpoint {
129 // Min-API
130 /// Min-API Endpoint
131 ///
132 /// Description: Returns a list of all coins for which CCData currently gets the blockchain data
133 ///
134 /// URL: https://min-api.cryptocompare.com/data/blockchain/list
135 AvailableCoinList,
136 /// Min-API Endpoint
137 ///
138 /// Description: Retrieves the daily aggregated blockchain data for the requested coin
139 ///
140 /// URL: https://min-api.cryptocompare.com/data/blockchain/histo/day
141 HistoricalDaily,
142 /// Min-API Endpoint
143 ///
144 /// Description: Retrieves the balance distribution for a specified asset over a specified time range at a daily interval
145 ///
146 /// Note: Only data for BTC (Bitcoin) is currently available
147 ///
148 /// URL: https://min-api.cryptocompare.com/data/blockchain/balancedistribution/histo/day
149 BalanceDistribution,
150 // Data-API
151 // Indices & Reference Rates
152 /// Data-API Endpoint
153 ///
154 /// Description: Provides historical candlestick data for various indices
155 ///
156 /// URL: https://data-api.ccdata.io/index/cc/v1/historical
157 IndicesOHLCV,
158 // Spot
159 /// Data-API Endpoint
160 ///
161 /// Description: Provides candlestick data for specific cryptocurrency instruments across selected exchanges
162 ///
163 /// URL: https://data-api.ccdata.io/spot/v1/historical
164 SpotOHLCV,
165 /// Data-API Endpoint
166 ///
167 /// Description: Delivers vital metadata about financial instruments traded on specified exchanges, focusing solely on non-price related information
168 ///
169 /// URL: https://data-api.ccdata.io/spot/v1/latest/instrument/metadata
170 SpotInstrumentMetadata,
171 /// Data-API Endpoint
172 ///
173 /// Description: Provides comprehensive information about various cryptocurrency spot markets
174 ///
175 /// URL: https://data-api.ccdata.io/spot/v1/markets
176 SpotMarkets,
177 /// Data-API Endpoint
178 ///
179 /// Description: Retrieves a comprehensive dictionary of mapped instruments across one or more spot markets, filtered by a specified state or status
180 ///
181 /// URL: https://data-api.ccdata.io/spot/v1/markets/instruments
182 SpotMarketsInstruments,
183 // Futures
184 /// Data-API Endpoint
185 ///
186 /// Description: Provides aggregated candlestick data for specific futures instruments on designated exchanges
187 ///
188 /// URL: https://data-api.ccdata.io/futures/v1/historical
189 FuturesOHLCV,
190 /// Data-API Endpoint
191 ///
192 /// Description: Provides comprehensive information about various cryptocurrency futures markets
193 ///
194 /// URL: https://data-api.ccdata.io/futures/v1/markets
195 FuturesMarkets,
196 // Options
197 /// Data-API Endpoint
198 ///
199 /// Description: Provides historical OHLCV (open, high, low, close, volume) data for specified options instruments on a chosen exchange
200 ///
201 /// URL: https://data-api.ccdata.io/options/v1/historical
202 OptionsOHLCV,
203 /// Data-API Endpoint
204 ///
205 /// Description: Provides comprehensive information about the various options markets integrated by our platform
206 ///
207 /// URL: https://data-api.ccdata.io/options/v1/markets
208 OptionsMarkets,
209 // Derivatives Indices
210 /// Data-API Endpoint
211 ///
212 /// Description: Provides historical OHLC (open, high, low, close) data for specified index instruments on a selected market
213 ///
214 /// URL: https://data-api.ccdata.io/index/v1/historical
215 DerIndicesOHLCV,
216 /// Data-API Endpoint
217 ///
218 /// Description: Provides comprehensive information about various derivatives index markets
219 ///
220 /// URL: https://data-api.ccdata.io/index/v1/markets
221 DerIndicesMarkets,
222 // On-Chain DEX
223 /// Data-API Endpoint
224 ///
225 /// Description: Retrieves aggregated candlestick data for AMM swap transactions
226 ///
227 /// URL: https://data-api.ccdata.io/onchain/v1/amm/historical/swap
228 OCDEXOHLCV,
229 /// Data-API Endpoint
230 ///
231 /// Description: Provides comprehensive information about various decentralized exchange (DEX) markets within the blockchain ecosystem
232 ///
233 /// URL: https://data-api.ccdata.io/onchain/v1/amm/markets
234 OCDEXMarkets,
235 // On-Chain Core
236 /// Data-API Endpoint
237 ///
238 /// Description: Delivers exhaustive details on a specific Ethereum block in a meticulously processed format, complete with detailed explanations for each field
239 ///
240 /// URL: https://data-api.ccdata.io/onchain/v1/block/2
241 OCCoreETHBlocks,
242 /// Data-API Endpoint
243 ///
244 /// Description: Retrieves a comprehensive summary of chain asset information for a specified blockchain, identified by its chain symbol
245 ///
246 /// URL: https://data-api.ccdata.io/onchain/v3/summary/by/chain
247 OCCoreAssetsByChain,
248 /// Data-API Endpoint
249 ///
250 /// Description: Retrieves comprehensive asset information for a specific asset identified by its smart contract address and associated blockchain asset
251 ///
252 /// URL: https://data-api.ccdata.io/onchain/v2/data/by/address
253 OCCoreAssetByAddress,
254 /// Data-API Endpoint
255 ///
256 /// Description: Retrieves comprehensive historical supply data for various digital assets identified by either their CCData asset ID or unique asset symbol
257 ///
258 /// URL: https://data-api.ccdata.io/onchain/v2/historical/supply/days
259 OCCoreSupply,
260 // Asset
261 /// Data-API Endpoint
262 ///
263 /// Description: Returns an object that provides detailed and comprehensive information about multiple cryptocurrency assets in response to a request
264 ///
265 /// URL: https://data-api.ccdata.io/asset/v1/metadata
266 AssetMetadata,
267 /// Data-API Endpoint
268 ///
269 /// Description: Retrieves an array of significant events related to digital assets, such as security incidents, rebrandings, blockchain forks, and other impactful developments
270 ///
271 /// URL: https://data-api.ccdata.io/asset/v1/events
272 AssetEvents,
273 /// Data-API Endpoint
274 ///
275 /// Description: Provides an in-depth, daily snapshot of a digital asset's code repositories
276 ///
277 /// URL: https://data-api.ccdata.io/asset/v1/historical/code-repository/days
278 AssetCodeRepo,
279 /// Data-API Endpoint
280 ///
281 /// Description: Aggregates detailed daily metrics from all Discord servers related to a specific digital asset, offering a multifaceted view into community engagement and the asset's standing within Discord communities
282 ///
283 /// URL: https://data-api.ccdata.io/asset/v1/historical/discord/days
284 AssetDiscord,
285 /// Data-API Endpoint
286 ///
287 /// Description: Aggregates key performance indicators from all the subreddits related to a specific digital asset, providing a comprehensive understanding of the asset's footprint on Reddit
288 ///
289 /// URL: https://data-api.ccdata.io/asset/v1/historical/reddit/days
290 AssetReddit,
291 /// Data-API Endpoint
292 ///
293 /// Description: Collates essential data points across all Telegram groups affiliated with a particular cryptocurrency asset
294 ///
295 /// URL: https://data-api.ccdata.io/asset/v1/historical/telegram/days
296 AssetTelegram,
297 /// Data-API Endpoint
298 ///
299 /// Description: Aggregates essential metrics from all X (Twitter) accounts associated with a specific cryptocurrency asset
300 ///
301 /// URL: https://data-api.ccdata.io/asset/v1/historical/twitter/days
302 AssetTwitter,
303 // News
304 /// Data-API Endpoint
305 ///
306 /// Description: Serves as the pulse of the crypto news landscape, providing users with instant access to the most recent articles across the industry
307 ///
308 /// URL: https://data-api.ccdata.io/news/v1/article/list
309 NewsLatestArticles,
310 /// Data-API Endpoint
311 ///
312 /// Description: Offers a comprehensive listing of all news sources available through CCData API
313 ///
314 /// URL: https://data-api.ccdata.io/news/v1/source/list
315 NewsSources,
316 /// Data-API Endpoint
317 ///
318 /// Description: Provide a straightforward listing of all news categories available through CCData API
319 ///
320 /// URL: https://data-api.ccdata.io/news/v1/category/list
321 NewsCategories,
322 // Overview
323 /// Data-API Endpoint
324 ///
325 /// Description: Presents a thorough historical daily overview of market capitalisation for digital assets that meet the volume and listing criteria
326 ///
327 /// URL: https://data-api.ccdata.io/overview/v1/historical/marketcap/all/assets/days
328 OverviewMktCapOHLCV,
329}
330
331impl CCAPIEndpoint {
332 fn resolve_url(&self) -> String {
333 match self {
334 // Min-API
335 CCAPIEndpoint::AvailableCoinList => String::from("https://min-api.cryptocompare.com/data/blockchain/list"),
336 CCAPIEndpoint::HistoricalDaily => String::from("https://min-api.cryptocompare.com/data/blockchain/histo/day"),
337 CCAPIEndpoint::BalanceDistribution => String::from("https://min-api.cryptocompare.com/data/blockchain/balancedistribution/histo/day"),
338 // Data-API
339 // Indices & Reference Rates
340 CCAPIEndpoint::IndicesOHLCV => String::from("https://data-api.ccdata.io/index/cc/v1/historical"),
341 // Spot
342 CCAPIEndpoint::SpotOHLCV => String::from("https://data-api.ccdata.io/spot/v1/historical"),
343 CCAPIEndpoint::SpotInstrumentMetadata => String::from("https://data-api.ccdata.io/spot/v1/latest/instrument/metadata"),
344 CCAPIEndpoint::SpotMarkets => String::from("https://data-api.ccdata.io/spot/v1/markets"),
345 CCAPIEndpoint::SpotMarketsInstruments => String::from("https://data-api.ccdata.io/spot/v1/markets/instruments"),
346 // Futures
347 CCAPIEndpoint::FuturesOHLCV => String::from("https://data-api.ccdata.io/futures/v1/historical"),
348 CCAPIEndpoint::FuturesMarkets => String::from("https://data-api.ccdata.io/futures/v1/markets"),
349 // Options
350 CCAPIEndpoint::OptionsOHLCV => String::from("https://data-api.ccdata.io/options/v1/historical"),
351 CCAPIEndpoint::OptionsMarkets => String::from("https://data-api.ccdata.io/options/v1/markets"),
352 // Derivatives Indices
353 CCAPIEndpoint::DerIndicesOHLCV => String::from("https://data-api.ccdata.io/index/v1/historical"),
354 CCAPIEndpoint::DerIndicesMarkets => String::from("https://data-api.ccdata.io/index/v1/markets"),
355 // On-Chain DEX
356 CCAPIEndpoint::OCDEXOHLCV => String::from("https://data-api.ccdata.io/onchain/v1/amm/historical/swap"),
357 CCAPIEndpoint::OCDEXMarkets => String::from("https://data-api.ccdata.io/onchain/v1/amm/markets"),
358 // On-Chain Core
359 CCAPIEndpoint::OCCoreETHBlocks => String::from("https://data-api.ccdata.io/onchain/v1/block/2"),
360 CCAPIEndpoint::OCCoreAssetsByChain => String::from("https://data-api.ccdata.io/onchain/v3/summary/by/chain"),
361 CCAPIEndpoint::OCCoreAssetByAddress => String::from("https://data-api.ccdata.io/onchain/v2/data/by/address"),
362 CCAPIEndpoint::OCCoreSupply => String::from("https://data-api.ccdata.io/onchain/v2/historical/supply/days"),
363 // Asset
364 CCAPIEndpoint::AssetMetadata => String::from("https://data-api.ccdata.io/asset/v1/metadata"),
365 CCAPIEndpoint::AssetEvents => String::from("https://data-api.ccdata.io/asset/v1/events"),
366 CCAPIEndpoint::AssetCodeRepo => String::from("https://data-api.ccdata.io/asset/v1/historical/code-repository/days"),
367 CCAPIEndpoint::AssetDiscord => String::from("https://data-api.ccdata.io/asset/v1/historical/discord/days"),
368 CCAPIEndpoint::AssetReddit => String::from("https://data-api.ccdata.io/asset/v1/historical/reddit/days"),
369 CCAPIEndpoint::AssetTelegram => String::from("https://data-api.ccdata.io/asset/v1/historical/telegram/days"),
370 CCAPIEndpoint::AssetTwitter => String::from("https://data-api.ccdata.io/asset/v1/historical/twitter/days"),
371 // News
372 CCAPIEndpoint::NewsLatestArticles => String::from("https://data-api.ccdata.io/news/v1/article/list"),
373 CCAPIEndpoint::NewsSources => String::from("https://data-api.ccdata.io/news/v1/source/list"),
374 CCAPIEndpoint::NewsCategories => String::from("https://data-api.ccdata.io/news/v1/category/list"),
375 // Overview
376 CCAPIEndpoint::OverviewMktCapOHLCV => String::from("https://data-api.ccdata.io/overview/v1/historical/marketcap/all/assets/days"),
377 }
378 }
379
380 fn add_unit_to_url(&self, url: &mut String, unit: &CCUnit) -> () {
381 match self {
382 CCAPIEndpoint::IndicesOHLCV | CCAPIEndpoint::SpotOHLCV | CCAPIEndpoint::FuturesOHLCV |
383 CCAPIEndpoint::OptionsOHLCV | CCAPIEndpoint::DerIndicesOHLCV | CCAPIEndpoint::OCDEXOHLCV => {
384 match unit {
385 CCUnit::Day | CCUnit::NA => url.push_str(&"/days"),
386 CCUnit::Hour => url.push_str(&"/hours"),
387 CCUnit::Minute => url.push_str(&"/minutes"),
388 }
389 },
390 _ => (),
391 }
392 }
393
394 /// Produces URL for a given API endpoint.
395 ///
396 /// # Input
397 /// - `unit`: Unit of the interval between successive data points
398 pub fn url(&self, unit: &CCUnit) -> String {
399 let mut url: String = self.resolve_url();
400 self.add_unit_to_url(&mut url, unit);
401 url
402 }
403}
404
405
406#[cfg(test)]
407mod tests {
408
409 #[test]
410 fn unit_test_add_unit_to_url() -> () {
411 use crate::{CCUnit, CCAPIEndpoint};
412 let unit: CCUnit = CCUnit::Hour;
413 let api_endpoint: CCAPIEndpoint = CCAPIEndpoint::IndicesOHLCV;
414 assert_eq!(api_endpoint.url(&unit), String::from("https://data-api.ccdata.io/index/cc/v1/historical/hours"));
415 }
416}