1use 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#[derive(Debug, Clone, Serialize, Zeroize)]
50pub struct CoinbaseWsSubscription {
51 #[serde(rename = "type")]
53 #[zeroize(skip)]
54 pub msg_type: CoinbaseWsAction,
55 #[serde(skip_serializing_if = "Vec::is_empty")]
57 #[zeroize(skip)]
58 pub product_ids: Vec<Ustr>,
59 #[zeroize(skip)]
61 pub channel: CoinbaseWsChannel,
62 #[serde(skip_serializing_if = "Option::is_none")]
64 pub jwt: Option<SecretString>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "snake_case")]
70pub enum CoinbaseWsAction {
71 Subscribe,
72 Unsubscribe,
73}
74
75#[derive(Debug, Clone, Deserialize)]
80#[serde(tag = "channel")]
81pub enum CoinbaseWsMessage {
82 #[serde(rename = "l2_data")]
84 L2Data {
85 timestamp: String,
86 sequence_num: u64,
87 events: Vec<WsL2DataEvent>,
88 },
89
90 #[serde(rename = "market_trades")]
92 MarketTrades {
93 timestamp: String,
94 sequence_num: u64,
95 events: Vec<WsMarketTradesEvent>,
96 },
97
98 #[serde(rename = "ticker")]
100 Ticker {
101 timestamp: String,
102 sequence_num: u64,
103 events: Vec<WsTickerEvent>,
104 },
105
106 #[serde(rename = "ticker_batch")]
108 TickerBatch {
109 timestamp: String,
110 sequence_num: u64,
111 events: Vec<WsTickerEvent>,
112 },
113
114 #[serde(rename = "candles")]
116 Candles {
117 timestamp: String,
118 sequence_num: u64,
119 events: Vec<WsCandlesEvent>,
120 },
121
122 #[serde(rename = "user")]
127 User {
128 timestamp: String,
129 sequence_num: u64,
130 events: Vec<WsUserEvent>,
131 },
132
133 #[serde(rename = "heartbeats")]
135 Heartbeats {
136 timestamp: String,
137 sequence_num: u64,
138 events: Vec<WsHeartbeatEvent>,
139 },
140
141 #[serde(rename = "futures_balance_summary")]
146 FuturesBalanceSummary {
147 timestamp: String,
148 sequence_num: u64,
149 events: Vec<WsFuturesBalanceSummaryEvent>,
150 },
151
152 #[serde(rename = "status")]
157 Status {
158 timestamp: String,
159 sequence_num: u64,
160 events: Vec<WsStatusEvent>,
161 },
162
163 #[serde(rename = "subscriptions")]
165 Subscriptions {
166 timestamp: String,
167 sequence_num: u64,
168 events: Vec<WsSubscriptionsEvent>,
169 },
170}
171
172impl CoinbaseWsMessage {
173 #[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#[derive(Debug, Clone, Deserialize)]
196pub struct WsL2DataEvent {
197 #[serde(rename = "type")]
199 pub event_type: WsEventType,
200 pub product_id: Ustr,
201 pub updates: Vec<WsL2Update>,
202}
203
204#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum WsBookSide {
217 Bid,
218 Offer,
219}
220
221#[derive(Debug, Clone, Deserialize)]
223pub struct WsMarketTradesEvent {
224 #[serde(rename = "type")]
226 pub event_type: WsEventType,
227 pub trades: Vec<WsTrade>,
228}
229
230#[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#[derive(Debug, Clone, Deserialize)]
243pub struct WsTickerEvent {
244 #[serde(rename = "type")]
246 pub event_type: WsEventType,
247 pub tickers: Vec<WsTicker>,
248}
249
250#[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#[derive(Debug, Clone, Deserialize)]
271pub struct WsCandlesEvent {
272 #[serde(rename = "type")]
274 pub event_type: WsEventType,
275 pub candles: Vec<WsCandle>,
276}
277
278#[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#[derive(Debug, Clone, Deserialize)]
292pub struct WsUserEvent {
293 #[serde(rename = "type")]
295 pub event_type: WsEventType,
296 pub orders: Vec<WsOrderUpdate>,
297}
298
299#[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#[derive(Debug, Clone, Deserialize)]
328pub struct WsHeartbeatEvent {
329 pub current_time: String,
330 pub heartbeat_counter: u64,
331}
332
333#[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#[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#[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#[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#[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#[derive(Debug, Clone, Deserialize)]
418pub struct WsSubscriptionsEvent {
419 pub subscriptions: HashMap<CoinbaseWsChannel, Vec<Ustr>>,
420}
421
422#[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 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 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}