nautilus-binance 0.55.0

Binance exchange integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Binance Futures WebSocket Trading API client.
//!
//! ## Connection details
//!
//! - Endpoint: `ws-fapi.binance.com/ws-fapi/v1` (USD-M only)
//! - Authentication: HMAC-SHA256 signature per request
//! - JSON request/response pattern
//! - Connection validity: 24 hours
//! - Ping/pong: every 20 seconds

use std::{
    fmt::Debug,
    num::NonZeroU32,
    sync::{
        Arc, LazyLock, Mutex,
        atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
    },
};

use arc_swap::ArcSwap;
use nautilus_common::live::get_runtime;
use nautilus_core::string::REDACTED;
use nautilus_network::{
    mode::ConnectionMode,
    ratelimiter::quota::Quota,
    websocket::{PingHandler, WebSocketClient, WebSocketConfig, channel_message_handler},
};
use tokio_util::sync::CancellationToken;
use ustr::Ustr;

use super::{
    error::{BinanceFuturesWsApiError, BinanceFuturesWsApiResult},
    handler::BinanceFuturesWsTradingHandler,
    messages::{BinanceFuturesWsTradingCommand, BinanceFuturesWsTradingMessage},
};
use crate::{
    common::{
        consts::{BINANCE_API_KEY_HEADER, BINANCE_FUTURES_USD_WS_API_URL},
        credential::SigningCredential,
    },
    futures::http::query::{
        BinanceCancelOrderParams, BinanceModifyOrderParams, BinanceNewOrderParams,
    },
};

/// Pre-interned rate limit key for futures order operations (place/cancel/modify).
///
/// Binance Futures WebSocket API: 1200 requests per minute per IP (20/sec).
pub static BINANCE_FUTURES_WS_RATE_LIMIT_KEY_ORDER: LazyLock<[Ustr; 1]> =
    LazyLock::new(|| [Ustr::from("futures_order")]);

/// Returns the Binance Futures WebSocket API order rate limit quota (1200 per minute).
// Constant values are provably valid
#[allow(clippy::missing_panics_doc)]
#[must_use]
pub fn binance_futures_ws_order_quota() -> Quota {
    Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant")
}

/// Binance Futures WebSocket Trading API client.
///
/// Provides order management via WebSocket with JSON responses,
/// complementing the HTTP client with lower-latency order submission.
/// Only available for USD-M Futures.
#[derive(Clone)]
pub struct BinanceFuturesWsTradingClient {
    url: String,
    credential: Arc<SigningCredential>,
    heartbeat: Option<u64>,
    signal: Arc<AtomicBool>,
    connection_mode: Arc<ArcSwap<AtomicU8>>,
    cmd_tx: Arc<
        tokio::sync::RwLock<tokio::sync::mpsc::UnboundedSender<BinanceFuturesWsTradingCommand>>,
    >,
    out_rx:
        Arc<Mutex<Option<tokio::sync::mpsc::UnboundedReceiver<BinanceFuturesWsTradingMessage>>>>,
    task_handle: Option<Arc<tokio::task::JoinHandle<()>>>,
    request_id_counter: Arc<AtomicU64>,
    cancellation_token: CancellationToken,
}

impl Debug for BinanceFuturesWsTradingClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(stringify!(BinanceFuturesWsTradingClient))
            .field("url", &self.url)
            .field("credential", &REDACTED)
            .field("heartbeat", &self.heartbeat)
            .finish_non_exhaustive()
    }
}

impl BinanceFuturesWsTradingClient {
    /// Creates a new [`BinanceFuturesWsTradingClient`] instance.
    #[must_use]
    pub fn new(
        url: Option<String>,
        api_key: String,
        api_secret: String,
        heartbeat: Option<u64>,
    ) -> Self {
        let url = url.unwrap_or_else(|| BINANCE_FUTURES_USD_WS_API_URL.to_string());
        let credential = Arc::new(SigningCredential::new(api_key, api_secret));

        let (cmd_tx, _cmd_rx) = tokio::sync::mpsc::unbounded_channel();

        Self {
            url,
            credential,
            heartbeat,
            signal: Arc::new(AtomicBool::new(false)),
            connection_mode: Arc::new(ArcSwap::new(Arc::new(AtomicU8::new(
                ConnectionMode::Closed as u8,
            )))),
            cmd_tx: Arc::new(tokio::sync::RwLock::new(cmd_tx)),
            out_rx: Arc::new(Mutex::new(None)),
            task_handle: None,
            request_id_counter: Arc::new(AtomicU64::new(1)),
            cancellation_token: CancellationToken::new(),
        }
    }

    /// Returns whether the client is actively connected.
    #[must_use]
    pub fn is_active(&self) -> bool {
        let mode_u8 = self.connection_mode.load().load(Ordering::Relaxed);
        mode_u8 == ConnectionMode::Active as u8
    }

    /// Returns whether the client is closed.
    #[must_use]
    pub fn is_closed(&self) -> bool {
        let mode_u8 = self.connection_mode.load().load(Ordering::Relaxed);
        mode_u8 == ConnectionMode::Closed as u8
    }

    pub fn next_request_id(&self) -> String {
        let id = self.request_id_counter.fetch_add(1, Ordering::Relaxed);
        format!("req-{id}")
    }

    /// Connects to the WebSocket Trading API server.
    ///
    /// # Errors
    ///
    /// Returns an error if connection fails.
    // Mutex poisoning is not documented individually
    #[allow(clippy::missing_panics_doc)]
    pub async fn connect(&mut self) -> BinanceFuturesWsApiResult<()> {
        self.signal.store(false, Ordering::Relaxed);
        self.cancellation_token = CancellationToken::new();

        let (raw_handler, raw_rx) = channel_message_handler();
        let ping_handler: PingHandler = Arc::new(move |_| {});

        let headers = vec![(
            BINANCE_API_KEY_HEADER.to_string(),
            self.credential.api_key().to_string(),
        )];

        let config = WebSocketConfig {
            url: self.url.clone(),
            headers,
            heartbeat: self.heartbeat,
            heartbeat_msg: None,
            reconnect_timeout_ms: Some(5_000),
            reconnect_delay_initial_ms: Some(500),
            reconnect_delay_max_ms: Some(5_000),
            reconnect_backoff_factor: Some(2.0),
            reconnect_jitter_ms: Some(250),
            reconnect_max_attempts: None,
            idle_timeout_ms: None,
        };

        let keyed_quotas = vec![(
            BINANCE_FUTURES_WS_RATE_LIMIT_KEY_ORDER[0]
                .as_str()
                .to_string(),
            binance_futures_ws_order_quota(),
        )];

        let client = WebSocketClient::connect(
            config,
            Some(raw_handler),
            Some(ping_handler),
            None,
            keyed_quotas,
            Some(binance_futures_ws_order_quota()),
        )
        .await
        .map_err(|e| BinanceFuturesWsApiError::ConnectionError(e.to_string()))?;

        self.connection_mode.store(client.connection_mode_atomic());

        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel();

        {
            let mut rx_guard = self.out_rx.lock().expect("Mutex poisoned");
            *rx_guard = Some(out_rx);
        }

        {
            let mut tx_guard = self.cmd_tx.write().await;
            *tx_guard = cmd_tx;
        }

        let signal = self.signal.clone();
        let credential = self.credential.clone();
        let mut handler =
            BinanceFuturesWsTradingHandler::new(signal, cmd_rx, raw_rx, out_tx, credential);

        self.cmd_tx
            .read()
            .await
            .send(BinanceFuturesWsTradingCommand::SetClient(client))
            .map_err(|e| BinanceFuturesWsApiError::HandlerUnavailable(e.to_string()))?;

        let cancellation_token = self.cancellation_token.clone();
        let handle = get_runtime().spawn(async move {
            tokio::select! {
                () = cancellation_token.cancelled() => {
                    log::debug!("Handler task cancelled");
                }
                _ = handler.run() => {
                    log::debug!("Handler run completed");
                }
            }
        });

        self.task_handle = Some(Arc::new(handle));

        Ok(())
    }

    /// Disconnects from the WebSocket Trading API server.
    pub async fn disconnect(&mut self) {
        self.signal.store(true, Ordering::Relaxed);

        if let Err(e) = self
            .cmd_tx
            .read()
            .await
            .send(BinanceFuturesWsTradingCommand::Disconnect)
        {
            log::warn!("Failed to send disconnect command: {e}");
        }

        self.cancellation_token.cancel();

        if let Some(handle) = self.task_handle.take()
            && let Ok(handle) = Arc::try_unwrap(handle)
        {
            let _ = handle.await;
        }
    }

    /// Places a new order via the WebSocket Trading API.
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn place_order(
        &self,
        params: BinanceNewOrderParams,
    ) -> BinanceFuturesWsApiResult<String> {
        let id = self.next_request_id();
        self.place_order_with_id(id.clone(), params).await?;
        Ok(id)
    }

    /// Places a new order via the WebSocket Trading API using a pre-generated request ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn place_order_with_id(
        &self,
        id: String,
        params: BinanceNewOrderParams,
    ) -> BinanceFuturesWsApiResult<()> {
        let cmd = BinanceFuturesWsTradingCommand::PlaceOrder { id, params };
        self.send_cmd(cmd).await
    }

    /// Cancels an order via the WebSocket Trading API.
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn cancel_order(
        &self,
        params: BinanceCancelOrderParams,
    ) -> BinanceFuturesWsApiResult<String> {
        let id = self.next_request_id();
        self.cancel_order_with_id(id.clone(), params).await?;
        Ok(id)
    }

    /// Cancels an order via the WebSocket Trading API using a pre-generated request ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn cancel_order_with_id(
        &self,
        id: String,
        params: BinanceCancelOrderParams,
    ) -> BinanceFuturesWsApiResult<()> {
        let cmd = BinanceFuturesWsTradingCommand::CancelOrder { id, params };
        self.send_cmd(cmd).await
    }

    /// Modifies an order via the WebSocket Trading API (in-place amendment).
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn modify_order(
        &self,
        params: BinanceModifyOrderParams,
    ) -> BinanceFuturesWsApiResult<String> {
        let id = self.next_request_id();
        self.modify_order_with_id(id.clone(), params).await?;
        Ok(id)
    }

    /// Modifies an order via the WebSocket Trading API using a pre-generated request ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn modify_order_with_id(
        &self,
        id: String,
        params: BinanceModifyOrderParams,
    ) -> BinanceFuturesWsApiResult<()> {
        let cmd = BinanceFuturesWsTradingCommand::ModifyOrder { id, params };
        self.send_cmd(cmd).await
    }

    /// Cancels all open orders for a symbol via the WebSocket Trading API.
    ///
    /// # Errors
    ///
    /// Returns an error if the handler is unavailable.
    pub async fn cancel_all_orders(
        &self,
        symbol: impl Into<String>,
    ) -> BinanceFuturesWsApiResult<String> {
        let id = self.next_request_id();
        let cmd = BinanceFuturesWsTradingCommand::CancelAllOrders {
            id: id.clone(),
            symbol: symbol.into(),
        };
        self.send_cmd(cmd).await?;
        Ok(id)
    }

    /// Receives the next message from the handler.
    ///
    /// Returns `None` if the receiver is closed or not initialized.
    ///
    /// # Panics
    ///
    /// Panics if the internal output receiver mutex is poisoned.
    pub async fn recv(&self) -> Option<BinanceFuturesWsTradingMessage> {
        let rx_opt = {
            let mut rx_guard = self.out_rx.lock().expect("Mutex poisoned");
            rx_guard.take()
        };

        if let Some(mut rx) = rx_opt {
            let result = rx.recv().await;

            let mut rx_guard = self.out_rx.lock().expect("Mutex poisoned");
            *rx_guard = Some(rx);
            result
        } else {
            None
        }
    }

    async fn send_cmd(&self, cmd: BinanceFuturesWsTradingCommand) -> BinanceFuturesWsApiResult<()> {
        self.cmd_tx
            .read()
            .await
            .send(cmd)
            .map_err(|e| BinanceFuturesWsApiError::HandlerUnavailable(e.to_string()))
    }
}