Skip to main content

financial_api/
index.rs

1use crate::endpoints;
2use crate::endpoints::join_values;
3use crate::{
4    Client, Error, IndexCatalogData, IndexConstituentsData, IndexHistoricalData, IndexTag,
5    PriceSnapshotData, Response, Thscode, UnixMillis, ValidationError,
6};
7
8const TEN_YEARS_MS: i64 = 315_576_000_000;
9
10impl Client {
11    /// 按目录标签列出同花顺指数。
12    ///
13    /// # 示例
14    #[doc = concat!(
15        "```no_run\n",
16        include_str!("../examples/index_catalog_ths_index_list.rs"),
17        "\n```"
18    )]
19    pub async fn index_catalog_ths_index_list(
20        &self,
21        tag: IndexTag,
22    ) -> Result<Response<IndexCatalogData>, Error> {
23        self.get(endpoints::INDEX_CATALOG, &[("tag", tag.to_string())])
24            .await
25    }
26
27    /// 获取指定指数当前的成分股列表。
28    ///
29    /// # 示例
30    #[doc = concat!(
31        "```no_run\n",
32        include_str!("../examples/index_constituents_ths_stock_list.rs"),
33        "\n```"
34    )]
35    pub async fn index_constituents_ths_stock_list(
36        &self,
37        thscode: &Thscode,
38    ) -> Result<Response<IndexConstituentsData>, Error> {
39        self.get(
40            endpoints::INDEX_CONSTITUENTS,
41            &[("thscode", thscode.to_string())],
42        )
43        .await
44    }
45
46    /// 获取一个或多个交易所指数或同花顺指数的行情快照。
47    ///
48    /// # 示例
49    #[doc = concat!(
50        "```no_run\n",
51        include_str!("../examples/index_prices_snapshot.rs"),
52        "\n```"
53    )]
54    pub async fn index_prices_snapshot(
55        &self,
56        thscodes: &[Thscode],
57    ) -> Result<Response<PriceSnapshotData>, Error> {
58        self.get(
59            endpoints::INDEX_SNAPSHOT,
60            &[("thscodes", join_values("thscodes", thscodes, None)?)],
61        )
62        .await
63    }
64
65    /// 获取指定指数的历史日 K 线。
66    ///
67    /// # 示例
68    #[doc = concat!(
69        "```no_run\n",
70        include_str!("../examples/index_prices_historical.rs"),
71        "\n```"
72    )]
73    pub async fn index_prices_historical(
74        &self,
75        thscode: &Thscode,
76        start: UnixMillis,
77        end: UnixMillis,
78    ) -> Result<Response<IndexHistoricalData>, Error> {
79        validate_history_window(start, end)?;
80        let query = [
81            ("thscode", thscode.to_string()),
82            ("interval", "1d".to_owned()),
83            ("start", start.to_string()),
84            ("end", end.to_string()),
85        ];
86        self.get(endpoints::INDEX_HISTORICAL, &query).await
87    }
88}
89
90fn validate_history_window(start: UnixMillis, end: UnixMillis) -> Result<(), ValidationError> {
91    if end < start {
92        return Err(ValidationError::new(
93            "end",
94            "must not be earlier than start",
95        ));
96    }
97    if end.get() - start.get() > TEN_YEARS_MS {
98        return Err(ValidationError::new(
99            "end",
100            "requested time window exceeds ten years",
101        ));
102    }
103    Ok(())
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::ApiKey;
110
111    #[test]
112    fn historical_window_enforces_order_and_ten_year_limit() {
113        let start = UnixMillis::new(1_000_000_000_000).unwrap();
114        let before_start = UnixMillis::new(start.get() - 1).unwrap();
115        let limit = UnixMillis::new(start.get() + TEN_YEARS_MS).unwrap();
116        let after_limit = UnixMillis::new(limit.get() + 1).unwrap();
117
118        assert!(validate_history_window(start, before_start).is_err());
119        assert!(validate_history_window(start, limit).is_ok());
120        assert!(validate_history_window(start, after_limit).is_err());
121    }
122
123    #[tokio::test]
124    async fn historical_prices_keeps_window_validation_on_its_call_edge() {
125        let client = Client::builder(ApiKey::new("test-api-key").unwrap())
126            .base_url("http://127.0.0.1:9")
127            .build()
128            .unwrap();
129        let index = Thscode::new("000300.SH").unwrap();
130        let start = UnixMillis::new(1_000_000_000_000).unwrap();
131        let invalid_ends = [
132            UnixMillis::new(start.get() - 1).unwrap(),
133            UnixMillis::new(start.get() + TEN_YEARS_MS + 1).unwrap(),
134        ];
135
136        for end in invalid_ends {
137            let error = client
138                .index_prices_historical(&index, start, end)
139                .await
140                .unwrap_err();
141            assert!(matches!(error, Error::InvalidInput(_)));
142        }
143    }
144}