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