nautilus_binance/spot/websocket/streams/
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//! Binance Spot WebSocket message types.
17//!
18//! This module defines:
19//! - [`NautilusWsMessage`]: Output messages emitted by the handler to the client.
20//! - [`HandlerCommand`]: Commands sent from the client to the handler.
21//! - Subscription request/response structures for the Binance WebSocket API.
22
23use nautilus_model::{
24    data::{Data, OrderBookDeltas},
25    instruments::InstrumentAny,
26};
27use nautilus_network::websocket::WebSocketClient;
28use serde::{Deserialize, Serialize};
29
30use crate::common::enums::BinanceWsMethod;
31// Re-export SBE stream types for convenience
32pub use crate::common::sbe::stream::{
33    BestBidAskStreamEvent, DepthDiffStreamEvent, DepthSnapshotStreamEvent, PriceLevel, Trade,
34    TradesStreamEvent,
35};
36
37/// Normalized output message from the WebSocket handler.
38///
39/// These messages are emitted by the handler and consumed by the client
40/// for routing to the data engine or other consumers.
41#[derive(Debug, Clone)]
42pub enum NautilusWsMessage {
43    /// Market data (trades, quotes, bars).
44    Data(Vec<Data>),
45    /// Order book deltas.
46    Deltas(OrderBookDeltas),
47    /// Instrument definition update.
48    Instrument(Box<InstrumentAny>),
49    /// WebSocket error from venue.
50    Error(BinanceWsErrorMsg),
51    /// Raw binary message (unhandled).
52    RawBinary(Vec<u8>),
53    /// Raw JSON message (unhandled).
54    RawJson(serde_json::Value),
55    /// Connection was re-established after disconnect.
56    Reconnected,
57}
58
59/// Binance WebSocket error message.
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct BinanceWsErrorMsg {
62    /// Error code from Binance.
63    pub code: i32,
64    /// Error message from Binance.
65    pub msg: String,
66}
67
68/// Commands sent from the outer client to the inner handler.
69///
70/// The handler runs in a dedicated Tokio task and processes these commands
71/// to perform WebSocket operations.
72#[allow(
73    missing_debug_implementations,
74    clippy::large_enum_variant,
75    reason = "Commands are ephemeral and immediately consumed"
76)]
77pub enum HandlerCommand {
78    /// Set the WebSocket client after connection.
79    SetClient(WebSocketClient),
80    /// Disconnect and clean up.
81    Disconnect,
82    /// Initialize instrument cache with bulk data.
83    InitializeInstruments(Vec<InstrumentAny>),
84    /// Update a single instrument in the cache.
85    UpdateInstrument(InstrumentAny),
86    /// Subscribe to streams.
87    Subscribe { streams: Vec<String> },
88    /// Unsubscribe from streams.
89    Unsubscribe { streams: Vec<String> },
90}
91
92/// Binance WebSocket subscription request.
93#[derive(Debug, Clone, Serialize)]
94pub struct BinanceWsSubscription {
95    /// Request method.
96    pub method: BinanceWsMethod,
97    /// Stream names to subscribe/unsubscribe.
98    pub params: Vec<String>,
99    /// Request ID for correlation.
100    pub id: u64,
101}
102
103impl BinanceWsSubscription {
104    /// Create a subscribe request.
105    #[must_use]
106    pub fn subscribe(streams: Vec<String>, id: u64) -> Self {
107        Self {
108            method: BinanceWsMethod::Subscribe,
109            params: streams,
110            id,
111        }
112    }
113
114    /// Create an unsubscribe request.
115    #[must_use]
116    pub fn unsubscribe(streams: Vec<String>, id: u64) -> Self {
117        Self {
118            method: BinanceWsMethod::Unsubscribe,
119            params: streams,
120            id,
121        }
122    }
123}
124
125/// Binance WebSocket subscription response.
126#[derive(Debug, Clone, Deserialize)]
127pub struct BinanceWsResponse {
128    /// Result (null on success).
129    pub result: Option<serde_json::Value>,
130    /// Request ID for correlation.
131    pub id: u64,
132}
133
134/// Binance WebSocket error response.
135#[derive(Debug, Clone, Deserialize)]
136pub struct BinanceWsErrorResponse {
137    /// Error code.
138    pub code: i32,
139    /// Error message.
140    pub msg: String,
141    /// Request ID if available.
142    pub id: Option<u64>,
143}