Skip to main content

nautilus_polymarket/websocket/
parse.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Parse functions for converting Polymarket WebSocket messages to Nautilus data types.
17
18use aws_lc_rs::digest::{SHA1_FOR_LEGACY_USE_ONLY, digest};
19use nautilus_core::{
20    UnixNanos,
21    correctness::{CorrectnessError, CorrectnessResult},
22    datetime::NANOSECONDS_IN_MILLISECOND,
23    hex,
24};
25use nautilus_model::{
26    data::{BookOrder, OrderBookDelta, OrderBookDeltas, QuoteTick, TradeTick},
27    enums::{AggressorSide, BookAction, OrderSide, RecordFlag},
28    identifiers::InstrumentId,
29    types::{Price, Quantity},
30};
31use rust_decimal::Decimal;
32use serde::Serialize;
33
34use super::messages::{
35    PolymarketBestBidAsk, PolymarketBookLevel, PolymarketBookSnapshot, PolymarketQuote,
36    PolymarketTrade,
37};
38use crate::common::{
39    enums::PolymarketOrderSide,
40    parse::{determine_trade_id, parse_decimal_exact},
41};
42
43/// Parses a millisecond epoch timestamp string into [`UnixNanos`].
44pub fn parse_timestamp_ms(ts: &str) -> anyhow::Result<UnixNanos> {
45    let ms: u64 = ts
46        .parse()
47        .map_err(|e| anyhow::anyhow!("Invalid timestamp '{ts}': {e}"))?;
48    let ns = ms
49        .checked_mul(NANOSECONDS_IN_MILLISECOND)
50        .ok_or_else(|| anyhow::anyhow!("Timestamp overflow for '{ts}'"))?;
51    Ok(UnixNanos::from(ns))
52}
53
54pub(crate) fn parse_price(s: &str, precision: u8) -> CorrectnessResult<Price> {
55    let value = parse_decimal_exact(s).map_err(|e| CorrectnessError::PredicateViolation {
56        message: format!("Invalid price '{s}': {e}"),
57    })?;
58    Price::from_decimal_dp(value, precision)
59}
60
61pub(crate) fn parse_quantity(s: &str, precision: u8) -> CorrectnessResult<Quantity> {
62    let value = parse_decimal_exact(s).map_err(|e| CorrectnessError::PredicateViolation {
63        message: format!("Invalid quantity '{s}': {e}"),
64    })?;
65    Quantity::from_decimal_dp(value, precision)
66}
67
68pub(crate) fn verify_book_snapshot_hash(
69    snap: &PolymarketBookSnapshot,
70    min_order_size: Option<&str>,
71    neg_risk: Option<bool>,
72) -> anyhow::Result<bool> {
73    let Some(expected) = snap.hash.as_deref() else {
74        return Ok(false);
75    };
76
77    let Some(computed) = book_snapshot_hash(snap, min_order_size, neg_risk)? else {
78        return Ok(false);
79    };
80
81    if computed != expected {
82        anyhow::bail!(
83            "Book snapshot hash mismatch for {}: expected {expected}, computed {computed}",
84            snap.asset_id
85        );
86    }
87
88    Ok(true)
89}
90
91pub(crate) fn book_snapshot_hash(
92    snap: &PolymarketBookSnapshot,
93    min_order_size: Option<&str>,
94    neg_risk: Option<bool>,
95) -> anyhow::Result<Option<String>> {
96    let Some(min_order_size) = snap.min_order_size.as_deref().or(min_order_size) else {
97        return Ok(None);
98    };
99
100    let Some(tick_size) = snap.tick_size.as_deref() else {
101        return Ok(None);
102    };
103
104    let Some(neg_risk) = snap.neg_risk.or(neg_risk) else {
105        return Ok(None);
106    };
107
108    let Some(last_trade_price) = snap.last_trade_price.as_deref() else {
109        return Ok(None);
110    };
111
112    // V2 appends the wire version; unversioned books retain the SDK field order
113    // Polymarket/py-clob-client-v2@215fc63a8fd6ec3a10c7edb73997c9772d8686d3:utilities.py
114    let preimage = BookSnapshotHashPreimage {
115        market: snap.market.as_str(),
116        asset_id: snap.asset_id.as_str(),
117        timestamp: &snap.timestamp,
118        hash: "",
119        bids: &snap.bids,
120        asks: &snap.asks,
121        min_order_size,
122        tick_size,
123        neg_risk,
124        last_trade_price,
125        version: snap.version.as_deref(),
126    };
127
128    let serialized = serde_json::to_vec(&preimage)?;
129    let hash = digest(&SHA1_FOR_LEGACY_USE_ONLY, &serialized);
130
131    Ok(Some(hex::encode(hash)))
132}
133
134#[derive(Serialize)]
135struct BookSnapshotHashPreimage<'a> {
136    market: &'a str,
137    asset_id: &'a str,
138    timestamp: &'a str,
139    hash: &'static str,
140    bids: &'a [PolymarketBookLevel],
141    asks: &'a [PolymarketBookLevel],
142    min_order_size: &'a str,
143    tick_size: &'a str,
144    neg_risk: bool,
145    last_trade_price: &'a str,
146    #[serde(skip_serializing_if = "Option::is_none")]
147    version: Option<&'a str>,
148}
149
150/// Parses a book snapshot into [`OrderBookDeltas`] (CLEAR + ADD).
151///
152/// A book with no resting orders is a valid snapshot: it parses to a lone
153/// CLEAR so the baseline is accepted instead of burning recovery budget.
154pub fn parse_book_snapshot(
155    snap: &PolymarketBookSnapshot,
156    instrument_id: InstrumentId,
157    price_precision: u8,
158    size_precision: u8,
159    ts_init: UnixNanos,
160) -> anyhow::Result<OrderBookDeltas> {
161    let ts_event = parse_timestamp_ms(&snap.timestamp)?;
162
163    let bids_len = snap.bids.len();
164    let asks_len = snap.asks.len();
165
166    let total = bids_len + asks_len;
167    let mut deltas = Vec::with_capacity(total + 1);
168
169    // Every snapshot delta (including the opening CLEAR) carries F_SNAPSHOT so
170    // downstream consumers can recognize the rebuild; F_LAST closes the batch
171    // on the final delta. `OrderBookDelta::clear` already sets F_SNAPSHOT.
172    let snapshot_flag = RecordFlag::F_SNAPSHOT as u8;
173    let mut clear = OrderBookDelta::clear(instrument_id, 0, ts_event, ts_init);
174
175    if total == 0 {
176        clear.flags |= RecordFlag::F_LAST as u8;
177    }
178
179    deltas.push(clear);
180
181    let mut count = 0;
182
183    for (side, levels) in [(OrderSide::Buy, &snap.bids), (OrderSide::Sell, &snap.asks)] {
184        for level in levels {
185            count += 1;
186            let price = parse_price(&level.price, price_precision)?;
187            let size = parse_quantity(&level.size, size_precision)?;
188            let order = BookOrder::new(side, price, size, 0);
189
190            let mut flags = snapshot_flag;
191            if count == total {
192                flags |= RecordFlag::F_LAST as u8;
193            }
194
195            deltas.push(OrderBookDelta::new_checked(
196                instrument_id,
197                BookAction::Add,
198                order,
199                flags,
200                0,
201                ts_event,
202                ts_init,
203            )?);
204        }
205    }
206
207    Ok(OrderBookDeltas::new(instrument_id, deltas))
208}
209
210/// Parses price change quotes into incremental book deltas.
211///
212/// Each result corresponds to one quote. The final successful delta carries
213/// [`RecordFlag::F_LAST`], including when later quotes fail to parse.
214pub fn parse_book_deltas(
215    quotes: &[&PolymarketQuote],
216    instrument_id: InstrumentId,
217    price_precision: u8,
218    size_precision: u8,
219    ts_event: UnixNanos,
220    ts_init: UnixNanos,
221) -> Vec<anyhow::Result<OrderBookDelta>> {
222    let mut deltas = quotes
223        .iter()
224        .map(|change| {
225            parse_book_delta(
226                change,
227                instrument_id,
228                price_precision,
229                size_precision,
230                ts_event,
231                ts_init,
232            )
233        })
234        .collect::<Vec<_>>();
235
236    if let Some(delta) = deltas
237        .iter_mut()
238        .rev()
239        .find_map(|result| result.as_mut().ok())
240    {
241        delta.flags |= RecordFlag::F_LAST as u8;
242    }
243
244    deltas
245}
246
247fn parse_book_delta(
248    change: &PolymarketQuote,
249    instrument_id: InstrumentId,
250    price_precision: u8,
251    size_precision: u8,
252    ts_event: UnixNanos,
253    ts_init: UnixNanos,
254) -> anyhow::Result<OrderBookDelta> {
255    let price = parse_price(&change.price, price_precision)?;
256    let size = parse_quantity(&change.size, size_precision)?;
257    let side = match change.side {
258        PolymarketOrderSide::Buy => OrderSide::Buy,
259        PolymarketOrderSide::Sell => OrderSide::Sell,
260    };
261    let (action, order_size) = if size.is_zero() {
262        (BookAction::Delete, Quantity::zero(size_precision))
263    } else {
264        (BookAction::Update, size)
265    };
266    let order = BookOrder::new(side, price, order_size, 0);
267
268    OrderBookDelta::new_checked(instrument_id, action, order, 0, 0, ts_event, ts_init)
269}
270
271/// Parses a trade message into a [`TradeTick`].
272pub fn parse_trade_tick(
273    trade: &PolymarketTrade,
274    instrument_id: InstrumentId,
275    price_precision: u8,
276    size_precision: u8,
277    ts_init: UnixNanos,
278) -> anyhow::Result<TradeTick> {
279    let price = parse_price(&trade.price, price_precision)?;
280    let size = parse_quantity(&trade.size, size_precision)?;
281    let aggressor_side = match trade.side {
282        PolymarketOrderSide::Buy => AggressorSide::Buy,
283        PolymarketOrderSide::Sell => AggressorSide::Sell,
284    };
285    let ts_event = parse_timestamp_ms(&trade.timestamp)?;
286
287    let trade_id = determine_trade_id(
288        &trade.asset_id,
289        trade.side,
290        &trade.price,
291        &trade.size,
292        &trade.timestamp,
293    );
294
295    TradeTick::new_checked(
296        instrument_id,
297        price,
298        size,
299        aggressor_side,
300        trade_id,
301        ts_event,
302        ts_init,
303    )
304}
305
306/// Extracts a top-of-book [`QuoteTick`] from a book snapshot.
307///
308/// Returns `None` if either side is empty and `drop_quotes_missing_side` is enabled.
309pub fn parse_quote_from_snapshot(
310    snap: &PolymarketBookSnapshot,
311    instrument_id: InstrumentId,
312    price_precision: u8,
313    size_precision: u8,
314    price_increment: Price,
315    drop_quotes_missing_side: bool,
316    ts_init: UnixNanos,
317) -> anyhow::Result<Option<QuoteTick>> {
318    if drop_quotes_missing_side && (snap.bids.is_empty() || snap.asks.is_empty()) {
319        return Ok(None);
320    }
321
322    let ts_event = parse_timestamp_ms(&snap.timestamp)?;
323    let (min_price, max_price) = quote_price_bounds(price_increment, price_increment.as_decimal())?;
324
325    // Polymarket sends bids ascending and asks descending, so best-of-book is last.
326    let (bid_price, bid_size) = match snap.bids.last() {
327        Some(best_bid) => (
328            parse_price(&best_bid.price, price_precision)?,
329            parse_quantity(&best_bid.size, size_precision)?,
330        ),
331        None => (min_price, Quantity::zero(size_precision)),
332    };
333    let (ask_price, ask_size) = match snap.asks.last() {
334        Some(best_ask) => (
335            parse_price(&best_ask.price, price_precision)?,
336            parse_quantity(&best_ask.size, size_precision)?,
337        ),
338        None => (max_price, Quantity::zero(size_precision)),
339    };
340
341    Ok(Some(QuoteTick::new_checked(
342        instrument_id,
343        bid_price,
344        ask_price,
345        bid_size,
346        ask_size,
347        ts_event,
348        ts_init,
349    )?))
350}
351
352/// Parses a quote tick from a price change message using its best_bid/best_ask fields.
353///
354/// Returns `None` when either top-of-book side is absent or at the resolution
355/// boundary and `drop_quotes_missing_side` is enabled.
356/// Returns `None` for locked or crossed top-of-book prices.
357/// Uses the changed level's size when it matches the reported top on that side.
358/// Otherwise, carries each previous size only when its price still matches the
359/// reported top; moved or unknown sides have zero size.
360#[expect(clippy::too_many_arguments)]
361pub fn parse_quote_from_price_change(
362    quote: &PolymarketQuote,
363    instrument_id: InstrumentId,
364    price_precision: u8,
365    size_precision: u8,
366    price_increment: Price,
367    drop_quotes_missing_side: bool,
368    last_quote: Option<&QuoteTick>,
369    ts_event: UnixNanos,
370    ts_init: UnixNanos,
371) -> anyhow::Result<Option<QuoteTick>> {
372    let bid_top = parse_bid_top(quote.best_bid.as_deref(), price_precision)?;
373    let ask_top = parse_ask_top(quote.best_ask.as_deref(), price_precision)?;
374    if drop_quotes_missing_side && (bid_top.is_none() || ask_top.is_none()) {
375        return Ok(None);
376    }
377
378    let (min_price, max_price) = quote_price_bounds(price_increment, price_increment.as_decimal())?;
379    let bid_missing = bid_top.is_none();
380    let ask_missing = ask_top.is_none();
381    let bid_price = match bid_top {
382        Some(price) => price,
383        None => min_price,
384    };
385    let ask_price = match ask_top {
386        Some(price) => price,
387        None => max_price,
388    };
389
390    if !bid_missing && !ask_missing && bid_price >= ask_price {
391        return Ok(None);
392    }
393
394    let changed_price = parse_price(&quote.price, price_precision)?;
395
396    let size = parse_quantity(&quote.size, size_precision)?;
397    let zero = || Quantity::zero(size_precision);
398
399    let bid_size = if bid_missing {
400        zero()
401    } else if quote.side == PolymarketOrderSide::Buy && changed_price == bid_price {
402        size
403    } else {
404        last_quote
405            .filter(|q| q.bid_price == bid_price)
406            .map_or_else(zero, |q| q.bid_size)
407    };
408
409    let ask_size = if ask_missing {
410        zero()
411    } else if quote.side == PolymarketOrderSide::Sell && changed_price == ask_price {
412        size
413    } else {
414        last_quote
415            .filter(|q| q.ask_price == ask_price)
416            .map_or_else(zero, |q| q.ask_size)
417    };
418
419    Ok(Some(QuoteTick::new_checked(
420        instrument_id,
421        bid_price,
422        ask_price,
423        bid_size,
424        ask_size,
425        ts_event,
426        ts_init,
427    )?))
428}
429
430enum BestBidAskTop {
431    Missing,
432    Invalid,
433    Price(Price),
434}
435
436/// Parses a quote tick from a best bid/ask message.
437///
438/// The payload carries top-of-book prices only. Each side's size comes from the supplied known
439/// level when its price matches the message and is zero otherwise.
440///
441/// Returns `None` when a side is missing and `drop_quotes_missing_side` is enabled. When missing
442/// sides are allowed, the quote uses the current tick-relative venue bounds. Returns `None` for
443/// locked, crossed, out-of-range, or off-grid prices.
444#[expect(clippy::too_many_arguments)]
445pub fn parse_quote_from_best_bid_ask(
446    bba: &PolymarketBestBidAsk,
447    instrument_id: InstrumentId,
448    price_precision: u8,
449    size_precision: u8,
450    price_increment: Price,
451    drop_quotes_missing_side: bool,
452    bid_top: Option<(Price, Quantity)>,
453    ask_top: Option<(Price, Quantity)>,
454    ts_event: UnixNanos,
455    ts_init: UnixNanos,
456) -> anyhow::Result<Option<QuoteTick>> {
457    let tick_size = price_increment.as_decimal();
458    let bid = parse_best_bid_ask_top(
459        non_empty(&bba.best_bid),
460        price_precision,
461        tick_size,
462        |value| value <= Decimal::ZERO,
463    )?;
464    let ask = parse_best_bid_ask_top(
465        non_empty(&bba.best_ask),
466        price_precision,
467        tick_size,
468        |value| value >= Decimal::ONE,
469    )?;
470    let (bid, ask) = match (bid, ask) {
471        (BestBidAskTop::Invalid, _) | (_, BestBidAskTop::Invalid) => return Ok(None),
472        (BestBidAskTop::Missing, BestBidAskTop::Missing) => (None, None),
473        (BestBidAskTop::Missing, BestBidAskTop::Price(ask)) => (None, Some(ask)),
474        (BestBidAskTop::Price(bid), BestBidAskTop::Missing) => (Some(bid), None),
475        (BestBidAskTop::Price(bid), BestBidAskTop::Price(ask)) => (Some(bid), Some(ask)),
476    };
477
478    if drop_quotes_missing_side && (bid.is_none() || ask.is_none()) {
479        return Ok(None);
480    }
481
482    let (min_price, max_price) = quote_price_bounds(price_increment, tick_size)?;
483    let bid_price = bid.unwrap_or(min_price);
484    let ask_price = ask.unwrap_or(max_price);
485    if bid_price < min_price || ask_price > max_price || bid_price >= ask_price {
486        return Ok(None);
487    }
488
489    let size_at = |price: Option<Price>, top: Option<(Price, Quantity)>| match (price, top) {
490        (Some(price), Some((top_price, top_size))) if top_price == price => top_size,
491        _ => Quantity::zero(size_precision),
492    };
493
494    Ok(Some(QuoteTick::new_checked(
495        instrument_id,
496        bid_price,
497        ask_price,
498        size_at(bid, bid_top),
499        size_at(ask, ask_top),
500        ts_event,
501        ts_init,
502    )?))
503}
504
505fn quote_price_bounds(
506    price_increment: Price,
507    tick_size: Decimal,
508) -> anyhow::Result<(Price, Price)> {
509    let max_price = Price::from_decimal_dp(Decimal::ONE - tick_size, price_increment.precision)?;
510    Ok((price_increment, max_price))
511}
512
513fn parse_best_bid_ask_top(
514    value: Option<&str>,
515    precision: u8,
516    tick_size: Decimal,
517    is_missing: impl FnOnce(Decimal) -> bool,
518) -> CorrectnessResult<BestBidAskTop> {
519    let Some(value) = value else {
520        return Ok(BestBidAskTop::Missing);
521    };
522    let decimal = parse_decimal_exact(value).map_err(|e| CorrectnessError::PredicateViolation {
523        message: format!("Invalid price '{value}': {e}"),
524    })?;
525
526    if is_missing(decimal) {
527        return Ok(BestBidAskTop::Missing);
528    }
529
530    let price = Price::from_decimal_dp(decimal, precision)?;
531    if price.as_decimal() != decimal || decimal % tick_size != Decimal::ZERO {
532        return Ok(BestBidAskTop::Invalid);
533    }
534
535    Ok(BestBidAskTop::Price(price))
536}
537
538fn non_empty(value: &str) -> Option<&str> {
539    let value = value.trim();
540    (!value.is_empty()).then_some(value)
541}
542
543fn parse_bid_top(value: Option<&str>, precision: u8) -> CorrectnessResult<Option<Price>> {
544    parse_top_price(value, precision, |value| value <= Decimal::ZERO)
545}
546
547fn parse_ask_top(value: Option<&str>, precision: u8) -> CorrectnessResult<Option<Price>> {
548    parse_top_price(value, precision, |value| value >= Decimal::ONE)
549}
550
551fn parse_top_price(
552    value: Option<&str>,
553    precision: u8,
554    is_missing: impl FnOnce(Decimal) -> bool,
555) -> CorrectnessResult<Option<Price>> {
556    let Some(value) = value else {
557        return Ok(None);
558    };
559    let decimal = parse_decimal_exact(value).map_err(|e| CorrectnessError::PredicateViolation {
560        message: format!("Invalid price '{value}': {e}"),
561    })?;
562
563    if is_missing(decimal) {
564        return Ok(None);
565    }
566
567    Ok(Some(Price::from_decimal_dp(decimal, precision)?))
568}
569
570#[cfg(test)]
571mod tests {
572    use nautilus_core::UnixNanos;
573    use nautilus_model::instruments::{Instrument, InstrumentAny};
574    use rstest::rstest;
575    use ustr::Ustr;
576
577    use super::*;
578    use crate::{
579        http::parse::{
580            create_instrument_from_def, parse_gamma_market, rebuild_instrument_with_tick_size,
581        },
582        websocket::messages::PolymarketQuotes,
583    };
584
585    fn load<T: serde::de::DeserializeOwned>(filename: &str) -> T {
586        let content =
587            std::fs::read_to_string(format!("test_data/{filename}")).expect("test data missing");
588        serde_json::from_str(&content).expect("parse failed")
589    }
590
591    fn test_instrument() -> InstrumentAny {
592        let market: crate::http::models::GammaMarket = load("gamma_market.json");
593        let defs = parse_gamma_market(&market).unwrap();
594        create_instrument_from_def(&defs[0], UnixNanos::from(1_000_000_000u64)).unwrap()
595    }
596
597    fn test_instrument_with_tick(tick_size: &str) -> InstrumentAny {
598        let instrument = test_instrument();
599        let ts = UnixNanos::from(1_000_000_000u64);
600        rebuild_instrument_with_tick_size(&instrument, tick_size, ts, ts).unwrap()
601    }
602
603    #[rstest]
604    fn test_parse_timestamp_ms() {
605        let ns = parse_timestamp_ms("1703875200000").unwrap();
606        assert_eq!(ns, UnixNanos::from(1_703_875_200_000_000_000u64));
607    }
608
609    #[rstest]
610    fn test_parse_timestamp_ms_invalid() {
611        assert!(parse_timestamp_ms("not_a_number").is_err());
612    }
613
614    #[rstest]
615    fn test_book_snapshot_hash_matches_captured_v2_snapshot() {
616        let snap: PolymarketBookSnapshot = load("ws_book_snapshot_v2_captured.json");
617
618        assert_eq!(snap.version.as_deref(), Some("v2"));
619        assert_eq!(
620            book_snapshot_hash(&snap, None, None).unwrap(),
621            Some("8a112445c8ac8c7fc9e66d9a404e3530a4668d88".to_string())
622        );
623        assert!(verify_book_snapshot_hash(&snap, None, None).unwrap());
624    }
625
626    #[rstest]
627    fn test_book_snapshot_hash_matches_captured_snapshot() {
628        let snap: PolymarketBookSnapshot = load("ws_book_snapshot_captured.json");
629
630        assert_eq!(snap.min_order_size, None);
631        assert_eq!(snap.neg_risk, None);
632        assert_eq!(snap.tick_size.as_deref(), Some("0.01"));
633        assert_eq!(snap.last_trade_price.as_deref(), Some("0.920"));
634        assert_eq!(
635            book_snapshot_hash(&snap, Some("5"), Some(false)).unwrap(),
636            Some("ed47eb91f3c7985fac1cb18cb7c19535eddd3c0a".to_string())
637        );
638        assert!(verify_book_snapshot_hash(&snap, Some("5"), Some(false)).unwrap());
639    }
640
641    #[rstest]
642    fn test_book_snapshot_hash_rejects_mismatch() {
643        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot_captured.json");
644        snap.bids[0].size = "3149725.71".to_string();
645
646        let error = verify_book_snapshot_hash(&snap, Some("5"), Some(false)).unwrap_err();
647
648        assert_eq!(
649            error.to_string(),
650            concat!(
651                "Book snapshot hash mismatch for ",
652                "350977769852917329387037893294763093471844346281449484439085576212613048126: ",
653                "expected ed47eb91f3c7985fac1cb18cb7c19535eddd3c0a, ",
654                "computed 6402b534c270a1ce46a75c62f1d7e3651182cc75"
655            )
656        );
657    }
658
659    #[rstest]
660    #[case::missing(None, "87898258384b99c2c750cffe88735ff1017aaca7")]
661    #[case::changed(Some("v1"), "baf7e0f98650e72eec1ae9f158f901731416b189")]
662    fn test_book_snapshot_hash_v2_requires_captured_version(
663        #[case] version: Option<&str>,
664        #[case] computed: &str,
665    ) {
666        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot_v2_captured.json");
667        snap.version = version.map(str::to_string);
668
669        assert_eq!(
670            book_snapshot_hash(&snap, None, None).unwrap(),
671            Some(computed.to_string())
672        );
673        assert_eq!(
674            verify_book_snapshot_hash(&snap, None, None)
675                .unwrap_err()
676                .to_string(),
677            format!(
678                "Book snapshot hash mismatch for {}: expected {}, computed {computed}",
679                snap.asset_id,
680                snap.hash.as_deref().unwrap()
681            )
682        );
683    }
684
685    #[rstest]
686    fn test_book_snapshot_hash_v2_rejects_corrupted_book() {
687        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot_v2_captured.json");
688        snap.bids[0].size = "32".to_string();
689
690        assert_eq!(
691            verify_book_snapshot_hash(&snap, None, None)
692                .unwrap_err()
693                .to_string(),
694            format!(
695                "Book snapshot hash mismatch for {}: expected {}, computed a000d2ac896d14ce413a2f164eb6fb94dc98bf4a",
696                snap.asset_id,
697                snap.hash.as_deref().unwrap()
698            )
699        );
700    }
701
702    #[rstest]
703    fn test_book_snapshot_hash_allows_missing_hash() {
704        let snap: PolymarketBookSnapshot = load("ws_book_snapshot_missing_hash.json");
705
706        assert!(!verify_book_snapshot_hash(&snap, None, None).unwrap());
707    }
708
709    #[rstest]
710    fn test_book_snapshot_hash_allows_incomplete_preimage() {
711        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot_captured.json");
712        snap.tick_size = None;
713        snap.last_trade_price = None;
714
715        assert!(!verify_book_snapshot_hash(&snap, Some("5"), Some(false)).unwrap());
716    }
717
718    #[rstest]
719    fn test_parse_book_snapshot() {
720        let snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
721        let instrument = test_instrument();
722        let ts_init = UnixNanos::from(1_000_000_000u64);
723
724        let deltas = parse_book_snapshot(
725            &snap,
726            instrument.id(),
727            instrument.price_precision(),
728            instrument.size_precision(),
729            ts_init,
730        )
731        .unwrap();
732
733        // CLEAR + 3 bids + 3 asks = 7 deltas
734        assert_eq!(deltas.deltas.len(), 7);
735        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
736        assert_eq!(deltas.deltas[1].action, BookAction::Add);
737        assert_eq!(deltas.deltas[1].order.side, Some(OrderSide::Buy));
738        assert_eq!(deltas.deltas[4].action, BookAction::Add);
739        assert_eq!(deltas.deltas[4].order.side, Some(OrderSide::Sell));
740
741        // Every snapshot delta carries F_SNAPSHOT
742        for delta in &deltas.deltas {
743            assert_ne!(delta.flags & RecordFlag::F_SNAPSHOT as u8, 0);
744        }
745
746        // Exactly one delta carries F_LAST, and it must be the last one
747        let f_last_count = deltas
748            .deltas
749            .iter()
750            .filter(|d| d.flags & RecordFlag::F_LAST as u8 != 0)
751            .count();
752        assert_eq!(f_last_count, 1);
753        assert_ne!(
754            deltas.deltas.last().unwrap().flags & RecordFlag::F_LAST as u8,
755            0
756        );
757    }
758
759    #[rstest]
760    #[case::bids_only(OrderSide::Buy, "0.48", "500.00")]
761    #[case::asks_only(OrderSide::Sell, "0.53", "400.00")]
762    fn test_parse_book_snapshot_single_side(
763        #[case] side: OrderSide,
764        #[case] price: &str,
765        #[case] size: &str,
766    ) {
767        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
768
769        match side {
770            OrderSide::Buy => {
771                snap.bids.truncate(1);
772                snap.asks.clear();
773            }
774            OrderSide::Sell => {
775                snap.bids.clear();
776                snap.asks.truncate(1);
777            }
778        }
779
780        let instrument_id = InstrumentId::from("test.POLYMARKET");
781        let ts_event = UnixNanos::from(1_703_875_200_000_000_000u64);
782        let ts_init = UnixNanos::from(1_000_000_000u64);
783        let deltas = parse_book_snapshot(&snap, instrument_id, 2, 2, ts_init).unwrap();
784        let order = BookOrder::new(side, Price::from(price), Quantity::from(size), 0);
785        let last = OrderBookDelta::new_checked(
786            instrument_id,
787            BookAction::Add,
788            order,
789            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8,
790            0,
791            ts_event,
792            ts_init,
793        )
794        .unwrap();
795
796        assert_eq!(
797            deltas.deltas,
798            vec![
799                OrderBookDelta::clear(instrument_id, 0, ts_event, ts_init),
800                last
801            ]
802        );
803    }
804
805    #[rstest]
806    fn test_parse_book_snapshot_empty_book_parses_to_lone_clear() {
807        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
808        snap.bids.clear();
809        snap.asks.clear();
810        let instrument = test_instrument();
811        let ts_init = UnixNanos::from(1_000_000_000u64);
812
813        let deltas = parse_book_snapshot(
814            &snap,
815            instrument.id(),
816            instrument.price_precision(),
817            instrument.size_precision(),
818            ts_init,
819        )
820        .unwrap();
821
822        assert_eq!(deltas.deltas.len(), 1);
823        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
824        assert_ne!(deltas.deltas[0].flags & RecordFlag::F_SNAPSHOT as u8, 0);
825        assert_ne!(deltas.deltas[0].flags & RecordFlag::F_LAST as u8, 0);
826    }
827
828    #[rstest]
829    fn test_parse_book_deltas() {
830        let quotes: PolymarketQuotes = load("ws_quotes.json");
831        let instrument = test_instrument();
832        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
833        let ts_init = UnixNanos::from(1_000_000_000u64);
834        let changes = quotes.price_changes.iter().collect::<Vec<_>>();
835
836        let deltas = parse_book_deltas(
837            &changes,
838            instrument.id(),
839            instrument.price_precision(),
840            instrument.size_precision(),
841            ts_event,
842            ts_init,
843        )
844        .into_iter()
845        .collect::<anyhow::Result<Vec<_>>>()
846        .unwrap();
847
848        assert_eq!(deltas.len(), 2);
849
850        // Exactly one delta carries F_LAST, and it must be the last one
851        let f_last_count = deltas
852            .iter()
853            .filter(|d| d.flags & RecordFlag::F_LAST as u8 != 0)
854            .count();
855        assert_eq!(f_last_count, 1);
856        assert_ne!(deltas.last().unwrap().flags & RecordFlag::F_LAST as u8, 0);
857    }
858
859    #[rstest]
860    fn test_parse_book_deltas_zero_size_is_delete() {
861        let mut quotes: PolymarketQuotes = load("ws_quotes.json");
862        quotes.price_changes[0].size = "0".to_string();
863        let instrument = test_instrument();
864        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
865        let ts_init = UnixNanos::from(1_000_000_000u64);
866        let changes = quotes.price_changes.iter().collect::<Vec<_>>();
867
868        let deltas = parse_book_deltas(
869            &changes,
870            instrument.id(),
871            instrument.price_precision(),
872            instrument.size_precision(),
873            ts_event,
874            ts_init,
875        )
876        .into_iter()
877        .collect::<anyhow::Result<Vec<_>>>()
878        .unwrap();
879
880        assert_eq!(deltas[0].action, BookAction::Delete);
881    }
882
883    #[rstest]
884    fn test_parse_trade_tick() {
885        let trade: PolymarketTrade = load("ws_last_trade.json");
886        let instrument = test_instrument();
887        let ts_init = UnixNanos::from(1_000_000_000u64);
888
889        let tick = parse_trade_tick(
890            &trade,
891            instrument.id(),
892            instrument.price_precision(),
893            instrument.size_precision(),
894            ts_init,
895        )
896        .unwrap();
897
898        assert_eq!(tick.instrument_id, instrument.id());
899        assert_eq!(tick.aggressor_side, AggressorSide::Buy);
900        assert_eq!(tick.ts_event, UnixNanos::from(1_703_875_202_000_000_000u64));
901    }
902
903    #[rstest]
904    fn test_parse_trade_tick_deterministic_id() {
905        let trade: PolymarketTrade = load("ws_last_trade.json");
906        let instrument = test_instrument();
907        let ts_init = UnixNanos::from(1_000_000_000u64);
908
909        let tick1 = parse_trade_tick(
910            &trade,
911            instrument.id(),
912            instrument.price_precision(),
913            instrument.size_precision(),
914            ts_init,
915        )
916        .unwrap();
917        let tick2 = parse_trade_tick(
918            &trade,
919            instrument.id(),
920            instrument.price_precision(),
921            instrument.size_precision(),
922            ts_init,
923        )
924        .unwrap();
925
926        assert_eq!(tick1.trade_id, tick2.trade_id);
927    }
928
929    #[rstest]
930    fn test_parse_quote_from_snapshot() {
931        let snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
932        let instrument = test_instrument();
933        let ts_init = UnixNanos::from(1_000_000_000u64);
934
935        let quote = parse_quote_from_snapshot(
936            &snap,
937            instrument.id(),
938            instrument.price_precision(),
939            instrument.size_precision(),
940            instrument.price_increment(),
941            true,
942            ts_init,
943        )
944        .unwrap()
945        .unwrap();
946
947        assert_eq!(quote.instrument_id, instrument.id());
948        assert_eq!(quote.bid_price, Price::from("0.50"));
949        assert_eq!(quote.ask_price, Price::from("0.51"));
950        assert_eq!(
951            quote.ts_event,
952            UnixNanos::from(1_703_875_200_000_000_000u64)
953        );
954    }
955
956    #[rstest]
957    fn test_parse_quote_from_snapshot_empty_side_returns_none() {
958        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
959        snap.bids.clear();
960        let instrument = test_instrument();
961        let ts_init = UnixNanos::from(1_000_000_000u64);
962
963        let result = parse_quote_from_snapshot(
964            &snap,
965            instrument.id(),
966            instrument.price_precision(),
967            instrument.size_precision(),
968            instrument.price_increment(),
969            true,
970            ts_init,
971        )
972        .unwrap();
973
974        assert!(result.is_none());
975    }
976
977    #[rstest]
978    fn test_parse_quote_from_snapshot_empty_side_uses_boundary_when_drop_disabled() {
979        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
980        snap.asks.clear();
981        let instrument = test_instrument_with_tick("0.005");
982        let ts_init = UnixNanos::from(1_000_000_000u64);
983
984        let quote = parse_quote_from_snapshot(
985            &snap,
986            instrument.id(),
987            instrument.price_precision(),
988            instrument.size_precision(),
989            instrument.price_increment(),
990            false,
991            ts_init,
992        )
993        .unwrap()
994        .expect("quote should use boundary ask when drop is disabled");
995
996        assert_eq!(quote.bid_price, Price::from("0.50"));
997        assert_eq!(quote.bid_size, Quantity::from("200.00"));
998        assert_eq!(quote.ask_price, Price::from("0.995"));
999        assert_eq!(quote.ask_size, Quantity::from("0.00"));
1000    }
1001
1002    #[rstest]
1003    fn test_parse_quote_from_snapshot_empty_bid_uses_boundary_when_drop_disabled() {
1004        let mut snap: PolymarketBookSnapshot = load("ws_book_snapshot.json");
1005        snap.bids.clear();
1006        let instrument = test_instrument_with_tick("0.0025");
1007        let ts_init = UnixNanos::from(1_000_000_000u64);
1008
1009        let quote = parse_quote_from_snapshot(
1010            &snap,
1011            instrument.id(),
1012            instrument.price_precision(),
1013            instrument.size_precision(),
1014            instrument.price_increment(),
1015            false,
1016            ts_init,
1017        )
1018        .unwrap()
1019        .expect("quote should use boundary bid when drop is disabled");
1020
1021        assert_eq!(quote.bid_price, Price::from("0.0025"));
1022        assert_eq!(quote.bid_size, Quantity::from("0.00"));
1023        assert_eq!(quote.ask_price, Price::from("0.51"));
1024        assert_eq!(quote.ask_size, Quantity::from("150.00"));
1025    }
1026
1027    #[rstest]
1028    fn test_parse_quote_from_price_change() {
1029        let quotes: PolymarketQuotes = load("ws_quotes.json");
1030        let instrument = test_instrument();
1031        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
1032        let ts_init = UnixNanos::from(1_000_000_000u64);
1033
1034        let quote = parse_quote_from_price_change(
1035            &quotes.price_changes[0],
1036            instrument.id(),
1037            instrument.price_precision(),
1038            instrument.size_precision(),
1039            instrument.price_increment(),
1040            true,
1041            None,
1042            ts_event,
1043            ts_init,
1044        )
1045        .unwrap()
1046        .expect("quote should be Some when best_bid/best_ask present");
1047
1048        assert_eq!(quote.instrument_id, instrument.id());
1049    }
1050
1051    #[rstest]
1052    #[case::buy_top(PolymarketOrderSide::Buy, "0.50", "0.50", "0.52", "37", "37", "75")]
1053    #[case::sell_top(PolymarketOrderSide::Sell, "0.52", "0.50", "0.52", "37", "100", "37")]
1054    #[case::buy_deeper(PolymarketOrderSide::Buy, "0.49", "0.50", "0.52", "37", "100", "75")]
1055    #[case::sell_deeper(PolymarketOrderSide::Sell, "0.53", "0.50", "0.52", "37", "100", "75")]
1056    #[case::buy_removed(PolymarketOrderSide::Buy, "0.50", "0.49", "0.52", "0", "0", "75")]
1057    #[case::sell_removed(PolymarketOrderSide::Sell, "0.52", "0.50", "0.53", "0", "100", "0")]
1058    #[case::buy_opposite_moved(PolymarketOrderSide::Buy, "0.50", "0.50", "0.53", "37", "37", "0")]
1059    #[case::sell_opposite_moved(PolymarketOrderSide::Sell, "0.52", "0.49", "0.52", "37", "0", "37")]
1060    fn test_parse_quote_from_price_change_sizes_only_matching_tops(
1061        #[case] side: PolymarketOrderSide,
1062        #[case] changed_price: &str,
1063        #[case] best_bid: &str,
1064        #[case] best_ask: &str,
1065        #[case] changed_size: &str,
1066        #[case] bid_size: &str,
1067        #[case] ask_size: &str,
1068    ) {
1069        let instrument_id = InstrumentId::from("TEST.POLYMARKET");
1070
1071        let last_quote = QuoteTick::new(
1072            instrument_id,
1073            Price::from("0.50"),
1074            Price::from("0.52"),
1075            Quantity::from("100.00"),
1076            Quantity::from("75.00"),
1077            UnixNanos::from(1_000_000u64),
1078            UnixNanos::from(2_000_000u64),
1079        );
1080
1081        let change = PolymarketQuote {
1082            asset_id: Ustr::from("TEST"),
1083            price: changed_price.to_string(),
1084            size: changed_size.to_string(),
1085            side,
1086            hash: String::new(),
1087            best_bid: Some(best_bid.to_string()),
1088            best_ask: Some(best_ask.to_string()),
1089        };
1090
1091        let ts_event = UnixNanos::from(3_000_000u64);
1092        let ts_init = UnixNanos::from(4_000_000u64);
1093        let quote = parse_quote_from_price_change(
1094            &change,
1095            instrument_id,
1096            2,
1097            2,
1098            Price::from("0.01"),
1099            true,
1100            Some(&last_quote),
1101            ts_event,
1102            ts_init,
1103        )
1104        .unwrap()
1105        .unwrap();
1106
1107        let expected = QuoteTick::new(
1108            instrument_id,
1109            Price::from(best_bid),
1110            Price::from(best_ask),
1111            quantity(bid_size, 2),
1112            quantity(ask_size, 2),
1113            ts_event,
1114            ts_init,
1115        );
1116
1117        assert_eq!(quote, expected);
1118    }
1119
1120    #[rstest]
1121    #[case(None)]
1122    #[case(Some("1"))]
1123    fn test_parse_quote_from_price_change_missing_side_drops_by_default(
1124        #[case] best_ask: Option<&str>,
1125    ) {
1126        let mut quotes: PolymarketQuotes = load("ws_quotes.json");
1127        quotes.price_changes[0].best_ask = best_ask.map(str::to_string);
1128        let instrument = test_instrument();
1129        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
1130        let ts_init = UnixNanos::from(1_000_000_000u64);
1131
1132        let result = parse_quote_from_price_change(
1133            &quotes.price_changes[0],
1134            instrument.id(),
1135            instrument.price_precision(),
1136            instrument.size_precision(),
1137            instrument.price_increment(),
1138            true,
1139            None,
1140            ts_event,
1141            ts_init,
1142        )
1143        .unwrap();
1144
1145        assert!(result.is_none());
1146    }
1147
1148    #[rstest]
1149    #[case(None)]
1150    #[case(Some("1"))]
1151    fn test_parse_quote_from_price_change_missing_side_uses_boundary_when_drop_disabled(
1152        #[case] best_ask: Option<&str>,
1153    ) {
1154        let mut quotes: PolymarketQuotes = load("ws_quotes.json");
1155        quotes.price_changes[0].best_ask = best_ask.map(str::to_string);
1156        let instrument = test_instrument_with_tick("0.005");
1157        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
1158        let ts_init = UnixNanos::from(1_000_000_000u64);
1159
1160        let quote = parse_quote_from_price_change(
1161            &quotes.price_changes[0],
1162            instrument.id(),
1163            instrument.price_precision(),
1164            instrument.size_precision(),
1165            instrument.price_increment(),
1166            false,
1167            None,
1168            ts_event,
1169            ts_init,
1170        )
1171        .unwrap()
1172        .expect("quote should use boundary ask when drop is disabled");
1173
1174        assert_eq!(quote.bid_price, Price::from("0.51"));
1175        assert_eq!(quote.bid_size, Quantity::from("150.00"));
1176        assert_eq!(quote.ask_price, Price::from("0.995"));
1177        assert_eq!(quote.ask_size, Quantity::from("0.00"));
1178    }
1179
1180    #[rstest]
1181    fn test_parse_quote_from_price_change_missing_bid_uses_boundary_when_drop_disabled() {
1182        let mut quotes: PolymarketQuotes = load("ws_quotes.json");
1183        quotes.price_changes[0].side = PolymarketOrderSide::Sell;
1184        quotes.price_changes[0].price = "0.52".to_string();
1185        quotes.price_changes[0].size = "75".to_string();
1186        quotes.price_changes[0].best_bid = Some("0".to_string());
1187        quotes.price_changes[0].best_ask = Some("0.52".to_string());
1188        let instrument = test_instrument_with_tick("0.0025");
1189        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
1190        let ts_init = UnixNanos::from(1_000_000_000u64);
1191
1192        let quote = parse_quote_from_price_change(
1193            &quotes.price_changes[0],
1194            instrument.id(),
1195            instrument.price_precision(),
1196            instrument.size_precision(),
1197            instrument.price_increment(),
1198            false,
1199            None,
1200            ts_event,
1201            ts_init,
1202        )
1203        .unwrap()
1204        .expect("quote should use boundary bid when drop is disabled");
1205
1206        assert_eq!(quote.bid_price, Price::from("0.0025"));
1207        assert_eq!(quote.bid_size, Quantity::from("0.00"));
1208        assert_eq!(quote.ask_price, Price::from("0.52"));
1209        assert_eq!(quote.ask_size, Quantity::from("75.00"));
1210    }
1211
1212    #[rstest]
1213    fn test_parse_quote_from_price_change_crossed_top_returns_none() {
1214        let mut quotes: PolymarketQuotes = load("ws_quotes.json");
1215        quotes.price_changes[0].best_bid = Some("0.70".to_string());
1216        quotes.price_changes[0].best_ask = Some("0.60".to_string());
1217        let instrument = test_instrument();
1218        let ts_event = parse_timestamp_ms(&quotes.timestamp).unwrap();
1219        let ts_init = UnixNanos::from(1_000_000_000u64);
1220
1221        let result = parse_quote_from_price_change(
1222            &quotes.price_changes[0],
1223            instrument.id(),
1224            instrument.price_precision(),
1225            instrument.size_precision(),
1226            instrument.price_increment(),
1227            false,
1228            None,
1229            ts_event,
1230            ts_init,
1231        )
1232        .unwrap();
1233
1234        assert!(result.is_none());
1235    }
1236
1237    fn best_bid_ask(best_bid: &str, best_ask: &str) -> PolymarketBestBidAsk {
1238        PolymarketBestBidAsk {
1239            market: Ustr::from("0xMARKET"),
1240            asset_id: Ustr::from("0xTOKEN"),
1241            best_bid: best_bid.to_string(),
1242            best_ask: best_ask.to_string(),
1243            spread: String::new(),
1244            timestamp: "1700000003000".to_string(),
1245        }
1246    }
1247
1248    fn quantity(value: &str, precision: u8) -> Quantity {
1249        Quantity::from_decimal_dp(value.parse().unwrap(), precision).unwrap()
1250    }
1251
1252    #[rstest]
1253    fn test_parse_quote_from_best_bid_ask_sizes_only_matching_tops() {
1254        let instrument = test_instrument();
1255        let size_precision = instrument.size_precision();
1256        let ts_event = UnixNanos::from(1_700_000_003_000_000_000u64);
1257        let ts_init = UnixNanos::from(1_000_000_000u64);
1258
1259        let quote = parse_quote_from_best_bid_ask(
1260            &best_bid_ask("0.50", "0.52"),
1261            instrument.id(),
1262            instrument.price_precision(),
1263            size_precision,
1264            instrument.price_increment(),
1265            true,
1266            Some((Price::from("0.50"), quantity("100.00", size_precision))),
1267            Some((Price::from("0.51"), quantity("75.00", size_precision))),
1268            ts_event,
1269            ts_init,
1270        )
1271        .unwrap()
1272        .unwrap();
1273
1274        assert_eq!(quote.instrument_id, instrument.id());
1275        assert_eq!(quote.bid_price, Price::from("0.50"));
1276        assert_eq!(quote.ask_price, Price::from("0.52"));
1277        assert_eq!(quote.bid_size, quantity("100.00", size_precision));
1278        assert_eq!(quote.ask_size, Quantity::zero(size_precision));
1279        assert_eq!(quote.ts_event, ts_event);
1280        assert_eq!(quote.ts_init, ts_init);
1281    }
1282
1283    #[rstest]
1284    #[case("0", "0.52")]
1285    #[case("0.50", "1")]
1286    #[case("", "0.52")]
1287    #[case("0.50", "")]
1288    fn test_parse_quote_from_best_bid_ask_missing_side_drops_by_default(
1289        #[case] best_bid: &str,
1290        #[case] best_ask: &str,
1291    ) {
1292        let instrument = test_instrument();
1293
1294        let result = parse_quote_from_best_bid_ask(
1295            &best_bid_ask(best_bid, best_ask),
1296            instrument.id(),
1297            instrument.price_precision(),
1298            instrument.size_precision(),
1299            instrument.price_increment(),
1300            true,
1301            None,
1302            None,
1303            UnixNanos::default(),
1304            UnixNanos::default(),
1305        )
1306        .unwrap();
1307
1308        assert!(result.is_none());
1309    }
1310
1311    #[rstest]
1312    #[case("0", "0.52", "0.01", "0.52", "0.00", "75.00")]
1313    #[case("0.50", "1", "0.50", "0.99", "100.00", "0.00")]
1314    fn test_parse_quote_from_best_bid_ask_missing_side_uses_tick_bound(
1315        #[case] best_bid: &str,
1316        #[case] best_ask: &str,
1317        #[case] expected_bid: &str,
1318        #[case] expected_ask: &str,
1319        #[case] expected_bid_size: &str,
1320        #[case] expected_ask_size: &str,
1321    ) {
1322        let instrument = test_instrument_with_tick("0.01");
1323        let size_precision = instrument.size_precision();
1324
1325        let quote = parse_quote_from_best_bid_ask(
1326            &best_bid_ask(best_bid, best_ask),
1327            instrument.id(),
1328            instrument.price_precision(),
1329            size_precision,
1330            instrument.price_increment(),
1331            false,
1332            Some((Price::from("0.50"), quantity("100.00", size_precision))),
1333            Some((Price::from("0.52"), quantity("75.00", size_precision))),
1334            UnixNanos::default(),
1335            UnixNanos::default(),
1336        )
1337        .unwrap()
1338        .unwrap();
1339
1340        assert_eq!(quote.instrument_id, instrument.id());
1341        assert_eq!(quote.bid_price, Price::from(expected_bid));
1342        assert_eq!(quote.ask_price, Price::from(expected_ask));
1343        assert_eq!(quote.bid_size, quantity(expected_bid_size, size_precision));
1344        assert_eq!(quote.ask_size, quantity(expected_ask_size, size_precision));
1345        assert_eq!(quote.ts_event, UnixNanos::default());
1346        assert_eq!(quote.ts_init, UnixNanos::default());
1347    }
1348
1349    #[rstest]
1350    #[case("0.60", "0.60")]
1351    #[case("0.70", "0.60")]
1352    #[case("1.10", "1")]
1353    #[case("0", "-0.10")]
1354    fn test_parse_quote_from_best_bid_ask_invalid_range_returns_none(
1355        #[case] best_bid: &str,
1356        #[case] best_ask: &str,
1357    ) {
1358        let instrument = test_instrument_with_tick("0.01");
1359
1360        let result = parse_quote_from_best_bid_ask(
1361            &best_bid_ask(best_bid, best_ask),
1362            instrument.id(),
1363            instrument.price_precision(),
1364            instrument.size_precision(),
1365            instrument.price_increment(),
1366            false,
1367            None,
1368            None,
1369            UnixNanos::default(),
1370            UnixNanos::default(),
1371        )
1372        .unwrap();
1373
1374        assert!(result.is_none());
1375    }
1376
1377    #[rstest]
1378    #[case("0.505", "0.52")]
1379    #[case("0.50", "0.525")]
1380    fn test_parse_quote_from_best_bid_ask_off_grid_returns_none(
1381        #[case] best_bid: &str,
1382        #[case] best_ask: &str,
1383    ) {
1384        let instrument = test_instrument_with_tick("0.01");
1385        assert_eq!(instrument.price_precision(), 4);
1386        assert_eq!(instrument.price_increment(), Price::from("0.01"));
1387        assert_eq!(instrument.price_increment().precision, 4);
1388
1389        let result = parse_quote_from_best_bid_ask(
1390            &best_bid_ask(best_bid, best_ask),
1391            instrument.id(),
1392            instrument.price_precision(),
1393            instrument.size_precision(),
1394            instrument.price_increment(),
1395            false,
1396            None,
1397            None,
1398            UnixNanos::default(),
1399            UnixNanos::default(),
1400        )
1401        .unwrap();
1402
1403        assert!(result.is_none());
1404    }
1405}