Skip to main content

financial_api/
index.rs

1use crate::endpoints;
2use crate::types::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    /// List Tonghuashun indices for a catalog tag.
12    pub async fn index_catalog_ths_index_list(
13        &self,
14        tag: IndexTag,
15    ) -> Result<Response<IndexCatalogData>, Error> {
16        self.get(endpoints::INDEX_CATALOG, &[("tag", tag.to_string())])
17            .await
18    }
19
20    /// Fetch the current constituent list of one index.
21    pub async fn index_constituents_ths_stock_list(
22        &self,
23        thscode: &Thscode,
24    ) -> Result<Response<IndexConstituentsData>, Error> {
25        self.get(
26            endpoints::INDEX_CONSTITUENTS,
27            &[("thscode", thscode.to_string())],
28        )
29        .await
30    }
31
32    /// Fetch snapshots for one or more exchange or Tonghuashun indices.
33    pub async fn index_prices_snapshot(
34        &self,
35        thscodes: &[Thscode],
36    ) -> Result<Response<PriceSnapshotData>, Error> {
37        self.get(
38            endpoints::INDEX_SNAPSHOT,
39            &[("thscodes", join_values("thscodes", thscodes, None)?)],
40        )
41        .await
42    }
43
44    /// Fetch historical daily K-lines for one index.
45    pub async fn index_prices_historical(
46        &self,
47        thscode: &Thscode,
48        start: UnixMillis,
49        end: UnixMillis,
50    ) -> Result<Response<IndexHistoricalData>, Error> {
51        if end < start {
52            return Err(ValidationError::new("end", "must not be earlier than start").into());
53        }
54        if end.get() - start.get() > TEN_YEARS_MS {
55            return Err(
56                ValidationError::new("end", "requested time window exceeds ten years").into(),
57            );
58        }
59        let query = [
60            ("thscode", thscode.to_string()),
61            ("interval", "1d".to_owned()),
62            ("start", start.to_string()),
63            ("end", end.to_string()),
64        ];
65        self.get(endpoints::INDEX_HISTORICAL, &query).await
66    }
67}