1use crate::endpoints;
2use crate::{
3 Client, CompanyId, Cursor, Error, FundAssetAllocationData, FundBalanceSheetsData,
4 FundCompanyData, FundDiagnosticsData, FundDividendsData, FundDrawdownsData,
5 FundFinancialIndicatorsData, FundHoldersData, FundHoldingsData, FundIncomeStatementsData,
6 FundIndicatorHistoryData, FundIndustryAllocationData, FundManagerDetailData,
7 FundManagerExperienceData, FundManagerPerformanceData, FundManagerStyleData,
8 FundMarketHistoricalData, FundMarketSnapshotData, FundNavData, FundNavType, FundNewsData,
9 FundOfferingsData, FundPortfolioHistoryData, FundProfileData, FundRange, FundReportDatesData,
10 FundReturnsData, FundTopHoldersData, FundType, HolderMergeScope, ManagerId,
11 ManagerPerformanceRange, NaturalDate, OfferingStatus, ReportType, Response, Thscode,
12 UnixMillis, ValidationError,
13};
14use serde::de::DeserializeOwned;
15use time::OffsetDateTime;
16
17const NANOS_PER_MILLISECOND: i128 = 1_000_000;
18
19impl Client {
20 pub async fn fund_companies_detail(
22 &self,
23 company_id: &CompanyId,
24 ) -> Result<Response<FundCompanyData>, Error> {
25 self.get(
26 endpoints::FUND_COMPANY_DETAIL,
27 &[("company_id", company_id.as_str())],
28 )
29 .await
30 }
31
32 pub async fn fund_corporate_actions_dividends(
34 &self,
35 fund_type: FundType,
36 thscode: &Thscode,
37 ) -> Result<Response<FundDividendsData>, Error> {
38 self.fund_detail(endpoints::FUND_DIVIDENDS, fund_type, thscode)
39 .await
40 }
41
42 pub async fn fund_diagnostics_detail(
44 &self,
45 fund_type: FundType,
46 thscode: &Thscode,
47 ) -> Result<Response<FundDiagnosticsData>, Error> {
48 self.fund_detail(endpoints::FUND_DIAGNOSTICS, fund_type, thscode)
49 .await
50 }
51
52 pub async fn fund_financials_indicators(
54 &self,
55 fund_type: FundType,
56 thscode: &Thscode,
57 ) -> Result<Response<FundFinancialIndicatorsData>, Error> {
58 self.fund_detail(endpoints::FUND_INDICATORS, fund_type, thscode)
59 .await
60 }
61
62 pub async fn fund_financials_income_statements(
64 &self,
65 fund_type: FundType,
66 thscode: &Thscode,
67 ) -> Result<Response<FundIncomeStatementsData>, Error> {
68 self.fund_detail(endpoints::FUND_INCOME_STATEMENTS, fund_type, thscode)
69 .await
70 }
71
72 pub async fn fund_financials_balance_sheets(
74 &self,
75 fund_type: FundType,
76 thscode: &Thscode,
77 ) -> Result<Response<FundBalanceSheetsData>, Error> {
78 self.fund_detail(endpoints::FUND_BALANCE_SHEETS, fund_type, thscode)
79 .await
80 }
81
82 pub async fn fund_holders_detail(
84 &self,
85 fund_type: FundType,
86 thscode: &Thscode,
87 merge_scope: HolderMergeScope,
88 ) -> Result<Response<FundHoldersData>, Error> {
89 validate_fund_target(fund_type, thscode)?;
90 let query = [
91 ("fund_type", fund_type.to_string()),
92 ("thscode", thscode.to_string()),
93 ("merge_scope", merge_scope.to_string()),
94 ];
95 self.get(endpoints::FUND_HOLDERS_DETAIL, &query).await
96 }
97
98 pub async fn fund_holders_top(
100 &self,
101 fund_type: FundType,
102 thscode: &Thscode,
103 limit: Option<u8>,
104 ) -> Result<Response<FundTopHoldersData>, Error> {
105 validate_fund_target(fund_type, thscode)?;
106 if limit.is_some_and(|limit| limit == 0 || limit > 10) {
107 return Err(ValidationError::new("limit", "must be in the range 1..=10").into());
108 }
109 let mut query = fund_query(fund_type, thscode);
110 if let Some(limit) = limit {
111 query.push(("limit", limit.to_string()));
112 }
113 self.get(endpoints::FUND_HOLDERS_TOP, &query).await
114 }
115
116 pub async fn fund_portfolio_holdings(
118 &self,
119 fund_type: FundType,
120 thscode: &Thscode,
121 ) -> Result<Response<FundHoldingsData>, Error> {
122 self.fund_detail(endpoints::FUND_HOLDINGS, fund_type, thscode)
123 .await
124 }
125
126 pub async fn fund_managers_investment_style(
128 &self,
129 manager_id: &ManagerId,
130 ) -> Result<Response<FundManagerStyleData>, Error> {
131 self.fund_manager(endpoints::FUND_MANAGER_STYLE, manager_id, None)
132 .await
133 }
134
135 pub async fn fund_managers_performance(
137 &self,
138 manager_id: &ManagerId,
139 range: ManagerPerformanceRange,
140 ) -> Result<Response<FundManagerPerformanceData>, Error> {
141 self.fund_manager(endpoints::FUND_MANAGER_PERFORMANCE, manager_id, Some(range))
142 .await
143 }
144
145 pub async fn fund_managers_experience(
147 &self,
148 manager_id: &ManagerId,
149 ) -> Result<Response<FundManagerExperienceData>, Error> {
150 self.fund_manager(endpoints::FUND_MANAGER_EXPERIENCE, manager_id, None)
151 .await
152 }
153
154 pub async fn fund_managers_detail(
156 &self,
157 manager_id: &ManagerId,
158 ) -> Result<Response<FundManagerDetailData>, Error> {
159 self.fund_manager(endpoints::FUND_MANAGER_DETAIL, manager_id, None)
160 .await
161 }
162
163 async fn fund_manager<T: DeserializeOwned>(
164 &self,
165 path: &str,
166 manager_id: &ManagerId,
167 range: Option<ManagerPerformanceRange>,
168 ) -> Result<Response<T>, Error> {
169 let mut query = vec![("manager_id", manager_id.to_string())];
170 if let Some(range) = range {
171 query.push(("range", range.to_string()));
172 }
173 self.get(path, &query).await
174 }
175
176 pub async fn fund_market_snapshot(
178 &self,
179 thscode: &Thscode,
180 ) -> Result<Response<FundMarketSnapshotData>, Error> {
181 validate_exchange_fund(thscode)?;
182 self.get(
183 endpoints::FUND_MARKET_SNAPSHOT,
184 &[("thscode", thscode.as_str())],
185 )
186 .await
187 }
188
189 pub async fn fund_market_historical(
191 &self,
192 thscode: &Thscode,
193 start: UnixMillis,
194 end: UnixMillis,
195 ) -> Result<Response<FundMarketHistoricalData>, Error> {
196 validate_exchange_fund(thscode)?;
197 validate_millis_range(start, end)?;
198 validate_max_years(start, end, 5)?;
199 let query = [
200 ("thscode", thscode.to_string()),
201 ("interval", "1d".to_owned()),
202 ("start", start.to_string()),
203 ("end", end.to_string()),
204 ];
205 self.get(endpoints::FUND_MARKET_HISTORICAL, &query).await
206 }
207
208 pub async fn fund_news_article_list(
210 &self,
211 fund_type: FundType,
212 thscode: &Thscode,
213 limit: Option<u32>,
214 offset: Option<&Cursor>,
215 ) -> Result<Response<FundNewsData>, Error> {
216 validate_fund_target(fund_type, thscode)?;
217 if limit == Some(0) {
218 return Err(ValidationError::new("limit", "must be at least 1").into());
219 }
220 let mut query = fund_query(fund_type, thscode);
221 if let Some(limit) = limit {
222 query.push(("limit", limit.to_string()));
223 }
224 if let Some(offset) = offset {
225 query.push(("offset", offset.to_string()));
226 }
227 self.get(endpoints::FUND_NEWS, &query).await
228 }
229
230 pub async fn fund_offerings_list(
232 &self,
233 status: OfferingStatus,
234 ) -> Result<Response<FundOfferingsData>, Error> {
235 self.get(
236 endpoints::FUND_OFFERINGS,
237 &[("subscribe", status.to_string())],
238 )
239 .await
240 }
241
242 pub async fn fund_performance_nav(
244 &self,
245 fund_type: FundType,
246 thscode: &Thscode,
247 range: Option<FundRange>,
248 nav_type: FundNavType,
249 ) -> Result<Response<FundNavData>, Error> {
250 validate_fund_target(fund_type, thscode)?;
251 let mut query = fund_query(fund_type, thscode);
252 if let Some(range) = range {
253 query.push(("range", range.to_string()));
254 }
255 query.push(("nav_type", nav_type.to_string()));
256 self.get(endpoints::FUND_NAV, &query).await
257 }
258
259 pub async fn fund_performance_returns(
261 &self,
262 fund_type: FundType,
263 thscode: &Thscode,
264 ) -> Result<Response<FundReturnsData>, Error> {
265 self.fund_detail(endpoints::FUND_RETURNS, fund_type, thscode)
266 .await
267 }
268
269 pub async fn fund_performance_indicators_historical(
271 &self,
272 fund_type: FundType,
273 thscode: &Thscode,
274 start: UnixMillis,
275 end: UnixMillis,
276 ) -> Result<Response<FundIndicatorHistoryData>, Error> {
277 validate_fund_target(fund_type, thscode)?;
278 validate_millis_range(start, end)?;
279 validate_max_years(start, end, 5)?;
280 let mut query = fund_query(fund_type, thscode);
281 query.push(("start", start.to_string()));
282 query.push(("end", end.to_string()));
283 self.get(endpoints::FUND_INDICATORS_HISTORICAL, &query)
284 .await
285 }
286
287 pub async fn fund_performance_drawdowns(
289 &self,
290 fund_type: FundType,
291 thscode: &Thscode,
292 ) -> Result<Response<FundDrawdownsData>, Error> {
293 self.fund_detail(endpoints::FUND_DRAWDOWNS, fund_type, thscode)
294 .await
295 }
296
297 pub async fn fund_portfolio_stock_history(
299 &self,
300 fund_type: FundType,
301 thscode: &Thscode,
302 report_type: &ReportType,
303 end_date: NaturalDate,
304 ) -> Result<Response<FundPortfolioHistoryData>, Error> {
305 self.fund_portfolio_history(
306 endpoints::FUND_STOCK_HISTORY,
307 fund_type,
308 thscode,
309 report_type,
310 end_date,
311 )
312 .await
313 }
314
315 pub async fn fund_portfolio_bond_history(
317 &self,
318 fund_type: FundType,
319 thscode: &Thscode,
320 report_type: &ReportType,
321 end_date: NaturalDate,
322 ) -> Result<Response<FundPortfolioHistoryData>, Error> {
323 self.fund_portfolio_history(
324 endpoints::FUND_BOND_HISTORY,
325 fund_type,
326 thscode,
327 report_type,
328 end_date,
329 )
330 .await
331 }
332
333 async fn fund_portfolio_history(
334 &self,
335 path: &str,
336 fund_type: FundType,
337 thscode: &Thscode,
338 report_type: &ReportType,
339 end_date: NaturalDate,
340 ) -> Result<Response<FundPortfolioHistoryData>, Error> {
341 validate_fund_target(fund_type, thscode)?;
342 let mut query = fund_query(fund_type, thscode);
343 query.push(("report_type", report_type.to_string()));
344 query.push(("end_date", end_date.to_string()));
345 self.get(path, &query).await
346 }
347
348 pub async fn fund_portfolio_stock_report_dates(
350 &self,
351 fund_type: FundType,
352 thscode: &Thscode,
353 report_type: Option<&ReportType>,
354 ) -> Result<Response<FundReportDatesData>, Error> {
355 self.fund_report_dates(
356 endpoints::FUND_STOCK_REPORT_DATES,
357 fund_type,
358 thscode,
359 report_type,
360 )
361 .await
362 }
363
364 pub async fn fund_portfolio_bond_report_dates(
366 &self,
367 fund_type: FundType,
368 thscode: &Thscode,
369 report_type: Option<&ReportType>,
370 ) -> Result<Response<FundReportDatesData>, Error> {
371 self.fund_report_dates(
372 endpoints::FUND_BOND_REPORT_DATES,
373 fund_type,
374 thscode,
375 report_type,
376 )
377 .await
378 }
379
380 async fn fund_report_dates<T: DeserializeOwned>(
381 &self,
382 path: &str,
383 fund_type: FundType,
384 thscode: &Thscode,
385 report_type: Option<&ReportType>,
386 ) -> Result<Response<T>, Error> {
387 validate_fund_target(fund_type, thscode)?;
388 let mut query = fund_query(fund_type, thscode);
389 if let Some(report_type) = report_type {
390 query.push(("report_type", report_type.to_string()));
391 }
392 self.get(path, &query).await
393 }
394
395 pub async fn fund_portfolio_asset_allocation(
397 &self,
398 fund_type: FundType,
399 thscode: &Thscode,
400 ) -> Result<Response<FundAssetAllocationData>, Error> {
401 self.fund_detail(endpoints::FUND_ASSET_ALLOCATION, fund_type, thscode)
402 .await
403 }
404
405 pub async fn fund_portfolio_industry_allocation(
407 &self,
408 fund_type: FundType,
409 thscode: &Thscode,
410 ) -> Result<Response<FundIndustryAllocationData>, Error> {
411 self.fund_detail(endpoints::FUND_INDUSTRY_ALLOCATION, fund_type, thscode)
412 .await
413 }
414
415 pub async fn fund_profile_detail(
417 &self,
418 fund_type: FundType,
419 thscode: &Thscode,
420 ) -> Result<Response<FundProfileData>, Error> {
421 self.fund_detail(endpoints::FUND_PROFILE, fund_type, thscode)
422 .await
423 }
424
425 async fn fund_detail<T: DeserializeOwned>(
426 &self,
427 path: &str,
428 fund_type: FundType,
429 thscode: &Thscode,
430 ) -> Result<Response<T>, Error> {
431 validate_fund_target(fund_type, thscode)?;
432 self.get(path, &fund_query(fund_type, thscode)).await
433 }
434}
435
436fn fund_query(fund_type: FundType, thscode: &Thscode) -> Vec<(&'static str, String)> {
437 vec![
438 ("fund_type", fund_type.to_string()),
439 ("thscode", thscode.to_string()),
440 ]
441}
442
443fn validate_fund_target(fund_type: FundType, thscode: &Thscode) -> Result<(), ValidationError> {
444 let suffix = thscode
445 .as_str()
446 .rsplit_once('.')
447 .map(|(_, suffix)| suffix)
448 .expect("validated thscode contains a suffix");
449 let valid = match fund_type {
450 FundType::Otc => suffix == "OF",
451 FundType::Exchange | FundType::Reits => matches!(suffix, "SH" | "SZ"),
452 };
453 if !valid {
454 return Err(ValidationError::new(
455 "thscode",
456 "market suffix does not match fund_type",
457 ));
458 }
459 Ok(())
460}
461
462fn validate_exchange_fund(thscode: &Thscode) -> Result<(), ValidationError> {
463 let (ticker, suffix) = thscode
464 .as_str()
465 .split_once('.')
466 .expect("validated thscode contains a suffix");
467 let valid = ticker.len() == 6
468 && ticker.bytes().all(|byte| byte.is_ascii_digit())
469 && matches!(suffix, "SH" | "SZ");
470 if !valid {
471 return Err(ValidationError::new(
472 "thscode",
473 "exchange fund code must be six digits ending in SH or SZ",
474 ));
475 }
476 Ok(())
477}
478
479fn validate_millis_range(start: UnixMillis, end: UnixMillis) -> Result<(), ValidationError> {
480 if end < start {
481 return Err(ValidationError::new(
482 "end",
483 "must not be earlier than start",
484 ));
485 }
486 Ok(())
487}
488
489fn validate_max_years(
490 start: UnixMillis,
491 end: UnixMillis,
492 years: i32,
493) -> Result<(), ValidationError> {
494 let start_datetime =
495 OffsetDateTime::from_unix_timestamp_nanos(i128::from(start.get()) * NANOS_PER_MILLISECOND)
496 .map_err(|_| {
497 ValidationError::new("start", "timestamp is outside the supported range")
498 })?;
499 let target_year = start_datetime
500 .year()
501 .checked_add(years)
502 .ok_or_else(|| ValidationError::new("end", "timestamp year overflowed"))?;
503 let limit = start_datetime
504 .replace_year(target_year)
505 .or_else(|_| start_datetime.replace_day(28)?.replace_year(target_year))
506 .map_err(|_| ValidationError::new("end", "could not calculate the year limit"))?;
507 if i128::from(end.get()) * NANOS_PER_MILLISECOND > limit.unix_timestamp_nanos() {
508 return Err(ValidationError::new(
509 "end",
510 "requested time window exceeds the endpoint year limit",
511 ));
512 }
513 Ok(())
514}