1use std::collections::HashMap;
19
20use jiff::Timestamp;
21use nautilus_core::serialization::decimal;
22use rust_decimal::Decimal;
23use serde::{Deserialize, Serialize};
24use serde_json::value::RawValue;
25use ustr::Ustr;
26
27use crate::common::enums::{MarketMechanism, OhlcvInterval, OhlcvUnit};
28
29#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
31pub struct Exchange {
32 pub exchange_id: Option<Ustr>,
34 pub market_name_institution_description: Option<String>,
36 pub website: Option<String>,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42pub enum MarketStatus {
43 Open,
45 Closed,
47 Resolved,
49 Suspended,
51 #[serde(other)]
53 Unknown,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58pub enum OutcomeType {
59 Binary,
61 MultipleChoice,
63 Numeric,
65 #[serde(other)]
67 Other,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
72pub enum TradeSide {
73 Buy,
75 Sell,
77 #[serde(other)]
79 Other,
80}
81
82#[derive(Debug, Clone, Deserialize)]
84pub struct Market {
85 pub exchange_id: Option<Ustr>,
87 pub market_id: Option<Ustr>,
89 pub outcome_type: OutcomeType,
91 pub outcome_name: Option<String>,
93 pub mechanism: Option<MarketMechanism>,
95 pub status: MarketStatus,
97 #[serde(deserialize_with = "decimal::deserialize_json")]
99 pub price: Decimal,
100 pub title: Option<String>,
102 pub description: Option<String>,
104 pub exchange: Option<Exchange>,
106 pub source_specific_data: Option<HashMap<String, Box<RawValue>>>,
108}
109
110#[derive(Debug, Clone, Deserialize)]
112pub struct MarketsPage {
113 pub data: Option<Vec<Market>>,
115 pub next_cursor: Option<String>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
121pub struct Trade {
122 pub market_id: Option<Ustr>,
124 pub id: Option<String>,
126 pub outcome: Option<String>,
128 pub side: TradeSide,
130 #[serde(deserialize_with = "decimal::deserialize_json")]
132 pub price: Decimal,
133 #[serde(deserialize_with = "decimal::deserialize_json")]
135 pub quantity: Decimal,
136 pub timestamp: Timestamp,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
142pub struct Quote {
143 #[serde(deserialize_with = "decimal::deserialize_json")]
145 pub bid: Decimal,
146 #[serde(deserialize_with = "decimal::deserialize_json")]
148 pub ask: Decimal,
149 #[serde(deserialize_with = "decimal::deserialize_json")]
151 pub bid_volume: Decimal,
152 #[serde(deserialize_with = "decimal::deserialize_json")]
154 pub ask_volume: Decimal,
155 pub entry_time: Timestamp,
157 pub recv_time: Timestamp,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
163pub struct ActivityCurrent {
164 pub quote: Option<Quote>,
166 pub trade: Option<Trade>,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
172pub struct ActivityBatch {
173 pub quotes: Option<Vec<Quote>>,
175 pub trades: Option<Vec<Trade>>,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
181pub struct BookLevel {
182 #[serde(deserialize_with = "decimal::deserialize_json")]
184 pub price: Decimal,
185 #[serde(deserialize_with = "decimal::deserialize_json")]
187 pub size: Decimal,
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
193pub struct Book {
194 pub exchange_id: Option<Ustr>,
196 pub market_id: Option<Ustr>,
198 pub bids: Option<Vec<BookLevel>>,
200 pub asks: Option<Vec<BookLevel>>,
202 pub time_exchange: Timestamp,
204 pub time_coinapi: Timestamp,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
214pub struct BookEvent {
215 pub symbol_id: Ustr,
217 pub id: String,
219 pub update_type: i64,
221 pub is_sell_ask: bool,
223 #[serde(deserialize_with = "decimal::deserialize_json")]
225 pub price: Decimal,
226 #[serde(deserialize_with = "decimal::deserialize_json")]
228 pub size: Decimal,
229 pub time_exchange: Timestamp,
231 pub time_coinapi: Option<Timestamp>,
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
237pub struct OhlcvPeriod {
238 pub period_id: Option<OhlcvInterval>,
240 pub unit_name: Option<OhlcvUnit>,
242 pub unit_count: Option<i32>,
244 pub length_seconds: i32,
246 pub length_months: i32,
248 pub display_name: Option<Ustr>,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
256pub struct Ohlcv {
257 pub market_id_exchange: Option<Ustr>,
259 #[serde(default, deserialize_with = "decimal::deserialize_optional_json")]
261 pub price_open: Option<Decimal>,
262 #[serde(default, deserialize_with = "decimal::deserialize_optional_json")]
264 pub price_high: Option<Decimal>,
265 #[serde(default, deserialize_with = "decimal::deserialize_optional_json")]
267 pub price_low: Option<Decimal>,
268 #[serde(default, deserialize_with = "decimal::deserialize_optional_json")]
270 pub price_close: Option<Decimal>,
271 #[serde(deserialize_with = "decimal::deserialize_json")]
273 pub volume_traded: Decimal,
274 pub trades_count: i64,
276 pub time_period_start: Timestamp,
278 pub time_period_end: Timestamp,
280 pub time_open: Option<Timestamp>,
282 pub time_close: Option<Timestamp>,
284}
285
286#[cfg(test)]
287mod tests {
288 use rstest::rstest;
289
290 use super::*;
291
292 const QUOTE: &str = include_str!("../../test_data/exact-quote.json");
293 const TRADE: &str = include_str!("../../test_data/exact-trade.json");
294 const BAR: &str = include_str!("../../test_data/exact-bar.json");
295
296 #[rstest]
297 #[case("Open", MarketStatus::Open)]
298 #[case("Closed", MarketStatus::Closed)]
299 #[case("Resolved", MarketStatus::Resolved)]
300 #[case("Suspended", MarketStatus::Suspended)]
301 #[case("FutureStatus", MarketStatus::Unknown)]
302 #[case("Unknown", MarketStatus::Unknown)]
303 #[case("", MarketStatus::Unknown)]
304 fn market_status_labels_preserve_known_values_and_classify_unknowns(
305 #[case] label: &str,
306 #[case] expected: MarketStatus,
307 ) {
308 let encoded = serde_json::to_string(label).unwrap();
309 assert_eq!(
310 serde_json::from_str::<MarketStatus>(&encoded).unwrap(),
311 expected
312 );
313 }
314
315 #[rstest]
316 #[case("Binary", OutcomeType::Binary)]
317 #[case("MultipleChoice", OutcomeType::MultipleChoice)]
318 #[case("Numeric", OutcomeType::Numeric)]
319 #[case("FutureOutcome", OutcomeType::Other)]
320 #[case("Other", OutcomeType::Other)]
321 #[case("", OutcomeType::Other)]
322 fn outcome_type_labels_preserve_known_values_and_classify_unknowns(
323 #[case] label: &str,
324 #[case] expected: OutcomeType,
325 ) {
326 let encoded = serde_json::to_string(label).unwrap();
327 assert_eq!(
328 serde_json::from_str::<OutcomeType>(&encoded).unwrap(),
329 expected
330 );
331 }
332
333 #[rstest]
334 #[case("Buy", TradeSide::Buy)]
335 #[case("Sell", TradeSide::Sell)]
336 #[case("FutureSide", TradeSide::Other)]
337 #[case("Other", TradeSide::Other)]
338 #[case("", TradeSide::Other)]
339 fn trade_side_labels_preserve_known_values_and_classify_unknowns(
340 #[case] label: &str,
341 #[case] expected: TradeSide,
342 ) {
343 let encoded = serde_json::to_string(label).unwrap();
344 assert_eq!(
345 serde_json::from_str::<TradeSide>(&encoded).unwrap(),
346 expected
347 );
348 }
349
350 #[rstest]
351 fn exact_numbers_identifiers_and_timestamps_preserve_every_field() {
352 assert_eq!(
353 serde_json::from_str::<Quote>(QUOTE).unwrap(),
354 Quote {
355 bid: "0.9876543210987654321098765432".parse().unwrap(),
356 ask: "0.1234567890123456789012345678".parse().unwrap(),
357 bid_volume: "18446744073709551617".parse().unwrap(),
358 ask_volume: "9007199254740993".parse().unwrap(),
359 entry_time: "2026-10-11T00:00:00.0000001Z".parse().unwrap(),
360 recv_time: "2026-10-11T00:00:00.0000003Z".parse().unwrap(),
361 }
362 );
363 assert_eq!(
364 serde_json::from_str::<Trade>(TRADE).unwrap(),
365 Trade {
366 market_id: Some("outcome/Y?+=%".into()),
367 id: Some("opaque/ID?+=%".into()),
368 outcome: Some("MixedCase".into()),
369 side: TradeSide::Buy,
370 price: "0.1234567890123456789012345678".parse().unwrap(),
371 quantity: "9007199254740993.125".parse().unwrap(),
372 timestamp: "2026-10-11T00:00:00.0000001Z".parse().unwrap(),
373 }
374 );
375 assert_eq!(
376 serde_json::from_str::<Ohlcv>(BAR).unwrap(),
377 Ohlcv {
378 market_id_exchange: None,
379 price_open: Some("0.1".parse().unwrap()),
380 price_high: Some("0.9".parse().unwrap()),
381 price_low: Some("0.01".parse().unwrap()),
382 price_close: Some("0.5".parse().unwrap()),
383 volume_traded: "9007199254740993.125".parse().unwrap(),
384 trades_count: 9223372036854775807,
385 time_period_start: "2026-10-11T00:00:00.0000001Z".parse().unwrap(),
386 time_period_end: "2026-10-11T00:01:00.0000002Z".parse().unwrap(),
387 time_open: Some("2026-10-11T00:00:02.0000003Z".parse().unwrap()),
388 time_close: Some("2026-10-11T00:00:58.0000004Z".parse().unwrap()),
389 }
390 );
391 }
392
393 #[rstest]
394 #[case(include_str!("../../test_data/overflow-quote.json"))]
395 #[case(include_str!("../../test_data/underflow-quote.json"))]
396 #[case(include_str!("../../test_data/null-quote.json"))]
397 #[case(include_str!("../../test_data/empty-quote.json"))]
398 #[case(include_str!("../../test_data/object-quote.json"))]
399 #[case(include_str!("../../test_data/boolean-quote.json"))]
400 #[case(include_str!("../../test_data/malformed.txt"))]
401 fn invalid_decimal_shapes_and_unrepresentable_values_fail(#[case] payload: &str) {
402 assert!(serde_json::from_str::<Quote>(payload).is_err());
403 }
404
405 #[rstest]
406 fn every_discrete_field_rejects_overflow() {
407 assert!(
408 serde_json::from_str::<Ohlcv>(include_str!("../../test_data/overflow-bar.json"))
409 .is_err()
410 );
411 let quote = serde_json::from_str::<serde_json::Value>(QUOTE).unwrap();
412 for field in ["ask", "bid", "ask_volume", "bid_volume"] {
413 let mut value = quote.clone();
414 value[field] = "79228162514264337593543950336".into();
415 assert!(
416 serde_json::from_str::<Quote>(&value.to_string()).is_err(),
417 "{field}"
418 );
419 }
420
421 for field in [
422 "price_open",
423 "price_high",
424 "price_low",
425 "price_close",
426 "volume_traded",
427 "trades_count",
428 ] {
429 let mut value = serde_json::from_str::<serde_json::Value>(BAR).unwrap();
430 value[field] = "79228162514264337593543950336".into();
431 assert!(
432 serde_json::from_str::<Ohlcv>(&value.to_string()).is_err(),
433 "{field}"
434 );
435 }
436
437 for field in ["price", "quantity"] {
438 let mut value = serde_json::from_str::<serde_json::Value>(TRADE).unwrap();
439 value[field] = "1e-29".into();
440 assert!(
441 serde_json::from_str::<Trade>(&value.to_string()).is_err(),
442 "{field}"
443 );
444 }
445 }
446
447 #[rstest]
448 fn fixtures_across_venues_and_optional_activity_decode() {
449 for (payload, count, terminal) in [
450 (
451 include_str!("../../test_data/polymarket-listings.json"),
452 2,
453 false,
454 ),
455 (
456 include_str!("../../test_data/kalshi-listings.json"),
457 2,
458 false,
459 ),
460 (
461 include_str!("../../test_data/myriad-listings.json"),
462 1,
463 false,
464 ),
465 (
466 include_str!("../../test_data/manifold-listings.json"),
467 1,
468 false,
469 ),
470 (
471 include_str!("../../test_data/hyperliquidoutcome-listings.json"),
472 1,
473 false,
474 ),
475 (
476 include_str!("../../test_data/pascal-listings.json"),
477 1,
478 false,
479 ),
480 (
481 include_str!("../../test_data/geminipm-listings.json"),
482 1,
483 false,
484 ),
485 (
486 include_str!("../../test_data/cryptocompm-listings.json"),
487 1,
488 false,
489 ),
490 (
491 include_str!("../../test_data/forecastex-listings.json"),
492 1,
493 false,
494 ),
495 ] {
496 let page: MarketsPage = serde_json::from_str(payload).unwrap();
497 assert_eq!(page.data.unwrap().len(), count);
498 assert_eq!(page.next_cursor.is_none(), terminal);
499 }
500
501 let current: ActivityCurrent =
502 serde_json::from_str(include_str!("../../test_data/kalshi-current.json")).unwrap();
503 assert_eq!(current.quote, None);
504 assert_eq!(current.trade.unwrap().side, TradeSide::Sell);
505
506 for payload in [
507 include_str!("../../test_data/missing-cursor.json"),
508 include_str!("../../test_data/terminal-listings.json"),
509 ] {
510 let terminal: MarketsPage = serde_json::from_str(payload).unwrap();
511 assert_eq!(terminal.data.unwrap().len(), 0);
512 assert_eq!(terminal.next_cursor, None);
513 }
514 }
515
516 #[rstest]
517 fn metadata_and_book_fields_preserve_exact_values() {
518 let market: Market =
519 serde_json::from_str(include_str!("../../test_data/exact-market.json")).unwrap();
520 assert_eq!(market.market_id.as_deref(), Some("Opaque/Outcome?+=%"));
521 assert_eq!(market.title.as_deref(), Some("distinct title"));
522 assert_eq!(market.description.as_deref(), Some("distinct description"));
523 assert_eq!(market.outcome_name, None);
524 assert_eq!(
525 market.price,
526 "0.1234567890123456789012345678".parse().unwrap()
527 );
528 assert_eq!(market.status, MarketStatus::Suspended);
529 assert_eq!(
530 market.exchange,
531 Some(Exchange {
532 exchange_id: Some("MYRIAD".into()),
533 market_name_institution_description: Some("distinct exchange".into()),
534 website: Some("https://example.com".into())
535 })
536 );
537 assert_eq!(market.exchange_id.as_deref(), Some("MYRIAD"));
538 assert_eq!(market.outcome_type, OutcomeType::MultipleChoice);
539 assert_eq!(market.mechanism.as_ref().map(AsRef::as_ref), Some("CPMM"));
540 let source = market.source_specific_data.unwrap();
541 assert_eq!(source.len(), 2);
542 assert_eq!(source["precise"].get(), "0.9876543210987654321098765432");
543 let nested: std::collections::HashMap<String, String> =
544 serde_json::from_str(source["nested"].get()).unwrap();
545 assert_eq!(
546 nested,
547 std::collections::HashMap::from([("token".into(), "opaque/Token?+=%".into())])
548 );
549 let book: Book =
550 serde_json::from_str(include_str!("../../test_data/polymarket-book.json")).unwrap();
551 assert_eq!(book.exchange_id.as_deref(), Some("POLYMARKET"));
552 assert_eq!(book.market_id.as_deref(), Some("TEST-OUTCOME_NO"));
553 assert_eq!(
554 book.time_exchange,
555 "2026-10-12T00:00:02.0000003Z".parse().unwrap()
556 );
557 assert_eq!(
558 book.time_coinapi,
559 "2026-10-12T00:00:02.0000003Z".parse().unwrap()
560 );
561 let mut invalid =
562 include_str!("../../test_data/polymarket-book.json").replace("0.6,", "1e-29,");
563 assert!(serde_json::from_str::<Book>(&invalid).is_err());
564 invalid = include_str!("../../test_data/polymarket-book.json")
565 .replace("41.25", "79228162514264337593543950336");
566 assert!(serde_json::from_str::<Book>(&invalid).is_err());
567 }
568
569 #[rstest]
570 fn nullable_book_sides_do_not_become_empty_snapshots() {
571 assert_eq!(
572 serde_json::from_str::<Book>(include_str!("../../test_data/null-book.json")).unwrap(),
573 Book {
574 exchange_id: Some("KALSHI".into()),
575 market_id: Some("opaque/NO?+=%".into()),
576 bids: None,
577 asks: None,
578 time_exchange: "2026-10-11T00:00:00.0000001Z".parse().unwrap(),
579 time_coinapi: "2026-10-11T00:00:00.0000003Z".parse().unwrap(),
580 }
581 );
582 }
583
584 #[derive(serde::Deserialize)]
585 struct NullableIdentifiers {
586 exchange: Exchange,
587 market: Market,
588 trade: Trade,
589 book: Book,
590 period: OhlcvPeriod,
591 }
592
593 #[rstest]
594 fn nullable_identifiers_preserve_absence_and_period_fields() {
595 let data: NullableIdentifiers =
596 serde_json::from_str(include_str!("../../test_data/nullable-identifiers.json"))
597 .unwrap();
598 assert_eq!(data.exchange.exchange_id, None);
599 assert_eq!(data.market.market_id, None);
600 assert_eq!(data.market.exchange_id, None);
601 assert_eq!(data.trade.market_id, None);
602 assert_eq!(data.trade.id, None);
603 assert_eq!(data.book.market_id, None);
604 assert_eq!(data.book.exchange_id, None);
605 assert_eq!(
606 data.period,
607 OhlcvPeriod {
608 period_id: None,
609 unit_name: Some("distinct unit".into()),
610 unit_count: Some(13),
611 length_seconds: 59,
612 length_months: 17,
613 display_name: Some("distinct display".into()),
614 }
615 );
616 }
617}