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 /// Error from venue or network.
127 Error(String),
128}
129
130/// Metadata for a pending request.
131///
132/// Stored in the handler to match responses to their originating requests.
133#[derive(Debug, Clone, Copy)]
134pub enum BinanceFuturesWsTradingRequestMeta {
135 /// Pending order placement.
136 PlaceOrder,
137 /// Pending order cancellation.
138 CancelOrder,
139 /// Pending order modification.
140 ModifyOrder,
141}
142
143/// WebSocket Trading API request wrapper.
144///
145/// Requests are sent as JSON text frames, responses come back as JSON text.
146#[derive(Debug, Clone, Serialize)]
147pub struct BinanceFuturesWsTradingRequest {
148 /// Unique request ID for correlation.
149 pub id: String,
150 /// API method name (e.g., "order.place").
151 pub method: String,
152 /// Request parameters.
153 pub params: serde_json::Value,
154}
155
156impl BinanceFuturesWsTradingRequest {
157 /// Creates a new WebSocket Trading API request.
158 #[must_use]
159 pub fn new(
160 id: impl Into<String>,
161 method: impl Into<String>,
162 params: serde_json::Value,
163 ) -> Self {
164 Self {
165 id: id.into(),
166 method: method.into(),
167 params,
168 }
169 }
170}
171
172/// WebSocket Trading API response envelope.
173///
174/// Binance Futures WS API returns responses in this format.
175#[derive(Debug, Clone, Deserialize)]
176pub struct BinanceFuturesWsTradingResponse {
177 /// Request ID for correlation.
178 pub id: String,
179 /// HTTP-like status code (200 for success).
180 pub status: u16,
181 /// Result payload (present on success).
182 pub result: Option<serde_json::Value>,
183 /// Rate limit information.
184 #[serde(default, rename = "rateLimits")]
185 pub rate_limits: Vec<serde_json::Value>,
186 /// Error details (present on failure).
187 pub error: Option<BinanceFuturesWsTradingResponseError>,
188}
189
190/// Error details within a WebSocket Trading API response.
191#[derive(Debug, Clone, Deserialize)]
192pub struct BinanceFuturesWsTradingResponseError {
193 /// Error code from venue.
194 pub code: i32,
195 /// Error message from venue.
196 pub msg: String,
197}
198
199/// WebSocket Trading API method names for Binance Futures.
200pub mod method {
201 /// Places a new order.
202 pub const ORDER_PLACE: &str = "order.place";
203 /// Cancels an order.
204 pub const ORDER_CANCEL: &str = "order.cancel";
205 /// Modifies an order (in-place amendment).
206 pub const ORDER_MODIFY: &str = "order.modify";
207}