Skip to main content

nautilus_binance/
config.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 adapter configuration structures.
17
18use std::{any::Any, collections::HashMap};
19
20use nautilus_common::factories::ClientConfig;
21use nautilus_model::identifiers::{AccountId, TraderId};
22use nautilus_network::websocket::TransportBackend;
23use rust_decimal::Decimal;
24
25use crate::common::enums::{BinanceEnvironment, BinanceMarginType, BinanceProductType};
26
27/// Configuration for Binance data client.
28///
29/// Ed25519 API keys are required for SBE WebSocket streams.
30#[derive(Clone, Debug, bon::Builder)]
31#[cfg_attr(
32    feature = "python",
33    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.binance", from_py_object)
34)]
35#[cfg_attr(
36    feature = "python",
37    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.binance")
38)]
39pub struct BinanceDataClientConfig {
40    /// Product types to subscribe to.
41    #[builder(default = vec![BinanceProductType::Spot])]
42    pub product_types: Vec<BinanceProductType>,
43    /// Environment (mainnet or testnet).
44    #[builder(default = BinanceEnvironment::Mainnet)]
45    pub environment: BinanceEnvironment,
46    /// Optional base URL override for HTTP API.
47    pub base_url_http: Option<String>,
48    /// Optional base URL override for WebSocket.
49    ///
50    /// Live USD-M Futures data overrides are normalized onto the matching
51    /// `/market/ws` and `/public/ws` routes.
52    pub base_url_ws: Option<String>,
53    /// API key (Ed25519).
54    pub api_key: Option<String>,
55    /// API secret (Ed25519 base64-encoded or PEM).
56    pub api_secret: Option<String>,
57    /// Interval in seconds for polling exchange info to detect instrument status
58    /// changes (e.g. Trading -> Halt). Set to 0 to disable. Defaults to 3600 (60 minutes).
59    #[builder(default = 3600)]
60    pub instrument_status_poll_secs: u64,
61    /// WebSocket transport backend (defaults to `Tungstenite`).
62    #[builder(default)]
63    pub transport_backend: TransportBackend,
64}
65
66impl Default for BinanceDataClientConfig {
67    fn default() -> Self {
68        Self::builder().build()
69    }
70}
71
72impl ClientConfig for BinanceDataClientConfig {
73    fn as_any(&self) -> &dyn Any {
74        self
75    }
76}
77
78/// Configuration for Binance execution client.
79///
80/// Ed25519 API keys are required for execution clients. Binance deprecated
81/// listenKey-based user data streams in favor of WebSocket API authentication,
82/// which only supports Ed25519.
83#[derive(Clone, Debug, bon::Builder)]
84#[cfg_attr(
85    feature = "python",
86    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.binance", from_py_object)
87)]
88#[cfg_attr(
89    feature = "python",
90    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.binance")
91)]
92pub struct BinanceExecClientConfig {
93    /// Trader ID for the client.
94    #[builder(default = TraderId::from("TRADER-001"))]
95    pub trader_id: TraderId,
96    /// Account ID for the client.
97    #[builder(default = AccountId::from("BINANCE-001"))]
98    pub account_id: AccountId,
99    /// Product types to trade.
100    #[builder(default = vec![BinanceProductType::Spot])]
101    pub product_types: Vec<BinanceProductType>,
102    /// Environment (mainnet or testnet).
103    #[builder(default = BinanceEnvironment::Mainnet)]
104    pub environment: BinanceEnvironment,
105    /// Optional base URL override for HTTP API.
106    pub base_url_http: Option<String>,
107    /// Optional base URL override for WebSocket user data stream.
108    ///
109    /// Live USD-M Futures stream overrides are normalized onto the `/private/ws` route.
110    pub base_url_ws: Option<String>,
111    /// Optional base URL override for WebSocket trading API (Spot and USD-M Futures).
112    pub base_url_ws_trading: Option<String>,
113    /// Whether to use the WebSocket trading API for order operations (Spot and USD-M Futures).
114    #[builder(default = true)]
115    pub use_ws_trading: bool,
116    /// Whether to use Binance Futures hedging position IDs.
117    ///
118    /// When true, fill reports include a `venue_position_id` derived from
119    /// the instrument and position side (e.g. `ETHUSDT-PERP.BINANCE-LONG`).
120    /// When false, `venue_position_id` is None, allowing virtual positions
121    /// with `OmsType::Hedging`.
122    #[builder(default = true)]
123    pub use_position_ids: bool,
124    /// Default taker fee rate for commission estimation.
125    ///
126    /// Used as a fallback when the venue omits commission fields in
127    /// exchange-generated fills (liquidation, ADL, settlement).
128    /// Standard Binance Futures taker fee is 0.0004 (0.04%).
129    #[builder(default = Decimal::new(4, 4))]
130    pub default_taker_fee: Decimal,
131    /// API key (Ed25519 required, uses env var if not provided).
132    pub api_key: Option<String>,
133    /// API secret (Ed25519 base64-encoded, required, uses env var if not provided).
134    pub api_secret: Option<String>,
135    /// Initial leverage per Binance symbol (e.g. BTCUSDT -> 20), applied during connect.
136    pub futures_leverages: Option<HashMap<String, u32>>,
137    /// Margin type per Binance symbol (e.g. BTCUSDT -> Cross), applied during connect.
138    pub futures_margin_types: Option<HashMap<String, BinanceMarginType>>,
139    /// If true, the EXPIRED execution type emits `OrderCanceled` instead of `OrderExpired`.
140    ///
141    /// Binance uses EXPIRED for certain cancel scenarios depending on order type
142    /// and time-in-force combination.
143    #[builder(default = false)]
144    pub treat_expired_as_canceled: bool,
145    /// If true, drive fills from the lower-latency `TRADE_LITE` user data event
146    /// and dedup the matching fill portion of `ORDER_TRADE_UPDATE`. If false,
147    /// `TRADE_LITE` events are ignored and fills come from `ORDER_TRADE_UPDATE`.
148    #[builder(default = false)]
149    pub use_trade_lite: bool,
150    /// WebSocket transport backend (defaults to `Tungstenite`).
151    #[builder(default)]
152    pub transport_backend: TransportBackend,
153}
154
155impl Default for BinanceExecClientConfig {
156    fn default() -> Self {
157        Self::builder().build()
158    }
159}
160
161impl ClientConfig for BinanceExecClientConfig {
162    fn as_any(&self) -> &dyn Any {
163        self
164    }
165}