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