Skip to main content

financial_api/a_share/
prices.rs

1use 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/// Either explicit targets or a page of the complete A-share universe.
11#[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    /// Fetch current A-share price snapshots.
35    pub async fn prices_snapshot(
36        &self,
37        selection: &PriceSnapshotSelection,
38    ) -> Result<Response<PriceSnapshotData>, Error> {
39        let query = match selection {
40            PriceSnapshotSelection::Targets(codes) => {
41                vec![("thscodes", join_values("thscodes", codes, None)?)]
42            }
43            PriceSnapshotSelection::MarketPage { limit, offset } => {
44                vec![("limit", limit.to_string()), ("offset", offset.to_string())]
45            }
46        };
47        self.get(endpoints::PRICES_SNAPSHOT, &query).await
48    }
49
50    /// Fetch one target's historical daily K-line data.
51    pub async fn prices_historical(
52        &self,
53        thscode: &AShareCode,
54        start: UnixMillis,
55        end: UnixMillis,
56        adjustment: Adjustment,
57        offset: u32,
58    ) -> Result<Response<HistoricalData>, Error> {
59        validate_millis_window(start, end, Some(TEN_YEARS_MS))?;
60        let query = vec![
61            ("thscode", thscode.to_string()),
62            ("interval", "1d".to_owned()),
63            ("start", start.to_string()),
64            ("end", end.to_string()),
65            ("adjust", adjustment.to_string()),
66            ("offset", offset.to_string()),
67        ];
68        self.get(endpoints::PRICES_HISTORICAL, &query).await
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use crate::ApiKey;
76
77    #[test]
78    fn snapshot_selection_rejects_empty_targets_and_zero_page_size() {
79        assert!(PriceSnapshotSelection::targets(Vec::new()).is_err());
80        assert!(PriceSnapshotSelection::market_page(0, 0).is_err());
81        assert!(PriceSnapshotSelection::market_page(10_001, 0).is_ok());
82
83        let stock = AShareCode::new("600519.SH").unwrap();
84        assert!(PriceSnapshotSelection::targets(vec![stock]).is_ok());
85    }
86
87    #[tokio::test]
88    async fn historical_prices_keeps_the_shared_window_validation_on_its_call_edge() {
89        let client = Client::builder(ApiKey::new("test-api-key").unwrap())
90            .base_url("http://127.0.0.1:9")
91            .build()
92            .unwrap();
93        let stock = AShareCode::new("600519.SH").unwrap();
94        let start = UnixMillis::new(1_000_000_000_000).unwrap();
95        let invalid_ends = [
96            UnixMillis::new(start.get() - 1).unwrap(),
97            UnixMillis::new(start.get() + TEN_YEARS_MS + 1).unwrap(),
98        ];
99
100        for end in invalid_ends {
101            let error = client
102                .prices_historical(&stock, start, end, Adjustment::None, 0)
103                .await
104                .unwrap_err();
105            assert!(matches!(error, Error::InvalidInput(_)));
106        }
107    }
108}