Skip to main content

nautilus_coinbase/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//! Parsing functions for converting Coinbase WebSocket messages to Nautilus domain types.
17
18use std::str::FromStr;
19
20use anyhow::Context;
21use nautilus_core::UnixNanos;
22use nautilus_model::{
23    data::{
24        Bar, BarType, BookOrder, InstrumentStatus, OrderBookDelta, OrderBookDeltas, QuoteTick,
25        TradeTick,
26    },
27    enums::{BookAction, LiquiditySide, MarketStatusAction, OrderSide, OrderStatus, RecordFlag},
28    identifiers::{AccountId, ClientOrderId, InstrumentId, TradeId, VenueOrderId},
29    instruments::{Instrument, InstrumentAny},
30    reports::{FillReport, OrderStatusReport},
31    types::{Money, Price, Quantity},
32};
33use rust_decimal::Decimal;
34use ustr::Ustr;
35
36use crate::{
37    common::enums::CoinbaseProductStatus,
38    http::parse::{
39        coinbase_side_to_aggressor, parse_epoch_secs_timestamp, parse_order_side,
40        parse_order_side_optional, parse_order_status, parse_order_type, parse_price,
41        parse_quantity, parse_rfc3339_timestamp, parse_time_in_force,
42    },
43    websocket::messages::{
44        WsBookSide, WsCandle, WsL2DataEvent, WsL2Update, WsOrderUpdate, WsStatusProduct, WsTicker,
45        WsTrade,
46    },
47};
48
49/// Parses a WebSocket trade into a [`TradeTick`].
50pub fn parse_ws_trade(
51    trade: &WsTrade,
52    instrument: &InstrumentAny,
53    ts_init: UnixNanos,
54) -> anyhow::Result<TradeTick> {
55    let price = parse_price(&trade.price, instrument.price_precision())?;
56    let size = parse_quantity(&trade.size, instrument.size_precision())?;
57    let aggressor_side = coinbase_side_to_aggressor(&trade.side);
58    let trade_id = TradeId::new(&trade.trade_id);
59    let ts_event = parse_rfc3339_timestamp(&trade.time)?;
60
61    TradeTick::new_checked(
62        instrument.id(),
63        price,
64        size,
65        aggressor_side,
66        trade_id,
67        ts_event,
68        ts_init,
69    )
70}
71
72/// Parses a WebSocket ticker into a [`QuoteTick`].
73pub fn parse_ws_ticker(
74    ticker: &WsTicker,
75    instrument: &InstrumentAny,
76    ts_event: UnixNanos,
77    ts_init: UnixNanos,
78) -> anyhow::Result<QuoteTick> {
79    let bid_price = parse_price(&ticker.best_bid, instrument.price_precision())?;
80    let ask_price = parse_price(&ticker.best_ask, instrument.price_precision())?;
81    let bid_size = parse_quantity(&ticker.best_bid_quantity, instrument.size_precision())?;
82    let ask_size = parse_quantity(&ticker.best_ask_quantity, instrument.size_precision())?;
83
84    QuoteTick::new_checked(
85        instrument.id(),
86        bid_price,
87        ask_price,
88        bid_size,
89        ask_size,
90        ts_event,
91        ts_init,
92    )
93}
94
95/// Parses a WebSocket candle into a [`Bar`].
96pub fn parse_ws_candle(
97    candle: &WsCandle,
98    bar_type: BarType,
99    instrument: &InstrumentAny,
100    ts_init: UnixNanos,
101) -> anyhow::Result<Bar> {
102    let open = parse_price(&candle.open, instrument.price_precision())?;
103    let high = parse_price(&candle.high, instrument.price_precision())?;
104    let low = parse_price(&candle.low, instrument.price_precision())?;
105    let close = parse_price(&candle.close, instrument.price_precision())?;
106    let volume = parse_quantity(&candle.volume, instrument.size_precision())?;
107    let ts_event = parse_epoch_secs_timestamp(&candle.start)?;
108
109    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
110}
111
112/// Parses a WebSocket L2 snapshot event into [`OrderBookDeltas`].
113///
114/// All deltas in the batch share `ts_event`, which the caller derives from the
115/// message-level `timestamp`. Per-level `event_time` values are not monotonic
116/// across batches and would trigger out-of-order warnings in the managed book.
117pub fn parse_ws_l2_snapshot(
118    event: &WsL2DataEvent,
119    instrument: &InstrumentAny,
120    ts_event: UnixNanos,
121    ts_init: UnixNanos,
122) -> anyhow::Result<OrderBookDeltas> {
123    let instrument_id = instrument.id();
124
125    let total = event.updates.len();
126    let mut deltas = Vec::with_capacity(total + 1);
127
128    let mut clear = OrderBookDelta::clear(instrument_id, 0, ts_event, ts_init);
129    clear.flags |= RecordFlag::F_SNAPSHOT as u8;
130
131    if total == 0 {
132        clear.flags |= RecordFlag::F_LAST as u8;
133    }
134    deltas.push(clear);
135
136    for (i, update) in event.updates.iter().enumerate() {
137        let is_last = i == total - 1;
138        let delta = parse_l2_delta(
139            update,
140            instrument_id,
141            instrument.price_precision(),
142            instrument.size_precision(),
143            is_last,
144            ts_event,
145            ts_init,
146        )?;
147        deltas.push(delta);
148    }
149
150    OrderBookDeltas::new_checked(instrument_id, deltas)
151}
152
153/// Parses a WebSocket L2 update event into [`OrderBookDeltas`].
154///
155/// All deltas in the batch share `ts_event`, which the caller derives from the
156/// message-level `timestamp`. Per-level `event_time` values are not monotonic
157/// across batches and would trigger out-of-order warnings in the managed book.
158pub fn parse_ws_l2_update(
159    event: &WsL2DataEvent,
160    instrument: &InstrumentAny,
161    ts_event: UnixNanos,
162    ts_init: UnixNanos,
163) -> anyhow::Result<OrderBookDeltas> {
164    let instrument_id = instrument.id();
165    let total = event.updates.len();
166    let mut deltas = Vec::with_capacity(total);
167
168    for (i, update) in event.updates.iter().enumerate() {
169        let is_last = i == total - 1;
170        let price = parse_price(&update.price_level, instrument.price_precision())?;
171        let size = parse_quantity(&update.new_quantity, instrument.size_precision())?;
172        let side = ws_book_side_to_order_side(update.side);
173
174        let action = if size == Quantity::zero(instrument.size_precision()) {
175            BookAction::Delete
176        } else {
177            BookAction::Update
178        };
179
180        let mut flags = RecordFlag::F_MBP as u8;
181
182        if is_last {
183            flags |= RecordFlag::F_LAST as u8;
184        }
185
186        let order = BookOrder::new(side, price, size, 0);
187        let delta =
188            OrderBookDelta::new_checked(instrument_id, action, order, flags, 0, ts_event, ts_init)?;
189        deltas.push(delta);
190    }
191
192    OrderBookDeltas::new_checked(instrument_id, deltas)
193}
194
195/// Parses a single L2 snapshot level into an [`OrderBookDelta`].
196fn parse_l2_delta(
197    update: &WsL2Update,
198    instrument_id: InstrumentId,
199    price_precision: u8,
200    size_precision: u8,
201    is_last: bool,
202    ts_event: UnixNanos,
203    ts_init: UnixNanos,
204) -> anyhow::Result<OrderBookDelta> {
205    let price = parse_price(&update.price_level, price_precision)?;
206    let size = parse_quantity(&update.new_quantity, size_precision)?;
207    let side = ws_book_side_to_order_side(update.side);
208
209    let mut flags = RecordFlag::F_MBP as u8 | RecordFlag::F_SNAPSHOT as u8;
210
211    if is_last {
212        flags |= RecordFlag::F_LAST as u8;
213    }
214
215    let order = BookOrder::new(side, price, size, 0);
216    OrderBookDelta::new_checked(
217        instrument_id,
218        BookAction::Add,
219        order,
220        flags,
221        0,
222        ts_event,
223        ts_init,
224    )
225}
226
227/// Converts a Coinbase WebSocket book side to a Nautilus order side.
228fn ws_book_side_to_order_side(side: WsBookSide) -> OrderSide {
229    match side {
230        WsBookSide::Bid => OrderSide::Buy,
231        WsBookSide::Offer => OrderSide::Sell,
232    }
233}
234
235/// Parses a Coinbase user channel [`WsOrderUpdate`] into an [`OrderStatusReport`].
236///
237/// Derives the total quantity as `cumulative_quantity + leaves_quantity` and
238/// promotes the `Accepted` status to `PartiallyFilled` when the cumulative
239/// fill is positive but below the total quantity, mirroring the REST parser.
240///
241/// # Errors
242///
243/// Returns an error if any numeric field cannot be parsed against the instrument precision.
244pub fn parse_ws_user_event_to_order_status_report(
245    update: &WsOrderUpdate,
246    instrument: &InstrumentAny,
247    account_id: AccountId,
248    ts_event: UnixNanos,
249    ts_init: UnixNanos,
250) -> anyhow::Result<OrderStatusReport> {
251    let instrument_id = instrument.id();
252    let size_precision = instrument.size_precision();
253
254    let order_side = parse_order_side_optional(&update.order_side);
255    let order_type = parse_order_type(update.order_type);
256    let time_in_force = parse_time_in_force(Some(update.time_in_force));
257    let mut order_status = parse_order_status(update.status);
258
259    let venue_order_id = VenueOrderId::new(&update.order_id);
260    let client_order_id = if update.client_order_id.is_empty() {
261        None
262    } else {
263        Some(ClientOrderId::new(&update.client_order_id))
264    };
265
266    let filled_qty = if update.cumulative_quantity.is_empty() {
267        Quantity::zero(size_precision)
268    } else {
269        parse_quantity(&update.cumulative_quantity, size_precision)
270            .context("failed to parse cumulative_quantity")?
271    };
272    let leaves_qty = if update.leaves_quantity.is_empty() {
273        Quantity::zero(size_precision)
274    } else {
275        parse_quantity(&update.leaves_quantity, size_precision)
276            .context("failed to parse leaves_quantity")?
277    };
278
279    let quantity = filled_qty + leaves_qty;
280
281    if order_status == OrderStatus::Accepted && filled_qty.is_positive() && filled_qty < quantity {
282        order_status = OrderStatus::PartiallyFilled;
283    }
284
285    let ts_accepted = if update.creation_time.is_empty() {
286        ts_event
287    } else {
288        parse_rfc3339_timestamp(&update.creation_time).unwrap_or(ts_event)
289    };
290
291    let mut report = OrderStatusReport::new(
292        account_id,
293        instrument_id,
294        client_order_id,
295        venue_order_id,
296        order_side,
297        order_type,
298        time_in_force,
299        order_status,
300        quantity,
301        filled_qty,
302        ts_accepted,
303        ts_event,
304        ts_init,
305        None,
306    );
307
308    if !update.avg_price.is_empty()
309        && let Ok(avg_decimal) = Decimal::from_str(&update.avg_price)
310        && avg_decimal.is_sign_positive()
311        && !avg_decimal.is_zero()
312    {
313        report = report.with_avg_px(avg_decimal);
314    }
315
316    Ok(report)
317}
318
319/// Parses a Coinbase user channel [`WsOrderUpdate`] into a [`FillReport`].
320///
321/// Coinbase's user channel reports cumulative totals rather than per-trade
322/// fills, so the caller must supply:
323/// - `last_qty`: the quantity delta since the previous cumulative state
324/// - `last_px`: the price of the new fill, derived by the caller from the
325///   cumulative notional delta (Coinbase's `avg_price` is the *cumulative*
326///   weighted average and is not safe to use as the new fill's price for
327///   multi-fill orders)
328/// - `commission`: the commission delta since the previous cumulative state
329/// - `trade_id`: synthesized from the order ID plus the new cumulative total
330#[allow(clippy::too_many_arguments)]
331pub fn parse_ws_user_event_to_fill_report(
332    update: &WsOrderUpdate,
333    last_qty: Quantity,
334    last_px: Price,
335    commission: Money,
336    trade_id: TradeId,
337    instrument: &InstrumentAny,
338    account_id: AccountId,
339    liquidity_side: LiquiditySide,
340    ts_event: UnixNanos,
341    ts_init: UnixNanos,
342) -> anyhow::Result<FillReport> {
343    let instrument_id = instrument.id();
344
345    let venue_order_id = VenueOrderId::new(&update.order_id);
346    let client_order_id = if update.client_order_id.is_empty() {
347        None
348    } else {
349        Some(ClientOrderId::new(&update.client_order_id))
350    };
351    let order_side = parse_order_side(&update.order_side)?;
352
353    Ok(FillReport::new(
354        account_id,
355        instrument_id,
356        venue_order_id,
357        trade_id,
358        order_side,
359        last_qty,
360        last_px,
361        commission,
362        liquidity_side,
363        client_order_id,
364        None,
365        ts_event,
366        ts_init,
367        None,
368    ))
369}
370
371/// Parses a [`WsStatusProduct`] from the `status` channel into an
372/// [`InstrumentStatus`].
373///
374/// Returns `None` when the venue's status is unset (e.g. futures products in
375/// the FCM session), which carries no information for the data engine.
376pub fn parse_ws_status_product(
377    product: &WsStatusProduct,
378    instrument_id: InstrumentId,
379    ts_event: UnixNanos,
380    ts_init: UnixNanos,
381) -> Option<InstrumentStatus> {
382    let action = match product.status {
383        CoinbaseProductStatus::Online => MarketStatusAction::Trading,
384        CoinbaseProductStatus::Offline => MarketStatusAction::Halt,
385        CoinbaseProductStatus::Delisted => MarketStatusAction::Close,
386        // Unset (futures) carries no info; Unknown is an unmodeled status we cannot
387        // safely map to a market action, so emit nothing rather than guess.
388        CoinbaseProductStatus::Unset | CoinbaseProductStatus::Unknown => return None,
389    };
390    let reason = if product.status_message.is_empty() {
391        None
392    } else {
393        Some(Ustr::from(&product.status_message))
394    };
395    let is_trading = Some(matches!(action, MarketStatusAction::Trading));
396    Some(InstrumentStatus::new(
397        instrument_id,
398        action,
399        ts_event,
400        ts_init,
401        reason,
402        None,
403        is_trading,
404        None,
405        None,
406    ))
407}
408
409#[cfg(test)]
410mod tests {
411    use std::str::FromStr;
412
413    use nautilus_model::{
414        data::bar::BarSpecification,
415        enums::{AggregationSource, AggressorSide, BarAggregation, PriceType},
416        identifiers::Symbol,
417        instruments::CurrencyPair,
418        types::{Currency, Price},
419    };
420    use rstest::rstest;
421
422    use super::*;
423    use crate::{
424        common::{consts::COINBASE_VENUE, testing::load_test_fixture},
425        websocket::messages::{CoinbaseWsMessage, WsEventType},
426    };
427
428    fn test_instrument() -> InstrumentAny {
429        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), *COINBASE_VENUE);
430        let raw_symbol = Symbol::new("BTC-USD");
431        let base_currency = Currency::get_or_create_crypto("BTC");
432        let quote_currency = Currency::get_or_create_crypto("USD");
433
434        InstrumentAny::CurrencyPair(
435            CurrencyPair::builder()
436                .instrument_id(instrument_id)
437                .raw_symbol(raw_symbol)
438                .base_currency(base_currency)
439                .quote_currency(quote_currency)
440                .price_precision(2)
441                .size_precision(8)
442                .price_increment(Price::from("0.01"))
443                .size_increment(Quantity::from("0.00000001"))
444                .min_quantity(Quantity::from("0.00000001"))
445                .ts_event(UnixNanos::default())
446                .ts_init(UnixNanos::default())
447                .build()
448                .unwrap(),
449        )
450    }
451
452    #[rstest]
453    fn test_parse_ws_trade() {
454        let json = load_test_fixture("ws_market_trades.json");
455        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
456        let instrument = test_instrument();
457        let ts_init = UnixNanos::default();
458
459        match msg {
460            CoinbaseWsMessage::MarketTrades { events, .. } => {
461                let trade_data = &events[0].trades[0];
462                let tick = parse_ws_trade(trade_data, &instrument, ts_init).unwrap();
463
464                assert_eq!(tick.instrument_id, instrument.id());
465                assert_eq!(tick.price, Price::from("68900.50"));
466                assert_eq!(tick.size, Quantity::from("0.00150000"));
467                assert_eq!(tick.aggressor_side, AggressorSide::Sell);
468                assert_eq!(tick.trade_id.as_str(), "995098700");
469                assert!(tick.ts_event.as_u64() > 0);
470            }
471            _ => panic!("Expected MarketTrades"),
472        }
473    }
474
475    #[rstest]
476    fn test_parse_ws_trade_sell_side() {
477        let json = load_test_fixture("ws_market_trades.json");
478        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
479        let instrument = test_instrument();
480        let ts_init = UnixNanos::default();
481
482        match msg {
483            CoinbaseWsMessage::MarketTrades { events, .. } => {
484                let trade_data = &events[0].trades[1];
485                let tick = parse_ws_trade(trade_data, &instrument, ts_init).unwrap();
486
487                assert_eq!(tick.aggressor_side, AggressorSide::Buy);
488                assert_eq!(tick.price, Price::from("68900.00"));
489                assert_eq!(tick.size, Quantity::from("0.05000000"));
490            }
491            _ => panic!("Expected MarketTrades"),
492        }
493    }
494
495    #[rstest]
496    fn test_parse_ws_ticker() {
497        let json = load_test_fixture("ws_ticker.json");
498        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
499        let instrument = test_instrument();
500        let ts_init = UnixNanos::default();
501
502        match msg {
503            CoinbaseWsMessage::Ticker {
504                timestamp, events, ..
505            } => {
506                let ticker_data = &events[0].tickers[0];
507                let ts_event = parse_rfc3339_timestamp(&timestamp).unwrap();
508                let quote = parse_ws_ticker(ticker_data, &instrument, ts_event, ts_init).unwrap();
509
510                assert_eq!(quote.instrument_id, instrument.id());
511                assert_eq!(quote.bid_price, Price::from("68900.00"));
512                assert_eq!(quote.ask_price, Price::from("68901.00"));
513                assert_eq!(quote.bid_size, Quantity::from("1.50000000"));
514                assert_eq!(quote.ask_size, Quantity::from("0.50000000"));
515            }
516            _ => panic!("Expected Ticker"),
517        }
518    }
519
520    #[rstest]
521    fn test_parse_ws_candle() {
522        let json = load_test_fixture("ws_candles.json");
523        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
524        let instrument = test_instrument();
525        let ts_init = UnixNanos::default();
526
527        let bar_spec = BarSpecification::new(5, BarAggregation::Minute, PriceType::Last);
528        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::External);
529
530        match msg {
531            CoinbaseWsMessage::Candles { events, .. } => {
532                let candle_data = &events[0].candles[0];
533                let bar = parse_ws_candle(candle_data, bar_type, &instrument, ts_init).unwrap();
534
535                assert_eq!(bar.bar_type, bar_type);
536                assert_eq!(bar.open, Price::from("68900.00"));
537                assert_eq!(bar.high, Price::from("68950.00"));
538                assert_eq!(bar.low, Price::from("68850.00"));
539                assert_eq!(bar.close, Price::from("68920.50"));
540                assert_eq!(bar.volume, Quantity::from("42.15000000"));
541                assert_eq!(bar.ts_event.as_u64(), 1_775_521_800_000_000_000);
542            }
543            _ => panic!("Expected Candles"),
544        }
545    }
546
547    #[rstest]
548    fn test_parse_ws_l2_snapshot() {
549        let json = load_test_fixture("ws_l2_data_snapshot.json");
550        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
551        let instrument = test_instrument();
552        let ts_init = UnixNanos::default();
553
554        match msg {
555            CoinbaseWsMessage::L2Data {
556                timestamp, events, ..
557            } => {
558                let event = &events[0];
559                assert_eq!(event.event_type, WsEventType::Snapshot);
560                let ts_event = parse_rfc3339_timestamp(&timestamp).unwrap();
561
562                let deltas = parse_ws_l2_snapshot(event, &instrument, ts_event, ts_init).unwrap();
563                assert_eq!(deltas.instrument_id, instrument.id());
564                for delta in &deltas.deltas {
565                    assert_eq!(delta.ts_event, ts_event);
566                }
567
568                // 6 levels + 1 clear = 7 deltas
569                assert_eq!(deltas.deltas.len(), 7);
570
571                // First delta is clear
572                assert_eq!(deltas.deltas[0].action, BookAction::Clear);
573
574                // Bids
575                assert_eq!(deltas.deltas[1].order.side, OrderSide::Buy.into());
576                assert_eq!(deltas.deltas[1].order.price, Price::from("68900.00"));
577                assert_eq!(deltas.deltas[1].order.size, Quantity::from("1.50000000"));
578
579                // Asks
580                assert_eq!(deltas.deltas[4].order.side, OrderSide::Sell.into());
581                assert_eq!(deltas.deltas[4].order.price, Price::from("68901.00"));
582
583                // Last delta has F_LAST flag
584                let last = deltas.deltas.last().unwrap();
585                assert_ne!(last.flags & RecordFlag::F_LAST as u8, 0);
586
587                // Every delta in a snapshot sequence carries F_SNAPSHOT.
588                for delta in &deltas.deltas {
589                    assert_ne!(
590                        delta.flags & RecordFlag::F_SNAPSHOT as u8,
591                        0,
592                        "snapshot delta missing F_SNAPSHOT: {delta:?}",
593                    );
594                }
595            }
596            _ => panic!("Expected L2Data"),
597        }
598    }
599
600    // Empty-book snapshots must carry F_SNAPSHOT | F_LAST on the lone Clear
601    // delta so buffered consumers receive the clear event; without F_LAST the
602    // DataEngine never flushes and downstream subscribers see nothing.
603    #[rstest]
604    fn test_parse_ws_l2_snapshot_empty_book_clear_carries_snapshot_and_last() {
605        let event = WsL2DataEvent {
606            event_type: WsEventType::Snapshot,
607            product_id: Ustr::from("BTC-USD"),
608            updates: Vec::new(),
609        };
610        let instrument = test_instrument();
611        let ts_event = UnixNanos::from(1);
612        let ts_init = UnixNanos::from(2);
613
614        let deltas = parse_ws_l2_snapshot(&event, &instrument, ts_event, ts_init).unwrap();
615        assert_eq!(deltas.deltas.len(), 1);
616        let clear = &deltas.deltas[0];
617        assert_eq!(clear.action, BookAction::Clear);
618        assert_ne!(clear.flags & RecordFlag::F_SNAPSHOT as u8, 0);
619        assert_ne!(clear.flags & RecordFlag::F_LAST as u8, 0);
620    }
621
622    // Update deltas must NOT carry F_SNAPSHOT; only snapshot sequences do.
623    // A regression that copy-pastes the snapshot path would have updates
624    // misclassified by downstream consumers.
625    #[rstest]
626    fn test_parse_ws_l2_update_omits_snapshot_flag() {
627        let json = load_test_fixture("ws_l2_data_update.json");
628        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
629        let instrument = test_instrument();
630        let ts_init = UnixNanos::default();
631
632        match msg {
633            CoinbaseWsMessage::L2Data {
634                timestamp, events, ..
635            } => {
636                let event = &events[0];
637                let ts_event = parse_rfc3339_timestamp(&timestamp).unwrap();
638                let deltas = parse_ws_l2_update(event, &instrument, ts_event, ts_init).unwrap();
639
640                for delta in &deltas.deltas {
641                    assert_eq!(
642                        delta.flags & RecordFlag::F_SNAPSHOT as u8,
643                        0,
644                        "update delta must not carry F_SNAPSHOT: {delta:?}",
645                    );
646                }
647            }
648            _ => panic!("Expected L2Data"),
649        }
650    }
651
652    #[rstest]
653    fn test_parse_ws_l2_update() {
654        let json = load_test_fixture("ws_l2_data_update.json");
655        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
656        let instrument = test_instrument();
657        let ts_init = UnixNanos::default();
658
659        match msg {
660            CoinbaseWsMessage::L2Data {
661                timestamp, events, ..
662            } => {
663                let event = &events[0];
664                assert_eq!(event.event_type, WsEventType::Update);
665                let ts_event = parse_rfc3339_timestamp(&timestamp).unwrap();
666
667                let deltas = parse_ws_l2_update(event, &instrument, ts_event, ts_init).unwrap();
668                assert_eq!(deltas.deltas.len(), 2);
669                for delta in &deltas.deltas {
670                    assert_eq!(delta.ts_event, ts_event);
671                }
672
673                // First update: bid at 68900.00, qty 2.0 -> Update action
674                assert_eq!(deltas.deltas[0].order.side, OrderSide::Buy.into());
675                assert_eq!(deltas.deltas[0].order.price, Price::from("68900.00"));
676                assert_eq!(deltas.deltas[0].order.size, Quantity::from("2.00000000"));
677                assert_eq!(deltas.deltas[0].action, BookAction::Update);
678
679                // Second update: offer at 68901.00, qty 0.0 -> Delete action
680                assert_eq!(deltas.deltas[1].order.side, OrderSide::Sell.into());
681                assert_eq!(deltas.deltas[1].action, BookAction::Delete);
682                assert_eq!(deltas.deltas[1].order.size, Quantity::from("0.00000000"));
683
684                // Last delta has F_LAST flag
685                assert_ne!(deltas.deltas[1].flags & RecordFlag::F_LAST as u8, 0);
686            }
687            _ => panic!("Expected L2Data"),
688        }
689    }
690
691    #[rstest]
692    fn test_parse_ws_l2_update_zero_quantity_is_delete() {
693        let json = load_test_fixture("ws_l2_data_update.json");
694        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
695        let instrument = test_instrument();
696        let ts_init = UnixNanos::default();
697
698        match msg {
699            CoinbaseWsMessage::L2Data {
700                timestamp, events, ..
701            } => {
702                let event = &events[0];
703                let ts_event = parse_rfc3339_timestamp(&timestamp).unwrap();
704                let deltas = parse_ws_l2_update(event, &instrument, ts_event, ts_init).unwrap();
705
706                // The offer with new_quantity "0.00000000" should be a Delete
707                let delete_delta = deltas
708                    .deltas
709                    .iter()
710                    .find(|d| d.action == BookAction::Delete)
711                    .expect("should have a delete action for zero quantity");
712                assert_eq!(delete_delta.order.side, OrderSide::Sell.into());
713                assert_eq!(delete_delta.ts_event, ts_event);
714            }
715            _ => panic!("Expected L2Data"),
716        }
717    }
718
719    #[rstest]
720    fn test_ws_book_side_conversion() {
721        assert_eq!(ws_book_side_to_order_side(WsBookSide::Bid), OrderSide::Buy,);
722        assert_eq!(
723            ws_book_side_to_order_side(WsBookSide::Offer),
724            OrderSide::Sell
725        );
726    }
727
728    #[rstest]
729    fn test_parse_ws_user_event_to_order_status_report_open() {
730        let json = load_test_fixture("ws_user.json");
731        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
732        let instrument = test_instrument();
733        let account_id = AccountId::new("COINBASE-001");
734        let ts_event = UnixNanos::from(1_705_314_600_000_000_000u64);
735        let ts_init = UnixNanos::from(1_705_314_700_000_000_000u64);
736
737        let order = match msg {
738            CoinbaseWsMessage::User { events, .. } => events[0].orders[0].clone(),
739            other => panic!("expected User, was {other:?}"),
740        };
741
742        let report = parse_ws_user_event_to_order_status_report(
743            &order,
744            &instrument,
745            account_id,
746            ts_event,
747            ts_init,
748        )
749        .unwrap();
750
751        assert_eq!(report.account_id, account_id);
752        assert_eq!(report.instrument_id, instrument.id());
753        assert_eq!(
754            report.venue_order_id.as_str(),
755            "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
756        );
757        assert_eq!(
758            report.client_order_id.unwrap().as_str(),
759            "11111-000000-000001"
760        );
761        assert_eq!(report.order_side, OrderSide::Buy.into());
762        assert_eq!(report.order_status, OrderStatus::Accepted);
763        assert_eq!(report.filled_qty, Quantity::from("0.00000000"));
764        assert_eq!(report.quantity, Quantity::from("0.00100000"));
765        assert_eq!(report.ts_init, ts_init);
766    }
767
768    #[rstest]
769    fn test_parse_ws_user_event_to_order_status_report_promotes_partial_fill() {
770        let mut update = WsOrderUpdate {
771            order_id: "venue-1".to_string(),
772            client_order_id: "client-1".to_string(),
773            contract_expiry_type: crate::common::enums::CoinbaseContractExpiryType::Unknown,
774            cumulative_quantity: "0.5".to_string(),
775            leaves_quantity: "0.5".to_string(),
776            avg_price: "100.00".to_string(),
777            total_fees: "0.05".to_string(),
778            status: crate::common::enums::CoinbaseOrderStatus::Open,
779            product_id: ustr::Ustr::from("BTC-USD"),
780            product_type: crate::common::enums::CoinbaseProductType::Spot,
781            creation_time: String::new(),
782            order_side: crate::common::enums::CoinbaseOrderSide::Buy,
783            order_type: crate::common::enums::CoinbaseOrderType::Limit,
784            risk_managed_by: crate::common::enums::CoinbaseRiskManagedBy::Unknown,
785            time_in_force: crate::common::enums::CoinbaseTimeInForce::GoodUntilCancelled,
786            trigger_status: crate::common::enums::CoinbaseTriggerStatus::InvalidOrderType,
787            cancel_reason: String::new(),
788            reject_reason: String::new(),
789            total_value_after_fees: String::new(),
790        };
791        update.creation_time = String::new();
792
793        let instrument = test_instrument();
794        let report = parse_ws_user_event_to_order_status_report(
795            &update,
796            &instrument,
797            AccountId::new("COINBASE-001"),
798            UnixNanos::default(),
799            UnixNanos::default(),
800        )
801        .unwrap();
802
803        // Coinbase Open + positive cumulative + leaves > 0 should promote to PartiallyFilled.
804        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
805        assert_eq!(report.filled_qty, Quantity::from("0.50000000"));
806        assert_eq!(report.quantity, Quantity::from("1.00000000"));
807    }
808
809    #[rstest]
810    fn test_parse_ws_user_event_to_fill_report_uses_supplied_last_px_and_commission() {
811        let update = WsOrderUpdate {
812            order_id: "venue-1".to_string(),
813            client_order_id: "client-1".to_string(),
814            contract_expiry_type: crate::common::enums::CoinbaseContractExpiryType::Unknown,
815            cumulative_quantity: "0.5".to_string(),
816            leaves_quantity: "0.5".to_string(),
817            avg_price: "100.00".to_string(),
818            total_fees: "0.05".to_string(),
819            status: crate::common::enums::CoinbaseOrderStatus::Open,
820            product_id: ustr::Ustr::from("BTC-USD"),
821            product_type: crate::common::enums::CoinbaseProductType::Spot,
822            creation_time: String::new(),
823            order_side: crate::common::enums::CoinbaseOrderSide::Sell,
824            order_type: crate::common::enums::CoinbaseOrderType::Limit,
825            risk_managed_by: crate::common::enums::CoinbaseRiskManagedBy::Unknown,
826            time_in_force: crate::common::enums::CoinbaseTimeInForce::GoodUntilCancelled,
827            trigger_status: crate::common::enums::CoinbaseTriggerStatus::InvalidOrderType,
828            cancel_reason: String::new(),
829            reject_reason: String::new(),
830            total_value_after_fees: String::new(),
831        };
832
833        let instrument = test_instrument();
834        let usd = Currency::USD();
835        let last_px = Price::from("120.00");
836        let commission =
837            Money::from_decimal(rust_decimal::Decimal::from_str("0.10").unwrap(), usd).unwrap();
838        let trade_id = TradeId::new("venue-1-0.5");
839
840        let report = parse_ws_user_event_to_fill_report(
841            &update,
842            Quantity::from("0.50000000"),
843            last_px,
844            commission,
845            trade_id,
846            &instrument,
847            AccountId::new("COINBASE-001"),
848            LiquiditySide::Maker,
849            UnixNanos::default(),
850            UnixNanos::default(),
851        )
852        .unwrap();
853
854        assert_eq!(report.venue_order_id.as_str(), "venue-1");
855        assert_eq!(report.client_order_id.unwrap().as_str(), "client-1");
856        assert_eq!(report.order_side, OrderSide::Sell);
857        assert_eq!(report.last_qty, Quantity::from("0.50000000"));
858        assert_eq!(report.last_px, Price::from("120.00"));
859        assert_eq!(report.commission, commission);
860        assert_eq!(report.liquidity_side, LiquiditySide::Maker);
861        assert_eq!(report.trade_id, trade_id);
862    }
863
864    fn make_status_product(status: CoinbaseProductStatus, message: &str) -> WsStatusProduct {
865        WsStatusProduct {
866            product_type: crate::common::enums::CoinbaseProductType::Spot,
867            id: Ustr::from("BTC-USD"),
868            base_currency: Ustr::from("BTC"),
869            quote_currency: Ustr::from("USD"),
870            base_increment: "0.00000001".to_string(),
871            quote_increment: "0.01".to_string(),
872            display_name: "BTC/USD".to_string(),
873            status,
874            status_message: message.to_string(),
875            min_market_funds: Decimal::ONE,
876        }
877    }
878
879    #[rstest]
880    #[case::online(
881        CoinbaseProductStatus::Online,
882        "",
883        Some(MarketStatusAction::Trading),
884        Some(true),
885        None
886    )]
887    #[case::offline_with_reason(
888        CoinbaseProductStatus::Offline,
889        "maintenance",
890        Some(MarketStatusAction::Halt),
891        Some(false),
892        Some("maintenance")
893    )]
894    #[case::delisted(
895        CoinbaseProductStatus::Delisted,
896        "",
897        Some(MarketStatusAction::Close),
898        Some(false),
899        None
900    )]
901    #[case::unset_skipped(CoinbaseProductStatus::Unset, "", None, None, None)]
902    fn test_parse_ws_status_product(
903        #[case] status: CoinbaseProductStatus,
904        #[case] message: &str,
905        #[case] expected_action: Option<MarketStatusAction>,
906        #[case] expected_is_trading: Option<bool>,
907        #[case] expected_reason: Option<&str>,
908    ) {
909        let product = make_status_product(status, message);
910        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), *COINBASE_VENUE);
911        let result = parse_ws_status_product(
912            &product,
913            instrument_id,
914            UnixNanos::from(1),
915            UnixNanos::from(2),
916        );
917
918        match expected_action {
919            Some(action) => {
920                let status = result.expect("expected InstrumentStatus");
921                assert_eq!(status.instrument_id, instrument_id);
922                assert_eq!(status.action, action);
923                assert_eq!(status.is_trading, expected_is_trading);
924                assert_eq!(
925                    status.reason.map(|s| s.to_string()),
926                    expected_reason.map(|s| s.to_string()),
927                );
928                assert_eq!(status.ts_event, UnixNanos::from(1));
929                assert_eq!(status.ts_init, UnixNanos::from(2));
930            }
931            None => assert!(result.is_none(), "expected None for unset status"),
932        }
933    }
934}