financial_api/a_share/
prices.rs1use crate::endpoints;
2use crate::endpoints::join_values;
3use crate::{
4 AShareCode, Adjustment, Client, Error, HistoricalData, PriceSnapshotData, Response, UnixMillis,
5 ValidationError,
6};
7
8use super::{TEN_YEARS_MS, validate_millis_window};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum PriceSnapshotSelection {
13 Targets(Vec<AShareCode>),
14 MarketPage { limit: u32, offset: u32 },
15}
16
17impl PriceSnapshotSelection {
18 pub fn targets(targets: Vec<AShareCode>) -> Result<Self, ValidationError> {
19 if targets.is_empty() {
20 return Err(ValidationError::new("thscodes", "must not be empty"));
21 }
22 Ok(Self::Targets(targets))
23 }
24
25 pub const fn market_page(limit: u32, offset: u32) -> Result<Self, ValidationError> {
26 if limit == 0 {
27 return Err(ValidationError::new("limit", "must be at least 1"));
28 }
29 Ok(Self::MarketPage { limit, offset })
30 }
31}
32
33impl Client {
34 #[doc = concat!(
38 "```no_run\n",
39 include_str!("../../examples/prices_snapshot.rs"),
40 "\n```"
41 )]
42 pub async fn prices_snapshot(
43 &self,
44 selection: &PriceSnapshotSelection,
45 ) -> Result<Response<PriceSnapshotData>, Error> {
46 let query = match selection {
47 PriceSnapshotSelection::Targets(codes) => {
48 vec![("thscodes", join_values("thscodes", codes, None)?)]
49 }
50 PriceSnapshotSelection::MarketPage { limit, offset } => {
51 vec![("limit", limit.to_string()), ("offset", offset.to_string())]
52 }
53 };
54 self.get(endpoints::PRICES_SNAPSHOT, &query).await
55 }
56
57 #[doc = concat!(
61 "```no_run\n",
62 include_str!("../../examples/prices_historical.rs"),
63 "\n```"
64 )]
65 pub async fn prices_historical(
66 &self,
67 thscode: &AShareCode,
68 start: UnixMillis,
69 end: UnixMillis,
70 adjustment: Adjustment,
71 offset: u32,
72 ) -> Result<Response<HistoricalData>, Error> {
73 validate_millis_window(start, end, Some(TEN_YEARS_MS))?;
74 let query = vec![
75 ("thscode", thscode.to_string()),
76 ("interval", "1d".to_owned()),
77 ("start", start.to_string()),
78 ("end", end.to_string()),
79 ("adjust", adjustment.to_string()),
80 ("offset", offset.to_string()),
81 ];
82 self.get(endpoints::PRICES_HISTORICAL, &query).await
83 }
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89 use crate::ApiKey;
90
91 #[test]
92 fn snapshot_selection_rejects_empty_targets_and_zero_page_size() {
93 assert!(PriceSnapshotSelection::targets(Vec::new()).is_err());
94 assert!(PriceSnapshotSelection::market_page(0, 0).is_err());
95 assert!(PriceSnapshotSelection::market_page(10_001, 0).is_ok());
96
97 let stock = AShareCode::new("600519.SH").unwrap();
98 assert!(PriceSnapshotSelection::targets(vec![stock]).is_ok());
99 }
100
101 #[tokio::test]
102 async fn historical_prices_keeps_the_shared_window_validation_on_its_call_edge() {
103 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
104 .base_url("http://127.0.0.1:9")
105 .build()
106 .unwrap();
107 let stock = AShareCode::new("600519.SH").unwrap();
108 let start = UnixMillis::new(1_000_000_000_000).unwrap();
109 let invalid_ends = [
110 UnixMillis::new(start.get() - 1).unwrap(),
111 UnixMillis::new(start.get() + TEN_YEARS_MS + 1).unwrap(),
112 ];
113
114 for end in invalid_ends {
115 let error = client
116 .prices_historical(&stock, start, end, Adjustment::None, 0)
117 .await
118 .unwrap_err();
119 assert!(matches!(error, Error::InvalidInput(_)));
120 }
121 }
122}