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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Sina Finance data source.

use async_trait::async_trait;
use reqwest::header::{ACCEPT, ACCEPT_LANGUAGE, HOST, HeaderMap, HeaderValue, REFERER, USER_AGENT};
use serde::Deserialize;
use tracing::{debug, warn};

use crate::data::{
    BondCurrentData, ConvertibleBondCode, CurrentMarketData, ETFCode, ETFCurrentData,
    ETFMarketData, ETFMinuteData, Exchange, KLineType, MarketData, MinuteData, StockCode,
    StockInfo,
};
use crate::error::{DataError, DataResult};
use crate::request::{RequestConfig, RequestManager};
use crate::traits::{
    BondInfoSource, BondMarketSource, DataSource, FundInfoSource, FundMarketSource,
    StockInfoSource, StockMarketSource,
};

/// Sina Finance data source.
#[derive(Debug, Clone)]
pub struct SinaSource {
    /// HTTP request manager
    request: RequestManager,
    /// VIP API request manager
    vip_request: RequestManager,
}

impl SinaSource {
    /// Creates a new Sina source.
    pub fn new() -> DataResult<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(HOST, HeaderValue::from_static("hq.sinajs.cn"));
        headers.insert(
            USER_AGENT,
            HeaderValue::from_static(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0",
            ),
        );
        headers.insert(ACCEPT, HeaderValue::from_static("*/*"));
        headers.insert(
            ACCEPT_LANGUAGE,
            HeaderValue::from_static("zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2"),
        );
        headers.insert(
            REFERER,
            HeaderValue::from_static("http://vip.stock.finance.sina.com.cn/"),
        );

        let hq_config = RequestConfig::default().with_headers(headers);
        let vip_config = RequestConfig::default();

        Ok(Self {
            request: RequestManager::new(hq_config)?,
            vip_request: RequestManager::new(vip_config)?,
        })
    }

    /// Creates with a custom request manager.
    pub fn with_request_manager(request: RequestManager) -> Self {
        Self {
            request: request.clone(),
            vip_request: request,
        }
    }

    /// Gets exchange prefix for stock code.
    fn get_prefix(stock_code: &str) -> &'static str {
        match Exchange::from_stock_code(stock_code) {
            Exchange::SH => "sh",
            Exchange::SZ => "sz",
            Exchange::BJ => "bj",
            Exchange::Unknown => "sh",
        }
    }

    /// Parses stock quote line from Sina API response.
    fn parse_quote_line(line: &str) -> Option<CurrentMarketData> {
        let eq_pos = line.find('=')?;

        if eq_pos < 6 {
            return None;
        }
        let code_start = eq_pos - 6;
        let stock_code = &line[code_start..eq_pos];

        let quote_start = line.find('"')? + 1;
        let quote_end = line.rfind('"')?;
        if quote_start >= quote_end {
            return None;
        }

        let data = &line[quote_start..quote_end];
        let parts: Vec<&str> = data.split(',').collect();

        if parts.len() < 6 {
            return None;
        }

        let short_name = parts[0].to_string();
        let price: f64 = parts[1].parse().ok()?;
        let change: f64 = parts[2].parse().ok()?;
        let change_pct: f64 = parts[3].parse().ok()?;
        let volume: u64 = parts[4].parse().ok()?;
        let amount: f64 = parts[5].parse().ok()?;

        let (adj_volume, adj_amount) = if stock_code.starts_with(['0', '3', '6', '9']) {
            (volume * 100, amount * 10000.0)
        } else {
            (volume, amount)
        };

        Some(CurrentMarketData {
            stock_code: stock_code.to_string(),
            short_name,
            price,
            change,
            change_pct,
            volume: adj_volume,
            amount: adj_amount,
            open: None,
            high: None,
            low: None,
            pre_close: Some(price - change),
        })
    }

    /// Parses ETF quote line from Sina API response.
    fn parse_etf_quote_line(line: &str) -> Option<ETFCurrentData> {
        let eq_pos = line.find('=')?;

        if eq_pos < 6 {
            return None;
        }
        let code_start = eq_pos - 6;
        let fund_code = &line[code_start..eq_pos];

        let quote_start = line.find('"')? + 1;
        let quote_end = line.rfind('"')?;
        if quote_start >= quote_end {
            return None;
        }

        let data = &line[quote_start..quote_end];
        let parts: Vec<&str> = data.split(',').collect();

        if parts.len() < 6 {
            return None;
        }

        let short_name = parts[0].to_string();
        let price: f64 = parts[1].parse().ok()?;
        let change: f64 = parts[2].parse().ok()?;
        let change_pct: f64 = parts[3].parse().ok()?;
        let volume: u64 = parts[4].parse().ok()?;
        let amount: f64 = parts[5].parse().ok()?;

        let (adj_volume, adj_amount) = if fund_code.starts_with(['0', '1', '5']) {
            (volume * 100, amount * 10000.0)
        } else {
            (volume, amount)
        };

        Some(ETFCurrentData {
            fund_code: fund_code.to_string(),
            short_name,
            price,
            change: Some(change),
            change_pct: Some(change_pct),
            volume: adj_volume,
            amount: adj_amount,
            open: None,
            high: None,
            low: None,
        })
    }
}

impl Default for SinaSource {
    /// Creates default Sina source.
    fn default() -> Self {
        Self::new().expect("Failed to create SinaSource")
    }
}

/// Stock item from Sina API.
#[derive(Debug, Deserialize)]
struct SinaStockItem {
    /// Stock code
    code: String,
    /// Stock name
    name: String,
}

/// Bond item from Sina API.
#[derive(Debug, Deserialize)]
struct SinaBondItem {
    /// Bond code
    code: String,
    /// Bond name
    name: String,
    /// Current price
    #[serde(deserialize_with = "deserialize_string_or_number")]
    trade: String,
    /// Price change
    #[serde(deserialize_with = "deserialize_string_or_number")]
    pricechange: String,
    /// Change percentage
    #[serde(deserialize_with = "deserialize_string_or_number")]
    changepercent: String,
    /// Previous close
    #[serde(deserialize_with = "deserialize_string_or_number")]
    settlement: String,
    /// Open price
    #[serde(deserialize_with = "deserialize_string_or_number")]
    open: String,
    /// High price
    #[serde(deserialize_with = "deserialize_string_or_number")]
    high: String,
    /// Low price
    #[serde(deserialize_with = "deserialize_string_or_number")]
    low: String,
    /// Volume
    #[serde(deserialize_with = "deserialize_string_or_number")]
    volume: String,
    /// Amount
    #[serde(deserialize_with = "deserialize_string_or_number")]
    amount: String,
}

/// Deserializes a value that can be either a string or a number.
fn deserialize_string_or_number<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, Visitor};
    use std::fmt;

    struct StringOrNumberVisitor;

    impl<'de> Visitor<'de> for StringOrNumberVisitor {
        type Value = String;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a string or number")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }

        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v)
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }

        fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }

        fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }
    }

    deserializer.deserialize_any(StringOrNumberVisitor)
}

#[async_trait]
impl DataSource for SinaSource {
    /// Returns the source name.
    fn name(&self) -> &'static str {
        "sina"
    }

    /// Returns the source priority.
    fn priority(&self) -> u8 {
        2
    }

    /// Checks if the source is available.
    async fn is_available(&self) -> bool {
        self.request
            .get("https://hq.sinajs.cn/list=s_sh000001")
            .await
            .is_ok()
    }
}

#[async_trait]
impl StockMarketSource for SinaSource {
    /// Fetches historical K-line market data.
    async fn get_market(
        &self,
        _stock_code: &str,
        _start_date: Option<&str>,
        _end_date: Option<&str>,
        _k_type: KLineType,
    ) -> DataResult<Vec<MarketData>> {
        Err(DataError::not_supported("sina: get_market (K-line)"))
    }

    /// Fetches real-time market quotes.
    async fn get_market_current(&self, stock_codes: &[&str]) -> DataResult<Vec<CurrentMarketData>> {
        if stock_codes.is_empty() {
            return Ok(Vec::new());
        }

        let codes_str: String = stock_codes
            .iter()
            .map(|c| format!("s_{}{}", Self::get_prefix(c), c))
            .collect::<Vec<_>>()
            .join(",");

        let url = format!("https://hq.sinajs.cn/list={codes_str}");
        debug!("Fetching current market from Sina: {}", url);

        let response = self.request.get(&url).await?;
        let text = response.text().await.map_err(DataError::Network)?;

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

        let mut result = Vec::new();

        for line in text.split(';') {
            let line = line.trim();
            if line.len() < 10 {
                continue;
            }

            if let Some(data) = Self::parse_quote_line(line) {
                result.push(data);
            }
        }

        Ok(result)
    }

    /// Fetches intraday minute-level data.
    async fn get_market_min(&self, _stock_code: &str) -> DataResult<Vec<MinuteData>> {
        Err(DataError::not_supported("sina: get_market_min"))
    }
}

#[async_trait]
impl StockInfoSource for SinaSource {
    /// Fetches all available stock codes.
    async fn get_all_codes(&self, limit: Option<usize>) -> DataResult<Vec<StockCode>> {
        let url = "https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData";
        let mut all_codes = Vec::new();
        let page_size = 80;
        let mut page = 1;

        loop {
            let params = [
                ("page", page.to_string()),
                ("num", page_size.to_string()),
                ("sort", "changepercent".to_string()),
                ("asc", "0".to_string()),
                ("node", "hs_a".to_string()),
                ("symbol", "".to_string()),
                ("_s_r_a", "page".to_string()),
            ];

            debug!("Fetching stock codes page {} from Sina", page);

            let response = match self.vip_request.get_with_params(url, &params).await {
                Ok(r) => r,
                Err(e) => {
                    warn!("Failed to fetch page {}: {}", page, e);
                    break;
                }
            };

            let text = match response.text().await {
                Ok(t) => t,
                Err(e) => {
                    warn!("Failed to read response: {}", e);
                    break;
                }
            };

            if text.is_empty() || text == "null" {
                break;
            }

            let items: Vec<SinaStockItem> = match serde_json::from_str(&text) {
                Ok(items) => items,
                Err(e) => {
                    warn!("Failed to parse response: {}", e);
                    break;
                }
            };

            if items.is_empty() {
                break;
            }

            let count = items.len();

            for item in items {
                let exchange = Exchange::from_stock_code(&item.code);
                all_codes.push(StockCode {
                    stock_code: item.code,
                    short_name: item.name,
                    exchange,
                    list_date: None,
                });

                if let Some(lim) = limit {
                    if all_codes.len() >= lim {
                        return Ok(all_codes);
                    }
                }
            }

            if count < page_size {
                break;
            }
            page += 1;
        }

        Ok(all_codes)
    }

    /// Fetches detailed stock information.
    async fn get_stock_info(&self, stock_code: &str) -> DataResult<StockInfo> {
        let prefix = Self::get_prefix(stock_code);
        let url = format!("https://hq.sinajs.cn/list={prefix}{stock_code}");
        debug!("Fetching stock info from Sina: {}", stock_code);

        let response = self.request.get(&url).await?;
        let text = response.text().await.map_err(DataError::Network)?;

        if text.is_empty() || !text.contains('=') {
            return Err(DataError::custom("No stock info available"));
        }

        let quote_start = match text.find('"') {
            Some(pos) => pos + 1,
            None => return Err(DataError::custom("Invalid response format")),
        };
        let quote_end = match text.rfind('"') {
            Some(pos) => pos,
            None => return Err(DataError::custom("Invalid response format")),
        };

        if quote_start >= quote_end {
            return Err(DataError::custom("No stock info available"));
        }

        let data = &text[quote_start..quote_end];
        let parts: Vec<&str> = data.split(',').collect();

        if parts.is_empty() {
            return Err(DataError::custom("No stock info available"));
        }

        let short_name = parts.first().map(|s| s.to_string()).unwrap_or_default();
        let exchange = Exchange::from_stock_code(stock_code);

        Ok(StockInfo {
            stock_code: stock_code.to_string(),
            full_name: String::new(),
            short_name,
            exchange,
            industry: None,
            total_shares: None,
            circulating_shares: None,
            list_date: None,
        })
    }
}

#[async_trait]
impl FundInfoSource for SinaSource {
    /// Fetches all available ETF codes.
    async fn get_all_etf_codes(&self, limit: Option<usize>) -> DataResult<Vec<ETFCode>> {
        let url = "https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData";
        let mut all_codes = Vec::new();
        let page_size = 80;
        let mut page = 1;

        loop {
            let params = [
                ("page", page.to_string()),
                ("num", page_size.to_string()),
                ("sort", "changepercent".to_string()),
                ("asc", "0".to_string()),
                ("node", "etf_hq_fund".to_string()),
                ("symbol", "".to_string()),
                ("_s_r_a", "page".to_string()),
            ];

            debug!("Fetching ETF codes page {} from Sina", page);

            let response = match self.vip_request.get_with_params(url, &params).await {
                Ok(r) => r,
                Err(e) => {
                    warn!("Failed to fetch ETF page {}: {}", page, e);
                    break;
                }
            };

            let text = match response.text().await {
                Ok(t) => t,
                Err(e) => {
                    warn!("Failed to read ETF response: {}", e);
                    break;
                }
            };

            if text.is_empty() || text == "null" {
                break;
            }

            let items: Vec<SinaETFItem> = match serde_json::from_str(&text) {
                Ok(items) => items,
                Err(e) => {
                    warn!("Failed to parse ETF response: {}", e);
                    break;
                }
            };

            if items.is_empty() {
                break;
            }

            let count = items.len();

            for item in items {
                let exchange = Exchange::from_stock_code(&item.code);
                all_codes.push(ETFCode {
                    fund_code: item.code,
                    short_name: item.name,
                    exchange,
                    net_value: item.trade.parse().ok(),
                });

                if let Some(lim) = limit {
                    if all_codes.len() >= lim {
                        return Ok(all_codes);
                    }
                }
            }

            if count < page_size {
                break;
            }
            page += 1;
        }

        Ok(all_codes)
    }
}

/// ETF item from Sina API.
#[derive(Debug, Deserialize)]
struct SinaETFItem {
    /// ETF code
    code: String,
    /// ETF name
    name: String,
    /// Current price
    #[serde(default)]
    trade: String,
}

#[async_trait]
impl FundMarketSource for SinaSource {
    /// Fetches historical ETF K-line market data.
    async fn get_etf_market(
        &self,
        _fund_code: &str,
        _start_date: Option<&str>,
        _end_date: Option<&str>,
        _k_type: KLineType,
    ) -> DataResult<Vec<ETFMarketData>> {
        Err(DataError::not_supported("sina: get_etf_market (K-line)"))
    }

    /// Fetches real-time ETF quotes.
    async fn get_etf_current(&self, fund_codes: &[&str]) -> DataResult<Vec<ETFCurrentData>> {
        if fund_codes.is_empty() {
            return Ok(Vec::new());
        }

        let codes_str: String = fund_codes
            .iter()
            .map(|c| format!("s_{}{}", Self::get_prefix(c), c))
            .collect::<Vec<_>>()
            .join(",");

        let url = format!("https://hq.sinajs.cn/list={codes_str}");
        debug!("Fetching ETF current from Sina: {}", url);

        let response = self.request.get(&url).await?;
        let text = response.text().await.map_err(DataError::Network)?;

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

        let mut result = Vec::new();

        for line in text.split(';') {
            let line = line.trim();
            if line.len() < 10 {
                continue;
            }

            if let Some(data) = Self::parse_etf_quote_line(line) {
                result.push(data);
            }
        }

        Ok(result)
    }

    /// Fetches intraday ETF minute-level data.
    async fn get_etf_min(&self, _fund_code: &str) -> DataResult<Vec<ETFMinuteData>> {
        Err(DataError::not_supported("sina: get_etf_min"))
    }
}

#[async_trait]
impl BondInfoSource for SinaSource {
    /// Fetches all available convertible bond codes.
    async fn get_all_bond_codes(
        &self,
        _limit: Option<usize>,
    ) -> DataResult<Vec<ConvertibleBondCode>> {
        Err(DataError::not_supported("sina: get_all_bond_codes"))
    }
}

#[async_trait]
impl BondMarketSource for SinaSource {
    /// Fetches real-time bond quotes.
    async fn get_bond_current(
        &self,
        bond_codes: Option<&[&str]>,
    ) -> DataResult<Vec<BondCurrentData>> {
        if let Some(codes) = bond_codes {
            if !codes.is_empty() {
                return self.get_bond_current_by_codes(codes).await;
            }
        }

        self.get_all_bond_current().await
    }
}

impl SinaSource {
    /// Parses bond quote line from hq.sinajs.cn response.
    fn parse_bond_quote_line(line: &str) -> Option<BondCurrentData> {
        let eq_pos = line.find('=')?;
        if eq_pos < 6 {
            return None;
        }

        let code_start = eq_pos - 6;
        let bond_code = &line[code_start..eq_pos];

        let quote_start = line.find('"')? + 1;
        let quote_end = line.rfind('"')?;
        if quote_start >= quote_end {
            return None;
        }

        let data = &line[quote_start..quote_end];
        let parts: Vec<&str> = data.split(',').collect();

        if parts.len() < 10 {
            return None;
        }

        let bond_name = parts[0].to_string();
        let open: f64 = parts[1].parse().unwrap_or(0.0);
        let pre_close: f64 = parts[2].parse().unwrap_or(0.0);
        let price: f64 = parts[3].parse().unwrap_or(0.0);
        let high: f64 = parts[4].parse().unwrap_or(0.0);
        let low: f64 = parts[5].parse().unwrap_or(0.0);
        let volume: u64 = parts[8].parse().unwrap_or(0);
        let amount: f64 = parts[9].parse().unwrap_or(0.0);

        let change = price - pre_close;
        let change_pct = if pre_close > 0.0 {
            (change / pre_close) * 100.0
        } else {
            0.0
        };

        Some(BondCurrentData {
            bond_code: bond_code.to_string(),
            bond_name,
            price,
            open,
            high,
            low,
            pre_close,
            change,
            change_pct,
            volume,
            amount,
        })
    }

    /// Fetches bond data for specific codes directly.
    async fn get_bond_current_by_codes(&self, codes: &[&str]) -> DataResult<Vec<BondCurrentData>> {
        let symbols: Vec<String> = codes
            .iter()
            .map(|c| format!("{}{}", Self::get_prefix(c), c))
            .collect();
        let symbols_str = symbols.join(",");

        let url = format!("https://hq.sinajs.cn/list={}", symbols_str);
        debug!("Fetching bond quotes for {} codes from Sina", codes.len());

        let response = self.request.get(&url).await?;
        let text = response.text().await.map_err(DataError::Network)?;

        let mut results = Vec::with_capacity(codes.len());

        for line in text.lines() {
            if let Some(data) = Self::parse_bond_quote_line(line) {
                results.push(data);
            }
        }

        Ok(results)
    }

    /// Fetches all bond data with pagination.
    async fn get_all_bond_current(&self) -> DataResult<Vec<BondCurrentData>> {
        let url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeDataSimple";
        let mut all_bonds = Vec::new();
        let page_size = 80;
        let mut page = 1;

        loop {
            let params = [
                ("page", page.to_string()),
                ("num", page_size.to_string()),
                ("sort", "symbol".to_string()),
                ("asc", "1".to_string()),
                ("node", "hskzz_z".to_string()),
                ("_s_r_a", "page".to_string()),
            ];

            debug!("Fetching bond data page {} from Sina", page);

            let response = match self.vip_request.get_with_params(url, &params).await {
                Ok(r) => r,
                Err(e) => {
                    warn!("Failed to fetch bond page {}: {}", page, e);
                    break;
                }
            };

            let text = match response.text().await {
                Ok(t) => t,
                Err(e) => {
                    warn!("Failed to read bond response: {}", e);
                    break;
                }
            };

            if text.starts_with('<') || text.is_empty() || text == "null" || text == "[]" {
                debug!("Bond response is HTML or empty, trying next page or stopping");
                if page == 1 {
                    break;
                }
                page += 1;
                continue;
            }

            let items: Vec<SinaBondItem> = match serde_json::from_str(&text) {
                Ok(items) => items,
                Err(e) => {
                    warn!(
                        "Failed to parse bond response: {} (text starts with: {})",
                        e,
                        text.chars().take(100).collect::<String>()
                    );
                    break;
                }
            };

            if items.is_empty() {
                break;
            }

            let count = items.len();

            for item in items {
                let price: f64 = item.trade.parse().unwrap_or(0.0);
                let change: f64 = item.pricechange.parse().unwrap_or(0.0);
                let change_pct: f64 = item.changepercent.parse().unwrap_or(0.0);
                let pre_close: f64 = item.settlement.parse().unwrap_or(0.0);
                let open: f64 = item.open.parse().unwrap_or(0.0);
                let high: f64 = item.high.parse().unwrap_or(0.0);
                let low: f64 = item.low.parse().unwrap_or(0.0);
                let volume: u64 = item.volume.parse::<f64>().unwrap_or(0.0) as u64;
                let amount: f64 = item.amount.parse().unwrap_or(0.0);

                all_bonds.push(BondCurrentData {
                    bond_code: item.code,
                    bond_name: item.name,
                    price,
                    open,
                    high,
                    low,
                    pre_close,
                    change,
                    change_pct,
                    volume,
                    amount,
                });
            }

            if count < page_size {
                break;
            }
            page += 1;
        }

        let mut seen = std::collections::HashSet::new();
        all_bonds.retain(|b| seen.insert(b.bond_code.clone()));

        Ok(all_bonds)
    }
}

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

    #[test]
    fn test_get_prefix() {
        assert_eq!(SinaSource::get_prefix("600000"), "sh");
        assert_eq!(SinaSource::get_prefix("000001"), "sz");
        assert_eq!(SinaSource::get_prefix("300001"), "sz");
    }

    #[test]
    fn test_parse_quote_line() {
        let line = r#"var hq_str_s_sh600000="浦发银行,10.500,0.100,0.96,1234567,12345678.00";"#;
        let result = SinaSource::parse_quote_line(line);
        assert!(result.is_some());

        let data = result.unwrap();
        assert_eq!(data.stock_code, "600000");
        assert_eq!(data.short_name, "浦发银行");
        assert_eq!(data.price, 10.5);
    }

    #[test]
    fn test_parse_invalid_line() {
        let line = "invalid";
        assert!(SinaSource::parse_quote_line(line).is_none());
    }
}