tenk 0.1.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
//! 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, OrderBookData, StockCode,
    StockInfo, TickData,
};
use crate::error::{DataError, DataResult};
use crate::traits::{
    BondInfoSource, BondMarketSource, FundInfoSource, FundMarketSource, StockInfoSource,
    StockMarketSource,
};

/// Data client.
pub struct DataClient {
    market_sources: Vec<Arc<dyn StockMarketSource>>,
    info_sources: Vec<Arc<dyn StockInfoSource>>,
    fund_info_sources: Vec<Arc<dyn FundInfoSource>>,
    fund_market_sources: Vec<Arc<dyn FundMarketSource>>,
    bond_info_sources: Vec<Arc<dyn BondInfoSource>>,
    bond_market_sources: Vec<Arc<dyn BondMarketSource>>,
}

impl 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(),
        }
    }

    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
    }

    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
    }

    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
    }

    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
    }

    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
    }

    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
    }

    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
    }

    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
    }

    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
    }

    pub fn market_source_count(&self) -> usize {
        self.market_sources.len()
    }

    pub fn info_source_count(&self) -> usize {
        self.info_sources.len()
    }

    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)
    }

    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)
    }

    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)
    }

    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)
    }

    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)
    }

    pub async fn get_all_codes(&self) -> 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().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)
    }

    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)
    }

    pub async fn get_all_etf_codes(&self) -> 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().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)
    }

    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)
    }

    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)
    }

    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)
    }

    pub async fn get_all_bond_codes(&self) -> 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().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)
    }

    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)
    }
}

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);
    }
}