tenk 0.2.0

10K - A Rust library for fetching market data from multiple sources
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Data client with multi-source fallback.

use std::sync::Arc;
use tracing::{debug, info, warn};

use crate::data::{
    BondCurrentData, ConvertibleBondCode, CurrentMarketData, ETFCode, ETFCurrentData,
    ETFMarketData, ETFMinuteData, KLineType, MarketData, MinuteData, NewsArticle, NewsCategory,
    NewsContent, OrderBookData, StockCode, StockInfo, TickData,
};
use crate::error::{DataError, DataResult};
use crate::traits::{
    BondInfoSource, BondMarketSource, FundInfoSource, FundMarketSource, NewsSource,
    StockInfoSource, StockMarketSource,
};

/// Client for fetching financial data from multiple sources.
pub struct DataClient {
    /// Stock market data sources
    market_sources: Vec<Arc<dyn StockMarketSource>>,
    /// Stock info sources
    info_sources: Vec<Arc<dyn StockInfoSource>>,
    /// Fund/ETF info sources
    fund_info_sources: Vec<Arc<dyn FundInfoSource>>,
    /// Fund/ETF market data sources
    fund_market_sources: Vec<Arc<dyn FundMarketSource>>,
    /// Bond info sources
    bond_info_sources: Vec<Arc<dyn BondInfoSource>>,
    /// Bond market data sources
    bond_market_sources: Vec<Arc<dyn BondMarketSource>>,
    /// News sources
    news_sources: Vec<Arc<dyn NewsSource>>,
}

impl DataClient {
    /// Creates a new empty DataClient.
    pub fn new() -> Self {
        Self {
            market_sources: Vec::new(),
            info_sources: Vec::new(),
            fund_info_sources: Vec::new(),
            fund_market_sources: Vec::new(),
            bond_info_sources: Vec::new(),
            bond_market_sources: Vec::new(),
            news_sources: Vec::new(),
        }
    }

    /// Adds a stock market data source.
    pub fn with_market_source<S: StockMarketSource + 'static>(mut self, source: S) -> Self {
        self.market_sources.push(Arc::new(source));
        self.market_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a stock info source.
    pub fn with_info_source<S: StockInfoSource + 'static>(mut self, source: S) -> Self {
        self.info_sources.push(Arc::new(source));
        self.info_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a combined stock market and info source.
    pub fn with_source<S: StockMarketSource + StockInfoSource + Clone + 'static>(
        mut self,
        source: S,
    ) -> Self {
        self.market_sources.push(Arc::new(source.clone()));
        self.info_sources.push(Arc::new(source));
        self.market_sources.sort_by_key(|s| s.priority());
        self.info_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds an ETF info source.
    pub fn with_fund_info_source<S: FundInfoSource + 'static>(mut self, source: S) -> Self {
        self.fund_info_sources.push(Arc::new(source));
        self.fund_info_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds an ETF market data source.
    pub fn with_fund_market_source<S: FundMarketSource + 'static>(mut self, source: S) -> Self {
        self.fund_market_sources.push(Arc::new(source));
        self.fund_market_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a bond info source.
    pub fn with_bond_info_source<S: BondInfoSource + 'static>(mut self, source: S) -> Self {
        self.bond_info_sources.push(Arc::new(source));
        self.bond_info_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a bond market data source.
    pub fn with_bond_market_source<S: BondMarketSource + 'static>(mut self, source: S) -> Self {
        self.bond_market_sources.push(Arc::new(source));
        self.bond_market_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a combined ETF info and market source.
    pub fn with_fund_source<S: FundInfoSource + FundMarketSource + Clone + 'static>(
        mut self,
        source: S,
    ) -> Self {
        self.fund_info_sources.push(Arc::new(source.clone()));
        self.fund_market_sources.push(Arc::new(source));
        self.fund_info_sources.sort_by_key(|s| s.priority());
        self.fund_market_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a combined bond info and market source.
    pub fn with_bond_source<S: BondInfoSource + BondMarketSource + Clone + 'static>(
        mut self,
        source: S,
    ) -> Self {
        self.bond_info_sources.push(Arc::new(source.clone()));
        self.bond_market_sources.push(Arc::new(source));
        self.bond_info_sources.sort_by_key(|s| s.priority());
        self.bond_market_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Adds a news source.
    pub fn with_news_source<S: NewsSource + 'static>(mut self, source: S) -> Self {
        self.news_sources.push(Arc::new(source));
        self.news_sources.sort_by_key(|s| s.priority());
        self
    }

    /// Returns the number of registered market sources.
    pub fn market_source_count(&self) -> usize {
        self.market_sources.len()
    }

    /// Returns the number of registered info sources.
    pub fn info_source_count(&self) -> usize {
        self.info_sources.len()
    }

    /// Fetches historical K-line market data.
    pub async fn get_market(
        &self,
        stock_code: &str,
        start_date: Option<&str>,
        end_date: Option<&str>,
        k_type: KLineType,
    ) -> DataResult<Vec<MarketData>> {
        if self.market_sources.is_empty() {
            return Err(DataError::custom("No market sources configured"));
        }

        info!("Fetching market data for {} ({:?})", stock_code, k_type);

        for source in &self.market_sources {
            debug!("Trying source: {}", source.name());

            if !source.is_available().await {
                debug!("Source {} is not available, skipping", source.name());
                continue;
            }

            match source
                .get_market(stock_code, start_date, end_date, k_type)
                .await
            {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} records from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => {
                    debug!("Source {} returned empty data, trying next", source.name());
                    continue;
                }
                Err(e) => {
                    warn!("Source {} failed: {}", source.name(), e);
                    if !e.is_recoverable() {
                        return Err(e);
                    }
                    continue;
                }
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches real-time market quotes.
    pub async fn get_market_current(
        &self,
        stock_codes: &[&str],
    ) -> DataResult<Vec<CurrentMarketData>> {
        if self.market_sources.is_empty() {
            return Err(DataError::custom("No market sources configured"));
        }

        if stock_codes.is_empty() {
            return Ok(Vec::new());
        }

        info!(
            "Fetching current market data for {} stocks",
            stock_codes.len()
        );

        for source in &self.market_sources {
            debug!("Trying source: {}", source.name());

            if !source.is_available().await {
                continue;
            }

            match source.get_market_current(stock_codes).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} current records from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) => {
                    warn!("Source {} failed: {}", source.name(), e);
                    if !e.is_recoverable() {
                        return Err(e);
                    }
                    continue;
                }
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches intraday minute-level data.
    pub async fn get_market_min(&self, stock_code: &str) -> DataResult<Vec<MinuteData>> {
        if self.market_sources.is_empty() {
            return Err(DataError::custom("No market sources configured"));
        }

        info!("Fetching minute data for {}", stock_code);

        for source in &self.market_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_market_min(stock_code).await {
                Ok(data) if !data.is_empty() => return Ok(data),
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches order book data.
    pub async fn get_order_book(&self, stock_code: &str) -> DataResult<OrderBookData> {
        if self.market_sources.is_empty() {
            return Err(DataError::custom("No market sources configured"));
        }

        for source in &self.market_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_order_book(stock_code).await {
                Ok(data) => return Ok(data),
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches tick-by-tick trade data.
    pub async fn get_ticks(&self, stock_code: &str) -> DataResult<Vec<TickData>> {
        if self.market_sources.is_empty() {
            return Err(DataError::custom("No market sources configured"));
        }

        for source in &self.market_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_ticks(stock_code).await {
                Ok(data) if !data.is_empty() => return Ok(data),
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches all available stock codes.
    pub async fn get_all_codes(&self, limit: Option<usize>) -> DataResult<Vec<StockCode>> {
        if self.info_sources.is_empty() {
            return Err(DataError::custom("No info sources configured"));
        }

        info!("Fetching all stock codes");

        for source in &self.info_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_all_codes(limit).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} stock codes from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches detailed stock information.
    pub async fn get_stock_info(&self, stock_code: &str) -> DataResult<StockInfo> {
        if self.info_sources.is_empty() {
            return Err(DataError::custom("No info sources configured"));
        }

        for source in &self.info_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_stock_info(stock_code).await {
                Ok(info) => return Ok(info),
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches all available ETF codes.
    pub async fn get_all_etf_codes(&self, limit: Option<usize>) -> DataResult<Vec<ETFCode>> {
        if self.fund_info_sources.is_empty() {
            return Err(DataError::custom("No fund info sources configured"));
        }

        info!("Fetching all ETF codes");

        for source in &self.fund_info_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_all_etf_codes(limit).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} ETF codes from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches historical ETF K-line market data.
    pub async fn get_etf_market(
        &self,
        fund_code: &str,
        start_date: Option<&str>,
        end_date: Option<&str>,
        k_type: KLineType,
    ) -> DataResult<Vec<ETFMarketData>> {
        if self.fund_market_sources.is_empty() {
            return Err(DataError::custom("No fund market sources configured"));
        }

        info!("Fetching ETF market data for {}", fund_code);

        for source in &self.fund_market_sources {
            if !source.is_available().await {
                continue;
            }

            match source
                .get_etf_market(fund_code, start_date, end_date, k_type)
                .await
            {
                Ok(data) if !data.is_empty() => return Ok(data),
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches real-time ETF quotes.
    pub async fn get_etf_current(&self, fund_codes: &[&str]) -> DataResult<Vec<ETFCurrentData>> {
        if self.fund_market_sources.is_empty() {
            return Err(DataError::custom("No fund market sources configured"));
        }

        if fund_codes.is_empty() {
            return Ok(Vec::new());
        }

        for source in &self.fund_market_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_etf_current(fund_codes).await {
                Ok(data) if !data.is_empty() => return Ok(data),
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches intraday ETF minute-level data.
    pub async fn get_etf_min(&self, fund_code: &str) -> DataResult<Vec<ETFMinuteData>> {
        if self.fund_market_sources.is_empty() {
            return Err(DataError::custom("No fund market sources configured"));
        }

        for source in &self.fund_market_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_etf_min(fund_code).await {
                Ok(data) if !data.is_empty() => return Ok(data),
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches all available convertible bond codes.
    pub async fn get_all_bond_codes(
        &self,
        limit: Option<usize>,
    ) -> DataResult<Vec<ConvertibleBondCode>> {
        if self.bond_info_sources.is_empty() {
            return Err(DataError::custom("No bond info sources configured"));
        }

        info!("Fetching all bond codes");

        for source in &self.bond_info_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_all_bond_codes(limit).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} bond codes from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches real-time bond quotes.
    pub async fn get_bond_current(
        &self,
        bond_codes: Option<&[&str]>,
    ) -> DataResult<Vec<BondCurrentData>> {
        if self.bond_market_sources.is_empty() {
            return Err(DataError::custom("No bond market sources configured"));
        }

        info!("Fetching bond current data");

        for source in &self.bond_market_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_bond_current(bond_codes).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} bond records from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches news articles by category.
    pub async fn get_news(
        &self,
        category: NewsCategory,
        page: u32,
        limit: u32,
    ) -> DataResult<Vec<NewsArticle>> {
        if self.news_sources.is_empty() {
            return Err(DataError::custom("No news sources configured"));
        }

        info!("Fetching news: category={:?}, page={}", category, page);

        for source in &self.news_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_news(category, page, limit).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully fetched {} news articles from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Searches news articles by keyword.
    pub async fn search_news(
        &self,
        keyword: &str,
        page: u32,
        limit: u32,
    ) -> DataResult<Vec<NewsArticle>> {
        if self.news_sources.is_empty() {
            return Err(DataError::custom("No news sources configured"));
        }

        info!("Searching news: keyword={}, page={}", keyword, page);

        for source in &self.news_sources {
            if !source.is_available().await {
                continue;
            }

            match source.search_news(keyword, page, limit).await {
                Ok(data) if !data.is_empty() => {
                    info!(
                        "Successfully found {} news articles from {}",
                        data.len(),
                        source.name()
                    );
                    return Ok(data);
                }
                Ok(_) => continue,
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }

    /// Fetches full news content by ID.
    pub async fn get_news_content(&self, news_id: &str) -> DataResult<NewsContent> {
        if self.news_sources.is_empty() {
            return Err(DataError::custom("No news sources configured"));
        }

        info!("Fetching news content: id={}", news_id);

        for source in &self.news_sources {
            if !source.is_available().await {
                continue;
            }

            match source.get_news_content(news_id).await {
                Ok(content) => {
                    info!("Successfully fetched news content from {}", source.name());
                    return Ok(content);
                }
                Err(e) if e.is_recoverable() => continue,
                Err(e) => return Err(e),
            }
        }

        Err(DataError::NoDataAvailable)
    }
}

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

impl std::fmt::Debug for DataClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DataClient")
            .field("market_sources", &self.market_sources.len())
            .field("info_sources", &self.info_sources.len())
            .finish()
    }
}

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

    #[test]
    fn test_client_creation() {
        let client = DataClient::new();
        assert_eq!(client.market_source_count(), 0);
        assert_eq!(client.info_source_count(), 0);
    }

    #[test]
    fn test_client_default() {
        let client = DataClient::default();
        assert_eq!(client.market_source_count(), 0);
    }
}