nautilus_binance/futures/websocket/trading/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 Futures WebSocket Trading API message types.
17//!
18//! This module defines:
19//! - [`BinanceFuturesWsTradingCommand`]: Commands sent from the client to the handler.
20//! - [`BinanceFuturesWsTradingMessage`]: Output messages emitted by the handler to the client.
21//! - Request/response structures for the Binance Futures WebSocket Trading API.
22
23use nautilus_network::websocket::WebSocketClient;
24use serde::{Deserialize, Serialize};
25
26use crate::futures::http::{
27 models::BinanceFuturesOrder,
28 query::{BinanceCancelOrderParams, BinanceModifyOrderParams, BinanceNewOrderParams},
29};
30
31/// Commands sent from the outer client to the inner handler.
32///
33/// The handler runs in a dedicated Tokio task and processes these commands
34/// to perform WebSocket Trading API operations (JSON request/response pattern).
35#[allow(
36 missing_debug_implementations,
37 clippy::large_enum_variant,
38 reason = "Commands are ephemeral and immediately consumed"
39)]
40pub enum BinanceFuturesWsTradingCommand {
41 /// Sets the WebSocket client after connection.
42 SetClient(WebSocketClient),
43 /// Disconnects and cleans up.
44 Disconnect,
45 /// Places a new order.
46 PlaceOrder {
47 /// Request ID for correlation.
48 id: String,
49 /// Order parameters.
50 params: BinanceNewOrderParams,
51 },
52 /// Cancels an order.
53 CancelOrder {
54 /// Request ID for correlation.
55 id: String,
56 /// Cancel parameters.
57 params: BinanceCancelOrderParams,
58 },
59 /// Modifies an order (in-place price/quantity amendment).
60 ModifyOrder {
61 /// Request ID for correlation.
62 id: String,
63 /// Modify parameters.
64 params: BinanceModifyOrderParams,
65 },
66}
67
68/// Normalized output message from the Futures WebSocket Trading API handler.
69///
70/// These messages are emitted by the handler and consumed by the client
71/// for routing to callers or the execution engine.
72#[derive(Debug, Clone)]
73pub enum BinanceFuturesWsTradingMessage {
74 /// Connection established.
75 Connected,
76 /// Connection was re-established after disconnect.
77 Reconnected,
78 /// Order accepted by venue.
79 OrderAccepted {
80 /// Request ID for correlation.
81 request_id: String,
82 /// Order response from venue.
83 response: Box<BinanceFuturesOrder>,
84 },
85 /// Order rejected by venue.
86 OrderRejected {
87 /// Request ID for correlation.
88 request_id: String,
89 /// Venue response status.
90 status: u16,
91 /// Error code from venue.
92 code: i32,
93 /// Error message from venue.
94 msg: String,
95 },
96 /// Order canceled successfully.
97 OrderCanceled {
98 /// Request ID for correlation.
99 request_id: String,
100 /// Cancel response from venue.
101 response: Box<BinanceFuturesOrder>,
102 },
103 /// Cancel rejected by venue.
104 CancelRejected {
105 /// Request ID for correlation.
106 request_id: String,
107 /// Venue response status.
108 status: u16,
109 /// Error code from venue.
110 code: i32,
111 /// Error message from venue.
112 msg: String,
113 },
114 /// Order modified successfully.
115 OrderModified {
116 /// Request ID for correlation.
117 request_id: String,
118 /// Modified order response from venue.
119 response: Box<BinanceFuturesOrder>,
120 },
121 /// Modify rejected by venue.
122 ModifyRejected {
123 /// Request ID for correlation.
124 request_id: String,
125 /// Venue response status.
126 status: u16,
127 /// Error code from venue.
128 code: i32,
129 /// Error message from venue.
130 msg: String,
131 },
132 /// Request failed without a structured venue response.
133 RequestFailed {
134 /// Request ID for correlation.
135 request_id: String,
136 /// Failure reason.
137 msg: String,
138 },
139 /// Error from venue or network.
140 Error(String),
141}
142
143/// Metadata for a pending request.
144///
145/// Stored in the handler to match responses to their originating requests.
146#[derive(Debug, Clone, Copy)]
147pub enum BinanceFuturesWsTradingRequestMeta {
148 /// Pending order placement.
149 PlaceOrder,
150 /// Pending order cancellation.
151 CancelOrder,
152 /// Pending order modification.
153 ModifyOrder,
154}
155
156/// WebSocket Trading API request wrapper.
157///
158/// Requests are sent as JSON text frames, responses come back as JSON text.
159#[derive(Debug, Clone, Serialize)]
160pub struct BinanceFuturesWsTradingRequest {
161 /// Unique request ID for correlation.
162 pub id: String,
163 /// API method name (e.g., "order.place").
164 pub method: String,
165 /// Request parameters.
166 pub params: serde_json::Value,
167}
168
169impl BinanceFuturesWsTradingRequest {
170 /// Creates a new WebSocket Trading API request.
171 #[must_use]
172 pub fn new(
173 id: impl Into<String>,
174 method: impl Into<String>,
175 params: serde_json::Value,
176 ) -> Self {
177 Self {
178 id: id.into(),
179 method: method.into(),
180 params,
181 }
182 }
183}
184
185/// WebSocket Trading API response envelope.
186///
187/// Binance Futures WS API returns responses in this format.
188#[derive(Debug, Clone, Deserialize)]
189pub struct BinanceFuturesWsTradingResponse {
190 /// Request ID for correlation.
191 pub id: String,
192 /// HTTP-like status code (200 for success).
193 pub status: u16,
194 /// Result payload (present on success).
195 pub result: Option<serde_json::Value>,
196 /// Rate limit information.
197 #[serde(default, rename = "rateLimits")]
198 pub rate_limits: Vec<serde_json::Value>,
199 /// Error details (present on failure).
200 pub error: Option<BinanceFuturesWsTradingResponseError>,
201}
202
203/// Error details within a WebSocket Trading API response.
204#[derive(Debug, Clone, Deserialize)]
205pub struct BinanceFuturesWsTradingResponseError {
206 /// Error code from venue.
207 pub code: i32,
208 /// Error message from venue.
209 pub msg: String,
210}
211
212/// WebSocket Trading API method names for Binance Futures.
213pub mod method {
214 /// Places a new order.
215 pub const ORDER_PLACE: &str = "order.place";
216 /// Cancels an order.
217 pub const ORDER_CANCEL: &str = "order.cancel";
218 /// Modifies an order (in-place amendment).
219 pub const ORDER_MODIFY: &str = "order.modify";
220}