1use std::collections::HashMap;
2
3use crate::{Error, transport::pagination::PaginatedResponse};
4
5use super::{Bar, Quote, Snapshot, Trade};
6
7#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)]
8pub struct BarsResponse {
9 pub bars: HashMap<String, Vec<Bar>>,
10 pub next_page_token: Option<String>,
11}
12
13#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)]
14pub struct TradesResponse {
15 pub trades: HashMap<String, Vec<Trade>>,
16 pub next_page_token: Option<String>,
17}
18
19#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)]
20pub struct LatestQuotesResponse {
21 pub quotes: HashMap<String, Quote>,
22}
23
24#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)]
25pub struct LatestTradesResponse {
26 pub trades: HashMap<String, Trade>,
27}
28
29#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)]
30pub struct SnapshotsResponse {
31 pub snapshots: HashMap<String, Snapshot>,
32 pub next_page_token: Option<String>,
33}
34
35#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)]
36pub struct ChainResponse {
37 pub snapshots: HashMap<String, Snapshot>,
38 pub next_page_token: Option<String>,
39}
40
41pub type ConditionCodesResponse = HashMap<String, String>;
42
43pub type ExchangeCodesResponse = HashMap<String, String>;
44
45fn merge_batch_page<Item>(
46 current: &mut HashMap<String, Vec<Item>>,
47 next: HashMap<String, Vec<Item>>,
48) {
49 for (symbol, mut items) in next {
50 current.entry(symbol).or_default().append(&mut items);
51 }
52}
53
54fn merge_snapshot_page(
55 operation: &'static str,
56 current: &mut HashMap<String, Snapshot>,
57 next: HashMap<String, Snapshot>,
58) -> Result<(), Error> {
59 for (symbol, snapshot) in next {
60 if current.insert(symbol.clone(), snapshot).is_some() {
61 return Err(Error::Pagination(format!(
62 "{operation} received duplicate symbol across pages: {symbol}"
63 )));
64 }
65 }
66
67 Ok(())
68}
69
70impl PaginatedResponse for BarsResponse {
71 fn next_page_token(&self) -> Option<&str> {
72 self.next_page_token.as_deref()
73 }
74
75 fn merge_page(&mut self, next: Self) -> Result<(), Error> {
76 merge_batch_page(&mut self.bars, next.bars);
77 self.next_page_token = next.next_page_token;
78 Ok(())
79 }
80
81 fn clear_next_page_token(&mut self) {
82 self.next_page_token = None;
83 }
84}
85
86impl PaginatedResponse for TradesResponse {
87 fn next_page_token(&self) -> Option<&str> {
88 self.next_page_token.as_deref()
89 }
90
91 fn merge_page(&mut self, next: Self) -> Result<(), Error> {
92 merge_batch_page(&mut self.trades, next.trades);
93 self.next_page_token = next.next_page_token;
94 Ok(())
95 }
96
97 fn clear_next_page_token(&mut self) {
98 self.next_page_token = None;
99 }
100}
101
102impl PaginatedResponse for SnapshotsResponse {
103 fn next_page_token(&self) -> Option<&str> {
104 self.next_page_token.as_deref()
105 }
106
107 fn merge_page(&mut self, next: Self) -> Result<(), Error> {
108 merge_snapshot_page("options.snapshots", &mut self.snapshots, next.snapshots)?;
109 self.next_page_token = next.next_page_token;
110 Ok(())
111 }
112
113 fn clear_next_page_token(&mut self) {
114 self.next_page_token = None;
115 }
116}
117
118impl PaginatedResponse for ChainResponse {
119 fn next_page_token(&self) -> Option<&str> {
120 self.next_page_token.as_deref()
121 }
122
123 fn merge_page(&mut self, next: Self) -> Result<(), Error> {
124 merge_snapshot_page("options.chain", &mut self.snapshots, next.snapshots)?;
125 self.next_page_token = next.next_page_token;
126 Ok(())
127 }
128
129 fn clear_next_page_token(&mut self) {
130 self.next_page_token = None;
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use std::collections::HashMap;
137
138 use super::{
139 Bar, BarsResponse, ChainResponse, ConditionCodesResponse, ExchangeCodesResponse,
140 LatestQuotesResponse, LatestTradesResponse, SnapshotsResponse, Trade, TradesResponse,
141 };
142 use crate::{Error, transport::pagination::PaginatedResponse};
143
144 #[test]
145 fn historical_responses_deserialize_official_wrapper_shapes() {
146 let bars: BarsResponse = serde_json::from_str(
147 r#"{"bars":{"AAPL260406C00180000":[{"c":70.97,"h":71.21,"l":70.97,"n":2,"o":71.21,"t":"2026-04-02T04:00:00Z","v":2,"vw":71.09}]},"next_page_token":"page-2"}"#,
148 )
149 .expect("bars response should deserialize");
150 assert_eq!(bars.next_page_token.as_deref(), Some("page-2"));
151 assert_eq!(
152 bars.bars
153 .get("AAPL260406C00180000")
154 .map(Vec::len)
155 .unwrap_or_default(),
156 1
157 );
158
159 let trades: TradesResponse = serde_json::from_str(
160 r#"{"trades":{"AAPL260406C00180000":[{"c":"n","p":70.97,"s":1,"t":"2026-04-02T13:39:38.883488197Z","x":"I"}]},"next_page_token":"page-3"}"#,
161 )
162 .expect("trades response should deserialize");
163 assert_eq!(trades.next_page_token.as_deref(), Some("page-3"));
164 assert_eq!(
165 trades
166 .trades
167 .get("AAPL260406C00180000")
168 .map(Vec::len)
169 .unwrap_or_default(),
170 1
171 );
172 }
173
174 #[test]
175 fn historical_merge_combines_symbol_buckets_and_clears_next_page_token() {
176 let mut first = BarsResponse {
177 bars: HashMap::from([(
178 "AAPL260406C00180000".into(),
179 vec![Bar {
180 t: Some("2026-04-02T04:00:00Z".into()),
181 ..Bar::default()
182 }],
183 )]),
184 next_page_token: Some("page-2".into()),
185 };
186 let second = BarsResponse {
187 bars: HashMap::from([(
188 "AAPL260406C00185000".into(),
189 vec![Bar {
190 t: Some("2026-04-02T04:00:00Z".into()),
191 ..Bar::default()
192 }],
193 )]),
194 next_page_token: None,
195 };
196
197 first
198 .merge_page(second)
199 .expect("merge should combine pages without error");
200 first.clear_next_page_token();
201
202 assert_eq!(first.next_page_token, None);
203 assert_eq!(first.bars.len(), 2);
204 }
205
206 #[test]
207 fn historical_merge_accepts_multiple_trade_pages() {
208 let mut first = TradesResponse {
209 trades: HashMap::from([(
210 "AAPL260406C00180000".into(),
211 vec![Trade {
212 t: Some("2026-04-02T13:39:17.488838508Z".into()),
213 ..Trade::default()
214 }],
215 )]),
216 next_page_token: Some("page-2".into()),
217 };
218 let second = TradesResponse {
219 trades: HashMap::from([(
220 "AAPL260406C00180000".into(),
221 vec![Trade {
222 t: Some("2026-04-02T13:39:38.883488197Z".into()),
223 ..Trade::default()
224 }],
225 )]),
226 next_page_token: None,
227 };
228
229 first
230 .merge_page(second)
231 .expect("trade merge should append more items");
232
233 assert_eq!(
234 first
235 .trades
236 .get("AAPL260406C00180000")
237 .map(Vec::len)
238 .unwrap_or_default(),
239 2
240 );
241 }
242
243 #[test]
244 fn latest_responses_deserialize_official_wrapper_shapes() {
245 let quotes: LatestQuotesResponse = serde_json::from_str(
246 r#"{"quotes":{"AAPL260406C00180000":{"ap":77.75,"as":5,"ax":"A","bp":73.95,"bs":3,"bx":"N","c":" ","t":"2026-04-02T19:59:59.792862244Z"}}}"#,
247 )
248 .expect("latest quotes response should deserialize");
249 assert!(quotes.quotes.contains_key("AAPL260406C00180000"));
250
251 let trades: LatestTradesResponse = serde_json::from_str(
252 r#"{"trades":{"AAPL260406C00180000":{"c":"n","p":70.97,"s":1,"t":"2026-04-02T13:39:38.883488197Z","x":"I"}}}"#,
253 )
254 .expect("latest trades response should deserialize");
255 assert!(trades.trades.contains_key("AAPL260406C00180000"));
256 }
257
258 #[test]
259 fn condition_codes_response_deserializes_official_map_shape() {
260 let condition_codes: ConditionCodesResponse = serde_json::from_str(
261 r#"{"a":"SLAN - Single Leg Auction Non ISO","e":"SLFT - Single Leg Floor Trade"}"#,
262 )
263 .expect("condition codes response should deserialize");
264 assert_eq!(
265 condition_codes.get("a").map(String::as_str),
266 Some("SLAN - Single Leg Auction Non ISO")
267 );
268 assert_eq!(
269 condition_codes.get("e").map(String::as_str),
270 Some("SLFT - Single Leg Floor Trade")
271 );
272 }
273
274 #[test]
275 fn exchange_codes_response_deserializes_official_map_shape() {
276 let exchange_codes: ExchangeCodesResponse = serde_json::from_str(
277 r#"{"A":"AMEX - NYSE American","O":"OPRA - Options Price Reporting Authority"}"#,
278 )
279 .expect("exchange codes response should deserialize");
280 assert_eq!(
281 exchange_codes.get("A").map(String::as_str),
282 Some("AMEX - NYSE American")
283 );
284 assert_eq!(
285 exchange_codes.get("O").map(String::as_str),
286 Some("OPRA - Options Price Reporting Authority")
287 );
288 }
289
290 #[test]
291 fn snapshot_responses_deserialize_official_wrapper_shapes() {
292 let snapshots: SnapshotsResponse = serde_json::from_str(
293 r#"{"snapshots":{"AAPL260406C00180000":{"latestQuote":{"ap":77.75,"as":5,"ax":"A","bp":73.95,"bs":3,"bx":"N","c":" ","t":"2026-04-02T19:59:59.792862244Z"},"latestTrade":{"c":"n","p":70.97,"s":1,"t":"2026-04-02T13:39:38.883488197Z","x":"I"},"minuteBar":{"c":70.97,"h":71.21,"l":70.97,"n":2,"o":71.21,"t":"2026-04-02T13:39:00Z","v":2,"vw":71.09},"dailyBar":{"c":70.97,"h":71.21,"l":70.97,"n":2,"o":71.21,"t":"2026-04-02T04:00:00Z","v":2,"vw":71.09},"prevDailyBar":{"c":72.32,"h":72.32,"l":72.32,"n":1,"o":72.32,"t":"2026-04-01T04:00:00Z","v":1,"vw":72.32},"greeks":{"delta":0.0232,"gamma":0.0118,"rho":0.0005,"theta":-0.043,"vega":0.0127},"impliedVolatility":0.2006}},"next_page_token":"page-2"}"#,
294 )
295 .expect("snapshots response should deserialize");
296 assert_eq!(snapshots.next_page_token.as_deref(), Some("page-2"));
297 let snapshot = snapshots
298 .snapshots
299 .get("AAPL260406C00180000")
300 .expect("snapshots response should include the symbol");
301 assert!(snapshot.latestQuote.is_some());
302 assert!(snapshot.latestTrade.is_some());
303 assert!(snapshot.greeks.is_some());
304 assert_eq!(snapshot.impliedVolatility, Some(0.2006));
305
306 let chain: ChainResponse = serde_json::from_str(
307 r#"{"snapshots":{"AAPL260406C00185000":{"latestQuote":{"ap":72.85,"as":5,"ax":"X","bp":69.1,"bs":4,"bx":"S","c":" ","t":"2026-04-02T19:59:59.792862244Z"}}},"next_page_token":null}"#,
308 )
309 .expect("chain response should deserialize");
310 assert!(chain.snapshots.contains_key("AAPL260406C00185000"));
311 assert_eq!(chain.next_page_token, None);
312 }
313
314 #[test]
315 fn snapshot_merge_combines_distinct_symbol_pages_and_clears_next_page_token() {
316 let mut first = SnapshotsResponse {
317 snapshots: HashMap::from([(
318 "AAPL260406C00180000".into(),
319 serde_json::from_str(
320 r#"{"latestQuote":{"ap":77.75,"as":5,"ax":"A","bp":73.95,"bs":3,"bx":"N","c":" ","t":"2026-04-02T19:59:59.792862244Z"}}"#,
321 )
322 .expect("first snapshot should deserialize"),
323 )]),
324 next_page_token: Some("page-2".into()),
325 };
326 let second = SnapshotsResponse {
327 snapshots: HashMap::from([(
328 "AAPL260406C00185000".into(),
329 serde_json::from_str(
330 r#"{"latestQuote":{"ap":72.85,"as":5,"ax":"X","bp":69.1,"bs":4,"bx":"S","c":" ","t":"2026-04-02T19:59:59.792862244Z"}}"#,
331 )
332 .expect("second snapshot should deserialize"),
333 )]),
334 next_page_token: None,
335 };
336
337 first
338 .merge_page(second)
339 .expect("snapshots merge should combine distinct symbols");
340 first.clear_next_page_token();
341
342 assert_eq!(first.next_page_token, None);
343 assert_eq!(first.snapshots.len(), 2);
344 }
345
346 #[test]
347 fn snapshot_merge_rejects_duplicate_symbols_across_pages() {
348 let mut first = ChainResponse {
349 snapshots: HashMap::from([(
350 "AAPL260406C00180000".into(),
351 serde_json::from_str(
352 r#"{"latestQuote":{"ap":77.75,"as":5,"ax":"A","bp":73.95,"bs":3,"bx":"N","c":" ","t":"2026-04-02T19:59:59.792862244Z"}}"#,
353 )
354 .expect("first snapshot should deserialize"),
355 )]),
356 next_page_token: Some("page-2".into()),
357 };
358 let second = ChainResponse {
359 snapshots: HashMap::from([(
360 "AAPL260406C00180000".into(),
361 serde_json::from_str(
362 r#"{"latestQuote":{"ap":78.00,"as":1,"ax":"B","bp":74.00,"bs":2,"bx":"A","c":" ","t":"2026-04-02T20:00:00Z"}}"#,
363 )
364 .expect("duplicate snapshot should deserialize"),
365 )]),
366 next_page_token: None,
367 };
368
369 let error = first
370 .merge_page(second)
371 .expect_err("duplicate symbols should be rejected");
372 assert!(matches!(error, Error::Pagination(_)));
373 }
374}