digdigdig3 0.3.3

Unified async Rust API for 47 exchange connectors (REST + WebSocket). The core layer — pure ExchangeHub + connectors. Higher-level builder, persistence, replay, OB tracker live in `digdigdig3-station`.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! CryptoCompare connector implementation

use async_trait::async_trait;
use reqwest::Client;
use std::collections::HashMap;
use std::time::Duration;

use crate::core::types::{
    Symbol, AccountType, Price, Ticker, Kline, OrderBook, FundingRate,
    ExchangeId, ExchangeError, ExchangeResult,
    Order, Balance, AccountInfo, Position, SymbolInfo, SymbolInput,
    OrderRequest, CancelRequest, OrderHistoryFilter, PlaceOrderResponse, FeeInfo,
    BalanceQuery, PositionQuery, PositionModification,
};
use crate::core::traits::{ExchangeIdentity, MarketData, Trading, Account, Positions};

use super::endpoints::*;
use super::auth::*;
use super::parser::*;

/// CryptoCompare connector
pub struct CryptoCompareConnector {
    client: Client,
    auth: CryptoCompareAuth,
    endpoints: CryptoCompareEndpoints,
}

impl CryptoCompareConnector {
    /// Create new connector with explicit auth
    pub fn new(auth: CryptoCompareAuth) -> Self {
        Self {
            client: Client::new(),
            auth,
            endpoints: CryptoCompareEndpoints::default(),
        }
    }

    /// Create connector from environment variables
    ///
    /// Looks for CRYPTOCOMPARE_API_KEY environment variable.
    pub fn from_env() -> Self {
        Self::new(CryptoCompareAuth::from_env())
    }

    /// Create connector without API key (public endpoints only, low rate limits)
    pub fn public() -> Self {
        Self::new(CryptoCompareAuth::public())
    }

    /// Internal: Make GET request with single retry on rate-limit (Type 99).
    ///
    /// CryptoCompare's /data/all/coinlist endpoint has a tighter per-second quota
    /// than price/ticker endpoints. When the harness fires all REST methods back-to-back,
    /// the CoinList call often hits the limit. One 1 s sleep + retry is enough.
    async fn get_with_rate_limit_retry(
        &self,
        endpoint: CryptoCompareEndpoint,
        params: HashMap<String, String>,
    ) -> ExchangeResult<serde_json::Value> {
        match self.get(endpoint.clone(), params.clone()).await {
            Err(ExchangeError::RateLimitExceeded { .. }) => {
                tokio::time::sleep(Duration::from_secs(1)).await;
                self.get(endpoint, params).await
            }
            other => other,
        }
    }

    /// Internal: Make GET request
    async fn get(
        &self,
        endpoint: CryptoCompareEndpoint,
        mut params: HashMap<String, String>,
    ) -> ExchangeResult<serde_json::Value> {
        let url = format!("{}{}", self.endpoints.rest_base, endpoint.path());

        // Add authentication (query parameter is preferred for CryptoCompare)
        self.auth.sign_query(&mut params);

        let response = self
            .client
            .get(&url)
            .query(&params)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        if !response.status().is_success() {
            let status_code = response.status().as_u16() as i32;
            let message = format!(
                "HTTP {} - {}",
                response.status(),
                response.text().await.unwrap_or_default()
            );
            return Err(ExchangeError::Api { code: status_code, message });
        }

        response
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: ExchangeIdentity (ALWAYS implement)
// ═══════════════════════════════════════════════════════════════════════════════

impl ExchangeIdentity for CryptoCompareConnector {
    fn exchange_name(&self) -> &'static str {
        "cryptocompare"
    }

    fn exchange_id(&self) -> ExchangeId {
        ExchangeId::CryptoCompare
    }

    fn is_testnet(&self) -> bool {
        false // CryptoCompare doesn't have testnet
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        // CryptoCompare is data provider for spot crypto only
        vec![AccountType::Spot]
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: MarketData (Implement what makes sense)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl MarketData for CryptoCompareConnector {
    /// Get current price
    async fn get_price(
        &self,
        symbol: SymbolInput<'_>,
        _account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let symbol: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let (fsym, tsym) = symbol.split_once('-')
            .or_else(|| symbol.split_once('/'))
            .or_else(|| symbol.split_once('_'))
            .map(|(b, q)| (b.to_uppercase(), q.to_uppercase()))
            .unwrap_or_else(|| (symbol.to_uppercase(), "USD".to_string()));

        let mut params = HashMap::new();
        params.insert("fsym".to_string(), fsym);
        params.insert("tsyms".to_string(), tsym.clone());

        let response = self.get(CryptoCompareEndpoint::Price, params).await?;
        CryptoCompareParser::parse_price(&response, &tsym)
    }

    /// Get ticker (24h stats)
    async fn get_ticker(
        &self,
        symbol: SymbolInput<'_>,
        _account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let symbol: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let (fsym, tsym) = symbol.split_once('-')
            .or_else(|| symbol.split_once('/'))
            .or_else(|| symbol.split_once('_'))
            .map(|(b, q)| (b.to_uppercase(), q.to_uppercase()))
            .unwrap_or_else(|| (symbol.to_uppercase(), "USD".to_string()));

        let mut params = HashMap::new();
        params.insert("fsyms".to_string(), fsym.clone());
        params.insert("tsyms".to_string(), tsym.clone());

        let response = self.get(CryptoCompareEndpoint::PriceMultiFull, params).await?;
        CryptoCompareParser::parse_ticker(&response, &fsym, &tsym)
    }

    /// Get orderbook
    ///
    /// NOTE: CryptoCompare orderbook data is PAID TIER ONLY (WebSocket Channel 16).
    /// Not available via REST API.
    async fn get_orderbook(
        &self,
        _symbol: SymbolInput<'_>,
        _depth: Option<u16>,
        _account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare orderbook data requires paid tier and WebSocket connection - not available via REST API".to_string()
        ))
    }

    /// Get klines/candles
    async fn get_klines(
        &self,
        symbol: SymbolInput<'_>,
        interval: &str,
        limit: Option<u16>,
        _account_type: AccountType,
        _end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        let symbol: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let (fsym, tsym) = symbol.split_once('-')
            .or_else(|| symbol.split_once('/'))
            .or_else(|| symbol.split_once('_'))
            .map(|(b, q)| (b.to_uppercase(), q.to_uppercase()))
            .unwrap_or_else(|| (symbol.to_uppercase(), "USD".to_string()));
        let (endpoint, aggregate) = map_interval_aggregate(interval);

        let mut params = HashMap::new();
        params.insert("fsym".to_string(), fsym);
        params.insert("tsym".to_string(), tsym);
        params.insert("aggregate".to_string(), aggregate.to_string());

        if let Some(lim) = limit {
            params.insert("limit".to_string(), lim.to_string());
        } else {
            params.insert("limit".to_string(), "100".to_string());
        }

        let response = self.get(endpoint, params).await?;
        CryptoCompareParser::parse_klines(&response)
    }

    /// Ping endpoint (check connection)
    async fn ping(&self) -> ExchangeResult<()> {
        // CryptoCompare doesn't have a dedicated ping endpoint
        // We'll use a lightweight endpoint to verify connection
        let mut params = HashMap::new();
        params.insert("fsym".to_string(), "BTC".to_string());
        params.insert("tsyms".to_string(), "USD".to_string());

        let _ = self.get(CryptoCompareEndpoint::Price, params).await?;
        Ok(())
    }

    /// Get all coins listed on CryptoCompare
    async fn get_exchange_info(&self, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
        let response = self.get_with_rate_limit_retry(CryptoCompareEndpoint::CoinList, HashMap::new()).await?;
        let symbols = CryptoCompareParser::parse_symbols(&response)?;

        let infos = symbols
            .into_iter()
            .map(|symbol| SymbolInfo {
                symbol: symbol.clone(),
                base_asset: symbol,
                quote_asset: "USD".to_string(), // CryptoCompare tracks crypto vs USD by default
                status: "TRADING".to_string(),
                price_precision: 8,
                quantity_precision: 8,
                min_quantity: None,
                max_quantity: None,
                tick_size: None,
                step_size: None,
                min_notional: None,
                account_type,
            })
            .collect();

        Ok(infos)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: Trading (UnsupportedOperation for data providers)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Trading for CryptoCompareConnector {
    async fn place_order(&self, _req: OrderRequest) -> ExchangeResult<PlaceOrderResponse> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - trading not supported".to_string()
        ))
    }

    async fn cancel_order(&self, _req: CancelRequest) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - trading not supported".to_string()
        ))
    }

    async fn get_order(
        &self,
        _symbol: &str,
        _order_id: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - trading not supported".to_string()
        ))
    }

    async fn get_open_orders(
        &self,
        _symbol: Option<&str>,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - trading not supported".to_string()
        ))
    }

    async fn get_order_history(
        &self,
        _filter: OrderHistoryFilter,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - trading not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: Account (UnsupportedOperation for data providers)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Account for CryptoCompareConnector {
    async fn get_balance(&self, _query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - account operations not supported".to_string()
        ))
    
    }

    async fn get_account_info(&self, _account_type: AccountType) -> ExchangeResult<AccountInfo> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - account operations not supported".to_string()
        ))
    }

    async fn get_fees(&self, _symbol: Option<&str>) -> ExchangeResult<FeeInfo> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - account operations not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: Positions (UnsupportedOperation for data providers)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Positions for CryptoCompareConnector {
    async fn get_positions(&self, _query: PositionQuery) -> ExchangeResult<Vec<Position>> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - position tracking not supported".to_string()
        ))
    }

    async fn get_funding_rate(
        &self,
        _symbol: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<FundingRate> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - position tracking not supported".to_string()
        ))
    }

    async fn modify_position(&self, _req: PositionModification) -> ExchangeResult<()> {
        Err(ExchangeError::UnsupportedOperation(
            "CryptoCompare is a data provider - position tracking not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXTENDED METHODS (CryptoCompare-specific, not from traits)
// ═══════════════════════════════════════════════════════════════════════════════

impl CryptoCompareConnector {
    /// Get historical price at specific timestamp
    ///
    /// Returns price at end of day GMT for given timestamp.
    pub async fn get_historical_price(
        &self,
        symbol: Symbol,
        timestamp: i64,
    ) -> ExchangeResult<f64> {
        let (fsym, tsym) = format_symbol(&symbol);

        let mut params = HashMap::new();
        params.insert("fsym".to_string(), fsym);
        params.insert("tsyms".to_string(), tsym.clone());
        params.insert("ts".to_string(), (timestamp / 1000).to_string()); // Convert to seconds

        let response = self.get(CryptoCompareEndpoint::PriceHistorical, params).await?;
        CryptoCompareParser::parse_price(&response, &tsym)
    }

    /// Get top exchanges by volume for a trading pair
    pub async fn get_top_exchanges(
        &self,
        symbol: Symbol,
        limit: Option<u16>,
    ) -> ExchangeResult<serde_json::Value> {
        let (fsym, tsym) = format_symbol(&symbol);

        let mut params = HashMap::new();
        params.insert("fsym".to_string(), fsym);
        params.insert("tsym".to_string(), tsym);
        if let Some(lim) = limit {
            params.insert("limit".to_string(), lim.to_string());
        }

        self.get(CryptoCompareEndpoint::TopExchanges, params).await
    }

    /// Get rate limit status (requires API key)
    pub async fn get_rate_limit(&self) -> ExchangeResult<serde_json::Value> {
        if !self.auth.has_key() {
            return Err(ExchangeError::Auth(
                "API key required to check rate limits".to_string()
            ));
        }

        self.get(CryptoCompareEndpoint::RateLimit, HashMap::new()).await
    }
}