-
Notifications
You must be signed in to change notification settings - Fork 0
Binance
Founded in 2017, Binance is one of the largest cryptocurrency exchanges in terms of daily trading volume, and open interest of crypto assets and crypto derivative products. This integration supports live market data ingest and order execution with Binance.
币安成立于 2017 年,是全球交易量最大的加密货币交易所之一,拥有大量的加密资产和加密衍生品未平仓合约。此集成支持币安的实时市场数据获取和订单执行。
The following documentation assumes a trader is setting up for both live market data feeds, and trade execution. The full Binance integration consists of an assortment of components, which can be used together or separately depending on the users needs.
以下文档假定交易者正在设置实时市场数据馈送和交易执行。完整的币安集成由各种组件组成,可以根据用户的需求一起使用或单独使用。
BinanceHttpClient
: Low-level HTTP API connectivity.BinanceHttpClient
:低级 HTTP API 连接。BinanceWebSocketClient
: Low-level WebSocket API connectivity.BinanceWebSocketClient
:低级 WebSocket API 连接。BinanceInstrumentProvider
: Instrument parsing and loading functionality.BinanceInstrumentProvider
:Instrument解析和加载功能。BinanceSpotDataClient
/BinanceFuturesDataClient
: A market data feed manager.BinanceSpotDataClient
/BinanceFuturesDataClient
:市场数据馈送管理器。BinanceSpotExecutionClient
/BinanceFuturesExecutionClient
: An account management and trade execution gateway.BinanceSpotExecutionClient
/BinanceFuturesExecutionClient
:账户管理和交易执行网关。BinanceLiveDataClientFactory
: Factory for Binance data clients (used by the trading node builder).BinanceLiveDataClientFactory
:币安数据客户端的工厂(由交易节点构建器使用)。BinanceLiveExecClientFactory
: Factory for Binance execution clients (used by the trading node builder).BinanceLiveExecClientFactory
:币安执行客户端的工厂(由交易节点构建器使用)。
Most users will simply define a configuration for a live trading node (as below), and won't need to necessarily work with these lower level components directly.
大多数用户只需为实时交易节点定义一个配置(如下所示),而无需直接使用这些较低级别的组件。
To provide complete API functionality to traders, the integration includes several custom data types:
为了向交易者提供完整的 API 功能,集成中包含几种自定义数据类型:
BinanceTicker
returned when subscribing to Binance 24hr tickers (contains many prices and stats). 订阅币安 24 小时行情时返回BinanceTicker
(包含许多价格和统计数据)。BinanceBar
returned when requesting historical, or subscribing to, Binance bars (contains extra volume information). 请求历史记录或订阅币安K线时返回BinanceBar
(包含额外的交易量信息)。BinanceFuturesMarkPriceUpdate
returned when subscribing to Binance Futures mark price updates. 订阅币安期货标记价格更新时返回BinanceFuturesMarkPriceUpdate
。
See the Binance API Reference for full definitions.
有关完整的定义,请参阅币安 API 参考。
As per the Nautilus unification policy for symbols, the native Binance symbols are used where possible including for spot assets and futures contracts. Because NautilusTrader is capable of multi-venue + multi-account trading, it's necessary to explicitly clarify the difference between BTCUSDT as the spot and margin traded pair, and the BTCUSDT perpetual futures contract (this symbol is used for both natively by Binance). Therefore, NautilusTrader appends
-PERP
to all native perpetual symbols. E.g. for Binance Futures, the said instruments symbol isBTCUSDT-PERP
within the Nautilus system boundary.根据 Nautilus 的符号统一策略,在可能的情况下使用本地币安符号,包括现货资产和期货合约。由于 NautilusTrader 能够进行多交易平台 + 多账户交易,因此有必要明确区分作为现货和保证金交易对的 BTCUSDT 与 BTCUSDT 永续期货合约之间的区别(此符号由币安本地使用)。因此,NautilusTrader 在所有本地永续符号后附加
-PERP
。例如,对于币安期货,上述Instrument符号在 Nautilus 系统边界内为BTCUSDT-PERP
。
Spot | Margin | Futures | |
---|---|---|---|
MARKET | ✓ | ✓ | ✓ |
LIMIT | ✓ | ✓ | ✓ |
STOP_MARKET | ✓ | ✓ | |
STOP_LIMIT | ✓ | ✓ | ✓ |
MARKET_IF_TOUCHED | ✓ | ||
LIMIT_IF_TOUCHED | ✓ | ✓ | ✓ |
TRAILING_STOP_MARKET | ✓ |
Binance uses the concept of an activation price for trailing stops, as detailed in their documentation. This approach is somewhat unconventional. For trailing stop orders to function on Binance, the activation price can optionally be set using the
trigger_price
value.币安使用激活价格的概念来进行追踪止损,如其文档中所述。这种方法有些不寻常。为了使追踪止损订单在币安上起作用,可以选择使用
trigger_price
值设置激活价格。
Note that the activation price is not the same as the trigger/STOP price. Binance will always calculate the trigger price for the order based on the current market price and the callback rate provided by
trailing_offset
. The activated price is simply the price at which the order will begin trailing based on the callback rate.请注意,激活价格与触发/止损价格不同。币安将始终根据当前市场价格和
trailing_offset
提供的回调率计算订单的触发价格。激活价格只是订单根据回调率开始追踪的价格。
When submitting trailing stop orders from your strategy, you have two options:
从您的策略提交追踪止损订单时,您有两个选择:
- Use the
trigger_price
to manually set the activation price. 使用trigger_price
手动设置激活价格。- Leave the
trigger_price
asNone
, making the trailing action immediately "active". 将trigger_price
保留为None
,使追踪操作立即“激活”。
You must also have at least one of the following:
您还必须至少具备以下条件之一:
- The
trigger_price
for the order is set (this will act as the Binanceactivation_price
). 订单的trigger_price
已设置(这将充当币安的activation_price
)。- (or) you have subscribed to quote ticks for the instrument you're submitting the order for (used to infer activation price). (或者)您已订阅了要为其提交订单的Instrument的报价(用于推断激活价格)。
- (or) you have subscribed to trade ticks for the instrument you're submitting the order for (used to infer activation price). (或者)您已订阅了要为其提交订单的Instrument的交易(用于推断激活价格)。
The most common use case is to configure a live
TradingNode
to include Binance data and execution clients. To achieve this, add aBINANCE
section to your client configuration(s):最常见的用例是配置实时
TradingNode
以包含币安数据和执行客户端。为此,请将BINANCE
部分添加到您的客户端配置中:
from nautilus_trader.live.node import TradingNode
config = TradingNodeConfig(
..., # Omitted
data_clients={
"BINANCE": {
"api_key": "YOUR_BINANCE_API_KEY",
"api_secret": "YOUR_BINANCE_API_SECRET",
"account_type": "spot", # {spot, margin, usdt_future, coin_future}
"base_url_http": None, # Override with custom endpoint 使用自定义端点覆盖
"base_url_ws": None, # Override with custom endpoint 使用自定义端点覆盖
"us": False, # If client is for Binance US 如果客户端用于币安美国站
},
},
exec_clients={
"BINANCE": {
"api_key": "YOUR_BINANCE_API_KEY",
"api_secret": "YOUR_BINANCE_API_SECRET",
"account_type": "spot", # {spot, margin, usdt_future, coin_future}
"base_url_http": None, # Override with custom endpoint 使用自定义端点覆盖
"base_url_ws": None, # Override with custom endpoint 使用自定义端点覆盖
"us": False, # If client is for Binance US 如果客户端用于币安美国站
},
},
)
Then, create a
TradingNode
and add the client factories:然后,创建一个
TradingNode
并添加客户端工厂:
from nautilus_trader.adapters.binance.factories import BinanceLiveDataClientFactory
from nautilus_trader.adapters.binance.factories import BinanceLiveExecClientFactory
from nautilus_trader.live.node import TradingNode
# Instantiate the live trading node with a configuration
# 使用配置实例化实时交易节点
node = TradingNode(config=config)
# Register the client factories with the node
# 向节点注册客户端工厂
node.add_data_client_factory("BINANCE", BinanceLiveDataClientFactory)
node.add_exec_client_factory("BINANCE", BinanceLiveExecClientFactory)
# Finally build the node
# 最后构建节点
node.build()
There are two options for supplying your credentials to the Binance clients. Either pass the corresponding
api_key
andapi_secret
values to the configuration objects, or set the following environment variables:向币安客户端提供凭据有两种选择。将相应的
api_key
和api_secret
值传递给配置对象,或者设置以下环境变量:
For Binance Spot/Margin live clients, you can set:
对于币安现货/保证金实时客户端,您可以设置:
BINANCE_API_KEY
BINANCE_API_SECRET
For Binance Spot/Margin testnet clients, you can set:
对于币安现货/保证金测试网客户端,您可以设置:
BINANCE_TESTNET_API_KEY
BINANCE_TESTNET_API_SECRET
For Binance Futures live clients, you can set:
对于币安期货实时客户端,您可以设置:
BINANCE_FUTURES_API_KEY
BINANCE_FUTURES_API_SECRET
For Binance Futures testnet clients, you can set:
对于币安期货测试网客户端,您可以设置:
BINANCE_FUTURES_TESTNET_API_KEY
BINANCE_FUTURES_TESTNET_API_SECRET
When starting the trading node, you'll receive immediate confirmation of whether your credentials are valid and have trading permissions.
启动交易节点时,您将立即收到您的凭据是否有效以及是否具有交易权限的确认。
All the Binance account types will be supported for live trading. Set the
account_type
using theBinanceAccountType
enum. The account type options are:所有币安账户类型都将支持实时交易。使用
BinanceAccountType
枚举设置account_type
。账户类型选项包括:
SPOT
MARGIN
(Margin shared between open positions.)MARGIN
(保证金在未平仓头寸之间共享。)ISOLATED_MARGIN
(Margin assigned to a single position.)ISOLATED_MARGIN
(保证金分配给单个头寸。)USDT_FUTURE
(USDT or BUSD stablecoins as collateral)USDT_FUTURE
(USDT 或 BUSD 稳定币作为抵押品)COIN_FUTURE
(other cryptocurrency as collateral)COIN_FUTURE
(其他加密货币作为抵押品)
It's possible to override the default base URLs for both HTTP Rest and WebSocket APIs. This is useful for configuring API clusters for performance reasons, or when Binance has provided you with specialized endpoints.
可以覆盖 HTTP Rest 和 WebSocket API 的默认基本 URL。这对于出于性能原因配置 API 集群或当币安为您提供了专用端点时非常有用。
There is support for Binance US accounts by setting the
us
option in the configs toTrue
(this isFalse
by default). All functionality available to US accounts should behave identically to standard Binance.通过在配置中将
us
选项设置为True
(默认情况下为False
),可以支持币安美国站账户。美国站账户可用的所有功能的行为应与标准币安相同。
It's also possible to configure one or both clients to connect to the Binance testnet. Simply set the
testnet
option toTrue
(this isFalse
by default):也可以将一个或两个客户端配置为连接到币安测试网。只需将
testnet
选项设置为True
(默认情况下为False
):
config = TradingNodeConfig(
..., # Omitted
data_clients={
"BINANCE": {
"api_key": "YOUR_BINANCE_TESTNET_API_KEY",
"api_secret": "YOUR_BINANCE_TESTNET_API_SECRET",
"account_type": "spot", # {spot, margin, usdt_future}
"testnet": True, # If client uses the testnet 如果客户端使用测试网
},
},
exec_clients={
"BINANCE": {
"api_key": "YOUR_BINANCE_TESTNET_API_KEY",
"api_secret": "YOUR_BINANCE_TESTNET_API_SECRET",
"account_type": "spot", # {spot, margin, usdt_future}
"testnet": True, # If client uses the testnet 如果客户端使用测试网
},
},
)
Binance provide aggregated trade data endpoints as an alternative source of trade ticks. In comparison to the default trade endpoints, aggregated trade data endpoints can return all ticks between a
start_time
andend_time
.币安提供聚合交易数据端点作为交易的替代来源。与默认交易端点相比,聚合交易数据端点可以返回
start_time
和end_time
之间的所有数据。
To use aggregated trades and the endpoint features, set the
use_agg_trade_ticks
option toTrue
(this isFalse
by default.)要使用聚合交易和端点功能,请将
use_agg_trade_ticks
选项设置为True
(默认情况下为False
)。
Some Binance instruments are unable to be parsed into Nautilus objects if they contain enormous field values beyond what can be handled by the platform. In these cases, a warn and continue approach is taken (the instrument will not be available).
如果某些币安Instrument包含平台无法处理的巨大字段值,则无法将其解析为 Nautilus 对象。在这些情况下,将采用警告并继续的方法(该Instrument将不可用)。
These warnings may cause unnecessary log noise, and so it's possible to configure the provider to not log the warnings, as per the client configuration example below:
这些警告可能会导致不必要的日志噪音,因此可以将提供程序配置为不记录警告,如下面的客户端配置示例所示:
from nautilus_trader.config import InstrumentProviderConfig
instrument_provider=InstrumentProviderConfig(
load_all=True,
log_warnings=False,
)
Binance Futures Hedge mode is a position mode where a trader opens positions in both long and short directions to mitigate risk and potentially profit from market volatility.
币安期货对冲模式是一种头寸模式,交易者在多头和空头方向都开仓,以降低风险并可能从市场波动中获利。
To use Binance Future Hedge mode, you need to follow the three items below:
要使用币安期货对冲模式,您需要遵循以下三项:
- Before starting the strategy, ensure that hedge mode is configured on Binance. 在开始策略之前,请确保在币安上配置了对冲模式。
- Set the
use_reduce_only
option toFalse
inBinanceExecClientConfig
(this isTrue
by default.) 在BinanceExecClientConfig
中将use_reduce_only
选项设置为False
(默认情况下为True
。)
config = TradingNodeConfig(
..., # Omitted
data_clients={
"BINANCE": BinanceDataClientConfig(
api_key=None, # 'BINANCE_API_KEY' env var
api_secret=None, # 'BINANCE_API_SECRET' env var
account_type=BinanceAccountType.USDT_FUTURE,
base_url_http=None, # Override with custom endpoint 使用自定义端点覆盖
base_url_ws=None, # Override with custom endpoint 使用自定义端点覆盖
),
},
exec_clients={
"BINANCE": BinanceExecClientConfig(
api_key=None, # 'BINANCE_API_KEY' env var
api_secret=None, # 'BINANCE_API_SECRET' env var
account_type=BinanceAccountType.USDT_FUTURE,
base_url_http=None, # Override with custom endpoint 使用自定义端点覆盖
base_url_ws=None, # Override with custom endpoint 使用自定义端点覆盖
use_reduce_only=False, # Must be disabled for Hedge mode 必须为对冲模式禁用
),
}
)
- When submitting an order, use a suffix (LONG or SHORT ) in the
position_id
to indicate the position direction. 提交订单时,在position_id
中使用后缀(LONG 或 SHORT)来指示头寸方向。
class EMACrossHedgeMode(Strategy):
..., # Omitted
def buy(self) -> None:
"""
Users simple buy method (example).
# 用户简单的买入方法(示例)。
"""
order: MarketOrder = self.order_factory.market(
instrument_id=self.instrument_id,
order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(self.trade_size),
# time_in_force=TimeInForce.FOK,
)
# LONG suffix is recognized as a long position by Binance adapter.
# LONG 后缀被币安适配器识别为多头头寸。
position_id = PositionId(f"{self.instrument_id}-LONG")
self.submit_order(order, position_id)
def sell(self) -> None:
"""
Users simple sell method (example).
# 用户简单的卖出方法(示例)。
"""
order: MarketOrder = self.order_factory.market(
instrument_id=self.instrument_id,
order_side=OrderSide.SELL,
quantity=self.instrument.make_qty(self.trade_size),
# time_in_force=TimeInForce.FOK,
)
# SHORT suffix is recognized as a short position by Binance adapter.
# SHORT 后缀被币安适配器识别为空头头寸。
position_id = PositionId(f"{self.instrument_id}-SHORT")
self.submit_order(order, position_id)
Order books can be maintained at full or partial depths depending on the subscription. WebSocket stream throttling is different between Spot and Futures exchanges, Nautilus will use the highest streaming rate possible:
订单簿可以根据订阅维护完整或部分深度。现货和期货交易所之间的 WebSocket 流限制不同,Nautilus 将使用尽可能高的流速率:
- Spot 100ms 现货 100 毫秒
- Futures 0ms (unthrottled) 期货 0 毫秒(无限制)
There is a limitation of one order book per instrument per trader instance. As stream subscriptions may vary, the latest order book data (deltas or snapshots) subscription will be used by the Binance data client.
每个交易者实例每个Instrument限制一个订单簿。由于流订阅可能会有所不同,币安数据客户端将使用最新的订单簿数据(增量或快照)订阅。
Order book snapshot rebuilds will be triggered on:
订单簿快照重建将在以下情况下触发:
- Initial subscription of the order book data 订单簿数据的初始订阅
- Data websocket reconnects 数据 websocket 重新连接
The sequence of events is as follows:
事件顺序如下:
- Deltas will start buffered. 增量将开始缓冲。
- Snapshot is requested and awaited. 请求并等待快照。
- Snapshot response is parsed to
OrderBookDeltas
. 快照响应被解析为OrderBookDeltas
。- Snapshot deltas are sent to the
DataEngine
. 快照增量被发送到DataEngine
。- Buffered deltas are iterated, dropping those where the sequence number is not greater than the last delta in the snapshot. 迭代缓冲的增量,删除序列号不大于快照中最后一个增量的增量。
- Deltas will stop buffering. 增量将停止缓冲。
- Remaining deltas are sent to the
DataEngine
. 剩余的增量被发送到DataEngine
。
The
ts_event
field value forQuoteTick
objects will differ between Spot and Futures exchanges, where the former does not provide an event timestamp, so thets_init
is used (which meansts_event
andts_init
are identical).
QuoteTick
对象的ts_event
字段值在现货和期货交易所之间会有所不同,前者不提供事件时间戳,因此使用ts_init
(这意味着ts_event
和ts_init
相同)。
It's possible to subscribe to Binance specific data streams as they become available to the adapter over time.
可以订阅币安特定的数据流,因为它们会随着时间的推移而对适配器可用。
Bars are not considered 'Binance specific' and can be subscribed to in the normal way. As more adapters are built out which need for example mark price and funding rate updates, then these methods may eventually become first-class (not requiring custom/generic subscriptions as below).
K线不被视为“币安特定”,可以以正常方式订阅。随着更多适配器的构建,例如需要标记价格和资金费率更新,这些方法最终可能会成为一流的(不需要如下所示的自定义/通用订阅)。
You can subscribe to
BinanceFuturesMarkPriceUpdate
(included funding rating info) data streams by subscribing in the following way from your actor or strategy:您可以通过以下方式从您的参与者或策略订阅
BinanceFuturesMarkPriceUpdate
(包括资金费率信息)数据流:
from nautilus_trader.adapters.binance.futures.types import BinanceFuturesMarkPriceUpdate
from nautilus_trader.model.data import DataType
from nautilus_trader.model.identifiers import ClientId
# In your `on_start` method
# 在您的 `on_start` 方法中
self.subscribe_data(
data_type=DataType(BinanceFuturesMarkPriceUpdate, metadata={"instrument_id": self.instrument.id}),
client_id=ClientId("BINANCE"),
)
This will result in your actor/strategy passing these received
BinanceFuturesMarkPriceUpdate
objects to youron_data
method. You will need to check the type, as this method acts as a flexible handler for all custom/generic data.这将导致您的参与者/策略将这些接收到的
BinanceFuturesMarkPriceUpdate
对象传递给您的on_data
方法。您需要检查类型,因为此方法充当所有自定义/通用数据的灵活处理程序。
from nautilus_trader.core.data import Data
def on_data(self, data: Data):
# First check the type of data
# 首先检查数据的类型
if isinstance(data, BinanceFuturesMarkPriceUpdate):
# Do something with the data
# 对数据做一些处理