Skip to main content

nautilus_binance/common/
consts.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 venue constants and API endpoints.
17
18use std::{num::NonZeroU32, sync::LazyLock, time::Duration};
19
20use nautilus_model::identifiers::{ClientId, Venue};
21use nautilus_network::ratelimiter::quota::Quota;
22use ustr::Ustr;
23
24use super::enums::{BinanceRateLimitInterval, BinanceRateLimitType};
25
26/// The Binance venue identifier string.
27pub const BINANCE: &str = "BINANCE";
28
29/// Static venue instance for Binance.
30pub static BINANCE_VENUE: LazyLock<Venue> = LazyLock::new(|| Venue::new(Ustr::from(BINANCE)));
31
32/// Static client ID instance for Binance.
33pub static BINANCE_CLIENT_ID: LazyLock<ClientId> =
34    LazyLock::new(|| ClientId::new(Ustr::from(BINANCE)));
35
36/// Binance Link and Trade integration ID for Spot.
37///
38/// <https://developers.binance.com/docs/binance_link/link-and-trade>
39pub const BINANCE_NAUTILUS_SPOT_BROKER_ID: &str = "TD67BGP9";
40
41/// Binance Link and Trade integration ID for Futures.
42///
43/// <https://developers.binance.com/docs/binance_link/link-and-trade>
44pub const BINANCE_NAUTILUS_FUTURES_BROKER_ID: &str = "aHRE4BCj";
45
46/// Binance Spot API base URL (live exchange).
47pub const BINANCE_SPOT_HTTP_URL: &str = "https://api.binance.com";
48
49/// Binance US Spot API base URL.
50pub const BINANCE_US_SPOT_HTTP_URL: &str = "https://api.binance.us";
51
52/// Binance USD-M Futures API base URL (live exchange).
53pub const BINANCE_FUTURES_USD_HTTP_URL: &str = "https://fapi.binance.com";
54
55/// Binance COIN-M Futures API base URL (live exchange).
56pub const BINANCE_FUTURES_COIN_HTTP_URL: &str = "https://dapi.binance.com";
57
58/// Default WebSocket heartbeat interval in seconds.
59///
60/// Binance caps ping/pong frames at 5 per second, so this sits well inside the limit while keeping
61/// the derived liveness window tight.
62pub const BINANCE_WS_HEARTBEAT_SECS: u64 = 20;
63
64/// Binance European Options API base URL (live exchange).
65pub const BINANCE_OPTIONS_HTTP_URL: &str = "https://eapi.binance.com";
66
67/// Binance Portfolio Margin API base URL (live exchange).
68///
69/// The Portfolio Margin General Info page documents only this production host; no PAPI testnet or
70/// demo host exists. Testnet and demo environments must be rejected rather than redirected here
71/// or to a standard Futures host.
72///
73/// <https://developers.binance.com/docs/derivatives/portfolio-margin/general-info>
74pub const BINANCE_PAPI_HTTP_URL: &str = "https://papi.binance.com";
75
76/// Binance European Options API base URL (testnet/demo).
77pub const BINANCE_OPTIONS_TESTNET_HTTP_URL: &str = "https://testnet.binancefuture.com";
78
79/// Binance Spot API base URL (testnet).
80pub const BINANCE_SPOT_TESTNET_HTTP_URL: &str = "https://testnet.binance.vision";
81
82/// Binance USD-M Futures API base URL (testnet).
83pub const BINANCE_FUTURES_USD_TESTNET_HTTP_URL: &str = "https://testnet.binancefuture.com";
84
85/// Binance COIN-M Futures API base URL (testnet).
86pub const BINANCE_FUTURES_COIN_TESTNET_HTTP_URL: &str = "https://testnet.binancefuture.com";
87
88/// Binance Spot API base URL (demo).
89pub const BINANCE_SPOT_DEMO_HTTP_URL: &str = "https://demo-api.binance.com";
90
91/// Binance USD-M Futures API base URL (demo).
92pub const BINANCE_FUTURES_USD_DEMO_HTTP_URL: &str = "https://demo-fapi.binance.com";
93
94/// Binance COIN-M Futures API base URL (demo).
95pub const BINANCE_FUTURES_COIN_DEMO_HTTP_URL: &str = "https://demo-dapi.binance.com";
96
97/// Binance Spot WebSocket base URL (live exchange).
98pub const BINANCE_SPOT_WS_URL: &str = "wss://stream.binance.com:9443/ws";
99
100/// Binance US Spot public WebSocket base URL.
101pub const BINANCE_US_SPOT_WS_URL: &str = "wss://stream.binance.us:9443/ws";
102
103/// Binance US Spot user data WebSocket root URL.
104pub const BINANCE_US_SPOT_USER_WS_URL: &str = "wss://stream.binance.us:443";
105
106/// Binance USD-M Futures WebSocket base URL (live exchange).
107pub const BINANCE_FUTURES_USD_WS_URL: &str = "wss://fstream.binance.com/market/ws";
108
109/// Binance USD-M Futures WebSocket public stream URL (live exchange, high-frequency book data).
110pub const BINANCE_FUTURES_USD_WS_PUBLIC_URL: &str = "wss://fstream.binance.com/public/ws";
111
112/// Binance USD-M Futures WebSocket private stream URL (live exchange).
113pub const BINANCE_FUTURES_USD_WS_PRIVATE_URL: &str = "wss://fstream.binance.com/private/ws";
114
115/// Binance COIN-M Futures WebSocket base URL (live exchange).
116pub const BINANCE_FUTURES_COIN_WS_URL: &str = "wss://dstream.binance.com/ws";
117
118/// Binance European Options WebSocket base URL (live exchange).
119pub const BINANCE_OPTIONS_WS_URL: &str = "wss://nbstream.binance.com/eoptions";
120
121/// Binance European Options WebSocket base URL (testnet/demo).
122pub const BINANCE_OPTIONS_TESTNET_WS_URL: &str = "wss://fstream.binancefuture.com/market/ws";
123
124/// Binance European Options WebSocket public stream URL (testnet/demo).
125pub const BINANCE_OPTIONS_TESTNET_WS_PUBLIC_URL: &str = "wss://fstream.binancefuture.com/public/ws";
126
127/// Binance European Options WebSocket private stream URL (testnet/demo).
128pub const BINANCE_OPTIONS_TESTNET_WS_PRIVATE_URL: &str =
129    "wss://fstream.binancefuture.com/private/ws";
130
131/// Binance Spot SBE WebSocket stream URL (live exchange).
132pub const BINANCE_SPOT_SBE_WS_URL: &str = "wss://stream-sbe.binance.com/ws";
133
134/// Binance Spot SBE WebSocket API URL (live exchange).
135pub const BINANCE_SPOT_SBE_WS_API_URL: &str =
136    "wss://ws-api.binance.com:443/ws-api/v3?responseFormat=sbe&sbeSchemaId=3&sbeSchemaVersion=5";
137
138/// Binance USD-M Futures WebSocket Trading API URL (live exchange).
139pub const BINANCE_FUTURES_USD_WS_API_URL: &str = "wss://ws-fapi.binance.com/ws-fapi/v1";
140
141/// Binance USD-M Futures WebSocket Trading API URL (testnet).
142pub const BINANCE_FUTURES_USD_WS_API_TESTNET_URL: &str =
143    "wss://testnet.binancefuture.com/ws-fapi/v1";
144
145/// Binance Spot SBE WebSocket API URL (testnet).
146pub const BINANCE_SPOT_SBE_WS_API_TESTNET_URL: &str = "wss://ws-api.testnet.binance.vision/ws-api/v3?responseFormat=sbe&sbeSchemaId=3&sbeSchemaVersion=5";
147
148/// Binance Spot SBE WebSocket API URL (demo).
149pub const BINANCE_SPOT_SBE_WS_API_DEMO_URL: &str =
150    "wss://demo-ws-api.binance.com/ws-api/v3?responseFormat=sbe&sbeSchemaId=3&sbeSchemaVersion=5";
151
152/// Binance Spot WebSocket base URL (testnet).
153pub const BINANCE_SPOT_TESTNET_WS_URL: &str = "wss://stream.testnet.binance.vision/ws";
154
155/// Binance Spot WebSocket base URL (demo).
156pub const BINANCE_SPOT_DEMO_WS_URL: &str = "wss://demo-stream.binance.com/ws";
157
158/// Binance USD-M Futures WebSocket base URL (demo).
159pub const BINANCE_FUTURES_USD_DEMO_WS_URL: &str = "wss://demo-fstream.binance.com/ws";
160
161/// Binance COIN-M Futures WebSocket base URL (demo).
162pub const BINANCE_FUTURES_COIN_DEMO_WS_URL: &str = "wss://demo-dstream.binance.com/ws";
163
164/// Binance USD-M Futures WebSocket base URL (testnet).
165pub const BINANCE_FUTURES_USD_TESTNET_WS_URL: &str = "wss://fstream.binancefuture.com/ws";
166
167/// Binance COIN-M Futures WebSocket base URL (testnet).
168pub const BINANCE_FUTURES_COIN_TESTNET_WS_URL: &str = "wss://dstream.binancefuture.com/ws";
169
170/// HTTP header name for the Binance API key.
171pub const BINANCE_API_KEY_HEADER: &str = "X-MBX-APIKEY";
172
173/// HTTP response header carrying the venue's minimum retry delay on HTTP 429 and 418 responses.
174pub const BINANCE_RETRY_AFTER_HEADER: &str = "Retry-After";
175
176/// Binance Spot API version path.
177pub const BINANCE_SPOT_API_PATH: &str = "/api/v3";
178
179/// Binance USD-M Futures API version path.
180pub const BINANCE_FAPI_PATH: &str = "/fapi/v1";
181
182/// Binance COIN-M Futures API version path.
183pub const BINANCE_DAPI_PATH: &str = "/dapi/v1";
184
185/// Binance European Options API version path.
186pub const BINANCE_EAPI_PATH: &str = "/eapi/v1";
187
188/// Binance SAPI version path for wallet, margin, and other account management endpoints.
189pub const BINANCE_SAPI_PATH: &str = "/sapi/v1";
190
191/// Binance Portfolio Margin API version path.
192pub const BINANCE_PAPI_PATH: &str = "/papi/v1";
193
194/// Describes a static rate limit quota for a product type.
195#[derive(Clone, Copy, Debug)]
196pub struct BinanceRateLimitQuota {
197    /// Rate limit type.
198    pub rate_limit_type: BinanceRateLimitType,
199    /// Time interval unit.
200    pub interval: BinanceRateLimitInterval,
201    /// Number of intervals.
202    pub interval_num: u32,
203    /// Maximum allowed requests for the interval.
204    pub limit: u32,
205}
206
207pub(crate) const BINANCE_SPOT_REQUEST_WEIGHT_PER_MINUTE: NonZeroU32 =
208    NonZeroU32::new(1_200).expect("non-zero");
209
210/// Spot & margin REST limits (default IP weights).
211///
212/// References:
213/// - <https://developers.binance.com/docs/binance-spot-api-docs/limits>
214pub const BINANCE_SPOT_RATE_LIMITS: &[BinanceRateLimitQuota] = &[
215    BinanceRateLimitQuota {
216        rate_limit_type: BinanceRateLimitType::RequestWeight,
217        interval: BinanceRateLimitInterval::Minute,
218        interval_num: 1,
219        limit: BINANCE_SPOT_REQUEST_WEIGHT_PER_MINUTE.get(),
220    },
221    BinanceRateLimitQuota {
222        rate_limit_type: BinanceRateLimitType::Orders,
223        interval: BinanceRateLimitInterval::Second,
224        interval_num: 1,
225        limit: 10,
226    },
227    BinanceRateLimitQuota {
228        rate_limit_type: BinanceRateLimitType::Orders,
229        interval: BinanceRateLimitInterval::Day,
230        interval_num: 1,
231        limit: 100_000,
232    },
233];
234
235/// USD-M Futures REST limits (default IP weights).
236///
237/// References:
238/// - <https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#limits>
239pub const BINANCE_FAPI_RATE_LIMITS: &[BinanceRateLimitQuota] = &[
240    BinanceRateLimitQuota {
241        rate_limit_type: BinanceRateLimitType::RequestWeight,
242        interval: BinanceRateLimitInterval::Minute,
243        interval_num: 1,
244        limit: 2_400,
245    },
246    BinanceRateLimitQuota {
247        rate_limit_type: BinanceRateLimitType::Orders,
248        interval: BinanceRateLimitInterval::Second,
249        interval_num: 10,
250        limit: 300,
251    },
252    BinanceRateLimitQuota {
253        rate_limit_type: BinanceRateLimitType::Orders,
254        interval: BinanceRateLimitInterval::Minute,
255        interval_num: 1,
256        limit: 1_200,
257    },
258];
259
260/// COIN-M Futures REST limits (shared with USD-M Futures).
261///
262/// References:
263/// - <https://developers.binance.com/docs/derivatives/coin-margined-futures/Important-CM-UM-Integration-Notice#a3-um-and-cm-share-the-same-rate-limit-pools>
264pub const BINANCE_DAPI_RATE_LIMITS: &[BinanceRateLimitQuota] = &[
265    BinanceRateLimitQuota {
266        rate_limit_type: BinanceRateLimitType::RequestWeight,
267        interval: BinanceRateLimitInterval::Minute,
268        interval_num: 1,
269        limit: 2_400,
270    },
271    BinanceRateLimitQuota {
272        rate_limit_type: BinanceRateLimitType::Orders,
273        interval: BinanceRateLimitInterval::Second,
274        interval_num: 10,
275        limit: 300,
276    },
277    BinanceRateLimitQuota {
278        rate_limit_type: BinanceRateLimitType::Orders,
279        interval: BinanceRateLimitInterval::Minute,
280        interval_num: 1,
281        limit: 1_200,
282    },
283];
284
285/// Options REST limits (default IP weights).
286///
287/// References:
288/// - <https://developers.binance.com/docs/derivatives/european-options/general-info#limits>
289pub const BINANCE_EAPI_RATE_LIMITS: &[BinanceRateLimitQuota] = &[
290    BinanceRateLimitQuota {
291        rate_limit_type: BinanceRateLimitType::RequestWeight,
292        interval: BinanceRateLimitInterval::Minute,
293        interval_num: 1,
294        limit: 3_000,
295    },
296    BinanceRateLimitQuota {
297        rate_limit_type: BinanceRateLimitType::Orders,
298        interval: BinanceRateLimitInterval::Second,
299        interval_num: 1,
300        limit: 5,
301    },
302    BinanceRateLimitQuota {
303        rate_limit_type: BinanceRateLimitType::Orders,
304        interval: BinanceRateLimitInterval::Minute,
305        interval_num: 1,
306        limit: 200,
307    },
308];
309
310/// Portfolio Margin REST limits (default IP weights and account order counts).
311///
312/// References:
313/// - <https://developers.binance.com/docs/derivatives/portfolio-margin/general-info>
314pub const BINANCE_PAPI_RATE_LIMITS: &[BinanceRateLimitQuota] = &[
315    BinanceRateLimitQuota {
316        rate_limit_type: BinanceRateLimitType::RequestWeight,
317        interval: BinanceRateLimitInterval::Minute,
318        interval_num: 1,
319        limit: 6_000,
320    },
321    BinanceRateLimitQuota {
322        rate_limit_type: BinanceRateLimitType::Orders,
323        interval: BinanceRateLimitInterval::Minute,
324        interval_num: 1,
325        limit: 1_200,
326    },
327];
328
329/// WebSocket subscription rate limit: one message per 300 ms with no burst.
330///
331/// Binance limits incoming WebSocket messages (subscribe/unsubscribe) to 5 per second and
332/// closes the connection with code 1008 ("Too many requests") when that is exceeded. A
333/// `Quota::per_second(5)` token bucket allows a burst of 5 followed by one refill every
334/// 200 ms, so up to 9 messages can land within the first rolling second and trip the
335/// limit. A fixed 300 ms period (about 3.3 messages per second) spaces every message
336/// evenly and stays under the venue limit with headroom.
337pub static BINANCE_WS_SUBSCRIPTION_QUOTA: LazyLock<Quota> =
338    LazyLock::new(|| Quota::with_period(Duration::from_millis(300)).expect("valid constant"));
339
340/// WebSocket connection rate limit: 1 per second (conservative).
341///
342/// Binance limits connections to 300 per 5 minutes per IP. This conservative quota
343/// of 1 per second helps avoid hitting the connection limit during reconnection storms.
344pub static BINANCE_WS_CONNECTION_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
345    Quota::per_second(NonZeroU32::new(1).expect("non-zero")).expect("valid constant")
346});
347
348/// Pre-interned rate limit key for WebSocket subscription operations.
349pub static BINANCE_RATE_LIMIT_KEY_SUBSCRIPTION: LazyLock<[Ustr; 1]> =
350    LazyLock::new(|| [Ustr::from("subscription")]);
351
352/// Binance error code for GTX (post-only) order rejection.
353///
354/// Returned when a GTX order would immediately match as taker.
355pub const BINANCE_GTX_ORDER_REJECT_CODE: i64 = -5022;
356
357/// Binance error code for new order rejected.
358///
359/// For spot LIMIT_MAKER orders, this code is returned with the message
360/// "Order would immediately match and take." to indicate a post-only rejection.
361pub const BINANCE_NEW_ORDER_REJECTED_CODE: i64 = -2010;
362
363/// Binance error code returned when an order is not found.
364pub const BINANCE_NO_SUCH_ORDER_CODE: i64 = -2013;
365
366/// Binance error code returned when a listen key does not exist.
367pub const BINANCE_INVALID_LISTEN_KEY_CODE: i64 = -1125;
368
369/// Binance error code returned when order execution status is unknown.
370pub const BINANCE_UNEXPECTED_RESPONSE_CODE: i64 = -1006;
371
372/// Binance error code returned when order execution status is unknown.
373pub const BINANCE_STATUS_UNKNOWN_CODE: i64 = -1007;
374
375/// Binance USD-M Futures error code for `dualSidePosition` sync rejection between
376/// UM (USDM) and CM (Coin-M) accounts on Portfolio Margin.
377///
378/// Returned when an order or position-mode change is incompatible with the
379/// account-level hedge mode that PM keeps in sync across UM/CM.
380pub const BINANCE_FUTURES_DUAL_SIDE_SYNC_REJECT_CODE: i64 = -4531;
381
382/// Binance Spot LIMIT_MAKER rejection message.
383///
384/// This message is specific to post-only (LIMIT_MAKER) orders that would match immediately.
385pub const BINANCE_SPOT_POST_ONLY_REJECT_MSG: &str = "Order would immediately match and take.";
386
387/// Maximum depth of a Binance partial order book snapshot.
388pub const BINANCE_PARTIAL_BOOK_DEPTH: usize = 20;
389
390/// Valid order book depth levels for Binance.
391pub const BINANCE_BOOK_DEPTHS: [u32; 7] = [5, 10, 20, 50, 100, 500, 1000];
392
393#[cfg(test)]
394mod tests {
395    use rstest::rstest;
396
397    use super::*;
398
399    #[rstest]
400    fn test_venue_error_code_values() {
401        assert_eq!(BINANCE_GTX_ORDER_REJECT_CODE, -5022);
402        assert_eq!(BINANCE_NEW_ORDER_REJECTED_CODE, -2010);
403        assert_eq!(BINANCE_NO_SUCH_ORDER_CODE, -2013);
404        assert_eq!(BINANCE_INVALID_LISTEN_KEY_CODE, -1125);
405        assert_eq!(BINANCE_UNEXPECTED_RESPONSE_CODE, -1006);
406        assert_eq!(BINANCE_STATUS_UNKNOWN_CODE, -1007);
407        assert_eq!(BINANCE_FUTURES_DUAL_SIDE_SYNC_REJECT_CODE, -4531);
408    }
409
410    #[rstest]
411    #[case(BINANCE_SPOT_SBE_WS_API_URL)]
412    #[case(BINANCE_SPOT_SBE_WS_API_TESTNET_URL)]
413    #[case(BINANCE_SPOT_SBE_WS_API_DEMO_URL)]
414    fn test_spot_sbe_ws_api_urls_use_current_schema(#[case] url: &str) {
415        assert!(url.ends_with("sbeSchemaId=3&sbeSchemaVersion=5"));
416    }
417
418    #[rstest]
419    fn test_ws_subscription_quota_paces_one_message_per_period() {
420        let quota = *BINANCE_WS_SUBSCRIPTION_QUOTA;
421        assert_eq!(quota.burst_size().get(), 1);
422        assert_eq!(quota.replenish_interval(), Duration::from_millis(300));
423    }
424}