Skip to main content

nautilus_coinbase/websocket/
messages.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//! WebSocket message types for the Coinbase Advanced Trade API.
17//!
18//! All incoming messages share an envelope with `channel`, `timestamp`,
19//! `sequence_num`, and a channel-specific `events` array. Outgoing
20//! subscription messages use a flat format with `type`, `product_ids`,
21//! `channel`, and `jwt`.
22
23use std::collections::HashMap;
24
25use nautilus_core::string::secret::SecretString;
26use rust_decimal::Decimal;
27use serde::{Deserialize, Serialize};
28use ustr::Ustr;
29use zeroize::Zeroize;
30
31use crate::common::{
32    enums::{
33        CoinbaseContractExpiryType, CoinbaseMarginLevel, CoinbaseMarginWindowType,
34        CoinbaseOrderSide, CoinbaseOrderStatus, CoinbaseOrderType, CoinbaseProductStatus,
35        CoinbaseProductType, CoinbaseRiskManagedBy, CoinbaseTimeInForce, CoinbaseTriggerStatus,
36        CoinbaseWsChannel,
37    },
38    parse::{
39        deserialize_decimal_from_str, deserialize_product_status_or_unknown,
40        deserialize_product_type_or_unknown,
41    },
42};
43
44/// Subscribe or unsubscribe request sent to the WebSocket.
45///
46/// Public channels (`level2`, `market_trades`, `ticker`, etc.) do not require
47/// a JWT. Set `jwt` to `None` for unauthenticated subscriptions; the field
48/// is omitted from the serialized JSON.
49#[derive(Debug, Clone, Serialize, Zeroize)]
50pub struct CoinbaseWsSubscription {
51    /// `"subscribe"` or `"unsubscribe"`.
52    #[serde(rename = "type")]
53    #[zeroize(skip)]
54    pub msg_type: CoinbaseWsAction,
55    /// Product IDs to subscribe to (omitted for channel-level subscriptions).
56    #[serde(skip_serializing_if = "Vec::is_empty")]
57    #[zeroize(skip)]
58    pub product_ids: Vec<Ustr>,
59    /// Channel name (subscription-side, e.g. `level2`).
60    #[zeroize(skip)]
61    pub channel: CoinbaseWsChannel,
62    /// JWT for authentication (required for `user` and `futures_balance_summary`).
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub jwt: Option<SecretString>,
65}
66
67/// WebSocket subscription action type.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "snake_case")]
70pub enum CoinbaseWsAction {
71    Subscribe,
72    Unsubscribe,
73}
74
75/// Top-level WebSocket message dispatched by channel.
76///
77/// Uses serde internally-tagged enum on the `channel` field so each variant
78/// deserializes only the events relevant to that channel.
79#[derive(Debug, Clone, Deserialize)]
80#[serde(tag = "channel")]
81pub enum CoinbaseWsMessage {
82    /// Order book snapshot or incremental update.
83    #[serde(rename = "l2_data")]
84    L2Data {
85        timestamp: String,
86        sequence_num: u64,
87        events: Vec<WsL2DataEvent>,
88    },
89
90    /// Market trade executions.
91    #[serde(rename = "market_trades")]
92    MarketTrades {
93        timestamp: String,
94        sequence_num: u64,
95        events: Vec<WsMarketTradesEvent>,
96    },
97
98    /// Price ticker for a single product.
99    #[serde(rename = "ticker")]
100    Ticker {
101        timestamp: String,
102        sequence_num: u64,
103        events: Vec<WsTickerEvent>,
104    },
105
106    /// Batched ticker updates for multiple products.
107    #[serde(rename = "ticker_batch")]
108    TickerBatch {
109        timestamp: String,
110        sequence_num: u64,
111        events: Vec<WsTickerEvent>,
112    },
113
114    /// OHLC candle updates.
115    #[serde(rename = "candles")]
116    Candles {
117        timestamp: String,
118        sequence_num: u64,
119        events: Vec<WsCandlesEvent>,
120    },
121
122    /// User order status updates.
123    ///
124    /// The feed handler deserializes this channel but ignores it until the
125    /// execution client is wired.
126    #[serde(rename = "user")]
127    User {
128        timestamp: String,
129        sequence_num: u64,
130        events: Vec<WsUserEvent>,
131    },
132
133    /// Connection heartbeat.
134    #[serde(rename = "heartbeats")]
135    Heartbeats {
136        timestamp: String,
137        sequence_num: u64,
138        events: Vec<WsHeartbeatEvent>,
139    },
140
141    /// Futures balance summary (requires auth).
142    ///
143    /// The feed handler deserializes this channel but ignores it until account
144    /// state handling is added.
145    #[serde(rename = "futures_balance_summary")]
146    FuturesBalanceSummary {
147        timestamp: String,
148        sequence_num: u64,
149        events: Vec<WsFuturesBalanceSummaryEvent>,
150    },
151
152    /// System status updates.
153    ///
154    /// The feed handler parses each product entry into an `InstrumentStatus`
155    /// event; the data client filters emissions to subscribed instruments.
156    #[serde(rename = "status")]
157    Status {
158        timestamp: String,
159        sequence_num: u64,
160        events: Vec<WsStatusEvent>,
161    },
162
163    /// Subscription confirmation.
164    #[serde(rename = "subscriptions")]
165    Subscriptions {
166        timestamp: String,
167        sequence_num: u64,
168        events: Vec<WsSubscriptionsEvent>,
169    },
170}
171
172impl CoinbaseWsMessage {
173    /// Returns the envelope `sequence_num`.
174    ///
175    /// Coinbase numbers every envelope on a connection with one counter, across all channels and
176    /// products, so a skipped value means an envelope was lost without saying which.
177    #[must_use]
178    pub fn sequence_num(&self) -> u64 {
179        match self {
180            Self::L2Data { sequence_num, .. }
181            | Self::MarketTrades { sequence_num, .. }
182            | Self::Ticker { sequence_num, .. }
183            | Self::TickerBatch { sequence_num, .. }
184            | Self::Candles { sequence_num, .. }
185            | Self::User { sequence_num, .. }
186            | Self::Heartbeats { sequence_num, .. }
187            | Self::FuturesBalanceSummary { sequence_num, .. }
188            | Self::Status { sequence_num, .. }
189            | Self::Subscriptions { sequence_num, .. } => *sequence_num,
190        }
191    }
192}
193
194/// L2 data event containing book updates.
195#[derive(Debug, Clone, Deserialize)]
196pub struct WsL2DataEvent {
197    /// `"snapshot"` for initial state, `"update"` for incremental.
198    #[serde(rename = "type")]
199    pub event_type: WsEventType,
200    pub product_id: Ustr,
201    pub updates: Vec<WsL2Update>,
202}
203
204/// A single order book level update.
205#[derive(Debug, Clone, Deserialize)]
206pub struct WsL2Update {
207    pub side: WsBookSide,
208    pub event_time: String,
209    pub price_level: String,
210    pub new_quantity: String,
211}
212
213/// Book side in L2 data messages.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum WsBookSide {
217    Bid,
218    Offer,
219}
220
221/// Market trades event.
222#[derive(Debug, Clone, Deserialize)]
223pub struct WsMarketTradesEvent {
224    /// `"snapshot"` or `"update"`.
225    #[serde(rename = "type")]
226    pub event_type: WsEventType,
227    pub trades: Vec<WsTrade>,
228}
229
230/// A single trade from the market_trades channel.
231#[derive(Debug, Clone, Deserialize)]
232pub struct WsTrade {
233    pub trade_id: String,
234    pub product_id: Ustr,
235    pub price: String,
236    pub size: String,
237    pub side: CoinbaseOrderSide,
238    pub time: String,
239}
240
241/// Ticker event.
242#[derive(Debug, Clone, Deserialize)]
243pub struct WsTickerEvent {
244    /// `"snapshot"` or `"update"`.
245    #[serde(rename = "type")]
246    pub event_type: WsEventType,
247    pub tickers: Vec<WsTicker>,
248}
249
250/// Ticker data for a single product.
251#[derive(Debug, Clone, Deserialize)]
252pub struct WsTicker {
253    pub product_id: Ustr,
254    pub price: String,
255    pub volume_24_h: String,
256    pub low_24_h: String,
257    pub high_24_h: String,
258    #[serde(default)]
259    pub low_52_w: String,
260    #[serde(default)]
261    pub high_52_w: String,
262    pub price_percent_chg_24_h: String,
263    pub best_bid: String,
264    pub best_bid_quantity: String,
265    pub best_ask: String,
266    pub best_ask_quantity: String,
267}
268
269/// Candles event.
270#[derive(Debug, Clone, Deserialize)]
271pub struct WsCandlesEvent {
272    /// `"snapshot"` or `"update"`.
273    #[serde(rename = "type")]
274    pub event_type: WsEventType,
275    pub candles: Vec<WsCandle>,
276}
277
278/// A single candle from the candles channel.
279#[derive(Debug, Clone, Deserialize)]
280pub struct WsCandle {
281    pub start: String,
282    pub high: String,
283    pub low: String,
284    pub open: String,
285    pub close: String,
286    pub volume: String,
287    pub product_id: Ustr,
288}
289
290/// User event containing order status updates.
291#[derive(Debug, Clone, Deserialize)]
292pub struct WsUserEvent {
293    /// `"snapshot"` or `"update"`.
294    #[serde(rename = "type")]
295    pub event_type: WsEventType,
296    pub orders: Vec<WsOrderUpdate>,
297}
298
299/// Order status update from the user channel.
300#[derive(Debug, Clone, Deserialize)]
301pub struct WsOrderUpdate {
302    pub order_id: String,
303    pub client_order_id: String,
304    pub contract_expiry_type: CoinbaseContractExpiryType,
305    pub cumulative_quantity: String,
306    pub leaves_quantity: String,
307    pub avg_price: String,
308    pub total_fees: String,
309    pub status: CoinbaseOrderStatus,
310    pub product_id: Ustr,
311    pub product_type: CoinbaseProductType,
312    pub creation_time: String,
313    pub order_side: CoinbaseOrderSide,
314    pub order_type: CoinbaseOrderType,
315    pub risk_managed_by: CoinbaseRiskManagedBy,
316    pub time_in_force: CoinbaseTimeInForce,
317    pub trigger_status: CoinbaseTriggerStatus,
318    #[serde(default)]
319    pub cancel_reason: String,
320    #[serde(default)]
321    pub reject_reason: String,
322    #[serde(default)]
323    pub total_value_after_fees: String,
324}
325
326/// Heartbeat event.
327#[derive(Debug, Clone, Deserialize)]
328pub struct WsHeartbeatEvent {
329    pub current_time: String,
330    pub heartbeat_counter: u64,
331}
332
333/// Futures balance summary event.
334#[derive(Debug, Clone, Deserialize)]
335pub struct WsFuturesBalanceSummaryEvent {
336    #[serde(rename = "type")]
337    pub event_type: WsEventType,
338    pub fcm_balance_summary: WsFcmBalanceSummary,
339}
340
341/// Futures balance summary snapshot.
342#[derive(Debug, Clone, Deserialize)]
343pub struct WsFcmBalanceSummary {
344    #[serde(deserialize_with = "deserialize_decimal_from_str")]
345    pub futures_buying_power: Decimal,
346    #[serde(deserialize_with = "deserialize_decimal_from_str")]
347    pub total_usd_balance: Decimal,
348    #[serde(deserialize_with = "deserialize_decimal_from_str")]
349    pub cbi_usd_balance: Decimal,
350    #[serde(deserialize_with = "deserialize_decimal_from_str")]
351    pub cfm_usd_balance: Decimal,
352    #[serde(deserialize_with = "deserialize_decimal_from_str")]
353    pub total_open_orders_hold_amount: Decimal,
354    #[serde(deserialize_with = "deserialize_decimal_from_str")]
355    pub unrealized_pnl: Decimal,
356    #[serde(deserialize_with = "deserialize_decimal_from_str")]
357    pub daily_realized_pnl: Decimal,
358    #[serde(deserialize_with = "deserialize_decimal_from_str")]
359    pub initial_margin: Decimal,
360    #[serde(deserialize_with = "deserialize_decimal_from_str")]
361    pub available_margin: Decimal,
362    #[serde(deserialize_with = "deserialize_decimal_from_str")]
363    pub liquidation_threshold: Decimal,
364    #[serde(deserialize_with = "deserialize_decimal_from_str")]
365    pub liquidation_buffer_amount: Decimal,
366    #[serde(deserialize_with = "deserialize_decimal_from_str")]
367    pub liquidation_buffer_percentage: Decimal,
368    pub intraday_margin_window_measure: WsMarginWindowMeasure,
369    pub overnight_margin_window_measure: WsMarginWindowMeasure,
370}
371
372/// Margin window summary inside a futures balance snapshot.
373#[derive(Debug, Clone, Deserialize)]
374pub struct WsMarginWindowMeasure {
375    pub margin_window_type: CoinbaseMarginWindowType,
376    pub margin_level: CoinbaseMarginLevel,
377    #[serde(deserialize_with = "deserialize_decimal_from_str")]
378    pub initial_margin: Decimal,
379    #[serde(deserialize_with = "deserialize_decimal_from_str")]
380    pub maintenance_margin: Decimal,
381    #[serde(deserialize_with = "deserialize_decimal_from_str")]
382    pub liquidation_buffer_percentage: Decimal,
383    #[serde(deserialize_with = "deserialize_decimal_from_str")]
384    pub total_hold: Decimal,
385    #[serde(deserialize_with = "deserialize_decimal_from_str")]
386    pub futures_buying_power: Decimal,
387}
388
389/// Status channel event.
390#[derive(Debug, Clone, Deserialize)]
391pub struct WsStatusEvent {
392    #[serde(rename = "type")]
393    pub event_type: WsEventType,
394    #[serde(default)]
395    pub products: Vec<WsStatusProduct>,
396}
397
398/// Status channel product snapshot.
399#[derive(Debug, Clone, Deserialize)]
400pub struct WsStatusProduct {
401    #[serde(deserialize_with = "deserialize_product_type_or_unknown")]
402    pub product_type: CoinbaseProductType,
403    pub id: Ustr,
404    pub base_currency: Ustr,
405    pub quote_currency: Ustr,
406    pub base_increment: String,
407    pub quote_increment: String,
408    pub display_name: String,
409    #[serde(deserialize_with = "deserialize_product_status_or_unknown")]
410    pub status: CoinbaseProductStatus,
411    pub status_message: String,
412    #[serde(deserialize_with = "deserialize_decimal_from_str")]
413    pub min_market_funds: Decimal,
414}
415
416/// Subscription confirmation event.
417#[derive(Debug, Clone, Deserialize)]
418pub struct WsSubscriptionsEvent {
419    pub subscriptions: HashMap<CoinbaseWsChannel, Vec<Ustr>>,
420}
421
422/// Event type discriminator for snapshot vs incremental update.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
424#[serde(rename_all = "snake_case")]
425pub enum WsEventType {
426    Snapshot,
427    Update,
428}
429
430#[cfg(test)]
431mod tests {
432    use rstest::rstest;
433
434    use super::*;
435    use crate::common::testing::load_test_fixture;
436
437    #[rstest]
438    fn test_deserialize_l2_snapshot() {
439        let json = load_test_fixture("ws_l2_data_snapshot.json");
440        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
441
442        match msg {
443            CoinbaseWsMessage::L2Data {
444                timestamp,
445                sequence_num,
446                events,
447            } => {
448                assert!(!timestamp.is_empty());
449                assert_eq!(sequence_num, 0);
450                assert_eq!(events.len(), 1);
451
452                let event = &events[0];
453                assert_eq!(event.event_type, WsEventType::Snapshot);
454                assert_eq!(event.product_id, "BTC-USD");
455                assert!(!event.updates.is_empty());
456
457                let bid = event
458                    .updates
459                    .iter()
460                    .find(|u| u.side == WsBookSide::Bid)
461                    .expect("should have a bid update");
462                assert!(!bid.price_level.is_empty());
463                assert!(!bid.new_quantity.is_empty());
464            }
465            other => panic!("Expected L2Data, was {other:?}"),
466        }
467    }
468
469    #[rstest]
470    fn test_deserialize_l2_update() {
471        let json = load_test_fixture("ws_l2_data_update.json");
472        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
473
474        match msg {
475            CoinbaseWsMessage::L2Data {
476                sequence_num,
477                events,
478                ..
479            } => {
480                assert!(sequence_num > 0);
481                assert_eq!(events[0].event_type, WsEventType::Update);
482            }
483            other => panic!("Expected L2Data, was {other:?}"),
484        }
485    }
486
487    #[rstest]
488    fn test_deserialize_market_trades() {
489        let json = load_test_fixture("ws_market_trades.json");
490        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
491
492        match msg {
493            CoinbaseWsMessage::MarketTrades { events, .. } => {
494                assert_eq!(events.len(), 1);
495                assert!(!events[0].trades.is_empty());
496
497                let trade = &events[0].trades[0];
498                assert_eq!(trade.product_id, "BTC-USD");
499                assert!(!trade.price.is_empty());
500                assert!(!trade.size.is_empty());
501                assert!(!trade.trade_id.is_empty());
502            }
503            other => panic!("Expected MarketTrades, was {other:?}"),
504        }
505    }
506
507    #[rstest]
508    fn test_deserialize_ticker() {
509        let json = load_test_fixture("ws_ticker.json");
510        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
511
512        match msg {
513            CoinbaseWsMessage::Ticker { events, .. } => {
514                assert_eq!(events.len(), 1);
515                assert!(!events[0].tickers.is_empty());
516
517                let ticker = &events[0].tickers[0];
518                assert_eq!(ticker.product_id, "BTC-USD");
519                assert!(!ticker.best_bid.is_empty());
520                assert!(!ticker.best_ask.is_empty());
521                assert!(!ticker.best_bid_quantity.is_empty());
522                assert!(!ticker.best_ask_quantity.is_empty());
523            }
524            other => panic!("Expected Ticker, was {other:?}"),
525        }
526    }
527
528    #[rstest]
529    fn test_deserialize_candles() {
530        let json = load_test_fixture("ws_candles.json");
531        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
532
533        match msg {
534            CoinbaseWsMessage::Candles { events, .. } => {
535                assert_eq!(events.len(), 1);
536                assert!(!events[0].candles.is_empty());
537
538                let candle = &events[0].candles[0];
539                assert_eq!(candle.product_id, "BTC-USD");
540                assert!(!candle.open.is_empty());
541                assert!(!candle.high.is_empty());
542                assert!(!candle.low.is_empty());
543                assert!(!candle.close.is_empty());
544                assert!(!candle.volume.is_empty());
545            }
546            other => panic!("Expected Candles, was {other:?}"),
547        }
548    }
549
550    #[rstest]
551    fn test_deserialize_user_order_update() {
552        let json = load_test_fixture("ws_user.json");
553        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
554
555        match msg {
556            CoinbaseWsMessage::User { events, .. } => {
557                assert_eq!(events.len(), 1);
558                assert!(!events[0].orders.is_empty());
559
560                let order = &events[0].orders[0];
561                assert!(!order.order_id.is_empty());
562                assert_eq!(order.product_id, "BTC-USD");
563                assert_eq!(order.status, CoinbaseOrderStatus::Open);
564                assert_eq!(order.order_side, CoinbaseOrderSide::Buy);
565                assert_eq!(order.order_type, CoinbaseOrderType::Limit);
566                assert_eq!(
567                    order.contract_expiry_type,
568                    CoinbaseContractExpiryType::Unknown
569                );
570                assert_eq!(order.product_type, CoinbaseProductType::Spot);
571                assert_eq!(order.risk_managed_by, CoinbaseRiskManagedBy::Unknown);
572                assert_eq!(order.time_in_force, CoinbaseTimeInForce::GoodUntilCancelled);
573                assert_eq!(
574                    order.trigger_status,
575                    CoinbaseTriggerStatus::InvalidOrderType
576                );
577            }
578            other => panic!("Expected User, was {other:?}"),
579        }
580    }
581
582    #[rstest]
583    fn test_deserialize_heartbeat() {
584        let json = load_test_fixture("ws_heartbeats.json");
585        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
586
587        match msg {
588            CoinbaseWsMessage::Heartbeats { events, .. } => {
589                assert_eq!(events.len(), 1);
590                assert!(!events[0].current_time.is_empty());
591                assert!(events[0].heartbeat_counter > 0);
592            }
593            other => panic!("Expected Heartbeats, was {other:?}"),
594        }
595    }
596
597    #[rstest]
598    fn test_deserialize_status_channel() {
599        let json = r#"{
600          "channel": "status",
601          "client_id": "",
602          "timestamp": "2023-02-09T20:29:49.753424311Z",
603          "sequence_num": 0,
604          "events": [
605            {
606              "type": "snapshot",
607              "products": [
608                {
609                  "product_type": "SPOT",
610                  "id": "BTC-USD",
611                  "base_currency": "BTC",
612                  "quote_currency": "USD",
613                  "base_increment": "0.00000001",
614                  "quote_increment": "0.01",
615                  "display_name": "BTC/USD",
616                  "status": "online",
617                  "status_message": "",
618                  "min_market_funds": "1"
619                }
620              ]
621            }
622          ]
623        }"#;
624        let msg: CoinbaseWsMessage = serde_json::from_str(json).unwrap();
625
626        match msg {
627            CoinbaseWsMessage::Status { events, .. } => {
628                assert_eq!(events.len(), 1);
629                assert_eq!(events[0].event_type, WsEventType::Snapshot);
630                assert_eq!(events[0].products.len(), 1);
631                let product = &events[0].products[0];
632                assert_eq!(product.id, "BTC-USD");
633                assert_eq!(product.product_type, CoinbaseProductType::Spot);
634                assert_eq!(product.status, CoinbaseProductStatus::Online);
635                assert_eq!(product.min_market_funds, Decimal::ONE);
636            }
637            other => panic!("Expected Status, was {other:?}"),
638        }
639    }
640
641    #[rstest]
642    fn test_deserialize_status_channel_unknown_status_does_not_fail() {
643        // Coinbase can introduce new product status values; deserialization must
644        // not hard-fail on an unrecognized status (e.g. a future "auction" state).
645        let json = r#"{
646          "channel": "status",
647          "client_id": "",
648          "timestamp": "2023-02-09T20:29:49.753424311Z",
649          "sequence_num": 0,
650          "events": [
651            {
652              "type": "snapshot",
653              "products": [
654                {
655                  "product_type": "SPOT",
656                  "id": "BTC-USD",
657                  "base_currency": "BTC",
658                  "quote_currency": "USD",
659                  "base_increment": "0.00000001",
660                  "quote_increment": "0.01",
661                  "display_name": "BTC/USD",
662                  "status": "auction",
663                  "status_message": "",
664                  "min_market_funds": "1"
665                }
666              ]
667            }
668          ]
669        }"#;
670        let msg: CoinbaseWsMessage = serde_json::from_str(json).unwrap();
671
672        match msg {
673            CoinbaseWsMessage::Status { events, .. } => {
674                assert_eq!(events[0].products[0].status, CoinbaseProductStatus::Unknown);
675            }
676            other => panic!("Expected Status, was {other:?}"),
677        }
678    }
679
680    #[rstest]
681    fn test_deserialize_status_channel_unknown_product_type_does_not_fail() {
682        // A new product type on the status channel must fall back to Unknown rather
683        // than hard-failing deserialization of the whole status message.
684        let json = r#"{
685          "channel": "status",
686          "client_id": "",
687          "timestamp": "2023-02-09T20:29:49.753424311Z",
688          "sequence_num": 0,
689          "events": [
690            {
691              "type": "snapshot",
692              "products": [
693                {
694                  "product_type": "PERPETUAL",
695                  "id": "BTC-PERP",
696                  "base_currency": "BTC",
697                  "quote_currency": "USD",
698                  "base_increment": "0.00000001",
699                  "quote_increment": "0.01",
700                  "display_name": "BTC-PERP",
701                  "status": "online",
702                  "status_message": "",
703                  "min_market_funds": "1"
704                }
705              ]
706            }
707          ]
708        }"#;
709        let msg: CoinbaseWsMessage = serde_json::from_str(json).unwrap();
710
711        match msg {
712            CoinbaseWsMessage::Status { events, .. } => {
713                assert_eq!(
714                    events[0].products[0].product_type,
715                    CoinbaseProductType::Unknown
716                );
717            }
718            other => panic!("Expected Status, was {other:?}"),
719        }
720    }
721
722    #[rstest]
723    fn test_deserialize_futures_balance_summary_channel() {
724        let json = r#"{
725          "channel": "futures_balance_summary",
726          "client_id": "",
727          "timestamp": "2023-02-09T20:33:57.609931463Z",
728          "sequence_num": 0,
729          "events": [
730            {
731              "type": "snapshot",
732              "fcm_balance_summary": {
733                "futures_buying_power": "100.00",
734                "total_usd_balance": "200.00",
735                "cbi_usd_balance": "300.00",
736                "cfm_usd_balance": "400.00",
737                "total_open_orders_hold_amount": "500.00",
738                "unrealized_pnl": "600.00",
739                "daily_realized_pnl": "0",
740                "initial_margin": "700.00",
741                "available_margin": "800.00",
742                "liquidation_threshold": "900.00",
743                "liquidation_buffer_amount": "1000.00",
744                "liquidation_buffer_percentage": "1000",
745                "intraday_margin_window_measure": {
746                  "margin_window_type": "FCM_MARGIN_WINDOW_TYPE_INTRADAY",
747                  "margin_level": "MARGIN_LEVEL_TYPE_BASE",
748                  "initial_margin": "100.00",
749                  "maintenance_margin": "200.00",
750                  "liquidation_buffer_percentage": "1000",
751                  "total_hold": "100.00",
752                  "futures_buying_power": "400.00"
753                },
754                "overnight_margin_window_measure": {
755                  "margin_window_type": "FCM_MARGIN_WINDOW_TYPE_OVERNIGHT",
756                  "margin_level": "MARGIN_LEVEL_TYPE_BASE",
757                  "initial_margin": "300.00",
758                  "maintenance_margin": "200.00",
759                  "liquidation_buffer_percentage": "1000",
760                  "total_hold": "-30.00",
761                  "futures_buying_power": "2000.00"
762                }
763              }
764            }
765          ]
766        }"#;
767        let msg: CoinbaseWsMessage = serde_json::from_str(json).unwrap();
768
769        match msg {
770            CoinbaseWsMessage::FuturesBalanceSummary { events, .. } => {
771                assert_eq!(events.len(), 1);
772                assert_eq!(events[0].event_type, WsEventType::Snapshot);
773                let summary = &events[0].fcm_balance_summary;
774                assert_eq!(summary.futures_buying_power, Decimal::from(100));
775                assert_eq!(summary.daily_realized_pnl, Decimal::ZERO);
776                assert_eq!(
777                    summary.intraday_margin_window_measure.margin_window_type,
778                    CoinbaseMarginWindowType::Intraday
779                );
780                assert_eq!(
781                    summary.overnight_margin_window_measure.margin_level,
782                    CoinbaseMarginLevel::Base
783                );
784                assert_eq!(
785                    summary.overnight_margin_window_measure.total_hold,
786                    "-30.00".parse::<Decimal>().unwrap()
787                );
788            }
789            other => panic!("Expected FuturesBalanceSummary, was {other:?}"),
790        }
791    }
792
793    #[rstest]
794    fn test_deserialize_subscriptions() {
795        let json = load_test_fixture("ws_subscriptions.json");
796        let msg: CoinbaseWsMessage = serde_json::from_str(&json).unwrap();
797
798        match msg {
799            CoinbaseWsMessage::Subscriptions { events, .. } => {
800                assert_eq!(events.len(), 1);
801                assert_eq!(
802                    events[0].subscriptions.get(&CoinbaseWsChannel::Level2),
803                    Some(&vec![Ustr::from("BTC-USD")])
804                );
805                assert_eq!(
806                    events[0]
807                        .subscriptions
808                        .get(&CoinbaseWsChannel::MarketTrades),
809                    Some(&vec![Ustr::from("BTC-USD"), Ustr::from("ETH-USD")])
810                );
811            }
812            other => panic!("Expected Subscriptions, was {other:?}"),
813        }
814    }
815
816    #[rstest]
817    fn test_serialize_subscribe_request_with_jwt() {
818        let sub = CoinbaseWsSubscription {
819            msg_type: CoinbaseWsAction::Subscribe,
820            product_ids: vec![Ustr::from("BTC-USD")],
821            channel: CoinbaseWsChannel::User,
822            jwt: Some(SecretString::from("test-jwt-token")),
823        };
824
825        let json = serde_json::to_value(&sub).unwrap();
826        assert_eq!(json["type"], "subscribe");
827        assert_eq!(json["channel"], "user");
828        assert_eq!(json["product_ids"][0], "BTC-USD");
829        assert_eq!(json["jwt"], "test-jwt-token");
830    }
831
832    #[rstest]
833    fn test_serialize_subscribe_request_public_omits_jwt() {
834        let sub = CoinbaseWsSubscription {
835            msg_type: CoinbaseWsAction::Subscribe,
836            product_ids: vec![Ustr::from("BTC-USD")],
837            channel: CoinbaseWsChannel::Level2,
838            jwt: None,
839        };
840
841        let json = serde_json::to_value(&sub).unwrap();
842        assert_eq!(json["type"], "subscribe");
843        assert_eq!(json["channel"], "level2");
844        assert!(json.get("jwt").is_none());
845    }
846
847    #[rstest]
848    fn test_serialize_unsubscribe_request() {
849        let sub = CoinbaseWsSubscription {
850            msg_type: CoinbaseWsAction::Unsubscribe,
851            product_ids: vec![Ustr::from("ETH-USD")],
852            channel: CoinbaseWsChannel::MarketTrades,
853            jwt: None,
854        };
855
856        let json = serde_json::to_value(&sub).unwrap();
857        assert_eq!(json["type"], "unsubscribe");
858        assert_eq!(json["channel"], "market_trades");
859        assert!(json.get("jwt").is_none());
860    }
861
862    #[rstest]
863    fn test_serialize_channel_level_subscription_omits_product_ids() {
864        let sub = CoinbaseWsSubscription {
865            msg_type: CoinbaseWsAction::Subscribe,
866            product_ids: vec![],
867            channel: CoinbaseWsChannel::Heartbeats,
868            jwt: None,
869        };
870
871        let json = serde_json::to_value(&sub).unwrap();
872        assert_eq!(json["type"], "subscribe");
873        assert_eq!(json["channel"], "heartbeats");
874        assert!(json.get("product_ids").is_none());
875        assert!(json.get("jwt").is_none());
876    }
877
878    #[rstest]
879    fn test_ws_event_type_values() {
880        let snapshot: WsEventType = serde_json::from_str("\"snapshot\"").unwrap();
881        assert_eq!(snapshot, WsEventType::Snapshot);
882
883        let update: WsEventType = serde_json::from_str("\"update\"").unwrap();
884        assert_eq!(update, WsEventType::Update);
885    }
886
887    #[rstest]
888    fn test_ws_book_side_values() {
889        let bid: WsBookSide = serde_json::from_str("\"bid\"").unwrap();
890        assert_eq!(bid, WsBookSide::Bid);
891
892        let offer: WsBookSide = serde_json::from_str("\"offer\"").unwrap();
893        assert_eq!(offer, WsBookSide::Offer);
894    }
895}