1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use time::macros::{format_description, offset};
6use time::{Date, Time};
7
8use crate::ValidationError;
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, derive_more::Display)]
12#[serde(transparent)]
13pub struct SearchQuery(String);
14
15impl SearchQuery {
16 pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
17 let value = value.into();
18 if value.trim().is_empty() {
19 return Err(ValidationError::new("q", "must not be empty"));
20 }
21 Ok(Self(value))
22 }
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
27#[serde(transparent)]
28pub struct Thscode(String);
29
30impl Thscode {
31 pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
32 let value = value.as_ref().trim().to_ascii_uppercase();
33 if value.contains(',') {
34 return Err(ValidationError::new(
35 "thscode",
36 "must contain exactly one target",
37 ));
38 }
39 let Some((ticker, suffix)) = value.split_once('.') else {
40 return Err(ValidationError::new(
41 "thscode",
42 "must include a market suffix",
43 ));
44 };
45 if ticker.is_empty()
46 || suffix.is_empty()
47 || suffix.contains('.')
48 || !ticker.bytes().all(|byte| byte.is_ascii_alphanumeric())
49 || !suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
50 {
51 return Err(ValidationError::new(
52 "thscode",
53 "must use TICKER.SUFFIX with ASCII letters or digits",
54 ));
55 }
56 Ok(Self(value))
57 }
58
59 #[must_use]
60 pub fn as_str(&self) -> &str {
61 &self.0
62 }
63}
64
65impl FromStr for Thscode {
66 type Err = ValidationError;
67
68 fn from_str(value: &str) -> Result<Self, Self::Err> {
69 Self::new(value)
70 }
71}
72
73impl<'de> Deserialize<'de> for Thscode {
74 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
75 let value = String::deserialize(deserializer)?;
76 Self::new(value).map_err(serde::de::Error::custom)
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
82#[serde(transparent)]
83pub struct AShareCode(Thscode);
84
85impl AShareCode {
86 pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
87 let code = Thscode::new(value)?;
88 let (ticker, suffix) = code
89 .as_str()
90 .split_once('.')
91 .expect("validated thscode always contains a dot");
92 if ticker.len() != 6
93 || !ticker.bytes().all(|byte| byte.is_ascii_digit())
94 || !matches!(suffix, "SH" | "SZ" | "BJ")
95 {
96 return Err(ValidationError::new(
97 "thscode",
98 "must be a six-digit A-share code ending in SH, SZ, or BJ",
99 ));
100 }
101 Ok(Self(code))
102 }
103
104 #[must_use]
105 pub fn as_str(&self) -> &str {
106 self.0.as_str()
107 }
108}
109
110impl FromStr for AShareCode {
111 type Err = ValidationError;
112
113 fn from_str(value: &str) -> Result<Self, Self::Err> {
114 Self::new(value)
115 }
116}
117
118impl<'de> Deserialize<'de> for AShareCode {
119 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
120 let value = String::deserialize(deserializer)?;
121 Self::new(value).map_err(serde::de::Error::custom)
122 }
123}
124
125impl From<AShareCode> for Thscode {
126 fn from(value: AShareCode) -> Self {
127 value.0
128 }
129}
130
131#[derive(
133 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display,
134)]
135#[serde(transparent)]
136pub struct UnixMillis(i64);
137
138impl UnixMillis {
139 pub const fn new(value: i64) -> Result<Self, ValidationError> {
140 if value < 0 {
141 return Err(ValidationError::new(
142 "timestamp",
143 "must be non-negative milliseconds since the Unix epoch",
144 ));
145 }
146 Ok(Self(value))
147 }
148
149 #[must_use]
150 pub const fn get(self) -> i64 {
151 self.0
152 }
153}
154
155impl<'de> Deserialize<'de> for UnixMillis {
156 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
157 let value = i64::deserialize(deserializer)?;
158 Self::new(value).map_err(serde::de::Error::custom)
159 }
160}
161
162#[derive(
164 Debug, Clone, PartialEq, Eq, Serialize, Deserialize, derive_more::Display, derive_more::From,
165)]
166#[serde(transparent)]
167#[display("{_0}")]
168pub struct PreciseDecimal(serde_json::Number);
169
170impl PreciseDecimal {
171 #[must_use]
173 pub const fn as_number(&self) -> &serde_json::Number {
174 &self.0
175 }
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::From)]
180pub struct NaturalDate(Date);
181
182impl NaturalDate {
183 pub fn parse(value: &str) -> Result<Self, ValidationError> {
184 if value.len() != 10 {
185 return Err(ValidationError::new("date", "must use YYYY-MM-DD format"));
186 }
187 Date::parse(value, format_description!("[year]-[month]-[day]"))
188 .map(Self)
189 .map_err(|_| ValidationError::new("date", "must be a valid Gregorian date"))
190 }
191
192 pub(crate) fn checked_add_years(self, years: i32) -> Option<Self> {
193 let target_year = self.0.year().checked_add(years)?;
194 self.0
195 .replace_year(target_year)
196 .or_else(|_| self.0.replace_day(28)?.replace_year(target_year))
197 .ok()
198 .map(Self)
199 }
200}
201
202impl fmt::Display for NaturalDate {
203 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204 let value = self
205 .0
206 .format(format_description!("[year]-[month]-[day]"))
207 .map_err(|_| fmt::Error)?;
208 formatter.write_str(&value)
209 }
210}
211
212impl FromStr for NaturalDate {
213 type Err = ValidationError;
214
215 fn from_str(value: &str) -> Result<Self, Self::Err> {
216 Self::parse(value)
217 }
218}
219
220impl<'de> Deserialize<'de> for NaturalDate {
221 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
222 let value = String::deserialize(deserializer)?;
223 Self::parse(&value).map_err(serde::de::Error::custom)
224 }
225}
226
227impl Serialize for NaturalDate {
228 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
229 serializer.collect_str(self)
230 }
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
235pub struct CompactDate(NaturalDate);
236
237impl CompactDate {
238 pub fn parse(value: &str) -> Result<Self, ValidationError> {
239 if value.len() != 8 {
240 return Err(ValidationError::new("date", "must use YYYYMMDD format"));
241 }
242 Date::parse(value, format_description!("[year][month][day]"))
243 .map(|date| Self(NaturalDate(date)))
244 .map_err(|_| ValidationError::new("date", "must be a valid Gregorian date"))
245 }
246
247 #[must_use]
248 pub const fn natural_date(self) -> NaturalDate {
249 self.0
250 }
251}
252
253impl fmt::Display for CompactDate {
254 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
255 let value = self
256 .0
257 .0
258 .format(format_description!("[year][month][day]"))
259 .map_err(|_| fmt::Error)?;
260 formatter.write_str(&value)
261 }
262}
263
264impl FromStr for CompactDate {
265 type Err = ValidationError;
266
267 fn from_str(value: &str) -> Result<Self, Self::Err> {
268 Self::parse(value)
269 }
270}
271
272impl<'de> Deserialize<'de> for CompactDate {
273 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
274 let value = String::deserialize(deserializer)?;
275 Self::parse(&value).map_err(serde::de::Error::custom)
276 }
277}
278
279impl Serialize for CompactDate {
280 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
281 serializer.collect_str(self)
282 }
283}
284
285#[derive(
287 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display,
288)]
289#[serde(transparent)]
290pub struct ShanghaiDateMillis(UnixMillis);
291
292impl ShanghaiDateMillis {
293 pub fn from_date(date: NaturalDate) -> Result<Self, ValidationError> {
294 let milliseconds = date
295 .0
296 .with_time(Time::MIDNIGHT)
297 .assume_offset(offset!(+8))
298 .unix_timestamp_nanos()
299 / 1_000_000;
300 let milliseconds = i64::try_from(milliseconds)
301 .map_err(|_| ValidationError::new("date", "is outside the timestamp range"))?;
302 UnixMillis::new(milliseconds).map(Self)
303 }
304
305 #[must_use]
306 pub const fn get(self) -> i64 {
307 self.0.get()
308 }
309}
310
311impl TryFrom<NaturalDate> for ShanghaiDateMillis {
312 type Error = ValidationError;
313
314 fn try_from(value: NaturalDate) -> Result<Self, Self::Error> {
315 Self::from_date(value)
316 }
317}
318
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum FinancialRange {
322 Recent { limit: u8 },
323 Between { start: UnixMillis, end: UnixMillis },
324}
325
326impl FinancialRange {
327 pub const fn recent(limit: u8) -> Result<Self, ValidationError> {
328 if limit == 0 || limit > 20 {
329 return Err(ValidationError::new("limit", "must be in the range 1..=20"));
330 }
331 Ok(Self::Recent { limit })
332 }
333
334 pub const fn between(start: UnixMillis, end: UnixMillis) -> Result<Self, ValidationError> {
335 if end.0 < start.0 {
336 return Err(ValidationError::new(
337 "end",
338 "must not be earlier than start",
339 ));
340 }
341 Ok(Self::Between { start, end })
342 }
343}
344
345macro_rules! identifier_type {
346 ($(#[$meta:meta])* $name:ident, $field:literal) => {
347 $(#[$meta])*
348 #[derive(
349 Debug,
350 Clone,
351 PartialEq,
352 Eq,
353 PartialOrd,
354 Ord,
355 Hash,
356 Serialize,
357 derive_more::Display,
358 )]
359 #[serde(transparent)]
360 pub struct $name(String);
361
362 impl $name {
363 pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
364 let value = value.into();
365 let value = value.trim();
366 if value.is_empty() {
367 return Err(ValidationError::new($field, "must not be empty"));
368 }
369 Ok(Self(value.to_owned()))
370 }
371
372 #[must_use]
373 pub fn as_str(&self) -> &str {
374 &self.0
375 }
376 }
377
378 impl FromStr for $name {
379 type Err = ValidationError;
380
381 fn from_str(value: &str) -> Result<Self, Self::Err> {
382 Self::new(value)
383 }
384 }
385
386 impl<'de> Deserialize<'de> for $name {
387 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
388 let value = String::deserialize(deserializer)?;
389 Self::new(value).map_err(serde::de::Error::custom)
390 }
391 }
392 };
393}
394
395identifier_type!(
396 ManagerId,
398 "manager_id"
399);
400identifier_type!(
401 CompanyId,
403 "company_id"
404);
405identifier_type!(
406 ReportType,
408 "report_type"
409);
410
411#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
413#[serde(transparent)]
414pub struct Cursor(String);
415
416impl Cursor {
417 pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
418 let value = value.into();
419 if value.trim().is_empty() {
420 return Err(ValidationError::new("offset", "must not be empty"));
421 }
422 Ok(Self(value))
423 }
424
425 #[must_use]
426 pub fn as_str(&self) -> &str {
427 &self.0
428 }
429}
430
431impl FromStr for Cursor {
432 type Err = ValidationError;
433
434 fn from_str(value: &str) -> Result<Self, Self::Err> {
435 Self::new(value)
436 }
437}
438
439impl<'de> Deserialize<'de> for Cursor {
440 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
441 let value = String::deserialize(deserializer)?;
442 Self::new(value).map_err(serde::de::Error::custom)
443 }
444}
445
446#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
448#[serde(transparent)]
449pub struct FinancialReport(String);
450
451impl FinancialReport {
452 pub fn parse(value: impl Into<String>) -> Result<Self, ValidationError> {
453 let value = value.into();
454 let bytes = value.as_bytes();
455 let valid = bytes.len() == 6
456 && bytes[..4].iter().all(u8::is_ascii_digit)
457 && bytes[4] == b'-'
458 && matches!(bytes[5], b'1'..=b'4');
459 if !valid {
460 return Err(ValidationError::new("report", "must use YYYY-[1-4] format"));
461 }
462 Ok(Self(value))
463 }
464
465 #[must_use]
466 pub fn as_str(&self) -> &str {
467 &self.0
468 }
469}
470
471impl FromStr for FinancialReport {
472 type Err = ValidationError;
473
474 fn from_str(value: &str) -> Result<Self, Self::Err> {
475 Self::parse(value)
476 }
477}
478
479impl<'de> Deserialize<'de> for FinancialReport {
480 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
481 let value = String::deserialize(deserializer)?;
482 Self::parse(value).map_err(serde::de::Error::custom)
483 }
484}
485
486macro_rules! wire_enum {
489 (
490 $(#[$meta:meta])*
491 pub enum $name:ident {
492 $($(#[$variant_meta:meta])* $variant:ident => $wire:literal),+ $(,)?
493 }
494 ) => {
495 $(#[$meta])*
496 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, derive_more::Display)]
497 pub enum $name {
498 $($(#[$variant_meta])* #[display($wire)] #[serde(rename = $wire)] $variant),+
499 }
500
501 impl $name {
502 #[must_use]
503 pub const fn as_str(self) -> &'static str {
504 match self {
505 $(Self::$variant => $wire),+
506 }
507 }
508 }
509
510 impl Serialize for $name {
511 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
512 serializer.serialize_str(self.as_str())
513 }
514 }
515 };
516}
517
518wire_enum! {
519 pub enum Adjustment {
521 None => "none",
522 Forward => "forward",
523 Backward => "backward",
524 }
525}
526
527wire_enum! {
528 pub enum FinancialPeriod {
530 Annual => "annual",
531 Quarterly => "quarterly",
532 }
533}
534
535wire_enum! {
536 pub enum FiscalPeriod {
538 FullYear => "FY",
539 FirstQuarter => "Q1",
540 SecondQuarter => "Q2",
541 ThirdQuarter => "Q3",
542 FourthQuarter => "Q4",
543 }
544}
545
546wire_enum! {
547 pub enum FinancialAbilityKind {
549 Growth => "growth",
550 Profitability => "profitability",
551 Solvency => "solvency",
552 Operation => "operation",
553 CashFlow => "cash-flow",
554 }
555}
556
557wire_enum! {
558 pub enum FinancialIndicatorId {
560 TotalAssetsGrowthRatio => "total_assets_growth_ratio",
561 NetProfitYoyGrowthRatio => "net_profit_yoy_growth_ratio",
562 OperatingIncomeYoyGrowthRatio => "operating_income_yoy_growth_ratio",
563 OperatingProfitYoyGrowthRatio => "operating_profit_yoy_growth_ratio",
564 SaleGrossMargin => "sale_gross_margin",
565 SaleNetInterestRatio => "sale_net_interest_ratio",
566 TotalAssetsNetRatio => "total_assets_net_ratio",
567 DeductWeightedAverageReturnOnEquity => "index_deduct_weighted_avg_roe",
568 WeightedAverageReturnOnEquity => "index_weighted_avg_roe",
569 CurrentRatio => "current_ratio",
570 QuickRatio => "quick_ratio",
571 AssetsDebtRatio => "assets_debt_ratio",
572 CashRatio => "cash_ratio",
573 EarnedInterestMultiple => "earned_interest_multiple",
574 LongTermDebtEquityRatio => "long_term_debt_equity_ratio",
575 TotalAssetsTurnoverRatio => "total_assets_turnover_ratio",
576 InventoryTurnoverRatio => "inventory_turnover_ratio",
577 CurrentAssetsTurnoverRatio => "current_assets_turnover_ratio",
578 ReceiveAccountTurnoverRatio => "receive_account_turnover_ratio",
579 CashOperatingIndex => "cash_operating_index",
580 OperatingCashFlowNetDivideIncome => "operating_cash_flow_net_divide_income",
581 NetProfitCashContent => "net_profit_cash_content",
582 OperatingCashNetYoyGrowthRatio => "operating_cash_net_yoy_growth_ratio",
583 CashMeetInvestRatio => "cash_meet_invest_ratio",
584 }
585}
586
587wire_enum! {
588 pub enum DailyInterval {
590 OneDay => "1d",
591 }
592}
593
594wire_enum! {
595 pub enum IndexTag {
597 Concept => "cn_concept",
598 Region => "region",
599 Featured => "tszs",
600 Industry => "industry",
601 }
602}
603
604wire_enum! {
605 pub enum AuctionStage {
607 Live => "live",
608 Final => "final",
609 }
610}
611
612wire_enum! {
613 pub enum AnomalyTag {
615 LimitUp => "LIMIT_UP",
616 LimitDown => "LIMIT_DOWN",
617 SharpRise => "SHARP_RISE",
618 SharpFall => "SHARP_FALL",
619 RapidRally => "RAPID_RALLY",
620 RapidDecline => "RAPID_DECLINE",
621 }
622}
623
624wire_enum! {
625 pub enum HotListPeriod {
627 Day => "day",
628 Hour => "hour",
629 }
630}
631
632wire_enum! {
633 pub enum DragonTigerBoard {
635 All => "all",
636 Organization => "org",
637 HotMoney => "hot_money",
638 }
639}
640
641wire_enum! {
642 pub enum SortDirection {
644 Ascending => "asc",
645 Descending => "desc",
646 }
647}
648
649wire_enum! {
650 pub enum LimitUpSortField {
652 LastPrice => "last_price",
653 ConsecutiveDays => "continue_day_cnt",
654 SealedAmount => "seal_money",
655 LimitUpTime => "limit_up_time",
656 }
657}
658
659wire_enum! {
660 pub enum LimitDownSortField {
662 LastLimitTime => "last_limit_time",
663 FirstLimitTime => "first_limit_time",
664 LastPrice => "last_price",
665 PriceChangeRatio => "price_change_ratio_pct",
666 TurnoverRatio => "turnover_ratio_pct",
667 }
668}
669
670wire_enum! {
671 pub enum LimitBreakSortField {
673 PriceChangeRatio => "price_change_ratio_pct",
674 OpenTimes => "open_times",
675 LastPrice => "last_price",
676 TurnoverRatio => "turnover_ratio_pct",
677 Turnover => "turnover",
678 }
679}
680
681wire_enum! {
682 pub enum FundType {
684 Otc => "otc",
685 Exchange => "exchange",
686 Reits => "reits",
687 }
688}
689
690wire_enum! {
691 pub enum HolderMergeScope {
693 All => "all",
694 Merged => "merged",
695 Separate => "separate",
696 }
697}
698
699wire_enum! {
700 pub enum FundRange {
702 Week => "week",
703 Month => "month",
704 ThreeMonths => "tmonth",
705 HalfYear => "hyear",
706 Year => "year",
707 TwoYears => "twoyear",
708 ThreeYears => "tyear",
709 FiveYears => "fyear",
710 }
711}
712
713wire_enum! {
714 pub enum FundNavType {
716 Unit => "unit",
717 Adjusted => "adj",
718 UnitAndAdjusted => "unit,adj",
719 }
720}
721
722wire_enum! {
723 pub enum ManagerPerformanceRange {
725 Month => "month",
726 ThreeMonths => "tmonth",
727 Year => "year",
728 CurrentYear => "nowyear",
729 SinceInception => "now",
730 }
731}
732
733wire_enum! {
734 pub enum OfferingStatus {
736 Active => "active",
737 Upcoming => "upcoming",
738 }
739}
740
741#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
743pub struct Page {
744 number: u32,
745 size: u16,
746}
747
748impl Page {
749 pub const fn new(number: u32, size: u16) -> Result<Self, ValidationError> {
750 if number == 0 {
751 return Err(ValidationError::new("page", "must be at least 1"));
752 }
753 if size == 0 || size > 200 {
754 return Err(ValidationError::new("size", "must be in the range 1..=200"));
755 }
756 Ok(Self { number, size })
757 }
758
759 #[must_use]
760 pub const fn number(self) -> u32 {
761 self.number
762 }
763
764 #[must_use]
765 pub const fn size(self) -> u16 {
766 self.size
767 }
768}
769
770impl Default for Page {
771 fn default() -> Self {
772 Self {
773 number: 1,
774 size: 50,
775 }
776 }
777}
778
779pub(crate) fn join_values<T: fmt::Display>(
780 field: &'static str,
781 values: &[T],
782 maximum: Option<usize>,
783) -> Result<String, ValidationError> {
784 if values.is_empty() {
785 return Err(ValidationError::new(field, "must not be empty"));
786 }
787 if maximum.is_some_and(|maximum| values.len() > maximum) {
788 return Err(ValidationError::new(
789 field,
790 "contains more values than the endpoint allows",
791 ));
792 }
793 Ok(values
794 .iter()
795 .map(ToString::to_string)
796 .collect::<Vec<_>>()
797 .join(","))
798}
799
800wire_enum! {
801 pub enum Exchange {
803 Shanghai => "SH",
804 Shenzhen => "SZ",
805 Beijing => "BJ",
806 }
807}
808
809wire_enum! {
810 pub enum AssetType {
812 AShare => "a-share",
813 AShareIndex => "a-share-index",
814 FundOtc => "fund-otc",
815 FundEtf => "fund-etf",
816 FundLof => "fund-lof",
817 }
818}
819
820wire_enum! {
821 pub enum RankTrend {
823 Up => "up",
824 Down => "down",
825 Flat => "flat",
826 Unknown => "unknown",
827 }
828}
829
830wire_enum! {
831 pub enum HolderRecordScope {
833 Merged => "merged",
834 Separate => "separate",
835 }
836}
837
838wire_enum! {
839 pub enum PortfolioAssetType {
841 Stock => "stock",
842 Bond => "bond",
843 Fund => "fund",
844 }
845}