financial_api/fund/
market.rs1use 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 #[doc = concat!(
14 "```no_run\n",
15 include_str!("../../examples/fund_market_snapshot.rs"),
16 "\n```"
17 )]
18 pub async fn fund_market_snapshot(
19 &self,
20 thscode: &Thscode,
21 ) -> Result<Response<FundMarketSnapshotData>, Error> {
22 validate_exchange_fund(thscode)?;
23 self.get(
24 endpoints::FUND_MARKET_SNAPSHOT,
25 &[("thscode", thscode.as_str())],
26 )
27 .await
28 }
29
30 #[doc = concat!(
34 "```no_run\n",
35 include_str!("../../examples/fund_market_historical.rs"),
36 "\n```"
37 )]
38 pub async fn fund_market_historical(
39 &self,
40 thscode: &Thscode,
41 start: UnixMillis,
42 end: UnixMillis,
43 ) -> Result<Response<FundMarketHistoricalData>, Error> {
44 validate_exchange_fund(thscode)?;
45 validate_history_range(start, end)?;
46 let query = [
47 ("thscode", thscode.to_string()),
48 ("interval", "1d".to_owned()),
49 ("start", start.to_string()),
50 ("end", end.to_string()),
51 ];
52 self.get(endpoints::FUND_MARKET_HISTORICAL, &query).await
53 }
54}
55
56fn validate_exchange_fund(thscode: &Thscode) -> Result<(), ValidationError> {
57 let (ticker, suffix) = thscode
58 .as_str()
59 .split_once('.')
60 .expect("validated thscode contains a suffix");
61 let valid = ticker.len() == 6
62 && ticker.bytes().all(|byte| byte.is_ascii_digit())
63 && matches!(suffix, "SH" | "SZ");
64 if !valid {
65 return Err(ValidationError::new(
66 "thscode",
67 "exchange fund code must be six digits ending in SH or SZ",
68 ));
69 }
70 Ok(())
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use crate::ApiKey;
77
78 #[test]
79 fn exchange_market_data_requires_a_six_digit_exchange_code() {
80 assert!(validate_exchange_fund(&Thscode::new("510300.SH").unwrap()).is_ok());
81 assert!(validate_exchange_fund(&Thscode::new("159915.SZ").unwrap()).is_ok());
82
83 for invalid in ["025480.OF", "ABCDEF.SH", "51030.SH", "510300.BJ"] {
84 let error = validate_exchange_fund(&Thscode::new(invalid).unwrap()).unwrap_err();
85 assert_eq!(error.field(), "thscode");
86 }
87 }
88
89 #[tokio::test]
90 async fn snapshot_keeps_exchange_validation_on_its_call_edge() {
91 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
92 .base_url("http://127.0.0.1:9")
93 .build()
94 .unwrap();
95 let otc_fund = Thscode::new("025480.OF").unwrap();
96
97 let error = client.fund_market_snapshot(&otc_fund).await.unwrap_err();
98
99 assert!(matches!(error, Error::InvalidInput(_)));
100 }
101}