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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Yahoo Finance connector implementation

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

use crate::core::types::*;
use crate::core::traits::*;

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

/// Yahoo Finance connector
pub struct YahooFinanceConnector {
    client: Client,
    auth: YahooFinanceAuth,
    urls: YahooFinanceUrls,
}

impl YahooFinanceConnector {
    /// Create new connector (no authentication needed for most endpoints)
    pub fn new() -> Self {
        Self {
            client: Client::new(),
            auth: YahooFinanceAuth::new(),
            urls: YahooFinanceUrls::default(),
        }
    }

    /// Create connector with authentication for historical downloads
    pub fn with_auth(auth: YahooFinanceAuth) -> Self {
        Self {
            client: Client::new(),
            auth,
            urls: YahooFinanceUrls::default(),
        }
    }

    /// Create connector from environment variables
    pub fn from_env() -> Self {
        Self {
            client: Client::new(),
            auth: YahooFinanceAuth::from_env(),
            urls: YahooFinanceUrls::default(),
        }
    }

    /// Get mutable reference to auth (for updating cookie/crumb)
    pub fn auth_mut(&mut self) -> &mut YahooFinanceAuth {
        &mut self.auth
    }

    /// Obtain crumb from Yahoo Finance
    ///
    /// This requires visiting Yahoo Finance first to get a valid cookie.
    /// Call this method after setting a cookie via `auth_mut().set_cookie(...)`.
    pub async fn obtain_crumb(&mut self) -> ExchangeResult<String> {
        if self.auth.cookie.is_none() {
            return Err(ExchangeError::Auth(
                "Cookie required to obtain crumb. Visit https://finance.yahoo.com first.".to_string()
            ));
        }

        let url = YahooFinanceEndpoint::GetCrumb.url(self.urls.rest_base, None);
        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.get(&url);
        for (key, value) in headers {
            request = request.header(key, value);
        }

        let response = request
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Failed to get crumb: {}", e)))?;

        if !response.status().is_success() {
            let status_code = response.status().as_u16() as i32;
            return Err(ExchangeError::Api {
                code: status_code,
                message: format!("Failed to get crumb: HTTP {}", status_code)
            });
        }

        let crumb_text = response
            .text()
            .await
            .map_err(|e| ExchangeError::Parse(format!("Failed to read crumb: {}", e)))?;

        let crumb = YahooFinanceParser::parse_crumb(&crumb_text)?;
        self.auth.set_crumb(&crumb);

        Ok(crumb)
    }

    /// Internal: Make GET request
    async fn get(
        &self,
        endpoint: YahooFinanceEndpoint,
        symbol: Option<&str>,
        mut params: HashMap<String, String>,
    ) -> ExchangeResult<serde_json::Value> {
        let url = endpoint.url(self.urls.rest_base, symbol);

        // Add authentication headers and query params
        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        if endpoint.requires_crumb() {
            self.auth.sign_query(&mut params);
        }

        let mut request = self.client.get(&url);

        // Add headers
        for (key, value) in headers {
            request = request.header(key, value);
        }

        // Add query params
        if !params.is_empty() {
            request = request.query(&params);
        }

        let response = request
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        // Check for rate limiting
        if response.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
            return Err(ExchangeError::RateLimit);
        }

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

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

        // Check for API errors in response
        YahooFinanceParser::check_error(&json)?;

        Ok(json)
    }

    /// Internal: Get quote via /v7/finance/quote?symbols= (carries bid/ask)
    async fn get_quote_v7(&self, yahoo_symbol: &str) -> ExchangeResult<serde_json::Value> {
        let mut params = HashMap::new();
        params.insert("symbols".to_string(), yahoo_symbol.to_string());
        self.get(YahooFinanceEndpoint::Quote, None, params).await
    }

    /// Internal: Get quote for a symbol via /v8/finance/chart/{symbol}
    ///
    /// Fallback path — chart endpoint does NOT carry bid/ask.
    async fn get_quote_internal(&self, yahoo_symbol: &str) -> ExchangeResult<serde_json::Value> {
        self.get(YahooFinanceEndpoint::Chart, Some(yahoo_symbol), HashMap::new()).await
    }
}

impl Default for YahooFinanceConnector {
    fn default() -> Self {
        Self::new()
    }
}

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

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

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

    fn is_testnet(&self) -> bool {
        false // Yahoo Finance has no testnet
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        // Yahoo Finance is a data provider only (treat as Spot for compatibility)
        vec![AccountType::Spot]
    }
}

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

#[async_trait]
impl MarketData for YahooFinanceConnector {
    /// Get current price
    async fn get_price(
        &self,
        symbol: SymbolInput<'_>,
        _account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let sym_str: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let response = self.get_quote_internal(&sym_str).await?;
        YahooFinanceParser::parse_price(&response)
    }

    /// Get ticker (24h stats)
    ///
    /// Tries /v7/finance/quote first (carries bid/ask); falls back to /v8/finance/chart
    /// when the quote endpoint returns an error or an empty result.
    async fn get_ticker(
        &self,
        symbol: SymbolInput<'_>,
        _account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let sym_str: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };

        // Primary: /v7/finance/quote — provides bid/ask
        match self.get_quote_v7(&sym_str).await {
            Ok(response) => {
                if let Ok(ticker) = YahooFinanceParser::parse_quote_ticker(&response, &sym_str) {
                    return Ok(ticker);
                }
                // Empty result array — fall through to chart
            }
            Err(_) => {
                // 401/404/network — fall through to chart
            }
        }

        // Fallback: /v8/finance/chart — no bid/ask but always works
        let response = self.get_quote_internal(&sym_str).await?;
        YahooFinanceParser::parse_ticker(&response, &sym_str)
    }

    /// Get orderbook — NOT SUPPORTED
    ///
    /// Yahoo Finance is a data feed; it does not expose level-2 order book data.
    /// No alternative endpoint exists in the public Yahoo Finance API.
    async fn get_orderbook(
        &self,
        _symbol: SymbolInput<'_>,
        _depth: Option<u16>,
        _account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        Err(ExchangeError::NotSupported(
            "Yahoo Finance does not expose order book data — data feed only (price, klines, ticker). \
             Use a dedicated exchange connector (Binance, Coinbase, etc.) for order book depth."
                .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 sym_str: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let yahoo_symbol = sym_str.as_str();
        let yahoo_interval = map_chart_interval(interval);

        let mut params = HashMap::new();
        params.insert("interval".to_string(), yahoo_interval.to_string());

        // Use range parameter for simplicity (Yahoo prefers this over period1/period2 for recent data)
        if let Some(lim) = limit {
            // Map limit to range
            let range = match interval {
                "1m" | "2m" | "5m" => format!("{}d", (lim as f64 / 390.0).ceil()), // ~390 1m candles per day
                "15m" => format!("{}d", (lim as f64 / 26.0).ceil()),                // ~26 15m candles per day
                "30m" => format!("{}d", (lim as f64 / 13.0).ceil()),                // ~13 30m candles per day
                "1h" => format!("{}d", (lim as f64 / 6.5).ceil()),                  // ~6.5 1h candles per day
                "1d" => format!("{}d", lim),
                "1wk" => format!("{}mo", (lim as f64 / 4.0).ceil()),
                "1mo" => format!("{}mo", lim),
                _ => format!("{}d", lim),
            };
            params.insert("range".to_string(), range);
        } else {
            // Default range
            params.insert("range".to_string(), "1mo".to_string());
        }

        let response = self
            .get(
                YahooFinanceEndpoint::Chart,
                Some(yahoo_symbol),
                params,
            )
            .await?;

        YahooFinanceParser::parse_klines(&response)
    }

    /// Ping (check connection)
    async fn ping(&self) -> ExchangeResult<()> {
        // Yahoo Finance doesn't have a dedicated ping endpoint
        // Try to get market summary as a health check
        self.get(YahooFinanceEndpoint::MarketSummary, None, HashMap::new())
            .await?;
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Trading (UnsupportedOperation - data provider only)
// ═══════════════════════════════════════════════════════════════════════════

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

    async fn cancel_order(&self, _req: CancelRequest) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "Yahoo Finance 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(
            "Yahoo Finance 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(
            "Yahoo Finance 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(
            "Yahoo Finance is a data provider - trading not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Account (UnsupportedOperation - data provider only)
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Account for YahooFinanceConnector {
    async fn get_balance(&self, query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        let _asset = query.asset.clone();
        let _account_type = query.account_type;
        Err(ExchangeError::UnsupportedOperation(
            "Yahoo Finance is a data provider - account operations not supported".to_string(),
        ))
    
    }

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

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

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Positions (UnsupportedOperation - data provider only)
// ═══════════════════════════════════════════════════════════════════════════

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

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

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

impl YahooFinanceConnector {
    /// Get market summary (major indices)
    pub async fn get_market_summary(&self) -> ExchangeResult<serde_json::Value> {
        self.get(YahooFinanceEndpoint::MarketSummary, None, HashMap::new())
            .await
    }

    /// Search for symbols
    ///
    /// # Parameters
    /// - `query`: Search query (e.g., "apple", "btc")
    /// - `quotes_count`: Max number of quotes to return (default: 10)
    pub async fn search_symbols(
        &self,
        query: &str,
        quotes_count: Option<u16>,
    ) -> ExchangeResult<serde_json::Value> {
        let mut params = HashMap::new();
        params.insert("q".to_string(), query.to_string());
        params.insert(
            "quotesCount".to_string(),
            quotes_count.unwrap_or(10).to_string(),
        );
        params.insert("enableFuzzyQuery".to_string(), "true".to_string());

        self.get(YahooFinanceEndpoint::Search, None, params).await
    }

    /// Get quote summary with specific modules
    ///
    /// # Parameters
    /// - `symbol`: Yahoo symbol (e.g., "AAPL", "BTC-USD")
    /// - `modules`: Comma-separated module names (see `quote_summary_modules`)
    ///
    /// # Example
    /// ```ignore
    /// let data = connector.get_quote_summary("AAPL", "assetProfile,financialData").await?;
    /// ```
    pub async fn get_quote_summary(
        &self,
        symbol: &str,
        modules: &str,
    ) -> ExchangeResult<serde_json::Value> {
        let mut params = HashMap::new();
        params.insert("modules".to_string(), modules.to_string());

        self.get(YahooFinanceEndpoint::QuoteSummary, Some(symbol), params)
            .await
    }

    /// Get asset profile (company information)
    pub async fn get_asset_profile(&self, symbol: &str) -> ExchangeResult<serde_json::Value> {
        self.get_quote_summary(symbol, quote_summary_modules::ASSET_PROFILE)
            .await
    }

    /// Get financial data (key metrics)
    pub async fn get_financial_data(&self, symbol: &str) -> ExchangeResult<serde_json::Value> {
        self.get_quote_summary(symbol, quote_summary_modules::FINANCIAL_DATA)
            .await
    }

    /// Get earnings data
    pub async fn get_earnings(&self, symbol: &str) -> ExchangeResult<serde_json::Value> {
        self.get_quote_summary(symbol, quote_summary_modules::EARNINGS)
            .await
    }

    /// Get options chain
    ///
    /// # Parameters
    /// - `symbol`: Underlying symbol (e.g., "AAPL")
    /// - `expiration_date`: Optional Unix timestamp for specific expiration
    pub async fn get_options_chain(
        &self,
        symbol: &str,
        expiration_date: Option<i64>,
    ) -> ExchangeResult<serde_json::Value> {
        let mut params = HashMap::new();
        if let Some(date) = expiration_date {
            params.insert("date".to_string(), date.to_string());
        }

        self.get(YahooFinanceEndpoint::Options, Some(symbol), params)
            .await
    }

    /// Download historical data as CSV (requires authentication)
    ///
    /// This endpoint requires cookie and crumb authentication.
    /// Use `obtain_crumb()` first to set up authentication.
    pub async fn download_history_csv(
        &self,
        symbol: &str,
        period1: i64,
        period2: i64,
        interval: &str,
    ) -> ExchangeResult<String> {
        if !self.auth.has_download_auth() {
            return Err(ExchangeError::Auth(
                "Cookie and crumb required for historical download".to_string(),
            ));
        }

        let mut params = HashMap::new();
        params.insert("period1".to_string(), period1.to_string());
        params.insert("period2".to_string(), period2.to_string());
        params.insert("interval".to_string(), interval.to_string());
        params.insert("events".to_string(), "history".to_string());

        // Add crumb to query params
        self.auth.sign_query(&mut params);

        let url = YahooFinanceEndpoint::DownloadHistory.url(self.urls.rest_base, Some(symbol));

        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.get(&url);
        for (key, value) in headers {
            request = request.header(key, value);
        }
        request = request.query(&params);

        let response = request
            .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;
            return Err(ExchangeError::Api {
                code: status_code,
                message: format!("HTTP {} - download failed", status_code)
            });
        }

        response
            .text()
            .await
            .map_err(|e| ExchangeError::Parse(format!("Failed to read CSV: {}", e)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_connector_creation() {
        let connector = YahooFinanceConnector::new();
        assert_eq!(connector.exchange_name(), "yahoo_finance");
        assert_eq!(connector.exchange_id(), ExchangeId::YahooFinance);
    }

    #[test]
    fn test_supported_account_types() {
        let connector = YahooFinanceConnector::new();
        let types = connector.supported_account_types();
        assert_eq!(types, vec![AccountType::Spot]);
    }
}