1use crate::endpoints;
2use crate::types::join_values;
3use crate::{
4 AShareCode, Adjustment, AdjustmentFactorsData, AnomalyData, AnomalyTag, AuctionBenchmarkData,
5 AuctionSnapshotData, AuctionStage, BalanceSheetsData, CashFlowStatementsData, Client,
6 DragonTigerBoard, DragonTigerData, Error, FinancialIndicatorsData, FinancialPeriod,
7 FinancialRange, FinancialReport, HistoricalData, HotListPeriod, HotStockData,
8 HotStockHistoryData, HotStockTrendData, IncomeStatementsData, LadderData, LimitBreakData,
9 LimitBreakSortField, LimitDownData, LimitDownSortField, LimitUpData, LimitUpSortField,
10 NaturalDate, Page, PriceSnapshotData, Response, ShanghaiDateMillis, SortDirection,
11 TradingDaysData, UnixMillis, ValidationError, ValuationsData,
12};
13use serde::de::DeserializeOwned;
14
15const TEN_YEARS_MS: i64 = 315_576_000_000;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum PriceSnapshotSelection {
20 Targets(Vec<AShareCode>),
21 MarketPage { limit: u32, offset: u32 },
22}
23
24impl PriceSnapshotSelection {
25 pub fn targets(targets: Vec<AShareCode>) -> Result<Self, ValidationError> {
26 if targets.is_empty() {
27 return Err(ValidationError::new("thscodes", "must not be empty"));
28 }
29 Ok(Self::Targets(targets))
30 }
31
32 pub const fn market_page(limit: u32, offset: u32) -> Result<Self, ValidationError> {
33 if limit == 0 {
34 return Err(ValidationError::new("limit", "must be at least 1"));
35 }
36 Ok(Self::MarketPage { limit, offset })
37 }
38}
39
40impl Client {
41 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 pub async fn prices_historical(
59 &self,
60 thscode: &AShareCode,
61 start: UnixMillis,
62 end: UnixMillis,
63 adjustment: Adjustment,
64 offset: u32,
65 ) -> Result<Response<HistoricalData>, Error> {
66 validate_millis_window(start, end, Some(TEN_YEARS_MS))?;
67 let query = vec![
68 ("thscode", thscode.to_string()),
69 ("interval", "1d".to_owned()),
70 ("start", start.to_string()),
71 ("end", end.to_string()),
72 ("adjust", adjustment.to_string()),
73 ("offset", offset.to_string()),
74 ];
75 self.get(endpoints::PRICES_HISTORICAL, &query).await
76 }
77
78 pub async fn corp_actions_adjustment_factors(
80 &self,
81 thscode: &AShareCode,
82 from: Option<NaturalDate>,
83 to: Option<NaturalDate>,
84 ) -> Result<Response<AdjustmentFactorsData>, Error> {
85 let mut query = vec![("thscode", thscode.to_string())];
86 if let (Some(from), Some(to)) = (from, to) {
87 validate_date_order(from, to, "to")?;
88 }
89 if let Some(from) = from {
90 query.push(("from", from.to_string()));
91 }
92 if let Some(to) = to {
93 query.push(("to", to.to_string()));
94 }
95 self.get(endpoints::ADJUSTMENT_FACTORS, &query).await
96 }
97
98 pub async fn financials_income_statements(
100 &self,
101 thscode: &AShareCode,
102 period: FinancialPeriod,
103 range: FinancialRange,
104 ) -> Result<Response<IncomeStatementsData>, Error> {
105 self.financial_statements(endpoints::INCOME_STATEMENTS, thscode, period, range)
106 .await
107 }
108
109 pub async fn financials_balance_sheets(
111 &self,
112 thscode: &AShareCode,
113 period: FinancialPeriod,
114 range: FinancialRange,
115 ) -> Result<Response<BalanceSheetsData>, Error> {
116 self.financial_statements(endpoints::BALANCE_SHEETS, thscode, period, range)
117 .await
118 }
119
120 pub async fn financials_cash_flow_statements(
122 &self,
123 thscode: &AShareCode,
124 period: FinancialPeriod,
125 range: FinancialRange,
126 ) -> Result<Response<CashFlowStatementsData>, Error> {
127 self.financial_statements(endpoints::CASH_FLOW_STATEMENTS, thscode, period, range)
128 .await
129 }
130
131 async fn financial_statements<T: DeserializeOwned>(
132 &self,
133 path: &str,
134 thscode: &AShareCode,
135 period: FinancialPeriod,
136 range: FinancialRange,
137 ) -> Result<Response<T>, Error> {
138 let mut query = vec![
139 ("thscode", thscode.to_string()),
140 ("period", period.to_string()),
141 ];
142 match range {
143 FinancialRange::Recent { limit } => query.push(("limit", limit.to_string())),
144 FinancialRange::Between { start, end } => {
145 validate_millis_window(start, end, Some(TEN_YEARS_MS))?;
146 query.push(("start", start.to_string()));
147 query.push(("end", end.to_string()));
148 }
149 }
150 self.get(path, &query).await
151 }
152
153 pub async fn financials_indicators(
155 &self,
156 thscode: &AShareCode,
157 report: &FinancialReport,
158 ) -> Result<Response<FinancialIndicatorsData>, Error> {
159 let query = [("thscode", thscode.as_str()), ("report", report.as_str())];
160 self.get(endpoints::FINANCIAL_INDICATORS, &query).await
161 }
162
163 pub async fn calendar_trading_days(&self) -> Result<Response<TradingDaysData>, Error> {
165 self.get(endpoints::TRADING_DAYS, &[] as &[(&str, &str)])
166 .await
167 }
168
169 pub async fn a_share_auction_snapshot(
171 &self,
172 thscodes: &[AShareCode],
173 stage: AuctionStage,
174 ) -> Result<Response<AuctionSnapshotData>, Error> {
175 let query = [
176 ("thscodes", join_values("thscodes", thscodes, None)?),
177 ("stage", stage.to_string()),
178 ];
179 self.get(endpoints::AUCTION_SNAPSHOT, &query).await
180 }
181
182 pub async fn a_share_auction_short_term_benchmark(
184 &self,
185 date: Option<NaturalDate>,
186 ) -> Result<Response<AuctionBenchmarkData>, Error> {
187 let query = date
188 .map(|date| vec![("date", date.to_string())])
189 .unwrap_or_default();
190 self.get(endpoints::AUCTION_BENCHMARK, &query).await
191 }
192
193 pub async fn a_share_valuations_snapshot(
195 &self,
196 thscodes: &[AShareCode],
197 ) -> Result<Response<ValuationsData>, Error> {
198 let query = [("thscodes", join_values("thscodes", thscodes, Some(100))?)];
199 self.get(endpoints::VALUATIONS_SNAPSHOT, &query).await
200 }
201
202 pub async fn special_data_anomaly_analysis_list(
204 &self,
205 tag_codes: &[AnomalyTag],
206 ) -> Result<Response<AnomalyData>, Error> {
207 let query = if tag_codes.is_empty() {
208 Vec::new()
209 } else {
210 vec![("tag_codes", join_values("tag_codes", tag_codes, None)?)]
211 };
212 self.get(endpoints::ANOMALY_LIST, &query).await
213 }
214
215 pub async fn special_data_anomaly_analysis_stock(
217 &self,
218 thscodes: &[AShareCode],
219 ) -> Result<Response<AnomalyData>, Error> {
220 let query = [("thscodes", join_values("thscodes", thscodes, Some(50))?)];
221 self.get(endpoints::ANOMALY_STOCK, &query).await
222 }
223
224 pub async fn special_data_dragon_tiger_list(
226 &self,
227 board_type: DragonTigerBoard,
228 date: Option<NaturalDate>,
229 ) -> Result<Response<DragonTigerData>, Error> {
230 if let Some(date) = date {
231 self.validate_recent_date(date, "date")?;
232 }
233 let mut query = vec![("board_type", board_type.to_string())];
234 if let Some(date) = date {
235 query.push(("date", date.to_string()));
236 }
237 self.get(endpoints::DRAGON_TIGER, &query).await
238 }
239
240 pub async fn special_data_hot_stock_list(
242 &self,
243 period: HotListPeriod,
244 ) -> Result<Response<HotStockData>, Error> {
245 self.get(endpoints::HOT_STOCK_LIST, &[("period", period.to_string())])
246 .await
247 }
248
249 pub async fn special_data_hot_stock_list_history(
251 &self,
252 date: NaturalDate,
253 ) -> Result<Response<HotStockHistoryData>, Error> {
254 self.validate_recent_date(date, "date")?;
255 self.get(endpoints::HOT_STOCK_HISTORY, &[("date", date.to_string())])
256 .await
257 }
258
259 pub async fn special_data_hot_stock_rank_trend(
261 &self,
262 thscode: &AShareCode,
263 start_date: NaturalDate,
264 end_date: NaturalDate,
265 ) -> Result<Response<HotStockTrendData>, Error> {
266 validate_date_order(start_date, end_date, "end_date")?;
267 self.validate_recent_date(start_date, "start_date")?;
268 self.validate_recent_date(end_date, "end_date")?;
269 if start_date
270 .checked_add_years(1)
271 .is_none_or(|limit| end_date > limit)
272 {
273 return Err(
274 ValidationError::new("end_date", "date range must not exceed one year").into(),
275 );
276 }
277 let query = [
278 ("thscode", thscode.to_string()),
279 ("start_date", start_date.to_string()),
280 ("end_date", end_date.to_string()),
281 ];
282 self.get(endpoints::HOT_STOCK_TREND, &query).await
283 }
284
285 pub async fn special_data_limit_up_pool(
287 &self,
288 date_ms: Option<ShanghaiDateMillis>,
289 page: Page,
290 sort_field: LimitUpSortField,
291 sort_dir: SortDirection,
292 ) -> Result<Response<LimitUpData>, Error> {
293 self.special_data_pool(
294 endpoints::LIMIT_UP_POOL,
295 date_ms,
296 page,
297 sort_field.to_string(),
298 sort_dir,
299 )
300 .await
301 }
302
303 pub async fn special_data_limit_down_pool(
305 &self,
306 date_ms: Option<ShanghaiDateMillis>,
307 page: Page,
308 sort_field: LimitDownSortField,
309 sort_dir: SortDirection,
310 ) -> Result<Response<LimitDownData>, Error> {
311 self.special_data_pool(
312 endpoints::LIMIT_DOWN_POOL,
313 date_ms,
314 page,
315 sort_field.to_string(),
316 sort_dir,
317 )
318 .await
319 }
320
321 pub async fn special_data_limit_break_pool(
323 &self,
324 date_ms: Option<ShanghaiDateMillis>,
325 page: Page,
326 sort_field: LimitBreakSortField,
327 sort_dir: SortDirection,
328 ) -> Result<Response<LimitBreakData>, Error> {
329 self.special_data_pool(
330 endpoints::LIMIT_BREAK_POOL,
331 date_ms,
332 page,
333 sort_field.to_string(),
334 sort_dir,
335 )
336 .await
337 }
338
339 async fn special_data_pool<T: DeserializeOwned>(
340 &self,
341 path: &str,
342 date_ms: Option<ShanghaiDateMillis>,
343 page: Page,
344 sort_field: String,
345 sort_dir: SortDirection,
346 ) -> Result<Response<T>, Error> {
347 let mut query = vec![
348 ("page", page.number().to_string()),
349 ("size", page.size().to_string()),
350 ("sort_field", sort_field),
351 ("sort_dir", sort_dir.to_string()),
352 ];
353 if let Some(date_ms) = date_ms {
354 query.push(("date_ms", date_ms.to_string()));
355 }
356 self.get(path, &query).await
357 }
358
359 fn validate_recent_date(
360 &self,
361 date: NaturalDate,
362 field: &'static str,
363 ) -> Result<(), ValidationError> {
364 let today = self.shanghai_today();
365 let earliest = today
366 .checked_add_years(-1)
367 .ok_or_else(|| ValidationError::new(field, "could not calculate one-year window"))?;
368 if date < earliest || date > today {
369 return Err(ValidationError::new(
370 field,
371 "must be within the previous natural year and not in the future",
372 ));
373 }
374 Ok(())
375 }
376
377 pub async fn special_data_limit_up_ladder(&self) -> Result<Response<LadderData>, Error> {
379 self.get(endpoints::LIMIT_UP_LADDER, &[] as &[(&str, &str)])
380 .await
381 }
382
383 pub async fn special_data_skyrocket_list(
385 &self,
386 period: HotListPeriod,
387 ) -> Result<Response<HotStockData>, Error> {
388 self.get(endpoints::SKYROCKET_LIST, &[("period", period.to_string())])
389 .await
390 }
391}
392
393fn validate_millis_window(
394 start: UnixMillis,
395 end: UnixMillis,
396 maximum: Option<i64>,
397) -> Result<(), ValidationError> {
398 if end < start {
399 return Err(ValidationError::new(
400 "end",
401 "must not be earlier than start",
402 ));
403 }
404 if maximum.is_some_and(|maximum| end.get() - start.get() > maximum) {
405 return Err(ValidationError::new(
406 "end",
407 "requested time window exceeds the endpoint limit",
408 ));
409 }
410 Ok(())
411}
412
413fn validate_date_order(
414 start: NaturalDate,
415 end: NaturalDate,
416 end_field: &'static str,
417) -> Result<(), ValidationError> {
418 if end < start {
419 return Err(ValidationError::new(
420 end_field,
421 "must not be earlier than the start date",
422 ));
423 }
424 Ok(())
425}