Skip to main content

nautilus_coinapi/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//! Raw CoinAPI WebSocket V1 frames, decoded directly from JSON bytes to preserve decimal tokens.
17
18use jiff::Timestamp;
19use nautilus_core::serialization::decimal;
20use rust_decimal::Decimal;
21use serde::{Deserialize, Serialize};
22use ustr::Ustr;
23
24use super::error::Error;
25use crate::{
26    common::enums::{OhlcvPeriod, TakerSide},
27    http::models::BookLevel,
28};
29
30/// A market data stream type accepted in `subscribe_data_type`.
31#[derive(
32    Debug,
33    Clone,
34    Copy,
35    PartialEq,
36    Eq,
37    Hash,
38    Serialize,
39    Deserialize,
40    strum::AsRefStr,
41    strum::EnumString,
42)]
43#[serde(rename_all = "snake_case")]
44#[strum(serialize_all = "snake_case")]
45pub enum DataType {
46    Book,
47    Book5,
48    Book20,
49    Book50,
50    BookL3,
51    Quote,
52    Trade,
53    Ohlcv,
54}
55
56impl DataType {
57    /// Returns whether this is an order book type.
58    ///
59    /// A session scope can list only one book type; CoinAPI rejects a second with a terminal
60    /// `error` frame.
61    #[must_use]
62    pub fn is_book(self) -> bool {
63        matches!(
64            self,
65            Self::Book | Self::Book5 | Self::Book20 | Self::Book50 | Self::BookL3
66        )
67    }
68}
69
70/// A data type, plus its period for OHLCV.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub struct Channel {
73    pub data_type: DataType,
74    /// Required for and only valid with [`DataType::Ohlcv`], for example `1MIN`.
75    pub period_id: Option<OhlcvPeriod>,
76}
77
78impl Channel {
79    pub(super) fn validate(&self) -> Result<(), Error> {
80        match (self.data_type, self.period_id) {
81            (DataType::Ohlcv, Some(period))
82                if !period.as_ref().is_empty()
83                    && period.as_ref().bytes().all(|b| b.is_ascii_alphanumeric()) =>
84            {
85                Ok(())
86            }
87            (DataType::Ohlcv, _) => Err(Error::Validation(
88                "OHLCV requires an alphanumeric period_id".into(),
89            )),
90            (_, Some(_)) => Err(Error::Validation(
91                "period_id is only valid for OHLCV".into(),
92            )),
93            (_, None) => Ok(()),
94        }
95    }
96}
97
98/// One symbol on one channel.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub struct Subscription {
101    pub channel: Channel,
102    /// Full CoinAPI `symbol_id`, matched exactly.
103    pub symbol_id: Ustr,
104}
105
106impl Subscription {
107    pub(super) fn validate(&self) -> Result<(), Error> {
108        self.channel.validate()?;
109
110        if self.symbol_id.is_empty()
111            || !self
112                .symbol_id
113                .bytes()
114                .all(|b| (33..=126).contains(&b) && b != b'$')
115        {
116            return Err(Error::Validation(
117                "symbol_id must contain visible ASCII characters other than '$'".into(),
118            ));
119        }
120
121        Ok(())
122    }
123}
124
125/// A change to the session scope, applied in order with others that share one `hello`.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ScopeChange {
128    Subscribe(Subscription),
129    Unsubscribe(Subscription),
130}
131
132impl ScopeChange {
133    /// Returns the pair the change adds or removes.
134    #[must_use]
135    pub fn subscription(&self) -> &Subscription {
136        match self {
137            Self::Subscribe(subscription) | Self::Unsubscribe(subscription) => subscription,
138        }
139    }
140}
141
142/// A `hello` request that replaces the whole session scope.
143///
144/// CoinAPI combines every listed data type, symbol, and period, so the scope can include
145/// pairs nobody subscribed to. Authentication uses the `X-CoinAPI-Key` upgrade header, so this
146/// frame carries no credential.
147#[derive(Debug, Serialize)]
148pub(super) struct Hello {
149    r#type: &'static str,
150    heartbeat: bool,
151    subscribe_data_type: Vec<DataType>,
152    subscribe_filter_symbol_id: Vec<String>,
153    #[serde(skip_serializing_if = "Vec::is_empty")]
154    subscribe_filter_period_id: Vec<OhlcvPeriod>,
155}
156
157impl Hello {
158    /// Builds the smallest exact-symbol scope covering every subscription, in sorted order.
159    pub(super) fn new(subscriptions: &[Subscription]) -> Self {
160        let mut data_types: Vec<DataType> =
161            subscriptions.iter().map(|s| s.channel.data_type).collect();
162        data_types.sort_unstable_by(|a, b| a.as_ref().cmp(b.as_ref()));
163        data_types.dedup();
164
165        let mut symbols: Vec<&str> = subscriptions.iter().map(|s| s.symbol_id.as_str()).collect();
166        symbols.sort_unstable();
167        symbols.dedup();
168
169        let mut periods: Vec<OhlcvPeriod> = subscriptions
170            .iter()
171            .filter_map(|s| s.channel.period_id)
172            .collect();
173        periods.sort_unstable_by(|a, b| a.as_ref().cmp(b.as_ref()));
174        periods.dedup();
175
176        Self {
177            r#type: "hello",
178            heartbeat: true,
179            subscribe_data_type: data_types,
180            subscribe_filter_symbol_id: symbols.iter().map(|s| format!("{s}$")).collect(),
181            subscribe_filter_period_id: periods,
182        }
183    }
184}
185
186/// An L2 book message from `book`, `book5`, `book20`, or `book50`.
187///
188/// Only `book` carries `is_snapshot`; the fixed-depth types always list their top levels.
189#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
190pub struct Book {
191    #[serde(rename = "type")]
192    pub data_type: DataType,
193    pub symbol_id: Ustr,
194    pub sequence: u64,
195    pub time_exchange: Timestamp,
196    pub time_coinapi: Timestamp,
197    pub is_snapshot: Option<bool>,
198    pub asks: Vec<BookLevel>,
199    pub bids: Vec<BookLevel>,
200}
201
202/// An order-by-order book snapshot or update.
203#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
204pub struct BookL3 {
205    pub symbol_id: Ustr,
206    pub sequence: u64,
207    pub time_exchange: Timestamp,
208    pub time_coinapi: Timestamp,
209    pub is_snapshot: bool,
210    pub asks: Vec<BookL3Entry>,
211    pub bids: Vec<BookL3Entry>,
212}
213
214/// An order entry; a missing identifier marks an aggregated L2 fallback entry.
215#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
216pub struct BookL3Entry {
217    pub id: Option<String>,
218    #[serde(deserialize_with = "decimal::deserialize_json")]
219    pub price: Decimal,
220    #[serde(deserialize_with = "decimal::deserialize_json")]
221    pub size: Decimal,
222    /// Absent in snapshots.
223    pub update_type: Option<BookUpdateType>,
224}
225
226/// How an L3 update changes an order.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
228#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
229pub enum BookUpdateType {
230    Add,
231    Update,
232    Subtract,
233    Delete,
234    Match,
235    #[serde(other)]
236    Other,
237}
238
239/// A best bid and ask update; zero sizes mean the size is unknown.
240#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
241pub struct Quote {
242    pub symbol_id: Ustr,
243    pub sequence: u64,
244    pub time_exchange: Timestamp,
245    pub time_coinapi: Timestamp,
246    #[serde(deserialize_with = "decimal::deserialize_json")]
247    pub ask_price: Decimal,
248    #[serde(deserialize_with = "decimal::deserialize_json")]
249    pub ask_size: Decimal,
250    #[serde(deserialize_with = "decimal::deserialize_json")]
251    pub bid_price: Decimal,
252    #[serde(deserialize_with = "decimal::deserialize_json")]
253    pub bid_size: Decimal,
254}
255
256/// An executed trade.
257#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
258pub struct Trade {
259    pub symbol_id: Ustr,
260    pub sequence: u64,
261    pub time_exchange: Timestamp,
262    pub time_coinapi: Timestamp,
263    pub uuid: String,
264    #[serde(deserialize_with = "decimal::deserialize_json")]
265    pub price: Decimal,
266    #[serde(deserialize_with = "decimal::deserialize_json")]
267    pub size: Decimal,
268    pub taker_side: TakerSide,
269}
270
271/// An OHLCV period update, sent on close or while the period is still open.
272#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
273pub struct Ohlcv {
274    pub symbol_id: Ustr,
275    pub sequence: u64,
276    pub period_id: OhlcvPeriod,
277    pub time_period_start: Timestamp,
278    pub time_period_end: Timestamp,
279    pub time_open: Timestamp,
280    pub time_close: Timestamp,
281    #[serde(deserialize_with = "decimal::deserialize_json")]
282    pub price_open: Decimal,
283    #[serde(deserialize_with = "decimal::deserialize_json")]
284    pub price_high: Decimal,
285    #[serde(deserialize_with = "decimal::deserialize_json")]
286    pub price_low: Decimal,
287    #[serde(deserialize_with = "decimal::deserialize_json")]
288    pub price_close: Decimal,
289    #[serde(deserialize_with = "decimal::deserialize_json")]
290    pub volume_traded: Decimal,
291    pub trades_count: u64,
292}
293
294/// A server notice that the connection closes before `before_time`.
295#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
296pub struct Reconnect {
297    pub within_seconds: u64,
298    pub before_time: Timestamp,
299}
300
301/// A terminal venue error; the server closes the connection after sending it.
302#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
303pub struct VenueError {
304    pub message: String,
305}
306
307/// Messages emitted by [`CoinApiWebSocketClient`](super::client::CoinApiWebSocketClient).
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub enum CoinApiWsMessage {
310    Book(Book),
311    BookL3(BookL3),
312    Quote(Quote),
313    Trade(Trade),
314    Ohlcv(Ohlcv),
315    /// The venue rejected the session; its connection and subscriptions are retired.
316    Error(String),
317    /// A replacement connection replayed the subscriptions.
318    ///
319    /// Sequence numbers restart per connection, so consumers must reset stream state such as books.
320    Reconnected,
321}
322
323impl CoinApiWsMessage {
324    /// Returns the channel and symbol a data message belongs to.
325    pub(super) fn subscription(&self) -> Option<Subscription> {
326        let (data_type, period_id, symbol_id) = match self {
327            Self::Book(book) => (book.data_type, None, book.symbol_id),
328            Self::BookL3(book) => (DataType::BookL3, None, book.symbol_id),
329            Self::Quote(quote) => (DataType::Quote, None, quote.symbol_id),
330            Self::Trade(trade) => (DataType::Trade, None, trade.symbol_id),
331            Self::Ohlcv(ohlcv) => (DataType::Ohlcv, Some(ohlcv.period_id), ohlcv.symbol_id),
332            Self::Error(_) | Self::Reconnected => return None,
333        };
334
335        Some(Subscription {
336            channel: Channel {
337                data_type,
338                period_id,
339            },
340            symbol_id,
341        })
342    }
343}
344
345/// One decoded inbound text frame.
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub enum Frame {
348    Data(CoinApiWsMessage),
349    Heartbeat,
350    Reconnect(Reconnect),
351    Error(VenueError),
352    Unknown(String),
353}
354
355#[derive(Deserialize)]
356struct Envelope<'a> {
357    #[serde(borrow)]
358    r#type: &'a str,
359}
360
361impl Frame {
362    /// Decodes a text frame by its `type` field.
363    ///
364    /// Reads the tag in a first pass and then decodes the matching struct from the original bytes:
365    /// Serde tagged enums buffer numbers and lose raw decimal tokens, and CoinAPI sends `type` last.
366    ///
367    /// # Errors
368    ///
369    /// Returns an error if the frame is not JSON, has no string `type`, or a known type's payload
370    /// does not decode.
371    pub fn decode(bytes: &[u8]) -> Result<Self, serde_json::Error> {
372        let envelope: Envelope = serde_json::from_slice(bytes)?;
373        Ok(match envelope.r#type {
374            "book" | "book5" | "book20" | "book50" => {
375                Self::Data(CoinApiWsMessage::Book(serde_json::from_slice(bytes)?))
376            }
377            "book_l3" => Self::Data(CoinApiWsMessage::BookL3(serde_json::from_slice(bytes)?)),
378            "quote" => Self::Data(CoinApiWsMessage::Quote(serde_json::from_slice(bytes)?)),
379            "trade" => Self::Data(CoinApiWsMessage::Trade(serde_json::from_slice(bytes)?)),
380            "ohlcv" => Self::Data(CoinApiWsMessage::Ohlcv(serde_json::from_slice(bytes)?)),
381
382            // CoinAPI spells the heartbeat type this way on the wire
383            "hearbeat" => Self::Heartbeat,
384            "reconnect" => Self::Reconnect(serde_json::from_slice(bytes)?),
385            "error" => Self::Error(serde_json::from_slice(bytes)?),
386            other => Self::Unknown(other.to_owned()),
387        })
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use rstest::rstest;
394
395    use super::*;
396
397    fn decimal(text: &str) -> Decimal {
398        Decimal::from_str_exact(text).unwrap()
399    }
400
401    fn time(text: &str) -> Timestamp {
402        text.parse().unwrap()
403    }
404
405    fn decode(bytes: &str) -> Frame {
406        Frame::decode(bytes.as_bytes()).unwrap()
407    }
408
409    fn level(price: &str, size: &str) -> BookLevel {
410        BookLevel {
411            id: None,
412            price: decimal(price),
413            size: decimal(size),
414        }
415    }
416
417    #[rstest]
418    fn full_book_carries_snapshot_flag() {
419        assert_eq!(
420            decode(include_str!("../../test_data/ws_book.json")),
421            Frame::Data(CoinApiWsMessage::Book(Book {
422                data_type: DataType::Book,
423                symbol_id: "BITSTAMP_SPOT_BTC_USD".into(),
424                sequence: 2_323_346,
425                time_exchange: time("2013-09-28T22:40:50.0000000Z"),
426                time_coinapi: time("2017-03-18T22:42:21.3763342Z"),
427                is_snapshot: Some(true),
428                asks: vec![level("456.35", "123"), level("456.36", "23")],
429                bids: vec![level("456.10", "42"), level("456.09", "5")],
430            }))
431        );
432    }
433
434    #[rstest]
435    fn fixed_depth_book_keeps_its_type_without_snapshot_flag() {
436        assert_eq!(
437            decode(include_str!("../../test_data/ws_book20.json")),
438            Frame::Data(CoinApiWsMessage::Book(Book {
439                data_type: DataType::Book20,
440                symbol_id: "BITSTAMP_SPOT_BTC_USD".into(),
441                sequence: 2_323_346,
442                time_exchange: time("2013-09-28T22:40:50.0000000Z"),
443                time_coinapi: time("2017-03-18T22:42:21.3763342Z"),
444                is_snapshot: None,
445                asks: vec![level("456.35", "123")],
446                bids: vec![level("456.10", "42")],
447            }))
448        );
449    }
450
451    #[rstest]
452    fn book_l3_preserves_order_identity_and_update_types() {
453        let entry = |id: Option<&str>, price: &str, size: &str, update_type| BookL3Entry {
454            id: id.map(Into::into),
455            price: decimal(price),
456            size: decimal(size),
457            update_type: Some(update_type),
458        };
459
460        assert_eq!(
461            decode(include_str!("../../test_data/ws_book_l3.json")),
462            Frame::Data(CoinApiWsMessage::BookL3(BookL3 {
463                symbol_id: "COINBASE_SPOT_BCH_USD".into(),
464                sequence: 2_323_346,
465                time_exchange: time("2020-08-26T12:36:04.3464706Z"),
466                time_coinapi: time("2020-08-26T12:36:04.2807750Z"),
467                is_snapshot: false,
468                asks: vec![
469                    entry(
470                        Some("520269d4-c085-47ed-8825-6d787af90800"),
471                        "273.01",
472                        "1.81940502",
473                        BookUpdateType::Add
474                    ),
475                    entry(
476                        Some("0ac891c7-8360-462c-8d9a-d8b217d3fca2"),
477                        "273.02",
478                        "1.0",
479                        BookUpdateType::Delete
480                    ),
481                ],
482                bids: vec![
483                    entry(
484                        Some("6340ec1e-8be8-404e-b9a4-a14120ec179e"),
485                        "272.94",
486                        "1.81940502",
487                        BookUpdateType::Update
488                    ),
489                    entry(None, "272.93", "4.5", BookUpdateType::Match),
490                ],
491            }))
492        );
493    }
494
495    #[rstest]
496    #[case("SUBTRACT", BookUpdateType::Subtract)]
497    #[case("REPLACE", BookUpdateType::Other)]
498    fn book_update_type_classifies_open_values(
499        #[case] wire: &str,
500        #[case] expected: BookUpdateType,
501    ) {
502        assert_eq!(
503            serde_json::from_str::<BookUpdateType>(&format!("\"{wire}\"")).unwrap(),
504            expected
505        );
506    }
507
508    #[rstest]
509    fn quote_preserves_every_field_and_decimal_scale() {
510        let Frame::Data(CoinApiWsMessage::Quote(quote)) =
511            decode(include_str!("../../test_data/ws_quote.json"))
512        else {
513            panic!("expected quote");
514        };
515
516        assert_eq!(
517            quote,
518            Quote {
519                symbol_id: "BITSTAMP_SPOT_BTC_USD".into(),
520                sequence: 2_323_346,
521                time_exchange: time("2013-09-28T22:40:50.0000000Z"),
522                time_coinapi: time("2017-03-18T22:42:21.3763342Z"),
523                ask_price: decimal("770.000000000"),
524                ask_size: decimal("3252"),
525                bid_price: decimal("760"),
526                bid_size: decimal("124"),
527            }
528        );
529        assert_eq!(quote.ask_price.scale(), 9);
530    }
531
532    #[rstest]
533    fn trade_preserves_every_field_and_decimal_scale() {
534        let Frame::Data(CoinApiWsMessage::Trade(trade)) =
535            decode(include_str!("../../test_data/ws_trade.json"))
536        else {
537            panic!("expected trade");
538        };
539
540        assert_eq!(
541            trade,
542            Trade {
543                symbol_id: "COINBASE_SPOT_BTC_USD".into(),
544                sequence: 1507,
545                time_exchange: time("2026-09-25T01:29:06.0656180Z"),
546                time_coinapi: time("2026-09-25T01:29:06.1438272Z"),
547                uuid: "c2519dfb-79a6-40e9-a1c8-a95d94209399".into(),
548                price: decimal("84520.02"),
549                size: decimal("0.00000004"),
550                taker_side: "SELL".into(),
551            }
552        );
553        assert_eq!((trade.price.scale(), trade.size.scale()), (2, 8));
554    }
555
556    #[rstest]
557    fn ohlcv_preserves_period_and_every_field() {
558        assert_eq!(
559            decode(include_str!("../../test_data/ws_ohlcv.json")),
560            Frame::Data(CoinApiWsMessage::Ohlcv(Ohlcv {
561                symbol_id: "COINBASE_SPOT_BTC_USD".into(),
562                sequence: 520_348,
563                period_id: "1SEC".into(),
564                time_period_start: time("2026-09-25T01:30:01.0000000Z"),
565                time_period_end: time("2026-09-25T01:30:02.0000000Z"),
566                time_open: time("2026-09-25T01:30:01.0173140Z"),
567                time_close: time("2026-09-25T01:30:01.7668490Z"),
568                price_open: decimal("84523.69"),
569                price_high: decimal("84523.69"),
570                price_low: decimal("84523.68"),
571                price_close: decimal("84523.69"),
572                volume_traded: decimal("0.00468951"),
573                trades_count: 5,
574            }))
575        );
576    }
577
578    #[rstest]
579    #[case(include_str!("../../test_data/ws_heartbeat.json"), Frame::Heartbeat)]
580    #[case(
581        include_str!("../../test_data/ws_reconnect.json"),
582        Frame::Reconnect(Reconnect {
583            within_seconds: 10,
584            before_time: "2020-08-06T19:19:09.7035429Z".parse().unwrap(),
585        })
586    )]
587    #[case(
588        include_str!("../../test_data/ws_error.json"),
589        Frame::Error(VenueError {
590            message: "Subscribed data type 'nonsense' is invalid. Allowed values: book5, book20, \
591                      book50, book, book_l3, quote, trade, ohlcv, exrate, asset, exchange, \
592                      symbol, connectivity_status."
593                .into(),
594        })
595    )]
596    #[case(r#"{"type":"heartbeat"}"#, Frame::Unknown("heartbeat".into()))]
597    #[case(r#"{"asset_id":"BTC","type":"asset"}"#, Frame::Unknown("asset".into()))]
598    fn control_frames_decode_by_type(#[case] bytes: &str, #[case] expected: Frame) {
599        assert_eq!(decode(bytes), expected);
600    }
601
602    #[rstest]
603    #[case(include_str!("../../test_data/malformed.txt"))]
604    #[case(r#"{"symbol_id":"TEST"}"#)]
605    #[case(r#"{"type":"trade","symbol_id":"TEST"}"#)]
606    #[case(r#"{"type":"error"}"#)]
607    fn malformed_frames_fail_decoding(#[case] bytes: &str) {
608        assert!(Frame::decode(bytes.as_bytes()).is_err());
609    }
610
611    fn sub(data_type: DataType, period_id: Option<&str>, symbol_id: &str) -> Subscription {
612        Subscription {
613            channel: Channel {
614                data_type,
615                period_id: period_id.map(OhlcvPeriod::from),
616            },
617            symbol_id: symbol_id.into(),
618        }
619    }
620
621    #[rstest]
622    #[case(
623        vec![sub(DataType::Trade, None, "B"), sub(DataType::Trade, None, "A")],
624        r#"{"type":"hello","heartbeat":true,"subscribe_data_type":["trade"],"subscribe_filter_symbol_id":["A$","B$"]}"#
625    )]
626    #[case(
627        vec![sub(DataType::Trade, None, "A"), sub(DataType::BookL3, None, "B"), sub(DataType::Book20, None, "A")],
628        r#"{"type":"hello","heartbeat":true,"subscribe_data_type":["book20","book_l3","trade"],"subscribe_filter_symbol_id":["A$","B$"]}"#
629    )]
630    #[case(
631        vec![sub(DataType::Ohlcv, Some("1SEC"), "A"), sub(DataType::Ohlcv, Some("1MIN"), "A"), sub(DataType::Quote, None, "A")],
632        r#"{"type":"hello","heartbeat":true,"subscribe_data_type":["ohlcv","quote"],"subscribe_filter_symbol_id":["A$"],"subscribe_filter_period_id":["1MIN","1SEC"]}"#
633    )]
634    fn hello_serializes_sorted_union_scope(
635        #[case] subscriptions: Vec<Subscription>,
636        #[case] expected: &str,
637    ) {
638        assert_eq!(
639            serde_json::to_string(&Hello::new(&subscriptions)).unwrap(),
640            expected
641        );
642    }
643
644    #[rstest]
645    #[case(DataType::Book, "book")]
646    #[case(DataType::Book5, "book5")]
647    #[case(DataType::Book20, "book20")]
648    #[case(DataType::Book50, "book50")]
649    #[case(DataType::BookL3, "book_l3")]
650    #[case(DataType::Quote, "quote")]
651    #[case(DataType::Trade, "trade")]
652    #[case(DataType::Ohlcv, "ohlcv")]
653    fn data_type_topic_name_matches_wire_name(#[case] data_type: DataType, #[case] wire: &str) {
654        assert_eq!(data_type.is_book(), wire.starts_with("book"));
655        assert_eq!(data_type.as_ref(), wire);
656        assert_eq!(wire.parse::<DataType>().unwrap(), data_type);
657        assert_eq!(
658            serde_json::to_string(&data_type).unwrap(),
659            format!("\"{wire}\"")
660        );
661    }
662
663    #[rstest]
664    #[case(DataType::Trade, None, "COINBASE_SPOT_BTC_USD", true)]
665    #[case(DataType::Ohlcv, Some("1MIN"), "COINBASE_SPOT_BTC_USD", true)]
666    #[case(DataType::Ohlcv, None, "COINBASE_SPOT_BTC_USD", false)]
667    #[case(DataType::Ohlcv, Some(""), "COINBASE_SPOT_BTC_USD", false)]
668    #[case(DataType::Ohlcv, Some("1:MIN"), "COINBASE_SPOT_BTC_USD", false)]
669    #[case(DataType::Trade, Some("1MIN"), "COINBASE_SPOT_BTC_USD", false)]
670    #[case(DataType::Trade, None, "", false)]
671    #[case(DataType::Trade, None, "COINBASE_SPOT_BTC_USD$", false)]
672    #[case(DataType::Trade, None, "COINBASE SPOT", false)]
673    fn subscription_validation(
674        #[case] data_type: DataType,
675        #[case] period_id: Option<&str>,
676        #[case] symbol_id: &str,
677        #[case] valid: bool,
678    ) {
679        let subscription = Subscription {
680            channel: Channel {
681                data_type,
682                period_id: period_id.map(OhlcvPeriod::from),
683            },
684            symbol_id: symbol_id.into(),
685        };
686
687        assert_eq!(subscription.validate().is_ok(), valid);
688    }
689}