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 /// Error code from venue.
90 code: i32,
91 /// Error message from venue.
92 msg: String,
93 },
94 /// Order canceled successfully.
95 OrderCanceled {
96 /// Request ID for correlation.
97 request_id: String,
98 /// Cancel response from venue.
99 response: Box<BinanceFuturesOrder>,
100 },
101 /// Cancel rejected by venue.
102 CancelRejected {
103 /// Request ID for correlation.
104 request_id: String,
105 /// Error code from venue.
106 code: i32,
107 /// Error message from venue.
108 msg: String,
109 },
110 /// Order modified successfully.
111 OrderModified {
112 /// Request ID for correlation.
113 request_id: String,
114 /// Modified order response from venue.
115 response: Box<BinanceFuturesOrder>,
116 },
117 /// Modify rejected by venue.
118 ModifyRejected {
119 /// Request ID for correlation.
120 request_id: String,
121 /// Error code from venue.
122 code: i32,
123 /// Error message from venue.
124 msg: String,
125 },
126 /// Request failed without a structured venue response.
127 RequestFailed {
128 /// Request ID for correlation.
129 request_id: String,
130 /// Failure reason.
131 msg: String,
132 },
133 /// Error from venue or network.
134 Error(String),
135}
136
137/// Metadata for a pending request.
138///
139/// Stored in the handler to match responses to their originating requests.
140#[derive(Debug, Clone, Copy)]
141pub enum BinanceFuturesWsTradingRequestMeta {
142 /// Pending order placement.
143 PlaceOrder,
144 /// Pending order cancellation.
145 CancelOrder,
146 /// Pending order modification.
147 ModifyOrder,
148}
149
150/// WebSocket Trading API request wrapper.
151///
152/// Requests are sent as JSON text frames, responses come back as JSON text.
153#[derive(Debug, Clone, Serialize)]
154pub struct BinanceFuturesWsTradingRequest {
155 /// Unique request ID for correlation.
156 pub id: String,
157 /// API method name (e.g., "order.place").
158 pub method: String,
159 /// Request parameters.
160 pub params: serde_json::Value,
161}
162
163impl BinanceFuturesWsTradingRequest {
164 /// Creates a new WebSocket Trading API request.
165 #[must_use]
166 pub fn new(
167 id: impl Into<String>,
168 method: impl Into<String>,
169 params: serde_json::Value,
170 ) -> Self {
171 Self {
172 id: id.into(),
173 method: method.into(),
174 params,
175 }
176 }
177}
178
179/// WebSocket Trading API response envelope.
180///
181/// Binance Futures WS API returns responses in this format.
182#[derive(Debug, Clone, Deserialize)]
183pub struct BinanceFuturesWsTradingResponse {
184 /// Request ID for correlation.
185 pub id: String,
186 /// HTTP-like status code (200 for success).
187 pub status: u16,
188 /// Result payload (present on success).
189 pub result: Option<serde_json::Value>,
190 /// Rate limit information.
191 #[serde(default, rename = "rateLimits")]
192 pub rate_limits: Vec<serde_json::Value>,
193 /// Error details (present on failure).
194 pub error: Option<BinanceFuturesWsTradingResponseError>,
195}
196
197/// Error details within a WebSocket Trading API response.
198#[derive(Debug, Clone, Deserialize)]
199pub struct BinanceFuturesWsTradingResponseError {
200 /// Error code from venue.
201 pub code: i32,
202 /// Error message from venue.
203 pub msg: String,
204}
205
206/// WebSocket Trading API method names for Binance Futures.
207pub mod method {
208 /// Places a new order.
209 pub const ORDER_PLACE: &str = "order.place";
210 /// Cancels an order.
211 pub const ORDER_CANCEL: &str = "order.cancel";
212 /// Modifies an order (in-place amendment).
213 pub const ORDER_MODIFY: &str = "order.modify";
214}