Skip to main content

nautilus_coinapi/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//! Conversion of CoinAPI WebSocket messages into Nautilus market data.
17//!
18//! Instrument precisions come from CoinAPI data resolutions, which can lag the stream. A value
19//! with more decimal places than its instrument precision is rejected, except for bounded
20//! numeric tails in OHLCV volume.
21
22use jiff::Timestamp;
23use nautilus_core::UnixNanos;
24use nautilus_model::{
25    data::{
26        Bar, BarSpecification, BarType, BookOrder, OrderBookDelta, OrderBookDeltas, OrderBookDepth,
27        QuoteTick, TradeTick,
28    },
29    enums::{
30        AggregationSource, AggressorSide, BarAggregation, BookAction, OrderSide, PriceType,
31        RecordFlag,
32    },
33    identifiers::TradeId,
34    instruments::{Instrument, InstrumentAny},
35    types::{Price, Quantity},
36};
37use rust_decimal::{Decimal, RoundingStrategy};
38use strum::VariantNames;
39
40use super::messages::{Book, Ohlcv, Quote, Trade};
41use crate::{
42    common::enums::{OhlcvPeriod, TakerSide},
43    http::{models::BookLevel, parse::unix_nanos},
44};
45
46/// Converts a full L2 `book` snapshot or update into deltas, taking `ts_event` from
47/// `time_exchange` and `ts_init` from `time_coinapi`.
48///
49/// A snapshot becomes a `Clear` followed by an `Add` per level, every delta flagged `F_SNAPSHOT`;
50/// an empty snapshot is a lone `Clear`. An update sets each listed level to its new size, and a
51/// zero size removes the level. The last delta carries `F_LAST`, and an update listing no levels
52/// returns `None`.
53///
54/// # Errors
55///
56/// Returns an error if a level is finer than the instrument precision, a snapshot level has zero
57/// size, or a timestamp is invalid; a single invalid level rejects the whole message.
58pub fn parse_book_deltas(
59    book: &Book,
60    instrument: &InstrumentAny,
61) -> anyhow::Result<Option<OrderBookDeltas>> {
62    let instrument_id = instrument.id();
63    let ts_event = timestamp(book.time_exchange, "time_exchange")?;
64    let ts_init = timestamp(book.time_coinapi, "time_coinapi")?;
65    let is_snapshot = book.is_snapshot == Some(true);
66    let mut deltas = Vec::with_capacity(book.bids.len() + book.asks.len() + 1);
67    let flags = if is_snapshot {
68        deltas.push(OrderBookDelta::clear(
69            instrument_id,
70            book.sequence,
71            ts_event,
72            ts_init,
73        ));
74        RecordFlag::F_SNAPSHOT as u8
75    } else {
76        0
77    };
78
79    for (side, level) in levels(book) {
80        let order = book_order(side, level, instrument)?;
81
82        let action = if is_snapshot {
83            BookAction::Add
84        } else if order.size.is_zero() {
85            BookAction::Delete
86        } else {
87            BookAction::Update
88        };
89
90        deltas.push(OrderBookDelta::new_checked(
91            instrument_id,
92            action,
93            order,
94            flags,
95            book.sequence,
96            ts_event,
97            ts_init,
98        )?);
99    }
100
101    let Some(last) = deltas.last_mut() else {
102        return Ok(None);
103    };
104
105    last.flags |= RecordFlag::F_LAST as u8;
106
107    Ok(Some(OrderBookDeltas::new(instrument_id, deltas)))
108}
109
110/// Converts a fixed-depth `book5`, `book20`, or `book50` message into its best `depth` levels
111/// per side, taking `ts_event` from `time_exchange` and `ts_init` from `time_coinapi`.
112///
113/// CoinAPI reports no order counts, so every level count is zero.
114///
115/// # Errors
116///
117/// Returns an error if a kept level is finer than the instrument precision or a timestamp is
118/// invalid.
119pub fn parse_book_depth(
120    book: &Book,
121    depth: usize,
122    instrument: &InstrumentAny,
123) -> anyhow::Result<OrderBookDepth> {
124    let side = |side: OrderSide, levels: &[BookLevel]| {
125        levels
126            .iter()
127            .take(depth)
128            .map(|level| book_order(side, level, instrument))
129            .collect::<anyhow::Result<Vec<BookOrder>>>()
130    };
131
132    let bids = side(OrderSide::Buy, &book.bids)?;
133    let asks = side(OrderSide::Sell, &book.asks)?;
134    let bid_counts = vec![0; bids.len()];
135    let ask_counts = vec![0; asks.len()];
136
137    OrderBookDepth::new_checked(
138        instrument.id(),
139        bids,
140        asks,
141        bid_counts,
142        ask_counts,
143        RecordFlag::F_SNAPSHOT as u8,
144        book.sequence,
145        timestamp(book.time_exchange, "time_exchange")?,
146        timestamp(book.time_coinapi, "time_coinapi")?,
147    )
148}
149
150/// Converts a best bid and ask, taking `ts_event` from `time_exchange` and `ts_init` from
151/// `time_coinapi`.
152///
153/// # Errors
154///
155/// Returns an error if a value is finer than the instrument precision or a timestamp is invalid.
156pub fn parse_quote_tick(quote: &Quote, instrument: &InstrumentAny) -> anyhow::Result<QuoteTick> {
157    QuoteTick::new_checked(
158        instrument.id(),
159        price(quote.bid_price, instrument, "bid_price")?,
160        price(quote.ask_price, instrument, "ask_price")?,
161        quantity(quote.bid_size, instrument, "bid_size")?,
162        quantity(quote.ask_size, instrument, "ask_size")?,
163        timestamp(quote.time_exchange, "time_exchange")?,
164        timestamp(quote.time_coinapi, "time_coinapi")?,
165    )
166}
167
168/// Converts a trade, taking `ts_event` from `time_exchange` and `ts_init` from `time_coinapi`.
169///
170/// Only exchange-reported taker sides set the aggressor; CoinAPI estimates and unknown sides
171/// become [`AggressorSide::NoAggressor`].
172///
173/// # Errors
174///
175/// Returns an error if a value is finer than the instrument precision, the size is not positive, or
176/// a timestamp or the trade identifier is invalid.
177pub fn parse_trade_tick(trade: &Trade, instrument: &InstrumentAny) -> anyhow::Result<TradeTick> {
178    TradeTick::new_checked(
179        instrument.id(),
180        price(trade.price, instrument, "price")?,
181        quantity(trade.size, instrument, "size")?,
182        parse_aggressor_side(trade.taker_side),
183        TradeId::new_checked(&trade.uuid)?,
184        timestamp(trade.time_exchange, "time_exchange")?,
185        timestamp(trade.time_coinapi, "time_coinapi")?,
186    )
187}
188
189/// Converts a completed OHLCV period into an external last-price bar closing at
190/// `time_period_end`.
191///
192/// Rounds volume to the instrument's size precision when the adjustment is at most both
193/// `1e-15` times the reported volume and `1e-6` times one unit at that precision.
194///
195/// # Errors
196///
197/// Returns an error if the period is unsupported, a price is finer than the instrument precision,
198/// volume needs rounding beyond the noise tolerance, the prices are inconsistent, or a timestamp is
199/// invalid.
200pub fn parse_bar(
201    ohlcv: &Ohlcv,
202    instrument: &InstrumentAny,
203    ts_init: UnixNanos,
204) -> anyhow::Result<Bar> {
205    let spec = period_id_to_bar_spec(ohlcv.period_id)
206        .ok_or_else(|| anyhow::anyhow!("unsupported period_id {}", ohlcv.period_id))?;
207
208    Bar::new_checked(
209        BarType::new(instrument.id(), spec, AggregationSource::External),
210        price(ohlcv.price_open, instrument, "price_open")?,
211        price(ohlcv.price_high, instrument, "price_high")?,
212        price(ohlcv.price_low, instrument, "price_low")?,
213        price(ohlcv.price_close, instrument, "price_close")?,
214        volume(ohlcv.volume_traded, instrument)?,
215        timestamp(ohlcv.time_period_end, "time_period_end")?,
216        ts_init,
217    )
218}
219
220/// Maps an exchange taker side to the aggressor side.
221#[must_use]
222pub fn parse_aggressor_side(taker_side: TakerSide) -> AggressorSide {
223    match taker_side {
224        TakerSide::Buy => AggressorSide::Buy,
225        TakerSide::Sell => AggressorSide::Sell,
226        TakerSide::BuyEstimated | TakerSide::SellEstimated | TakerSide::Unknown => {
227            AggressorSide::NoAggressor
228        }
229        TakerSide::Other(other) => {
230            log::warn!("Unknown CoinAPI taker_side {other}, using no aggressor");
231            AggressorSide::NoAggressor
232        }
233    }
234}
235
236/// Returns the CoinAPI streaming `period_id` for a last-price bar specification.
237///
238/// CoinAPI streams OHLCV periods from one second to one day.
239///
240/// # Errors
241///
242/// Returns an error if the price type is not last or CoinAPI has no matching period.
243pub fn bar_spec_to_period_id(spec: BarSpecification) -> anyhow::Result<OhlcvPeriod> {
244    anyhow::ensure!(
245        spec.price_type == PriceType::Last,
246        "CoinAPI OHLCV bars use last prices, was {}",
247        spec.price_type
248    );
249
250    let step = spec.step.get();
251
252    let unit = match spec.aggregation {
253        BarAggregation::Second => "SEC",
254        BarAggregation::Minute => "MIN",
255        BarAggregation::Hour => "HRS",
256        BarAggregation::Day if step == 1 => "DAY",
257        _ => anyhow::bail!("CoinAPI has no streaming OHLCV period for {spec}"),
258    };
259
260    let period = format!("{step}{unit}");
261    anyhow::ensure!(
262        OhlcvPeriod::VARIANTS.contains(&period.as_str()),
263        "CoinAPI has no streaming OHLCV period for {spec}"
264    );
265    Ok(period.as_str().into())
266}
267
268/// Returns the last-price bar specification for a CoinAPI streaming `period_id`.
269#[must_use]
270pub fn period_id_to_bar_spec(period_id: OhlcvPeriod) -> Option<BarSpecification> {
271    let period = period_id.as_ref();
272    let split = period.find(|c: char| !c.is_ascii_digit())?;
273    let (step, unit) = period.split_at(split);
274
275    let aggregation = match unit {
276        "SEC" => BarAggregation::Second,
277        "MIN" => BarAggregation::Minute,
278        "HRS" => BarAggregation::Hour,
279        "DAY" => BarAggregation::Day,
280        _ => return None,
281    };
282
283    let spec =
284        BarSpecification::new_checked(step.parse().ok()?, aggregation, PriceType::Last).ok()?;
285
286    // Rejects leading zeros and steps CoinAPI does not stream
287    (bar_spec_to_period_id(spec).ok()? == period_id).then_some(spec)
288}
289
290fn levels(book: &Book) -> impl Iterator<Item = (OrderSide, &BookLevel)> {
291    let bids = book.bids.iter().map(|level| (OrderSide::Buy, level));
292    let asks = book.asks.iter().map(|level| (OrderSide::Sell, level));
293    bids.chain(asks)
294}
295
296fn book_order(
297    side: OrderSide,
298    level: &BookLevel,
299    instrument: &InstrumentAny,
300) -> anyhow::Result<BookOrder> {
301    Ok(BookOrder::new(
302        side,
303        price(level.price, instrument, "price")?,
304        quantity(level.size, instrument, "size")?,
305        0,
306    ))
307}
308
309pub(crate) fn price(
310    value: Decimal,
311    instrument: &InstrumentAny,
312    field: &str,
313) -> anyhow::Result<Price> {
314    price_at(value, instrument.price_precision(), field)
315}
316
317pub(crate) fn quantity(
318    value: Decimal,
319    instrument: &InstrumentAny,
320    field: &str,
321) -> anyhow::Result<Quantity> {
322    quantity_at(value, instrument.size_precision(), field)
323}
324
325pub(crate) fn volume(value: Decimal, instrument: &InstrumentAny) -> anyhow::Result<Quantity> {
326    let precision = u32::from(instrument.size_precision());
327    let rounded = value.round_dp_with_strategy(precision, RoundingStrategy::MidpointNearestEven);
328    let adjustment = (value - rounded).abs();
329
330    // The size-unit cap rules out meaningful rounding even for coarse resolutions. Check it
331    // before scaling the adjustment, which keeps the relative comparison exact and bounded.
332    let normalized = if value >= Decimal::ZERO
333        && adjustment <= Decimal::new(1, precision + 6)
334        && adjustment * Decimal::new(1_000_000_000_000_000, 0) <= value
335    {
336        rounded
337    } else {
338        value
339    };
340
341    quantity_at(normalized, instrument.size_precision(), "volume_traded")
342}
343
344/// Converts `value` at `precision`, rejecting a value that would need rounding.
345pub(crate) fn price_at(value: Decimal, precision: u8, field: &str) -> anyhow::Result<Price> {
346    check_scale(value, precision, field)?;
347    Ok(Price::from_decimal_dp(value, precision)?)
348}
349
350/// Converts `value` at `precision`, rejecting a value that would need rounding.
351pub(crate) fn quantity_at(value: Decimal, precision: u8, field: &str) -> anyhow::Result<Quantity> {
352    check_scale(value, precision, field)?;
353    Ok(Quantity::from_decimal_dp(value, precision)?)
354}
355
356fn check_scale(value: Decimal, precision: u8, field: &str) -> anyhow::Result<()> {
357    anyhow::ensure!(
358        value.normalize().scale() <= u32::from(precision),
359        "{field} {value} is finer than instrument precision {precision}"
360    );
361    Ok(())
362}
363
364pub(crate) fn timestamp(value: Timestamp, field: &str) -> anyhow::Result<UnixNanos> {
365    unix_nanos(value).map_err(|e| anyhow::anyhow!("invalid {field}: {e}"))
366}
367
368#[cfg(test)]
369mod tests {
370    use nautilus_model::{identifiers::InstrumentId, instruments::CurrencyPair, types::Currency};
371    use rstest::rstest;
372    use ustr::Ustr;
373
374    use super::*;
375
376    fn instrument(price_precision: u8, size_precision: u8) -> InstrumentAny {
377        InstrumentAny::CurrencyPair(
378            CurrencyPair::builder()
379                .instrument_id(InstrumentId::from("BTC-USD.COINBASE"))
380                .raw_symbol("BTC-USD".into())
381                .base_currency(Currency::BTC())
382                .quote_currency(Currency::USD())
383                .price_precision(price_precision)
384                .size_precision(size_precision)
385                .price_increment(Price::new(
386                    10f64.powi(-i32::from(price_precision)),
387                    price_precision,
388                ))
389                .size_increment(Quantity::new(
390                    10f64.powi(-i32::from(size_precision)),
391                    size_precision,
392                ))
393                .ts_event(UnixNanos::default())
394                .ts_init(UnixNanos::default())
395                .build()
396                .unwrap(),
397        )
398    }
399
400    fn quote() -> Quote {
401        serde_json::from_str(include_str!("../../test_data/ws_quote.json")).unwrap()
402    }
403
404    fn trade() -> Trade {
405        serde_json::from_str(include_str!("../../test_data/ws_trade.json")).unwrap()
406    }
407
408    fn bar_spec(spec: &str) -> BarSpecification {
409        BarType::from(format!("BTC-USD.COINBASE-{spec}-EXTERNAL").as_str()).spec()
410    }
411
412    fn ohlcv() -> Ohlcv {
413        serde_json::from_str(include_str!("../../test_data/ws_ohlcv.json")).unwrap()
414    }
415
416    #[rstest]
417    fn quote_maps_every_field_and_ignores_trailing_zero_padding() {
418        let tick = parse_quote_tick(&quote(), &instrument(2, 0)).unwrap();
419
420        assert_eq!(
421            tick,
422            QuoteTick::new(
423                InstrumentId::from("BTC-USD.COINBASE"),
424                Price::from("760.00"),
425                Price::from("770.00"),
426                Quantity::from("124"),
427                Quantity::from("3252"),
428                UnixNanos::from(1_380_408_050_000_000_000),
429                UnixNanos::from(1_489_876_941_376_334_200),
430            )
431        );
432    }
433
434    #[rstest]
435    fn trade_maps_every_field_and_both_timestamps() {
436        let tick = parse_trade_tick(&trade(), &instrument(2, 8)).unwrap();
437
438        assert_eq!(
439            tick,
440            TradeTick::new(
441                InstrumentId::from("BTC-USD.COINBASE"),
442                Price::from("84520.02"),
443                Quantity::from("0.00000004"),
444                AggressorSide::Sell,
445                TradeId::new("c2519dfb-79a6-40e9-a1c8-a95d94209399"),
446                UnixNanos::from(1_790_299_746_065_618_000),
447                UnixNanos::from(1_790_299_746_143_827_200),
448            )
449        );
450    }
451
452    #[rstest]
453    fn bar_closes_at_period_end_with_given_ts_init() {
454        let ts_init = UnixNanos::from(1_790_299_803_000_000_000);
455        let bar = parse_bar(&ohlcv(), &instrument(2, 8), ts_init).unwrap();
456
457        assert_eq!(
458            bar,
459            Bar::new(
460                BarType::from("BTC-USD.COINBASE-1-SECOND-LAST-EXTERNAL"),
461                Price::from("84523.69"),
462                Price::from("84523.69"),
463                Price::from("84523.68"),
464                Price::from("84523.69"),
465                Quantity::from("0.00468951"),
466                UnixNanos::from(1_790_299_802_000_000_000),
467                ts_init,
468            )
469        );
470    }
471
472    #[rstest]
473    #[case("7.087936829999999", 8, "7.08793683")]
474    #[case("1.2582318399999999", 8, "1.25823184")]
475    #[case("28119.500000000004", 1, "28119.5")]
476    #[case("0.9707556800000001", 8, "0.97075568")]
477    #[case("1.000000000000001", 8, "1.00000000")]
478    #[case("100.00000000000001", 8, "100.00000000")]
479    #[case("0.000000001", 9, "0.000000001")]
480    #[case("0", 8, "0.00000000")]
481    fn bar_normalizes_volume_noise(
482        #[case] volume: &str,
483        #[case] size_precision: u8,
484        #[case] expected_volume: &str,
485    ) {
486        let mut ohlcv = ohlcv();
487        ohlcv.volume_traded = Decimal::from_str_exact(volume).unwrap();
488        let ts_init = UnixNanos::from(1_790_299_803_000_000_000);
489
490        let bar = parse_bar(&ohlcv, &instrument(2, size_precision), ts_init).unwrap();
491
492        assert_eq!(
493            bar,
494            Bar::new(
495                BarType::from("BTC-USD.COINBASE-1-SECOND-LAST-EXTERNAL"),
496                Price::from("84523.69"),
497                Price::from("84523.69"),
498                Price::from("84523.68"),
499                Price::from("84523.69"),
500                Quantity::from(expected_volume),
501                UnixNanos::from(1_790_299_802_000_000_000),
502                ts_init,
503            )
504        );
505        assert_eq!(bar.volume.precision, size_precision);
506    }
507
508    #[rstest]
509    #[case("1.000000000000002")]
510    #[case("100.00000000000002")]
511    #[case("1000000000.000000001")]
512    #[case("0.00000000000000000001")]
513    #[case("-0.0000000000000001")]
514    #[case("0.004689515")]
515    #[case("0.999999999999999")]
516    fn bar_rejects_volume_outside_noise_tolerance(#[case] volume: &str) {
517        let mut ohlcv = ohlcv();
518        ohlcv.volume_traded = Decimal::from_str_exact(volume).unwrap();
519
520        let error = parse_bar(&ohlcv, &instrument(2, 8), UnixNanos::default()).unwrap_err();
521
522        assert_eq!(
523            error.to_string(),
524            format!("volume_traded {volume} is finer than instrument precision 8")
525        );
526    }
527
528    #[cfg(feature = "high-precision")]
529    #[rstest]
530    #[case("0.0000000000000600000000000001", None)]
531    #[case("0.0000000000000999999999999999", None)]
532    #[case("0.0000000000001000000000000001", Some("0.0000000000001000"))]
533    fn volume_relative_bound_at_high_precision(
534        #[case] source: &str,
535        #[case] expected: Option<&str>,
536    ) {
537        let result = volume(Decimal::from_str_exact(source).unwrap(), &instrument(2, 16));
538        if let Some(expected) = expected {
539            let quantity = result.unwrap();
540            assert_eq!(quantity, Quantity::from(expected));
541            assert_eq!(quantity.precision, 16);
542        } else {
543            assert_eq!(
544                result.unwrap_err().to_string(),
545                format!("volume_traded {source} is finer than instrument precision 16")
546            );
547        }
548    }
549
550    #[rstest]
551    fn quote_finer_than_instrument_precision_is_rejected() {
552        let mut quote = quote();
553        quote.bid_price = Decimal::from_str_exact("760.005").unwrap();
554
555        let error = parse_quote_tick(&quote, &instrument(2, 0)).unwrap_err();
556
557        assert_eq!(
558            error.to_string(),
559            "bid_price 760.005 is finer than instrument precision 2"
560        );
561    }
562
563    #[rstest]
564    #[case(1, 8, "price 84520.02 is finer than instrument precision 1")]
565    #[case(2, 7, "size 0.00000004 is finer than instrument precision 7")]
566    fn trade_finer_than_instrument_precision_is_rejected(
567        #[case] price_precision: u8,
568        #[case] size_precision: u8,
569        #[case] expected: &str,
570    ) {
571        let error =
572            parse_trade_tick(&trade(), &instrument(price_precision, size_precision)).unwrap_err();
573
574        assert_eq!(error.to_string(), expected);
575    }
576
577    #[rstest]
578    fn bar_finer_than_instrument_precision_is_rejected() {
579        let error = parse_bar(&ohlcv(), &instrument(2, 7), UnixNanos::default()).unwrap_err();
580
581        assert_eq!(
582            error.to_string(),
583            "volume_traded 0.00468951 is finer than instrument precision 7"
584        );
585    }
586
587    fn book(is_snapshot: Option<bool>, bids: &[(&str, &str)], asks: &[(&str, &str)]) -> Book {
588        let level = |(price, size): &(&str, &str)| BookLevel {
589            id: None,
590            price: Decimal::from_str_exact(price).unwrap(),
591            size: Decimal::from_str_exact(size).unwrap(),
592        };
593
594        let mut book: Book =
595            serde_json::from_str(include_str!("../../test_data/ws_book.json")).unwrap();
596        book.is_snapshot = is_snapshot;
597        book.bids = bids.iter().map(level).collect();
598        book.asks = asks.iter().map(level).collect();
599        book
600    }
601
602    fn delta(
603        action: BookAction,
604        side: OrderSide,
605        price: &str,
606        size: &str,
607        flags: u8,
608    ) -> OrderBookDelta {
609        OrderBookDelta::new(
610            InstrumentId::from("BTC-USD.COINBASE"),
611            action,
612            BookOrder::new(side, Price::from(price), Quantity::from(size), 0),
613            flags,
614            2_323_346,
615            UnixNanos::from(1_380_408_050_000_000_000),
616            UnixNanos::from(1_489_876_941_376_334_200),
617        )
618    }
619
620    const SNAPSHOT: u8 = RecordFlag::F_SNAPSHOT as u8;
621    const LAST: u8 = RecordFlag::F_LAST as u8;
622
623    #[rstest]
624    fn book_snapshot_clears_then_adds_every_level() {
625        let deltas = parse_book_deltas(
626            &book(
627                Some(true),
628                &[("456.10", "42")],
629                &[("456.35", "123"), ("456.36", "23")],
630            ),
631            &instrument(2, 0),
632        )
633        .unwrap()
634        .unwrap();
635
636        let mut clear = OrderBookDelta::clear(
637            InstrumentId::from("BTC-USD.COINBASE"),
638            2_323_346,
639            UnixNanos::from(1_380_408_050_000_000_000),
640            UnixNanos::from(1_489_876_941_376_334_200),
641        );
642        clear.flags = SNAPSHOT;
643
644        assert_eq!(
645            deltas.deltas,
646            vec![
647                clear,
648                delta(BookAction::Add, OrderSide::Buy, "456.10", "42", SNAPSHOT),
649                delta(BookAction::Add, OrderSide::Sell, "456.35", "123", SNAPSHOT),
650                delta(
651                    BookAction::Add,
652                    OrderSide::Sell,
653                    "456.36",
654                    "23",
655                    SNAPSHOT | LAST
656                ),
657            ]
658        );
659    }
660
661    #[rstest]
662    fn empty_book_snapshot_is_a_lone_clear() {
663        let deltas = parse_book_deltas(&book(Some(true), &[], &[]), &instrument(2, 0))
664            .unwrap()
665            .unwrap();
666
667        assert_eq!(deltas.deltas.len(), 1);
668        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
669        assert_eq!(deltas.deltas[0].flags, SNAPSHOT | LAST);
670    }
671
672    #[rstest]
673    fn book_update_sets_levels_and_removes_zero_sizes() {
674        let deltas = parse_book_deltas(
675            &book(Some(false), &[("456.10", "0")], &[("456.35", "7")]),
676            &instrument(2, 0),
677        )
678        .unwrap()
679        .unwrap();
680
681        assert_eq!(
682            deltas.deltas,
683            vec![
684                delta(BookAction::Delete, OrderSide::Buy, "456.10", "0", 0),
685                delta(BookAction::Update, OrderSide::Sell, "456.35", "7", LAST),
686            ]
687        );
688    }
689
690    #[rstest]
691    fn book_update_without_levels_emits_nothing() {
692        let deltas = parse_book_deltas(&book(Some(false), &[], &[]), &instrument(2, 0)).unwrap();
693
694        assert_eq!(deltas, None);
695    }
696
697    #[rstest]
698    fn book_update_rejects_whole_message_for_one_finer_level() {
699        let error = parse_book_deltas(
700            &book(Some(false), &[("456.10", "1")], &[("456.355", "1")]),
701            &instrument(2, 0),
702        )
703        .unwrap_err();
704
705        assert_eq!(
706            error.to_string(),
707            "price 456.355 is finer than instrument precision 2"
708        );
709    }
710
711    #[rstest]
712    fn book_depth_keeps_best_levels_per_side() {
713        let mut fixed = book(
714            None,
715            &[("456.10", "1"), ("456.09", "2"), ("456.08", "3")],
716            &[("456.35", "4"), ("456.36", "5")],
717        );
718        fixed.data_type = super::super::messages::DataType::Book5;
719
720        let depth = parse_book_depth(&fixed, 2, &instrument(2, 0)).unwrap();
721
722        assert_eq!(
723            depth,
724            OrderBookDepth::new(
725                InstrumentId::from("BTC-USD.COINBASE"),
726                vec![
727                    BookOrder::new(
728                        OrderSide::Buy,
729                        Price::from("456.10"),
730                        Quantity::from("1"),
731                        0
732                    ),
733                    BookOrder::new(
734                        OrderSide::Buy,
735                        Price::from("456.09"),
736                        Quantity::from("2"),
737                        0
738                    ),
739                ],
740                vec![
741                    BookOrder::new(
742                        OrderSide::Sell,
743                        Price::from("456.35"),
744                        Quantity::from("4"),
745                        0
746                    ),
747                    BookOrder::new(
748                        OrderSide::Sell,
749                        Price::from("456.36"),
750                        Quantity::from("5"),
751                        0
752                    ),
753                ],
754                vec![0, 0],
755                vec![0, 0],
756                SNAPSHOT,
757                2_323_346,
758                UnixNanos::from(1_380_408_050_000_000_000),
759                UnixNanos::from(1_489_876_941_376_334_200),
760            )
761        );
762    }
763
764    #[rstest]
765    #[case("BUY", AggressorSide::Buy)]
766    #[case("SELL", AggressorSide::Sell)]
767    #[case("BUY_ESTIMATED", AggressorSide::NoAggressor)]
768    #[case("SELL_ESTIMATED", AggressorSide::NoAggressor)]
769    #[case("UNKNOWN", AggressorSide::NoAggressor)]
770    #[case("NEW_SIDE", AggressorSide::NoAggressor)]
771    fn taker_side_maps_only_reported_sides(#[case] wire: &str, #[case] expected: AggressorSide) {
772        assert_eq!(parse_aggressor_side(TakerSide::from(wire)), expected);
773    }
774
775    #[rstest]
776    #[case("1-SECOND-LAST", "1SEC")]
777    #[case("30-SECOND-LAST", "30SEC")]
778    #[case("1-MINUTE-LAST", "1MIN")]
779    #[case("15-MINUTE-LAST", "15MIN")]
780    #[case("1-HOUR-LAST", "1HRS")]
781    #[case("12-HOUR-LAST", "12HRS")]
782    #[case("1-DAY-LAST", "1DAY")]
783    fn bar_spec_maps_to_period_id_and_back(#[case] spec: &str, #[case] period_id: &str) {
784        let spec = bar_spec(spec);
785
786        assert_eq!(bar_spec_to_period_id(spec).unwrap().as_ref(), period_id);
787        assert_eq!(
788            period_id_to_bar_spec(OhlcvPeriod::from(period_id)),
789            Some(spec)
790        );
791    }
792
793    #[rstest]
794    #[case("12-SECOND-LAST")]
795    #[case("12-MINUTE-LAST")]
796    #[case("2-DAY-LAST")]
797    #[case("1-WEEK-LAST")]
798    #[case("1-MINUTE-MID")]
799    #[case("100-TICK-LAST")]
800    fn bar_spec_without_streaming_period_is_rejected(#[case] spec: &str) {
801        assert!(bar_spec_to_period_id(bar_spec(spec)).is_err());
802    }
803
804    #[rstest]
805    fn unsupported_bar_period_is_not_interned() {
806        let period = "12SEC";
807        assert_eq!(Ustr::from_existing(period), None);
808
809        let result = bar_spec_to_period_id(bar_spec("12-SECOND-LAST"));
810
811        assert!(result.is_err());
812        assert_eq!(Ustr::from_existing(period), None);
813    }
814
815    #[rstest]
816    #[case("01MIN")]
817    #[case("7SEC")]
818    #[case("1MTH")]
819    #[case("MIN")]
820    #[case("1")]
821    #[case("")]
822    fn unsupported_period_id_has_no_bar_spec(#[case] period_id: &str) {
823        assert_eq!(period_id_to_bar_spec(OhlcvPeriod::from(period_id)), None);
824    }
825}