Skip to main content

financial_api/fund/
market.rs

1use crate::endpoints;
2use crate::{
3    Client, Error, FundMarketHistoricalData, FundMarketSnapshotData, Response, Thscode, UnixMillis,
4    ValidationError,
5};
6
7use super::validate_history_range;
8
9impl Client {
10    /// Fetch the latest exchange-traded fund snapshot.
11    pub async fn fund_market_snapshot(
12        &self,
13        thscode: &Thscode,
14    ) -> Result<Response<FundMarketSnapshotData>, Error> {
15        validate_exchange_fund(thscode)?;
16        self.get(
17            endpoints::FUND_MARKET_SNAPSHOT,
18            &[("thscode", thscode.as_str())],
19        )
20        .await
21    }
22
23    /// Fetch exchange-traded fund historical daily prices.
24    pub async fn fund_market_historical(
25        &self,
26        thscode: &Thscode,
27        start: UnixMillis,
28        end: UnixMillis,
29    ) -> Result<Response<FundMarketHistoricalData>, Error> {
30        validate_exchange_fund(thscode)?;
31        validate_history_range(start, end)?;
32        let query = [
33            ("thscode", thscode.to_string()),
34            ("interval", "1d".to_owned()),
35            ("start", start.to_string()),
36            ("end", end.to_string()),
37        ];
38        self.get(endpoints::FUND_MARKET_HISTORICAL, &query).await
39    }
40}
41
42fn validate_exchange_fund(thscode: &Thscode) -> Result<(), ValidationError> {
43    let (ticker, suffix) = thscode
44        .as_str()
45        .split_once('.')
46        .expect("validated thscode contains a suffix");
47    let valid = ticker.len() == 6
48        && ticker.bytes().all(|byte| byte.is_ascii_digit())
49        && matches!(suffix, "SH" | "SZ");
50    if !valid {
51        return Err(ValidationError::new(
52            "thscode",
53            "exchange fund code must be six digits ending in SH or SZ",
54        ));
55    }
56    Ok(())
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::ApiKey;
63
64    #[test]
65    fn exchange_market_data_requires_a_six_digit_exchange_code() {
66        assert!(validate_exchange_fund(&Thscode::new("510300.SH").unwrap()).is_ok());
67        assert!(validate_exchange_fund(&Thscode::new("159915.SZ").unwrap()).is_ok());
68
69        for invalid in ["025480.OF", "ABCDEF.SH", "51030.SH", "510300.BJ"] {
70            let error = validate_exchange_fund(&Thscode::new(invalid).unwrap()).unwrap_err();
71            assert_eq!(error.field(), "thscode");
72        }
73    }
74
75    #[tokio::test]
76    async fn snapshot_keeps_exchange_validation_on_its_call_edge() {
77        let client = Client::builder(ApiKey::new("test-api-key").unwrap())
78            .base_url("http://127.0.0.1:9")
79            .build()
80            .unwrap();
81        let otc_fund = Thscode::new("025480.OF").unwrap();
82
83        let error = client.fund_market_snapshot(&otc_fund).await.unwrap_err();
84
85        assert!(matches!(error, Error::InvalidInput(_)));
86    }
87}