Binance 币安 - Loren1166/NautilusTrader- GitHub Wiki
Binance 币安
Provides an API integration for the Binance Crypto exchange.
为币安加密货币交易所提供 API 集成。
Config 配置
class BinanceDataClientConfig 币安数据客户端配置
class BinanceDataClientConfig(LiveDataClientConfig)
Configuration for
BinanceDataClient
instances.
BinanceDataClient
实例的配置。
Parameters:
venue
(Venue
, defaultBINANCE_VENUE
): The venue for the client.venue
(Venue
,默认为BINANCE_VENUE
):客户端的交易平台。api_key
(str
, optional): The Binance API public key. IfNone
then will source theBINANCE_API_KEY
orBINANCE_TESTNET_API_KEY
environment variables.api_key
(str
,可选):币安 API 公钥。如果为None
,则将获取BINANCE_API_KEY
或BINANCE_TESTNET_API_KEY
环境变量。api_secret
(str
, optional): The Binance API public key. IfNone
then will source theBINANCE_API_SECRET
orBINANCE_TESTNET_API_SECRET
environment variables.api_secret
(str
,可选):币安 API 公钥。如果为None
,则将获取BINANCE_API_SECRET
或BINANCE_TESTNET_API_SECRET
环境变量。key_type
(BinanceKeyType
, default 'HMAC'): The private key cryptographic algorithm type.key_type
(BinanceKeyType
,默认为“HMAC”):私钥加密算法类型。account_type
(BinanceAccountType
, defaultBinanceAccountType.SPOT
): The account type for the client.account_type
(BinanceAccountType
,默认为BinanceAccountType.SPOT
):客户端的账户类型。base_url_http
(str
, optional): The HTTP client custom endpoint override.base_url_http
(str
,可选):HTTP 客户端自定义端点覆盖。base_url_ws
(str
, optional): The WebSocket client custom endpoint override.base_url_ws
(str
,可选):WebSocket 客户端自定义端点覆盖。us
(bool
, defaultFalse
): If client is connecting to Binance US.us
(bool
,默认为False
):如果客户端连接到币安美国站。testnet
(bool
, defaultFalse
): If the client is connecting to a Binance testnet.testnet
(bool
,默认为False
):如果客户端连接到币安测试网。use_agg_trade_ticks
(bool
, defaultFalse
): Whether to use aggregated trade tick endpoints instead of raw trade ticks. TradeId of ticks will be the Aggregate tradeId returned by Binance.use_agg_trade_ticks
(bool
,默认为False
):是否使用聚合交易端点而不是原始交易。交易的 TradeId 将是币安返回的聚合 tradeId。
venue: Venue
api_key: str | None
api_secret: str | None
key_type: BinanceKeyType
account_type: BinanceAccountType
base_url_http: str | None
base_url_ws: str | None
us: bool
testnet: bool
use_agg_trade_ticks: bool
def __dict__(self) -> dict[str, Any]:
"""
Return a dictionary representation of the configuration.
Returns
-------
dict[str, Any]
"""
...
@classmethod
def fully_qualified_name() -> str:
"""
Return the fully qualified name for the NautilusConfig class.
Returns
-------
str
"""
...
@property
def handle_revised_bars(self) -> bool:
...
@property
def id(self) -> str:
"""
Return the hashed identifier for the configuration.
Returns
-------
str
"""
...
@property
def instrument_provider(self) -> InstrumentProviderConfig:
...
def json(self) -> bytes:
"""
Return serialized JSON encoded bytes.
Returns
-------
bytes
"""
...
def json_primitives(self) -> dict[str, Any]:
"""
Return a dictionary representation of the configuration with JSON primitive types as values.
Returns
-------
dict[str, Any]
"""
...
@classmethod
def parse(raw: bytes | str) -> Any:
"""
Return a decoded object of the given cls.
Parameters
----------
cls : type
The type to decode to.
raw : bytes or str
The raw bytes or JSON string to decode.
Returns
-------
Any
"""
...
@property
def routing(self) -> RoutingConfig:
...
def validate(self) -> bool:
"""
Return whether the configuration can be represented as valid JSON.
Returns
-------
bool
"""
...
class BinanceExecClientConfig 币安执行客户端配置
class BinanceExecClientConfig(LiveExecClientConfig)
Configuration for
BinanceExecutionClient
instances.
BinanceExecutionClient
实例的配置。
Parameters:
venue
(Venue
, defaultBINANCE_VENUE
): The venue for the client.venue
(Venue
,默认为BINANCE_VENUE
):客户端的交易平台。api_key
(str
, optional): The Binance API public key. IfNone
then will source theBINANCE_API_KEY
orBINANCE_TESTNET_API_KEY
environment variables.api_key
(str
,可选):币安 API 公钥。如果为None
,则将获取BINANCE_API_KEY
或BINANCE_TESTNET_API_KEY
环境变量。api_secret
(str
, optional): The Binance API public key. IfNone
then will source theBINANCE_API_KEY
orBINANCE_TESTNET_API_KEY
environment variables.api_secret
(str
,可选):币安 API 公钥。如果为None
,则将获取BINANCE_API_KEY
或BINANCE_TESTNET_API_KEY
环境变量。key_type
(BinanceKeyType
, default 'HMAC'): The private key cryptographic algorithm type.key_type
(BinanceKeyType
,默认为“HMAC”):私钥加密算法类型。account_type
(BinanceAccountType
, defaultBinanceAccountType.SPOT
): The account type for the client.account_type
(BinanceAccountType
,默认为BinanceAccountType.SPOT
):客户端的账户类型。base_url_http
(str
, optional): The HTTP client custom endpoint override.base_url_http
(str
,可选):HTTP 客户端自定义端点覆盖。base_url_ws
(str
, optional): The WebSocket client custom endpoint override.base_url_ws
(str
,可选):WebSocket 客户端自定义端点覆盖。us
(bool
, defaultFalse
): If client is connecting to Binance US.us
(bool
,默认为False
):如果客户端连接到币安美国站。testnet
(bool
, defaultFalse
): If the client is connecting to a Binance testnet.testnet
(bool
,默认为False
):如果客户端连接到币安测试网。use_gtd
(bool
, defaultTrue
): If GTD orders will use the Binance GTD TIF option. IfFalse
then GTD time in force will be remapped to GTC (this is useful if managing GTD orders locally).use_gtd
(bool
,默认为True
):如果 GTD 订单将使用币安 GTD TIF 选项。如果为False
,则 GTD 有效期将重新映射到 GTC(如果在本地管理 GTD 订单,这将非常有用)。use_reduce_only
(bool
, defaultTrue
): If thereduce_only
execution instruction on orders is sent through to the exchange. IfTrue
then will assign the value on orders sent to the exchange, otherwise will always beFalse
.use_reduce_only
(bool
,默认为True
):如果订单上的reduce_only
执行指令被发送到交易所。如果为True
,则将在发送到交易所的订单上分配该值,否则将始终为False
。use_position_ids
(bool
, defaultTrue
): If Binance Futures hedging position IDs should be used. IfFalse
then order eventposition_id
(s) from the execution client will beNone
, which allows virtual positions withOmsType.HEDGING
.use_position_ids
(bool
,默认为True
):是否应使用币安期货对冲头寸 ID。如果为False
,则执行客户端的订单事件position_id
将为None
,这允许使用OmsType.HEDGING
进行虚拟头寸。treat_expired_as_canceled
(bool
, defaultFalse
): If theEXPIRED
execution type is semantically treated asCANCELED
. Binance treats cancels with certain combinations of order type and time in force as expired events. This config option allows you to treat these uniformally as cancels.treat_expired_as_canceled
(bool
,默认为False
):如果EXPIRED
执行类型在语义上被视为CANCELED
。币安将某些订单类型和有效期组合的取消视为过期事件。此配置选项允许您将这些统一视为取消。recv_window_ms
(PositiveInt
, default 5000): The receive window (milliseconds) for Binance HTTP requests.recv_window_ms
(PositiveInt
,默认为 5000):币安 HTTP 请求的接收窗口(以毫秒为单位)。max_retries
(PositiveInt
, optional): The maximum number of times a submit, cancel or modify order request will be retried.max_retries
(PositiveInt
,可选):提交、取消或修改订单请求将重试的最大次数。retry_delay
(PositiveFloat
, optional): The delay (seconds) between retries. Short delays with frequent retries may result in account bans.retry_delay
(PositiveFloat
,可选):重试之间的延迟(以秒为单位)。频繁重试的短延迟可能会导致账户被封禁。
venue: Venue
api_key: str | None
api_secret: str | None
key_type: BinanceKeyType
account_type: BinanceAccountType
base_url_http: str | None
base_url_ws: str | None
us: bool
testnet: bool
use_gtd: bool
use_reduce_only: bool
use_position_ids: bool
treat_expired_as_canceled: bool
recv_window_ms: Annotated[int, msgspec.Meta(gt=0)]
max_retries: Annotated[int, msgspec.Meta(gt=0)] | None
retry_delay: Annotated[float, msgspec.Meta(gt=0.0)] | None
def __dict__(self) -> dict[str, Any]:
"""
Return a dictionary representation of the configuration.
Returns
-------
dict[str, Any]
"""
...
@classmethod
def fully_qualified_name() -> str:
"""
Return the fully qualified name for the NautilusConfig class.
Returns
-------
str
"""
...
@property
def id(self) -> str:
"""
Return the hashed identifier for the configuration.
Returns
-------
str
"""
...
@property
def instrument_provider(self) -> InstrumentProviderConfig:
...
def json(self) -> bytes:
"""
Return serialized JSON encoded bytes.
Returns
-------
bytes
"""
...
def json_primitives(self) -> dict[str, Any]:
"""
Return a dictionary representation of the configuration with JSON primitive types as values.
Returns
-------
dict[str, Any]
"""
...
@classmethod
def parse(raw: bytes | str) -> Any:
"""
Return a decoded object of the given cls.
Parameters
----------
cls : type
The type to decode to.
raw : bytes or str
The raw bytes or JSON string to decode.
Returns
-------
Any
"""
...
@property
def routing(self) -> RoutingConfig:
...
def validate(self) -> bool:
"""
Return whether the configuration can be represented as valid JSON.
Returns
-------
bool
"""
...
Factories 工厂
def get_cached_binance_http_client(clock: LiveClock, account_type: BinanceAccountType, api_key: str | None = None, api_secret: str | None = None, key_type: BinanceKeyType = BinanceKeyType.HMAC, base_url: str | None = None, is_testnet: bool = False, is_us: bool = False) -> BinanceHttpClient:
"""
Cache and return a Binance HTTP client with the given key and secret.
If a cached client with matching key and secret already exists, then that cached client will be returned.
Parameters
----------
clock : LiveClock
The clock for the client.
account_type : BinanceAccountType
The account type for the client.
api_key : str, optional
The API key for the client.
api_secret : str, optional
The API secret for the client.
key_type : BinanceKeyType, default 'HMAC'
The private key cryptographic algorithm type.
base_url : str, optional
The base URL for the API endpoints.
is_testnet : bool, default False
If the client is connecting to the testnet API.
is_us : bool, default False
If the client is connecting to Binance US.
Returns
-------
BinanceHttpClient
"""
...
def get_cached_binance_spot_instrument_provider(client: BinanceHttpClient, clock: LiveClock, account_type: BinanceAccountType, is_testnet: bool, config: InstrumentProviderConfig, venue: Venue) -> BinanceSpotInstrumentProvider:
"""
Cache and return an instrument provider for the Binance Spot/Margin exchange.
If a cached provider already exists, then that provider will be returned.
Parameters
----------
client : BinanceHttpClient
The client for the instrument provider.
clock : LiveClock
The clock for the instrument provider.
account_type : BinanceAccountType
The Binance account type for the instrument provider.
is_testnet : bool, default False
If the provider is for the Spot testnet.
config : InstrumentProviderConfig
The configuration for the instrument provider.
venue : Venue
The venue for the instrument provider.
Returns
-------
BinanceSpotInstrumentProvider
"""
...
def get_cached_binance_futures_instrument_provider(client: BinanceHttpClient, clock: LiveClock, account_type: BinanceAccountType, config: InstrumentProviderConfig, venue: Venue) -> BinanceFuturesInstrumentProvider:
"""
Cache and return an instrument provider for the Binance Futures exchange.
If a cached provider already exists, then that provider will be returned.
Parameters
----------
client : BinanceHttpClient
The client for the instrument provider.
clock : LiveClock
The clock for the instrument provider.
account_type : BinanceAccountType
The Binance account type for the instrument provider.
config : InstrumentProviderConfig
The configuration for the instrument provider.
venue : Venue
The venue for the instrument provider.
Returns
-------
BinanceFuturesInstrumentProvider
"""
...
class BinanceLiveDataClientFactory 币安实时数据客户端工厂
class BinanceLiveDataClientFactory(LiveDataClientFactory)
Provides a Binance live data client factory.
提供币安实时数据客户端工厂。
@staticmethod
def create(loop: AbstractEventLoop, name: str, config: BinanceDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) -> BinanceSpotDataClient | BinanceFuturesDataClient:
"""
Create a new Binance data client.
Parameters
----------
loop : asyncio.AbstractEventLoop
The event loop for the client.
name : str
The custom client ID.
config : BinanceDataClientConfig
The client configuration.
msgbus : MessageBus
The message bus for the client.
cache : Cache
The cache for the client.
clock : LiveClock
The clock for the client.
Returns
-------
BinanceSpotDataClient or BinanceFuturesDataClient
Raises
------
ValueError
If config.account_type is not a valid BinanceAccountType.
"""
...
class BinanceLiveExecClientFactory 币安实时执行客户端工厂
class BinanceLiveExecClientFactory(LiveExecClientFactory)
Provides a Binance live execution client factory.
提供币安实时执行客户端工厂。
@staticmethod
def create(loop: AbstractEventLoop, name: str, config: BinanceExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) -> BinanceSpotExecutionClient | BinanceFuturesExecutionClient:
"""
Create a new Binance execution client.
Parameters
----------
loop : asyncio.AbstractEventLoop
The event loop for the client.
name : str
The custom client ID.
config : BinanceExecClientConfig
The configuration for the client.
msgbus : MessageBus
The message bus for the client.
cache : Cache
The cache for the client.
clock : LiveClock
The clock for the client.
Returns
-------
BinanceExecutionClient
Raises
------
ValueError
If config.account_type is not a valid BinanceAccountType.
"""
...
Enums 枚举
Defines Binance common enums.
定义币安通用枚举。
class BinanceKeyType 币安密钥类型
class BinanceKeyType(Enum)
Represents a Binance private key cryptographic algorithm type.
表示币安私钥加密算法类型。
HMAC = "HMAC"
RSA = "RSA"
ED25519 = "Ed25519"
class BinanceFuturesPositionSide 币安期货头寸方向
class BinanceFuturesPositionSide(Enum)
Represents a Binance Futures position side.
表示币安期货头寸方向。
BOTH = "BOTH"
LONG = "LONG"
SHORT = "SHORT"
class BinanceRateLimitType 币安速率限制类型
class BinanceRateLimitType(Enum)
Represents a Binance rate limit type.
表示币安速率限制类型。
REQUEST_WEIGHT = "REQUEST_WEIGHT"
ORDERS = "ORDERS"
RAW_REQUESTS = "RAW_REQUESTS"
class BinanceRateLimitInterval 币安速率限制间隔
class BinanceRateLimitInterval(Enum)
Represents a Binance rate limit interval.
表示币安速率限制间隔。
SECOND = "SECOND"
MINUTE = "MINUTE"
DAY = "DAY"
class BinanceKlineInterval 币安 K 线间隔
class BinanceKlineInterval(Enum)
Represents a Binance kline chart interval.
表示币安 K 线图间隔。
SECOND_1 = "1s"
MINUTE_1 = "1m"
MINUTE_3 = "3m"
MINUTE_5 = "5m"
MINUTE_15 = "15m"
MINUTE_30 = "30m"
HOUR_1 = "1h"
HOUR_2 = "2h"
HOUR_4 = "4h"
HOUR_6 = "6h"
HOUR_8 = "8h"
HOUR_12 = "12h"
DAY_1 = "1d"
DAY_3 = "3d"
WEEK_1 = "1w"
MONTH_1 = "1M"
class BinanceExchangeFilterType 币安交易所过滤器类型
class BinanceExchangeFilterType(Enum)
Represents a Binance exchange filter type.
表示币安交易所过滤器类型。
EXCHANGE_MAX_NUM_ORDERS = "EXCHANGE_MAX_NUM_ORDERS"
EXCHANGE_MAX_NUM_ALGO_ORDERS = "EXCHANGE_MAX_NUM_ALGO_ORDERS"
class BinanceSymbolFilterType 币安符号过滤器类型
class BinanceSymbolFilterType(Enum)
Represents a Binance symbol filter type.
表示币安符号过滤器类型。
PRICE_FILTER = "PRICE_FILTER"
PERCENT_PRICE = "PERCENT_PRICE"
PERCENT_PRICE_BY_SIDE = "PERCENT_PRICE_BY_SIDE"
LOT_SIZE = "LOT_SIZE"
MIN_NOTIONAL = "MIN_NOTIONAL"
NOTIONAL = "NOTIONAL"
ICEBERG_PARTS = "ICEBERG_PARTS"
MARKET_LOT_SIZE = "MARKET_LOT_SIZE"
MAX_NUM_ORDERS = "MAX_NUM_ORDERS"
MAX_NUM_ALGO_ORDERS = "MAX_NUM_ALGO_ORDERS"
MAX_NUM_ICEBERG_ORDERS = "MAX_NUM_ICEBERG_ORDERS"
MAX_POSITION = "MAX_POSITION"
TRAILING_DELTA = "TRAILING_DELTA"
class BinanceAccountType 币安账户类型
class BinanceAccountType(Enum)
Represents a Binance account type.
表示币安账户类型。
SPOT = "SPOT"
MARGIN = "MARGIN"
ISOLATED_MARGIN = "ISOLATED_MARGIN"
USDT_FUTURE = "USDT_FUTURE"
COIN_FUTURE = "COIN_FUTURE"
@property
def is_spot(self) -> bool:
...
@property
def is_margin(self) -> bool:
...
@property
def is_spot_or_margin(self) -> bool:
...
@property
def is_futures(self) -> bool:
...
class BinanceOrderSide 币安订单方向
class BinanceOrderSide(Enum)
Represents a Binance order side.
表示币安订单方向。
BUY = "BUY"
SELL = "SELL"
class BinanceExecutionType 币安执行类型
class BinanceExecutionType(Enum)
Represents a Binance execution type.
表示币安执行类型。
NEW = "NEW"
CANCELED = "CANCELED"
CALCULATED = "CALCULATED"
REJECTED = "REJECTED"
TRADE = "TRADE"
EXPIRED = "EXPIRED"
AMENDMENT = "AMENDMENT"
TRADE_PREVENTION = "TRADE_PREVENTION"
class BinanceOrderStatus 币安订单状态
class BinanceOrderStatus(Enum)
Represents a Binance order status.
表示币安订单状态。
NEW = "NEW"
PARTIALLY_FILLED = "PARTIALLY_FILLED"
FILLED = "FILLED"
CANCELED = "CANCELED"
PENDING_CANCEL = "PENDING_CANCEL"
REJECTED = "REJECTED"
EXPIRED = "EXPIRED"
EXPIRED_IN_MATCH = "EXPIRED_IN_MATCH"
NEW_INSURANCE = "NEW_INSURANCE"
NEW_ADL = "NEW_ADL"
class BinanceTimeInForce 币安有效期
class BinanceTimeInForce(Enum)
Represents a Binance order time in force.
表示币安订单有效期。
GTC = "GTC"
IOC = "IOC"
FOK = "FOK"
GTX = "GTX"
GTD = "GTD"
GTE_GTC = "GTE_GTC"
class BinanceOrderType 币安订单类型
class BinanceOrderType(Enum)
Represents a Binance order type.
表示币安订单类型。
LIMIT = "LIMIT"
MARKET = "MARKET"
STOP = "STOP"
STOP_LOSS = "STOP_LOSS"
STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT"
TAKE_PROFIT = "TAKE_PROFIT"
TAKE_PROFIT_LIMIT = "TAKE_PROFIT_LIMIT"
LIMIT_MAKER = "LIMIT_MAKER"
STOP_MARKET = "STOP_MARKET"
TAKE_PROFIT_MARKET = "TAKE_PROFIT_MARKET"
TRAILING_STOP_MARKET = "TRAILING_STOP_MARKET"
INSURANCE_FUND = "INSURANCE_FUND"
class BinanceSecurityType 币安端点安全类型
class BinanceSecurityType(Enum)
Represents a Binance endpoint security type.
表示币安端点安全类型。
NONE = "NONE"
TRADE = "TRADE"
MARGIN = "MARGIN"
USER_DATA = "USER_DATA"
USER_STREAM = "USER_STREAM"
MARKET_DATA = "MARKET_DATA"
class BinanceNewOrderRespType 币安新订单响应类型
class BinanceNewOrderRespType(Enum)
Represents a Binance
newOrderRespType
.表示币安
newOrderRespType
。
ACK = "ACK"
RESULT = "RESULT"
FULL = "FULL"
class BinanceErrorCode 币安错误代码
class BinanceErrorCode(Enum)
Represents a Binance error code (covers futures).
表示币安错误代码(涵盖期货)。
UNKNOWN = -1000
DISCONNECTED = -1001
UNAUTHORIZED = -1002
TOO_MANY_REQUESTS = -1003
DUPLICATE_IP = -1004
NO_SUCH_IP = -1005
UNEXPECTED_RESP = -1006
TIMEOUT = -1007
SERVER_BUSY = -1008
ERROR_MSG_RECEIVED = -1010
NON_WHITE_LIST = -1011
INVALID_MESSAGE = -1013
UNKNOWN_ORDER_COMPOSITION = -1014
TOO_MANY_ORDERS = -1015
SERVICE_SHUTTING_DOWN = -1016
UNSUPPORTED_OPERATION = -1020
INVALID_TIMESTAMP = -1021
INVALID_SIGNATURE = -1022
START_TIME_GREATER_THAN_END_TIME = -1023
NOT_FOUND = -1099
ILLEGAL_CHARS = -1100
TOO_MANY_PARAMETERS = -1101
MANDATORY_PARAM_EMPTY_OR_MALFORMED = -1102
UNKNOWN_PARAM = -1103
UNREAD_PARAMETERS = -1104
PARAM_EMPTY = -1105
PARAM_NOT_REQUIRED = -1106
BAD_ASSET = -1108
BAD_ACCOUNT = -1109
BAD_INSTRUMENT_TYPE = -1110
BAD_PRECISION = -1111
NO_DEPTH = -1112
WITHDRAW_NOT_NEGATIVE = -1113
TIF_NOT_REQUIRED = -1114
INVALID_TIF = -1115
INVALID_ORDER_TYPE = -1116
INVALID_SIDE = -1117
EMPTY_NEW_CL_ORD_ID = -1118
EMPTY_ORG_CL_ORD_ID = -1119
BAD_INTERVAL = -1120
BAD_SYMBOL = -1121
INVALID_SYMBOL_STATUS = -1122
INVALID_LISTEN_KEY = -1125
ASSET_NOT_SUPPORTED = -1126
MORE_THAN_XX_HOURS = -1127
OPTIONAL_PARAMS_BAD_COMBO = -1128
INVALID_PARAMETER = -1130
INVALID_NEW_ORDER_RESP_TYPE = -1136
INVALID_CALLBACK_RATE = -2007
NEW_ORDER_REJECTED = -2010
CANCEL_REJECTED = -2011
CANCEL_ALL_FAIL = -2012
NO_SUCH_ORDER = -2013
BAD_API_KEY_FMT = -2014
REJECTED_MBX_KEY = -2015
NO_TRADING_WINDOW = -2016
API_KEYS_LOCKED = -2017
BALANCE_NOT_SUFFICIENT = -2018
MARGIN_NOT_SUFFICIENT = -2019
UNABLE_TO_FILL = -2020
ORDER_WOULD_IMMEDIATELY_TRIGGER = -2021
REDUCE_ONLY_REJECT = -2022
USER_IN_LIQUIDATION = -2023
POSITION_NOT_SUFFICIENT = -2024
MAX_OPEN_ORDER_EXCEEDED = -2025
REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED = -2026
MAX_LEVERAGE_RATIO = -2027
MIN_LEVERAGE_RATIO = -2028
INVALID_ORDER_STATUS = -4000
PRICE_LESS_THAN_ZERO = -4001
PRICE_GREATER_THAN_MAX_PRICE = -4002
QTY_LESS_THAN_ZERO = -4003
QTY_LESS_THAN_MIN_QTY = -4004
QTY_GREATER_THAN_MAX_QTY = -4005
STOP_PRICE_LESS_THAN_ZERO = -4006
STOP_PRICE_GREATER_THAN_MAX_PRICE = -4007
TICK_SIZE_LESS_THAN_ZERO = -4008
MAX_PRICE_LESS_THAN_MIN_PRICE = -4009
MAX_QTY_LESS_THAN_MIN_QTY = -4010
STEP_SIZE_LESS_THAN_ZERO = -4011
MAX_NUM_ORDERS_LESS_THAN_ZERO = -4012
PRICE_LESS_THAN_MIN_PRICE = -4013
PRICE_NOT_INCREASED_BY_TICK_SIZE = -4014
INVALID_CL_ORD_ID_LEN = -4015
PRICE_HIGHTER_THAN_MULTIPLIER_UP = -4016
MULTIPLIER_UP_LESS_THAN_ZERO = -4017
MULTIPLIER_DOWN_LESS_THAN_ZERO = -4018
COMPOSITE_SCALE_OVERFLOW = -4019
TARGET_STRATEGY_INVALID = -4020
INVALID_DEPTH_LIMIT = -4021
WRONG_MARKET_STATUS = -4022
QTY_NOT_INCREASED_BY_STEP_SIZE = -4023
PRICE_LOWER_THAN_MULTIPLIER_DOWN = -4024
MULTIPLIER_DECIMAL_LESS_THAN_ZERO = -4025
COMMISSION_INVALID = -4026
INVALID_ACCOUNT_TYPE = -4027
INVALID_LEVERAGE = -4028
INVALID_TICK_SIZE_PRECISION = -4029
INVALID_STEP_SIZE_PRECISION = -4030
INVALID_WORKING_TYPE = -4031
EXCEED_MAX_CANCEL_ORDER_SIZE = -4032
INSURANCE_ACCOUNT_NOT_FOUND = -4033
INVALID_BALANCE_TYPE = -4044
MAX_STOP_ORDER_EXCEEDED = -4045
NO_NEED_TO_CHANGE_MARGIN_TYPE = -4046
THERE_EXISTS_OPEN_ORDERS = -4047
THERE_EXISTS_QUANTITY = -4048
ADD_ISOLATED_MARGIN_REJECT = -4049
CROSS_BALANCE_INSUFFICIENT = -4050
ISOLATED_BALANCE_INSUFFICIENT = -4051
NO_NEED_TO_CHANGE_AUTO_ADD_MARGIN = -4052
AUTO_ADD_CROSSED_MARGIN_REJECT = -4053
ADD_ISOLATED_MARGIN_NO_POSITION_REJECT = -4054
AMOUNT_MUST_BE_POSITIVE = -4055
INVALID_API_KEY_TYPE = -4056
INVALID_RSA_PUBLIC_KEY = -4057
MAX_PRICE_TOO_LARGE = -4058
NO_NEED_TO_CHANGE_POSITION_SIDE = -4059
INVALID_POSITION_SIDE = -4060
POSITION_SIDE_NOT_MATCH = -4061
REDUCE_ONLY_CONFLICT = -4062
INVALID_OPTIONS_REQUEST_TYPE = -4063
INVALID_OPTIONS_TIME_FRAME = -4064
INVALID_OPTIONS_AMOUNT = -4065
INVALID_OPTIONS_EVENT_TYPE = -4066
POSITION_SIDE_CHANGE_EXISTS_OPEN_ORDERS = -4067
POSITION_SIDE_CHANGE_EXISTS_QUANTITY = -4068
INVALID_OPTIONS_PREMIUM_FEE = -4069
INVALID_CL_OPTIONS_ID_LEN = -4070
INVALID_OPTIONS_DIRECTION = -4071
OPTIONS_PREMIUM_NOT_UPDATE = -4072
OPTIONS_PREMIUM_INPUT_LESS_THAN_ZERO = -4073
OPTIONS_AMOUNT_BIGGER_THAN_UPPER = -4074
OPTIONS_PREMIUM_OUTPUT_ZERO = -4075
OPTIONS_PREMIUM_TOO_DIFF = -4076
OPTIONS_PREMIUM_REACH_LIMIT = -4077
OPTIONS_COMMON_ERROR = -4078
INVALID_OPTIONS_ID = -4079
OPTIONS_USER_NOT_FOUND = -4080
OPTIONS_NOT_FOUND = -4081
INVALID_BATCH_PLACE_ORDER_SIZE = -4082
PLACE_BATCH_ORDERS_FAIL = -4083
UPCOMING_METHOD = -4084
INVALID_NOTIONAL_LIMIT_COEF = -4085
INVALID_PRICE_SPREAD_THRESHOLD = -4086
REDUCE_ONLY_ORDER_PERMISSION = -4087
NO_PLACE_ORDER_PERMISSION = -4088
INVALID_CONTRACT_TYPE = -4104
INVALID_CLIENT_TRAN_ID_LEN = -4114
DUPLICATED_CLIENT_TRAN_ID = -4115
REDUCE_ONLY_MARGIN_CHECK_FAILED = -4118
MARKET_ORDER_REJECT = -4131
INVALID_ACTIVATION_PRICE = -4135
QUANTITY_EXISTS_WITH_CLOSE_POSITION = -4137
REDUCE_ONLY_MUST_BE_TRUE = -4138
ORDER_TYPE_CANNOT_BE_MKT = -4139
INVALID_OPENING_POSITION_STATUS = -4140
SYMBOL_ALREADY_CLOSED = -4141
STRATEGY_INVALID_TRIGGER_PRICE = -4142
INVALID_PAIR = -4144
ISOLATED_LEVERAGE_REJECT_WITH_POSITION = -4161
MIN_NOTIONAL = -4164
INVALID_TIME_INTERVAL = -4165
ISOLATED_REJECT_WITH_JOINT_MARGIN = -4167
JOINT_MARGIN_REJECT_WITH_ISOLATED = -4168
JOINT_MARGIN_REJECT_WITH_MB = -4169
JOINT_MARGIN_REJECT_WITH_OPEN_ORDER = -4170
NO_NEED_TO_CHANGE_JOINT_MARGIN = -4171
JOINT_MARGIN_REJECT_WITH_NEGATIVE_BALANCE = -4172
ISOLATED_REJECT_WITH_JOINT_MARGIN_2 = -4183
PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN = -4184
COOLING_OFF_PERIOD = -4192
ADJUST_LEVERAGE_KYC_FAILED = -4202
ADJUST_LEVERAGE_ONE_MONTH_FAILED = -4203
ADJUST_LEVERAGE_X_DAYS_FAILED = -4205
ADJUST_LEVERAGE_KYC_LIMIT = -4206
ADJUST_LEVERAGE_ACCOUNT_SYMBOL_FAILED = -4208
ADJUST_LEVERAGE_SYMBOL_FAILED = -4209
STOP_PRICE_HIGHER_THAN_PRICE_MULTIPLIER_LIMIT = -4210
STOP_PRICE_LOWER_THAN_PRICE_MULTIPLIER_LIMIT = -4211
TRADING_QUANTITATIVE_RULE = -4400
COMPLIANCE_RESTRICTION = -4401
COMPLIANCE_BLACK_SYMBOL_RESTRICTION = -4402
ADJUST_LEVERAGE_COMPLIANCE_FAILED = -4403
FOK_ORDER_REJECT = -5021
GTX_ORDER_REJECT = -5022
MOVE_ORDER_NOT_ALLOWED_SYMBOL_REASON = -5024
LIMIT_ORDER_ONLY = 5025
EXCEED_MAXIMUM_MODIFY_ORDER_LIMIT = -5026
SAME_ORDER = -5027
ME_RECVWINDOW_REJECT = -5028
INVALID_GOOD_TILL_DATE = -5040
class BinanceEnumParser 币安枚举解析器
class BinanceEnumParser
Provides common parsing methods for enums used by the ‘Binance’ exchange.
为“币安”交易所使用的枚举提供通用解析方法。
WARNING This class should not be used directly, but through a concrete subclass.
警告 此类不应直接使用,而应通过具体的子类使用。
def parse_binance_order_side(self, order_side: BinanceOrderSide) -> OrderSide:
...
def parse_internal_order_side(self, order_side: OrderSide) -> BinanceOrderSide:
...
def parse_binance_time_in_force(self, time_in_force: BinanceTimeInForce) -> TimeInForce:
...
def parse_internal_time_in_force(self, time_in_force: TimeInForce) -> BinanceTimeInForce:
...
def parse_binance_order_status(self, order_status: BinanceOrderStatus) -> OrderStatus:
...
def parse_binance_order_type(self, order_type: BinanceOrderType) -> OrderType:
...
def parse_internal_order_type(self, order: Order) -> BinanceOrderType:
...
def parse_binance_bar_agg(self, bar_agg: str) -> BarAggregation:
...
def parse_nautilus_bar_aggregation(self, bar_agg: BarAggregation) -> str:
...
def parse_binance_kline_interval_to_bar_spec(
self, kline_interval: BinanceKlineInterval
) -> BarSpecification:
...
def parse_binance_trigger_type(self, trigger_type: str) -> TriggerType:
...
def parse_position_id_to_binance_futures_position_side(
self, position_id: PositionId
) -> BinanceFuturesPositionSide:
...
Types 类型
class BinanceBar 币安K线
class BinanceBar(Bar)
Represents an aggregated Binance bar.
表示聚合的币安K线。
This data type includes the raw data provided by Binance.
此数据类型包括币安提供的原始数据。
Parameters:
bar_type
(BarType
): The bar type for this bar.bar_type
(BarType
):此K线的K线类型。open
(Price
): The bars open price.open
(Price
):K线的开盘价。high
(Price
): The bars high price.high
(Price
):K线的最高价。low
(Price
): The bars low price.low
(Price
):K线的最低价。close
(Price
): The bars close price.close
(Price
):K线的收盘价。volume
(Quantity
): The bars volume.volume
(Quantity
):K线的交易量。quote_volume
(Decimal
): The bars quote asset volume.quote_volume
(Decimal
):K线的报价资产交易量。count
(int
): The number of trades for the bar.count
(int
):K线的交易次数。taker_buy_base_volume
(Decimal
): The liquidity taker volume on the buy side for the base asset.taker_buy_base_volume
(Decimal
):买方基准资产的流动性接受者交易量。taker_buy_quote_volume
(Decimal
): The liquidity taker volume on the buy side for the quote asset.taker_buy_quote_volume
(Decimal
):买方报价资产的流动性接受者交易量。ts_event
(uint64_t
): UNIX timestamp (nanoseconds) when the data event occurred.ts_event
(uint64_t
):数据事件发生时的 UNIX 时间戳(纳秒)。ts_init
(uint64_t
): UNIX timestamp (nanoseconds) when the data object was initialized.ts_init
(uint64_t
):数据对象初始化时的 UNIX 时间戳(纳秒)。
@staticmethod
def from_dict(values: dict[str, Any]) -> BinanceBar:
"""
Return a Binance bar parsed from the given values.
Parameters
----------
values : dict[*str, Any]
The values for initialization.
# 初始化的值。
Returns
-------
BinanceBar
"""
...
@staticmethod
def to_dict(obj: BinanceBar) -> dict[str, Any]:
"""
Return a dictionary representation of this object.
Returns
-------
dict[str, Any]
"""
...
@property
def bar_type(self) -> BarType:
"""
BarType
Return the bar type of bar.
# 返回K线的K线类型。
Returns
-------
BarType
"""
...
@property
def close(self) -> Price:
"""
Price
Return the close price of the bar.
# 返回K线的收盘价。
Returns
-------
Price
"""
...
@staticmethod
def from_pyo3(pyo3_bar) -> Bar:
"""
Return a legacy Cython bar converted from the given pyo3 Rust object.
Parameters
----------
pyo3_bar : nautilus_pyo3.Bar
The pyo3 Rust bar to convert from.
# 要转换的 pyo3 Rust K线。
Returns
-------
Bar
"""
...
@staticmethod
def from_pyo3_list(pyo3_bars: list) -> list[Bar]:
"""
Return legacy Cython bars converted from the given pyo3 Rust objects.
Parameters
----------
pyo3_bars : list[*nautilus_pyo3.Bar]
The pyo3 Rust bars to convert from.
# 要转换的 pyo3 Rust K线。
Returns
-------
list[Bar]
"""
...
@staticmethod
def from_raw(bar_type: BarType, open: int, high: int, low: int, close: int, price_prec: int, volume: int, size_prec: int, ts_event: int, ts_init: int) -> Bar:
...
@staticmethod
def from_raw_arrays_to_list(bar_type: BarType, price_prec: int, size_prec: int, opens: list, highs: list, lows: list, closes: list, volumes: list, ts_events: list, ts_inits: list) -> list[Bar]:
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the Data class.
Returns
-------
str
"""
...
@property
def high(self) -> Price:
"""
Price
Return the high price of the bar.
# 返回K线的最高价。
Returns
-------
Price
"""
...
@property
def is_revision(self) -> bool:
"""
If this bar is a revision for a previous bar with the same ts_event.
# 如果此K线是对具有相同 ts_event 的先前K线的修订。
Returns
-------
bool
"""
...
@classmethod
def is_signal(cls, name: str = "") -> bool:
"""
Determine if the current class is a signal type, optionally checking for a specific signal name.
Parameters
----------
name : str, optional
The specific signal name to check. If name not provided or if an empty string is passed,
the method checks whether the class name indicates a general signal type. If name is
provided, the method checks if the class name corresponds to that specific signal.
# 要检查的特定信号名称。如果未提供名称或传递空字符串,则该方法检查类名是否指示
# 一般信号类型。如果提供了名称,则该方法检查类名是否对应于该特定信号。
Returns
-------
bool
True if the class name matches the signal type or the specific signal name, otherwise False.
# 如果类名与信号类型或特定信号名称匹配,则为 True,否则为 False。
"""
...
def is_single_price(self) -> bool:
"""
If the OHLC are all equal to a single price.
# 如果 OHLC 都等于一个价格。
Returns
-------
bool
"""
...
@property
def low(self) -> Price:
"""
Price
Return the low price of the bar.
# 返回K线的最低价。
Returns
-------
Price
"""
...
@property
def open(self) -> Price:
"""
Price
Return the open price of the bar.
# 返回K线的开盘价。
Returns
-------
Price
"""
...
def to_pyo3(self) -> Bar:
"""
Return a pyo3 object from this legacy Cython instance.
Returns
-------
nautilus_pyo3.Bar
"""
...
@staticmethod
def to_pyo3_list(bars: list) -> list:
"""
Return pyo3 Rust bars converted from the given legacy Cython objects.
Parameters
----------
bars : list[Bar]
The legacy Cython bars to convert from.
# 要转换的旧 Cython K线。
Returns
-------
list[nautilus_pyo3.Bar]
"""
...
@property
def ts_event(self) -> int:
"""
int
UNIX timestamp (nanoseconds) when the data event occurred.
# 数据事件发生时的 UNIX 时间戳(纳秒)。
Returns
-------
int
"""
...
@property
def ts_init(self) -> int:
"""
int
UNIX timestamp (nanoseconds) when the object was initialized.
# 数据对象初始化时的 UNIX 时间戳(纳秒)。
Returns
-------
int
"""
...
@property
def volume(self) -> Quantity:
"""
Quantity
Return the volume of the bar.
# 返回K线的交易量。
Returns
-------
Quantity
"""
...
class BinanceTicker 币安行情
class BinanceTicker(Data)
Represents a Binance 24hr statistics ticker.
表示币安 24 小时统计行情。
This data type includes the raw data provided by Binance.
此数据类型包括币安提供的原始数据。
Parameters:
instrument_id
(InstrumentId
): The instrument ID.instrument_id
(InstrumentId
):Instrument ID。price_change
(Decimal
): The price change.price_change
(Decimal
):价格变化。price_change_percent
(Decimal
): The price change percent.price_change_percent
(Decimal
):价格变化百分比。weighted_avg_price
(Decimal
): The weighted average price.weighted_avg_price
(Decimal
):加权平均价格。prev_close_price
(Decimal
, optional): The previous close price.prev_close_price
(Decimal
,可选):先前的收盘价。last_price
(Decimal
): The last price.last_price
(Decimal
):最新价。last_qty
(Decimal
): The last quantity.last_qty
(Decimal
):最新数量。bid_price
(Decimal
, optional): The bid price.bid_price
(Decimal
,可选):买入价。bid_qty
(Decimal
, optional): The bid quantity.bid_qty
(Decimal
,可选):买入数量。ask_price
(Decimal
, optional): The ask price.ask_price
(Decimal
,可选):卖出价。ask_qty
(Decimal
, optional): The ask quantity.ask_qty
(Decimal
,可选):卖出数量。open_price
(Decimal
): The open price.open_price
(Decimal
):开盘价。high_price
(Decimal
): The high price.high_price
(Decimal
):最高价。low_price
(Decimal
): The low price.low_price
(Decimal
):最低价。volume
(Decimal
): The volume.volume
(Decimal
):交易量。quote_volume
(Decimal
): The quote volume.quote_volume
(Decimal
):报价交易量。open_time_ms
(int
): UNIX timestamp (milliseconds) when the ticker opened.open_time_ms
(int
):行情开始时的 UNIX 时间戳(毫秒)。close_time_ms
(int
): UNIX timestamp (milliseconds) when the ticker closed.close_time_ms
(int
):行情结束时的 UNIX 时间戳(毫秒)。first_id
(int
): The first trade match ID (assigned by the venue) for the ticker.first_id
(int
):行情的第一个交易匹配 ID(由交易平台分配)。last_id
(int
): The last trade match ID (assigned by the venue) for the ticker.last_id
(int
):行情的最后一个交易匹配 ID(由交易平台分配)。count
(int
): The count of trades over the tickers time range.count
(int
):行情时间范围内的交易次数。ts_event
(uint64_t
): UNIX timestamp (nanoseconds) when the ticker event occurred.ts_event
(uint64_t
):行情事件发生时的 UNIX 时间戳(纳秒)。ts_init
(uint64_t
): UNIX timestamp (nanoseconds) when the object was initialized.ts_init
(uint64_t
):对象初始化时的 UNIX 时间戳(纳秒)。
@property
def ts_event(self) -> int:
"""
UNIX timestamp (nanoseconds) when the data event occurred.
# 数据事件发生时的 UNIX 时间戳(纳秒)。
Returns
-------
int
"""
...
@property
def ts_init(self) -> int:
"""
UNIX timestamp (nanoseconds) when the object was initialized.
# 数据对象初始化时的 UNIX 时间戳(纳秒)。
Returns
-------
int
"""
...
@staticmethod
def from_dict(values: dict[str, Any]) -> BinanceTicker:
"""
Return a Binance Spot/Margin ticker parsed from the given values.
Parameters
----------
values : dict[*str, Any]
The values for initialization.
# 初始化的值。
Returns
-------
BinanceTicker
"""
...
@staticmethod
def to_dict(obj: BinanceTicker) -> dict[str, Any]:
"""
Return a dictionary representation of this object.
Returns
-------
dict[str, Any]
"""
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the Data class.
Returns
-------
str
"""
...
@classmethod
def is_signal(cls, name: str = "") -> bool:
"""
Determine if the current class is a signal type, optionally checking for a specific signal name.
Parameters
----------
name : str, optional
The specific signal name to check. If name not provided or if an empty string is passed,
the method checks whether the class name indicates a general signal type. If name is
provided, the method checks if the class name corresponds to that specific signal.
# 要检查的特定信号名称。如果未提供名称或传递空字符串,则该方法检查类名是否指示
# 一般信号类型。如果提供了名称,则该方法检查类名是否对应于该特定信号。
Returns
-------
bool
True if the class name matches the signal type or the specific signal name, otherwise False.
# 如果类名与信号类型或特定信号名称匹配,则为 True,否则为 False。
"""
...
Futures 期货
Data 数据
class BinanceFuturesDataClient 币安期货数据客户端
class BinanceFuturesDataClient(BinanceCommonDataClient)
Provides a data client for the Binance Futures exchange.
为币安期货交易所提供数据客户端。
Parameters:
loop
(asyncio.AbstractEventLoop
): The event loop for the client.loop
(asyncio.AbstractEventLoop
):客户端的事件循环。client
(BinanceHttpClient
): The Binance HTTP client.client
(BinanceHttpClient
):币安 HTTP 客户端。msgbus
(MessageBus
): The message bus for the client.msgbus
(MessageBus
):客户端的消息总线。cache
(Cache
): The cache for the client.cache
(Cache
):客户端的缓存。clock
(LiveClock
): The clock for the client.clock
(LiveClock
):客户端的时钟。instrument_provider
(InstrumentProvider
): The instrument provider.instrument_provider
(InstrumentProvider
):Instrument适配器。base_url_ws
(str
): The base URL for the WebSocket client.base_url_ws
(str
):WebSocket 客户端的基本 URL。config
(BinanceDataClientConfig
): The configuration for the client.config
(BinanceDataClientConfig
):客户端的配置。account_type
(BinanceAccountType
, default'USDT_FUTURE'
): The account type for the client.account_type
(BinanceAccountType
,默认值'USDT_FUTURE'
):客户端的账户类型。name
(str
, optional): The custom client ID.name
(str
,可选):自定义客户端 ID。
def connect(self) -> None:
"""
Connect the client.
# 连接客户端。
"""
...
def create_task(self, coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = LogColor.NORMAL) -> Task:
"""
Run the given coroutine with error handling and optional callback actions when done.
Parameters
----------
coro : Coroutine
The coroutine to run.
# 要运行的协程。
log_msg : str, optional
The log message for the task.
# 任务的日志消息。
actions : Callable, optional
The actions callback to run when the coroutine is done.
# 协程完成后要运行的操作回调。
success_msg : str, optional
The log message to write on actions success.
# 操作成功时要写入的日志消息。
success_color : LogColor, default NORMAL
The log message color for actions success.
# 操作成功的日志消息颜色。
Returns
-------
asyncio.Task
"""
...
def degrade(self) -> void:
"""
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def disconnect(self) -> None:
"""
Disconnect the client.
# 断开客户端连接。
"""
...
def dispose(self) -> void:
"""
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def fault(self) -> void:
"""
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called,
it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the components class.
Returns
-------
str
"""
...
@property
def id(self) -> ComponentId:
"""
The components ID.
Returns
-------
ComponentId
"""
...
@property
def is_connected(self) -> bool:
"""
If the client is connected.
Returns
-------
bool
"""
...
@property
def is_degraded(self) -> bool:
"""
bool
Return whether the current component state is DEGRADED.
# 返回当前组件状态是否为 DEGRADED。
Returns
-------
bool
"""
...
@property
def is_disposed(self) -> bool:
"""
bool
Return whether the current component state is DISPOSED.
# 返回当前组件状态是否为 DISPOSED。
Returns
-------
bool
"""
...
@property
def is_faulted(self) -> bool:
"""
bool
Return whether the current component state is FAULTED.
# 返回当前组件状态是否为 FAULTED。
Returns
-------
bool
"""
...
@property
def is_initialized(self) -> bool:
"""
bool
Return whether the component has been initialized (component.state >= INITIALIZED).
# 返回组件是否已初始化 (component.state >= INITIALIZED)。
Returns
-------
bool
"""
...
@property
def is_running(self) -> bool:
"""
bool
Return whether the current component state is RUNNING.
# 返回当前组件状态是否为 RUNNING。
Returns
-------
bool
"""
...
@property
def is_stopped(self) -> bool:
"""
bool
Return whether the current component state is STOPPED.
# 返回当前组件状态是否为 STOPPED。
Returns
-------
bool
"""
...
def request(self, data_type: DataType, correlation_id: UUID4) -> void:
"""
Request data for the given data type.
Parameters
----------
data_type : DataType
The data type for the subscription.
# 订阅的数据类型。
correlation_id : UUID4
The correlation ID for the response.
# 响应的相关性 ID。
"""
...
def request_bars(self, bar_type: BarType, limit: int, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request historical Bar data.
Parameters
----------
bar_type : BarType
The bar type for the request.
# 请求的K线类型。
limit : int
The limit for the number of returned bars.
# 返回的K线数量限制。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_instrument(self, instrument_id: InstrumentId, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request Instrument data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The instrument ID for the request.
# 请求的Instrument ID。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_instruments(self, venue: Venue, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request all Instrument data for the given venue.
Parameters
----------
venue : Venue
The venue for the request.
# 请求的交易平台。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_order_book_snapshot(self, instrument_id: InstrumentId, limit: int, correlation_id: UUID4) -> void:
"""
Request order book snapshot data.
Parameters
----------
instrument_id : InstrumentId
The instrument ID for the order book snapshot request.
# 订单簿快照请求的Instrument ID。
limit : int
The limit on the depth of the order book snapshot.
# 订单簿快照的深度限制。
correction_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
"""
...
def request_quote_ticks(self, instrument_id: InstrumentId, limit: int, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request historical QuoteTick data.
Parameters
----------
instrument_id : InstrumentId
The tick instrument ID for the request.
# 请求的报价Instrument ID。
limit : int
The limit for the number of returned ticks.
# 返回的报价数量限制。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_trade_ticks(self, instrument_id: InstrumentId, limit: int, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request historical TradeTick data.
Parameters
----------
instrument_id : InstrumentId
The tick instrument ID for the request.
# 请求的交易Instrument ID。
limit : int
The limit for the number of returned ticks.
# 返回的交易数量限制。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def reset(self) -> void:
"""
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def resume(self) -> void:
"""
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
async def run_after_delay(delay: float, coro: Coroutine) -> None:
"""
Run the given coroutine after a delay.
Parameters
----------
delay : float
The delay (seconds) before running the coroutine.
# 运行协程之前的延迟(以秒为单位)。
coro : Coroutine
The coroutine to run after the initial delay.
# 初始延迟后要运行的协程。
"""
...
def start(self) -> void:
"""
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@property
def state(self) -> ComponentState:
"""
ComponentState
Return the components current state.
# 返回组件的当前状态。
Returns
-------
ComponentState
"""
...
def stop(self) -> void:
"""
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def subscribe(self, data_type: DataType) -> void:
"""
Subscribe to data for the given data type.
Parameters
----------
data_type : DataType
The data type for the subscription.
# 订阅的数据类型。
"""
...
def subscribe_bars(self, bar_type: BarType) -> void:
"""
Subscribe to Bar data for the given bar type.
Parameters
----------
bar_type : BarType
The bar type to subscribe to.
# 要订阅的K线类型。
"""
...
def subscribe_instrument(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to the Instrument with the given instrument ID.
# 订阅具有给定Instrument ID 的Instrument。
"""
...
def subscribe_instrument_close(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to InstrumentClose updates for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的报价Instrument。
"""
...
def subscribe_instrument_status(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to InstrumentStatus data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的报价Instrument。
"""
...
def subscribe_instruments(self) -> void:
"""
Subscribe to all Instrument data.
# 订阅所有Instrument数据。
"""
...
def subscribe_order_book_deltas(self, instrument_id: InstrumentId, book_type: BookType, depth: int = 0, kwargs: dict = None) -> void:
"""
Subscribe to OrderBookDeltas data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to subscribe to.
# 要订阅的订单簿Instrument。
book_type : BookType {L1_MBP, L2_MBP, L3_MBO}
The order book type.
# 订单簿类型。
depth : int, optional, default None
The maximum depth for the subscription.
# 订阅的最大深度。
kwargs : dict, optional
The keyword arguments for exchange specific parameters.
# 交易所特定参数的关键字参数。
"""
...
def subscribe_order_book_snapshots(self, instrument_id: InstrumentId, book_type: BookType, depth: int = 0, kwargs: dict = None) -> void:
"""
Subscribe to OrderBook snapshots data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to subscribe to.
# 要订阅的订单簿Instrument。
book_type : BookType {L1_MBP, L2_MBP, L3_MBO}
The order book level.
# 订单簿级别。
depth : int, optional
The maximum depth for the order book. A depth of 0 is maximum depth.
# 订单簿的最大深度。深度为 0 表示最大深度。
kwargs : dict, optional
The keyword arguments for exchange specific parameters.
# 交易所特定参数的关键字参数。
"""
...
def subscribe_quote_ticks(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to QuoteTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的报价Instrument。
"""
...
def subscribe_trade_ticks(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to TradeTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的交易Instrument。
"""
...
def subscribed_bars(self) -> list:
"""
Return the bar types subscribed to.
Returns
-------
list[BarType]
"""
...
def subscribed_custom_data(self) -> list:
"""
Return the custom data types subscribed to.
Returns
-------
list[DataType]
"""
...
def subscribed_instrument_close(self) -> list:
"""
Return the instrument closes subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_instrument_status(self) -> list:
"""
Return the status update instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_instruments(self) -> list:
"""
Return the instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_order_book_deltas(self) -> list:
"""
Return the order book delta instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_order_book_snapshots(self) -> list:
"""
Return the order book snapshot instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_quote_ticks(self) -> list:
"""
Return the quote tick instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_trade_ticks(self) -> list:
"""
Return the trade tick instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
@property
def trader_id(self) -> TraderId:
"""
The trader ID associated with the component.
Returns
-------
TraderId
"""
...
@property
def type(self) -> type:
"""
The components type.
Returns
-------
type
"""
...
def unsubscribe(self, data_type: DataType) -> void:
"""
Unsubscribe from data for the given data type.
Parameters
----------
data_type : DataType
The data type for the subscription.
# 订阅的数据类型。
"""
...
def unsubscribe_bars(self, bar_type: BarType) -> void:
"""
Unsubscribe from Bar data for the given bar type.
Parameters
----------
bar_type : BarType
The bar type to unsubscribe from.
# 要取消订阅的K线类型。
"""
...
def unsubscribe_instrument(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from Instrument data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The instrument to unsubscribe from.
# 要取消订阅的Instrument。
"""
...
def unsubscribe_instrument_close(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from InstrumentClose data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to unsubscribe from.
# 要取消订阅的报价Instrument。
"""
...
def unsubscribe_instrument_status(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from InstrumentStatus data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The instrument status updates to unsubscribe from.
# 要取消订阅的Instrument状态更新。
"""
...
def unsubscribe_instruments(self) -> void:
"""
Unsubscribe from all Instrument data.
# 取消订阅所有Instrument数据。
"""
...
def unsubscribe_order_book_deltas(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from OrderBookDeltas data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to unsubscribe from.
# 要取消订阅的订单簿Instrument。
"""
...
def unsubscribe_order_book_snapshots(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from OrderBook snapshots data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to unsubscribe from.
# 要取消订阅的订单簿Instrument。
"""
...
def unsubscribe_quote_ticks(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from QuoteTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to unsubscribe from.
# 要取消订阅的报价Instrument。
"""
...
def unsubscribe_trade_ticks(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from TradeTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to unsubscribe from.
# 要取消订阅的交易Instrument。
"""
...
@property
def venue(self) -> Venue | None:
"""
The clients venue ID (if applicable).
Returns
-------
Venue or None
"""
...
Enums 枚举
Defines Binance Futures specific enums.
定义币安期货特定的枚举。
class BinanceFuturesContractType(Enum):
"""
Represents a Binance Futures derivatives contract type.
# 表示币安期货衍生品合约类型。
"""
PERPETUAL = "PERPETUAL"
CURRENT_MONTH = "CURRENT_MONTH"
NEXT_MONTH = "NEXT_MONTH"
CURRENT_QUARTER = "CURRENT_QUARTER"
NEXT_QUARTER = "NEXT_QUARTER"
PERPETUAL_DELIVERING = "PERPETUAL_DELIVERING"
CURRENT_QUARTER_DELIVERING = "CURRENT_QUARTER DELIVERING"
class BinanceFuturesContractStatus(Enum):
"""
Represents a Binance Futures contract status.
# 表示币安期货合约状态。
"""
PENDING_TRADING = "PENDING_TRADING"
TRADING = "TRADING"
PRE_DELIVERING = "PRE_DELIVERING"
DELIVERING = "DELIVERING"
DELIVERED = "DELIVERED"
PRE_SETTLE = "PRE_SETTLE"
SETTLING = "SETTLING"
CLOSE = "CLOSE"
class BinanceFuturesWorkingType(Enum):
"""
Represents a Binance Futures working type.
# 表示币安期货工作类型。
"""
MARK_PRICE = "MARK_PRICE"
CONTRACT_PRICE = "CONTRACT_PRICE"
class BinanceFuturesMarginType(Enum):
"""
Represents a Binance Futures margin type.
# 表示币安期货保证金类型。
"""
ISOLATED = "isolated"
CROSS = "cross"
class BinanceFuturesPositionUpdateReason(Enum):
"""
Represents a Binance Futures position and balance update reason.
# 表示币安期货头寸和余额更新原因。
"""
DEPOSIT = "DEPOSIT"
WITHDRAW = "WITHDRAW"
ORDER = "ORDER"
FUNDING_FEE = "FUNDING_FEE"
WITHDRAW_REJECT = "WITHDRAW_REJECT"
ADJUSTMENT = "ADJUSTMENT"
INSURANCE_CLEAR = "INSURANCE_CLEAR"
ADMIN_DEPOSIT = "ADMIN_DEPOSIT"
ADMIN_WITHDRAW = "ADMIN_WITHDRAW"
MARGIN_TRANSFER = "MARGIN_TRANSFER"
MARGIN_TYPE_CHANGE = "MARGIN_TYPE_CHANGE"
ASSET_TRANSFER = "ASSET_TRANSFER"
OPTIONS_PREMIUM_FEE = "OPTIONS_PREMIUM_FEE"
OPTIONS_SETTLE_PROFIT = "OPTIONS_SETTLE_PROFIT"
AUTO_EXCHANGE = "AUTO_EXCHANGE"
COIN_SWAP_DEPOSIT = "COIN_SWAP_DEPOSIT"
COIN_SWAP_WITHDRAW = "COIN_SWAP_WITHDRAW"
class BinanceFuturesEventType(Enum):
"""
Represents a Binance Futures event type.
# 表示币安期货事件类型。
"""
LISTEN_KEY_EXPIRED = "listenKeyExpired"
MARGIN_CALL = "MARGIN_CALL"
ACCOUNT_UPDATE = "ACCOUNT_UPDATE"
ORDER_TRADE_UPDATE = "ORDER_TRADE_UPDATE"
ACCOUNT_CONFIG_UPDATE = "ACCOUNT_CONFIG_UPDATE"
TRADE_LITE = "TRADE_LITE"
class BinanceFuturesEnumParser(BinanceEnumParser):
"""
Provides parsing methods for enums used by the ‘Binance Futures’ exchange.
# 为“币安期货”交易所使用的枚举提供解析方法。
"""
def parse_binance_order_type(self, order_type: BinanceOrderType) -> OrderType:
...
def parse_internal_order_type(self, order: Order) -> BinanceOrderType:
...
def parse_binance_trigger_type(self, trigger_type: str) -> TriggerType:
...
def parse_futures_position_side(self, net_size: Decimal) -> PositionSide:
...
def parse_binance_bar_agg(self, bar_agg: str) -> BarAggregation:
...
def parse_binance_kline_interval_to_bar_spec(
self, kline_interval: BinanceKlineInterval
) -> BarSpecification:
...
def parse_binance_order_side(self, order_side: BinanceOrderSide) -> OrderSide:
...
def parse_binance_order_status(self, order_status: BinanceOrderStatus) -> OrderStatus:
...
def parse_binance_time_in_force(self, time_in_force: BinanceTimeInForce) -> TimeInForce:
...
def parse_internal_order_side(self, order_side: OrderSide) -> BinanceOrderSide:
...
def parse_internal_time_in_force(self, time_in_force: TimeInForce) -> BinanceTimeInForce:
...
def parse_nautilus_bar_aggregation(self, bar_agg: BarAggregation) -> str:
...
def parse_position_id_to_binance_futures_position_side(
self, position_id: PositionId
) -> BinanceFuturesPositionSide:
...
Execution 执行
class BinanceFuturesExecutionClient 币安期货执行客户端
class BinanceFuturesExecutionClient(BinanceCommonExecutionClient)
Provides an execution client for the Binance Futures exchange.
为币安期货交易所提供执行客户端。
Parameters:
loop
(asyncio.AbstractEventLoop
): The event loop for the client.loop
(asyncio.AbstractEventLoop
):客户端的事件循环。client
(BinanceHttpClient
): The Binance HTTP client.client
(BinanceHttpClient
):币安 HTTP 客户端。msgbus
(MessageBus
): The message bus for the client.msgbus
(MessageBus
):客户端的消息总线。cache
(Cache
): The cache for the client.cache
(Cache
):客户端的缓存。clock
(LiveClock
): The clock for the client.clock
(LiveClock
):客户端的时钟。instrument_provider
(BinanceFuturesInstrumentProvider
): The instrument provider.instrument_provider
(BinanceFuturesInstrumentProvider
):Instrument适配器。base_url_ws
(str
): The base URL for the WebSocket client.base_url_ws
(str
):WebSocket 客户端的基本 URL。config
(BinanceExecClientConfig
): The configuration for the client.config
(BinanceExecClientConfig
):客户端的配置。account_type
(BinanceAccountType
, default'USDT_FUTURE'
): The account type for the client.account_type
(BinanceAccountType
,默认值'USDT_FUTURE'
):客户端的账户类型。name
(str
, optional): The custom client ID.name
(str
,可选):自定义客户端 ID。
@property
def account_id(self) -> AccountId | None:
"""
The clients account ID.
Returns
-------
AccountId or None
"""
...
@property
def account_type(self) -> AccountType:
"""
The clients account type.
Returns
-------
AccountType
"""
...
@property
def base_currency(self) -> Currency | None:
"""
The clients account base currency (None for multi-currency accounts).
Returns
-------
Currency or None
"""
...
def batch_cancel_orders(self, command: BatchCancelOrders) -> void:
"""
Batch cancel orders for the instrument ID contained in the given command.
Parameters
----------
command : BatchCancelOrders
The command to execute.
# 要执行的命令。
"""
...
def cancel_all_orders(self, command: CancelAllOrders) -> void:
"""
Cancel all orders for the instrument ID contained in the given command.
Parameters
----------
command : CancelAllOrders
The command to execute.
# 要执行的命令。
"""
...
def cancel_order(self, command: CancelOrder) -> void:
"""
Cancel the order with the client order ID contained in the given command.
Parameters
----------
command : CancelOrder
The command to execute.
# 要执行的命令。
"""
...
def connect(self) -> None:
"""
Connect the client.
# 连接客户端。
"""
...
def create_task(self, coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = LogColor.NORMAL) -> Task:
"""
Run the given coroutine with error handling and optional callback actions when done.
Parameters
----------
coro : Coroutine
The coroutine to run.
# 要运行的协程。
log_msg : str, optional
The log message for the task.
# 任务的日志消息。
actions : Callable, optional
The actions callback to run when the coroutine is done.
# 协程完成后要运行的操作回调。
success_msg : str, optional
The log message to write on actions success.
# 操作成功时要写入的日志消息。
success_color : str, default NORMAL
The log message color for actions success.
# 操作成功的日志消息颜色。
Returns
-------
asyncio.Task
"""
...
def degrade(self) -> void:
"""
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def disconnect(self) -> None:
"""
Disconnect the client.
# 断开客户端连接。
"""
...
def dispose(self) -> void:
"""
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def fault(self) -> void:
"""
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called,
it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the components class.
Returns
-------
str
"""
...
def generate_account_state(self, balances: list, margins: list, reported: bool, ts_event: int, info: dict = None) -> void:
"""
Generate an AccountState event and publish on the message bus.
Parameters
----------
balances : list[AccountBalance]
The account balances.
# 账户余额。
margins : list[MarginBalance]
The margin balances.
# 保证金余额。
reported : bool
If the balances are reported directly from the exchange.
# 如果余额是直接从交易所报告的。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the account state event occurred.
# 账户状态事件发生时的 UNIX 时间戳(纳秒)。
info : dict[*str, object]
The additional implementation specific account information.
# 附加的特定于实现的账户信息。
"""
...
async def generate_fill_reports(self, instrument_id: InstrumentId | None = None, venue_order_id: VenueOrderId | None = None, start: Timestamp | None = None, end: Timestamp | None = None) -> list[FillReport]:
"""
Generate a list of `FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
Parameters
----------
instrument_id : InstrumentId, optional
The instrument ID query filter.
# Instrument ID 查询过滤器。
venue_order_id : VenueOrderId, optional
The venue order ID (assigned by the venue) query filter.
# 交易平台订单 ID(由交易平台分配)查询过滤器。
start : pd.Timestamp, optional
The start datetime (UTC) query filter.
# 开始日期时间(UTC)查询过滤器。
end : pd.Timestamp, optional
The end datetime (UTC) query filter.
# 结束日期时间(UTC)查询过滤器。
Returns
-------
list[FillReport]
"""
...
async def generate_mass_status(self, lookback_mins: int | None = None) -> ExecutionMassStatus | None:
"""
Generate an ExecutionMassStatus report.
Parameters
----------
lookback_mins : int, optional
The maximum lookback for querying closed orders, trades and positions.
# 查询已平仓订单、交易和头寸的最大回溯时间。
Returns
-------
ExecutionMassStatus or None
"""
...
def generate_order_accepted(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderAccepted event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order accepted event occurred.
# 订单接受事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_cancel_rejected(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, reason: str, ts_event: int) -> void:
"""
Generate an OrderCancelRejected event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
reason : str
The order cancel rejected reason.
# 订单取消被拒绝的原因。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.
# 订单取消被拒绝事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_canceled(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderCanceled event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when order canceled event occurred.
# 订单取消事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_expired(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderExpired event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order expired event occurred.
# 订单过期事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_filled(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, venue_position_id: PositionId | None, trade_id: TradeId, order_side: OrderSide, order_type: OrderType, last_qty: Quantity, last_px: Price, quote_currency: Currency, commission: Money, liquidity_side: LiquiditySide, ts_event: int) -> void:
"""
Generate an OrderFilled event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
trade_id : TradeId
The trade ID.
# 交易 ID。
venue_position_id : PositionId, optional with no default so None must be passed explicitly
The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket
then pass that here, otherwise pass None and the execution engine OMS will handle position ID resolution.
# 与订单关联的交易平台头寸 ID。如果交易平台已分配头寸 ID/票证,则在此处传递,
# 否则传递 None,执行引擎 OMS 将处理头寸 ID 解析。
order_side : OrderSide {BUY, SELL}
The execution order side.
# 执行订单方向。
order_type : OrderType
The execution order type.
# 执行订单类型。
last_qty : Quantity
The fill quantity for this execution.
# 此执行的成交数量。
last_px : Price
The fill price for this execution (not average price).
# 此执行的成交价格(非平均价格)。
quote_currency : Currency
The currency of the price.
# 价格的货币。
commission : Money
The fill commission.
# 成交佣金。
liquidity_side : LiquiditySide {NO_LIQUIDITY_SIDE, MAKER, TAKER}
The execution liquidity side.
# 执行流动性方向。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order filled event occurred.
# 订单成交事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_modify_rejected(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, reason: str, ts_event: int) -> void:
"""
Generate an OrderModifyRejected event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
reason : str
The order update rejected reason.
# 订单更新被拒绝的原因。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order update rejection event occurred.
# 订单更新拒绝事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_rejected(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, reason: str, ts_event: int) -> void:
"""
Generate an OrderRejected event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
reason : datetime
The order rejected reason.
# 订单被拒绝的原因。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order rejected event occurred.
# 订单拒绝事件发生时的 UNIX 时间戳(纳秒)。
"""
...
async def generate_order_status_report(self, instrument_id: InstrumentId, client_order_id: ClientOrderId | None = None, venue_order_id: VenueOrderId | None = None) -> OrderStatusReport | None:
"""
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns None.
Parameters
----------
instrument_id : InstrumentId
The instrument ID for the report.
# 报告的Instrument ID。
client_order_id : ClientOrderId, optional
The client order ID for the report.
# 报告的客户端订单 ID。
venue_order_id : VenueOrderId, optional
The venue order ID for the report.
# 报告的交易平台订单 ID。
Returns
-------
OrderStatusReport or None
Raises
------
ValueError
If both the client_order_id and venue_order_id are None.
"""
...
async def generate_order_status_reports(self, instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None, open_only: bool = False) -> list[OrderStatusReport]:
"""
Generate a list of `OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
Parameters
----------
instrument_id : InstrumentId, optional
The instrument ID query filter.
# Instrument ID 查询过滤器。
start : pd.Timestamp, optional
The start datetime (UTC) query filter.
# 开始日期时间(UTC)查询过滤器。
end : pd.Timestamp, optional
The end datetime (UTC) query filter.
# 结束日期时间(UTC)查询过滤器。
open_only : bool, default False
If the query is for open orders only.
# 如果查询仅针对未平仓订单。
Returns
-------
list[OrderStatusReport]
"""
...
def generate_order_submitted(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, ts_event: int) -> void:
"""
Generate an OrderSubmitted event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order submitted event occurred.
# 订单提交事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_triggered(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderTriggered event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order triggered event occurred.
# 订单触发事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_updated(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, quantity: Quantity, price: Price, trigger_price: Price, ts_event: int, venue_order_id_modified: bool = False) -> void:
"""
Generate an OrderUpdated event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
quantity : Quantity
The orders current quantity.
# 订单的当前数量。
price : Price
The orders current price.
# 订单的当前价格。
trigger_price : Price, optional with no default so None must be passed explicitly
The orders current trigger price.
# 订单的当前触发价格。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order update event occurred.
# 订单更新事件发生时的 UNIX 时间戳(纳秒)。
venue_order_id_modified : bool
If the ID was modified for this event.
# 如果此事件的 ID 已被修改。
"""
...
async def generate_position_status_reports(self, instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None) -> list[PositionStatusReport]:
"""
Generate a list of `PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
Parameters
----------
instrument_id : InstrumentId, optional
The instrument ID query filter.
# Instrument ID 查询过滤器。
start : pd.Timestamp, optional
The start datetime (UTC) query filter.
# 开始日期时间(UTC)查询过滤器。
end : pd.Timestamp, optional
The end datetime (UTC) query filter.
# 结束日期时间(UTC)查询过滤器。
Returns
-------
list[PositionStatusReport]
"""
...
def get_account(self) -> Account | None:
"""
Return the account for the client (if registered).
Returns
-------
Account or None
"""
...
@property
def id(self) -> ComponentId:
"""
The components ID.
Returns
-------
ComponentId
"""
...
@property
def is_connected(self) -> bool:
"""
If the client is connected.
Returns
-------
bool
"""
...
@property
def is_degraded(self) -> bool:
"""
bool
Return whether the current component state is DEGRADED.
# 返回当前组件状态是否为 DEGRADED。
Returns
-------
bool
"""
...
@property
def is_disposed(self) -> bool:
"""
bool
Return whether the current component state is DISPOSED.
# 返回当前组件状态是否为 DISPOSED。
Returns
-------
bool
"""
...
@property
def is_faulted(self) -> bool:
"""
bool
Return whether the current component state is FAULTED.
# 返回当前组件状态是否为 FAULTED。
Returns
-------
bool
"""
...
@property
def is_initialized(self) -> bool:
"""
bool
Return whether the component has been initialized (component.state >= INITIALIZED).
# 返回组件是否已初始化 (component.state >= INITIALIZED)。
Returns
-------
bool
"""
...
@property
def is_running(self) -> bool:
"""
bool
Return whether the current component state is RUNNING.
# 返回当前组件状态是否为 RUNNING。
Returns
-------
bool
"""
...
@property
def is_stopped(self) -> bool:
"""
bool
Return whether the current component state is STOPPED.
# 返回当前组件状态是否为 STOPPED。
Returns
-------
bool
"""
...
def modify_order(self, command: ModifyOrder) -> void:
"""
Modify the order with parameters contained in the command.
Parameters
----------
command : ModifyOrder
The command to execute.
# 要执行的命令。
"""
...
@property
def oms_type(self) -> OmsType:
"""
The venues order management system type.
Returns
-------
OmsType
"""
...
def query_order(self, command: QueryOrder) -> void:
"""
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
Parameters
----------
command : QueryOrder
The command to execute.
# 要执行的命令。
"""
...
def reset(self) -> void:
"""
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def resume(self) -> void:
"""
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
async def run_after_delay(delay: float, coro: Coroutine) -> None:
"""
Run the given coroutine after a delay.
Parameters
----------
delay : float
The delay (seconds) before running the coroutine.
# 运行协程之前的延迟(以秒为单位)。
coro : Coroutine
The coroutine to run after the initial delay.
# 初始延迟后要运行的协程。
"""
...
def start(self) -> void:
"""
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@property
def state(self) -> ComponentState:
"""
ComponentState
Return the components current state.
# 返回组件的当前状态。
Returns
-------
ComponentState
"""
...
def stop(self) -> void:
"""
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def submit_order(self, command: SubmitOrder) -> void:
"""
Submit the order contained in the given command for execution.
Parameters
----------
command : SubmitOrder
The command to execute.
# 要执行的命令。
"""
...
def submit_order_list(self, command: SubmitOrderList) -> void:
"""
Submit the order list contained in the given command for execution.
Parameters
----------
command : SubmitOrderList
The command to execute.
# 要执行的命令。
"""
...
@property
def trader_id(self) -> TraderId:
"""
The trader ID associated with the component.
Returns
-------
TraderId
"""
...
@property
def treat_expired_as_canceled(self) -> bool:
"""
Whether the EXPIRED execution type is treated as a CANCEL.
# EXPIRED 执行类型是否被视为 CANCEL。
Returns
-------
bool
"""
...
@property
def type(self) -> type:
"""
The components type.
Returns
-------
type
"""
...
@property
def use_position_ids(self) -> bool:
"""
Whether a position_id will be assigned to order events generated by the client.
# 是否将为客户端生成的订单事件分配 position_id。
Returns
-------
bool
"""
...
@property
def venue(self) -> Venue | None:
"""
The clients venue ID (if not a routing client).
Returns
-------
Venue or None
"""
...
Providers 提供程序
class BinanceFuturesInstrumentProvider 币安期货Instrument适配器
class BinanceFuturesInstrumentProvider(InstrumentProvider)
Provides a means of loading instruments from the Binance Futures exchange.
提供从币安期货交易所加载Instrument的方法。
Parameters:
client
(APIClient
): The client for the provider.client
(APIClient
):提供程序的客户端。config
(InstrumentProviderConfig
, optional): The configuration for the provider.config
(InstrumentProviderConfig
,可选):提供程序的配置。
async def load_all_async(self, filters: dict | None = None) -> None:
"""
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
# 异步加载最新的Instrument到提供程序中,可选地应用给定的过滤器。
"""
...
async def load_ids_async(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
"""
Load the instruments for the given IDs into the provider, optionally applying the given filters.
Parameters
----------
instrument_ids : list[InstrumentId]
The instrument IDs to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
Raises
------
ValueError
If any instrument_id.venue is not equal to self.venue.
"""
...
async def load_async(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
"""
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
Parameters
----------
instrument_id : InstrumentId
The instrument ID to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
Raises
------
ValueError
If instrument_id.venue is not equal to self.venue.
"""
...
def add(self, instrument: Instrument) -> None:
"""
Add the given instrument to the provider.
Parameters
----------
instrument : Instrument
The instrument to add.
# 要添加的Instrument。
"""
...
def add_bulk(self, instruments: list[Instrument]) -> None:
"""
Add the given instruments bulk to the provider.
Parameters
----------
instruments : list[Instrument]
The instruments to add.
# 要添加的Instrument。
"""
...
def add_currency(self, currency: Currency) -> None:
"""
Add the given currency to the provider.
Parameters
----------
currency : Currency
The currency to add.
# 要添加的货币。
"""
...
@property
def count(self) -> int:
"""
Return the count of instruments held by the provider.
Returns
-------
int
"""
...
def currencies(self) -> dict[str, Currency]:
"""
Return all currencies held by the instrument provider.
Returns
-------
dict[str, Currency]
"""
...
def currency(self, code: str) -> Currency | None:
"""
Return the currency with the given code (if found).
Parameters
----------
code : str
The currency code.
# 货币代码。
Returns
-------
Currency or None
Raises
------
ValueError
If code is not a valid string.
"""
...
def find(self, instrument_id: InstrumentId) -> Instrument | None:
"""
Return the instrument for the given instrument ID (if found).
Parameters
----------
instrument_id : InstrumentId
The ID for the instrument
# Instrument的 ID
Returns
-------
Instrument or None
"""
...
def get_all(self) -> dict[InstrumentId, Instrument]:
"""
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
Returns
-------
dict[InstrumentId, Instrument]
"""
...
async def initialize(self) -> None:
"""
Initialize the instrument provider.
If initialize() then will immediately return.
# 如果 initialize() 则将立即返回。
"""
...
def list_all(self) -> list[Instrument]:
"""
Return all loaded instruments.
Returns
-------
list[Instrument]
"""
...
def load(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
"""
Load the instrument for the given ID into the provider, optionally applying the given filters.
Parameters
----------
instrument_id : InstrumentId
The instrument ID to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
"""
...
def load_all(self, filters: dict | None = None) -> None:
"""
Load the latest instruments into the provider, optionally applying the given filters.
Parameters
----------
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
"""
...
def load_ids(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
"""
Load the instruments for the given IDs into the provider, optionally applying the given filters.
Parameters
----------
instrument_ids : list[InstrumentId]
The instrument IDs to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
"""
...
Types 类型
class BinanceFuturesMarkPriceUpdate 币安期货标记价格更新
class BinanceFuturesMarkPriceUpdate(Data)
Represents a Binance Futures mark price and funding rate update.
表示币安期货标记价格和资金费率更新。
Parameters:
instrument_id
(InstrumentId
): The instrument ID for the update.instrument_id
(InstrumentId
):更新的Instrument ID。mark
(Price
): The mark price for the instrument.mark
(Price
):Instrument的标记价格。index
(Price
): The index price for the instrument.index
(Price
):Instrument的指数价格。estimated_settle
(Price
): The estimated settle price for the instrument (only useful in the last hour before the settlement starts).estimated_settle
(Price
):Instrument的估计结算价格(仅在结算开始前最后一小时有用)。funding_rate
(Decimal
): The current funding rate for the instrument.funding_rate
(Decimal
):Instrument的当前资金费率。ts_next_funding
(uint64_t
): UNIX timestamp (nanoseconds) when next funding will occur.ts_next_funding
(uint64_t
):下一次资金发生时的 UNIX 时间戳(纳秒)。ts_event
(uint64_t
): UNIX timestamp (nanoseconds) when the data event occurred.ts_event
(uint64_t
):数据事件发生时的 UNIX 时间戳(纳秒)。ts_init
(uint64_t
): UNIX timestamp (nanoseconds) when the data object was initialized.ts_init
(uint64_t
):数据对象初始化时的 UNIX 时间戳(纳秒)。
@property
def ts_event(self) -> int:
"""
UNIX timestamp (nanoseconds) when the data event occurred.
# 数据事件发生时的 UNIX 时间戳(纳秒)。
Returns
-------
int
"""
...
@property
def ts_init(self) -> int:
"""
UNIX timestamp (nanoseconds) when the object was initialized.
# 数据对象初始化时的 UNIX 时间戳(纳秒)。
Returns
-------
int
"""
...
@staticmethod
def from_dict(values: dict[str, Any]) -> BinanceFuturesMarkPriceUpdate:
"""
Return a Binance Futures mark price update parsed from the given values.
Parameters
----------
values : dict[*str, Any]
The values for initialization.
# 初始化的值。
Returns
-------
BinanceFuturesMarkPriceUpdate
"""
...
@staticmethod
def to_dict(obj: BinanceFuturesMarkPriceUpdate) -> dict[str, Any]:
"""
Return a dictionary representation of this object.
Returns
-------
dict[str, Any]
"""
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the Data class.
Returns
-------
str
"""
...
@classmethod
def is_signal(cls, name: str = "") -> bool:
"""
Determine if the current class is a signal type, optionally checking for a specific signal name.
Parameters
----------
name : str, optional
The specific signal name to check. If name not provided or if an empty string is passed,
the method checks whether the class name indicates a general signal type. If name is
provided, the method checks if the class name corresponds to that specific signal.
# 要检查的特定信号名称。如果未提供名称或传递空字符串,则该方法检查类名是否指示
# 一般信号类型。如果提供了名称,则该方法检查类名是否对应于该特定信号。
Returns
-------
bool
True if the class name matches the signal type or the specific signal name, otherwise False.
# 如果类名与信号类型或特定信号名称匹配,则为 True,否则为 False。
"""
...
Spot 现货
Data 数据
class BinanceSpotDataClient 币安现货数据客户端
class BinanceSpotDataClient(BinanceCommonDataClient)
Provides a data client for the Binance Spot/Margin exchange.
为币安现货/保证金交易所提供数据客户端。
Parameters:
loop
(asyncio.AbstractEventLoop
): The event loop for the client.loop
(asyncio.AbstractEventLoop
):客户端的事件循环。client
(BinanceHttpClient
): The binance HTTP client.client
(BinanceHttpClient
):币安 HTTP 客户端。msgbus
(MessageBus
): The message bus for the client.msgbus
(MessageBus
):客户端的消息总线。cache
(Cache
): The cache for the client.cache
(Cache
):客户端的缓存。clock
(LiveClock
): The clock for the client.clock
(LiveClock
):客户端的时钟。instrument_provider
(InstrumentProvider
): The instrument provider.instrument_provider
(InstrumentProvider
):Instrument适配器。base_url_ws
(str
): The base URL for the WebSocket client.base_url_ws
(str
):WebSocket 客户端的基本 URL。config
(BinanceDataClientConfig
): The configuration for the client.config
(BinanceDataClientConfig
):客户端的配置。account_type
(BinanceAccountType
, default'SPOT'
): The account type for the client.account_type
(BinanceAccountType
,默认值'SPOT'
):客户端的账户类型。name
(str
, optional): The custom client ID.name
(str
,可选):自定义客户端 ID。
def connect(self) -> None:
"""
Connect the client.
# 连接客户端。
"""
...
def create_task(self, coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = LogColor.NORMAL) -> Task:
"""
Run the given coroutine with error handling and optional callback actions when done.
Parameters
----------
coro : Coroutine
The coroutine to run.
# 要运行的协程。
log_msg : str, optional
The log message for the task.
# 任务的日志消息。
actions : Callable, optional
The actions callback to run when the coroutine is done.
# 协程完成后要运行的操作回调。
success_msg : str, optional
The log message to write on actions success.
# 操作成功时要写入的日志消息。
success_color : LogColor, default NORMAL
The log message color for actions success.
# 操作成功的日志消息颜色。
Returns
-------
asyncio.Task
"""
...
def degrade(self) -> void:
"""
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def disconnect(self) -> None:
"""
Disconnect the client.
# 断开客户端连接。
"""
...
def dispose(self) -> void:
"""
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def fault(self) -> void:
"""
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called,
it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the components class.
Returns
-------
str
"""
...
@property
def id(self) -> ComponentId:
"""
The components ID.
Returns
-------
ComponentId
"""
...
@property
def is_connected(self) -> bool:
"""
If the client is connected.
Returns
-------
bool
"""
...
@property
def is_degraded(self) -> bool:
"""
bool
Return whether the current component state is DEGRADED.
# 返回当前组件状态是否为 DEGRADED。
Returns
-------
bool
"""
...
@property
def is_disposed(self) -> bool:
"""
bool
Return whether the current component state is DISPOSED.
# 返回当前组件状态是否为 DISPOSED。
Returns
-------
bool
"""
...
@property
def is_faulted(self) -> bool:
"""
bool
Return whether the current component state is FAULTED.
# 返回当前组件状态是否为 FAULTED。
Returns
-------
bool
"""
...
@property
def is_initialized(self) -> bool:
"""
bool
Return whether the component has been initialized (component.state >= INITIALIZED).
# 返回组件是否已初始化 (component.state >= INITIALIZED)。
Returns
-------
bool
"""
...
@property
def is_running(self) -> bool:
"""
bool
Return whether the current component state is RUNNING.
# 返回当前组件状态是否为 RUNNING。
Returns
-------
bool
"""
...
@property
def is_stopped(self) -> bool:
"""
bool
Return whether the current component state is STOPPED.
# 返回当前组件状态是否为 STOPPED。
Returns
-------
bool
"""
...
def request(self, data_type: DataType, correlation_id: UUID4) -> void:
"""
Request data for the given data type.
Parameters
----------
data_type : DataType
The data type for the subscription.
# 订阅的数据类型。
correlation_id : UUID4
The correlation ID for the response.
# 响应的相关性 ID。
"""
...
def request_bars(self, bar_type: BarType, limit: int, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request historical Bar data.
Parameters
----------
bar_type : BarType
The bar type for the request.
# 请求的K线类型。
limit : int
The limit for the number of returned bars.
# 返回的K线数量限制。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_instrument(self, instrument_id: InstrumentId, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request Instrument data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The instrument ID for the request.
# 请求的Instrument ID。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_instruments(self, venue: Venue, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request all Instrument data for the given venue.
Parameters
----------
venue : Venue
The venue for the request.
# 请求的交易平台。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_order_book_snapshot(self, instrument_id: InstrumentId, limit: int, correlation_id: UUID4) -> void:
"""
Request order book snapshot data.
Parameters
----------
instrument_id : InstrumentId
The instrument ID for the order book snapshot request.
# 订单簿快照请求的Instrument ID。
limit : int
The limit on the depth of the order book snapshot.
# 订单簿快照的深度限制。
correction_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
"""
...
def request_quote_ticks(self, instrument_id: InstrumentId, limit: int, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request historical QuoteTick data.
Parameters
----------
instrument_id : InstrumentId
The tick instrument ID for the request.
# 请求的报价Instrument ID。
limit : int
The limit for the number of returned ticks.
# 返回的报价数量限制。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def request_trade_ticks(self, instrument_id: InstrumentId, limit: int, correlation_id: UUID4, start: datetime = None, end: datetime = None) -> void:
"""
Request historical TradeTick data.
Parameters
----------
instrument_id : InstrumentId
The tick instrument ID for the request.
# 请求的交易Instrument ID。
limit : int
The limit for the number of returned ticks.
# 返回的交易数量限制。
correlation_id : UUID4
The correlation ID for the request.
# 请求的相关性 ID。
start : datetime, optional
The start datetime (UTC) of request time range (inclusive).
# 请求时间范围的开始日期时间(UTC)(包括)。
end : datetime, optional
The end datetime (UTC) of request time range. The inclusiveness depends on
individual data client implementation.
# 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
"""
...
def reset(self) -> void:
"""
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def resume(self) -> void:
"""
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
async def run_after_delay(delay: float, coro: Coroutine) -> None:
"""
Run the given coroutine after a delay.
Parameters
----------
delay : float
The delay (seconds) before running the coroutine.
# 运行协程之前的延迟(以秒为单位)。
coro : Coroutine
The coroutine to run after the initial delay.
# 初始延迟后要运行的协程。
"""
...
def start(self) -> void:
"""
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@property
def state(self) -> ComponentState:
"""
ComponentState
Return the components current state.
# 返回组件的当前状态。
Returns
-------
ComponentState
"""
...
def stop(self) -> void:
"""
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def subscribe(self, data_type: DataType) -> void:
"""
Subscribe to data for the given data type.
Parameters
----------
data_type : DataType
The data type for the subscription.
# 订阅的数据类型。
"""
...
def subscribe_bars(self, bar_type: BarType) -> void:
"""
Subscribe to Bar data for the given bar type.
Parameters
----------
bar_type : BarType
The bar type to subscribe to.
# 要订阅的K线类型。
"""
...
def subscribe_instrument(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to the Instrument with the given instrument ID.
# 订阅具有给定Instrument ID 的Instrument。
"""
...
def subscribe_instrument_close(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to InstrumentClose updates for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的报价Instrument。
"""
...
def subscribe_instrument_status(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to InstrumentStatus data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的报价Instrument。
"""
...
def subscribe_instruments(self) -> void:
"""
Subscribe to all Instrument data.
# 订阅所有Instrument数据。
"""
...
def subscribe_order_book_deltas(self, instrument_id: InstrumentId, book_type: BookType, depth: int = 0, kwargs: dict = None) -> void:
"""
Subscribe to OrderBookDeltas data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to subscribe to.
# 要订阅的订单簿Instrument。
book_type : BookType {L1_MBP, L2_MBP, L3_MBO}
The order book type.
# 订单簿类型。
depth : int, optional, default None
The maximum depth for the subscription.
# 订阅的最大深度。
kwargs : dict, optional
The keyword arguments for exchange specific parameters.
# 交易所特定参数的关键字参数。
"""
...
def subscribe_order_book_snapshots(self, instrument_id: InstrumentId, book_type: BookType, depth: int = 0, kwargs: dict = None) -> void:
"""
Subscribe to OrderBook snapshots data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to subscribe to.
# 要订阅的订单簿Instrument。
book_type : BookType {L1_MBP, L2_MBP, L3_MBO}
The order book level.
# 订单簿级别。
depth : int, optional
The maximum depth for the order book. A depth of 0 is maximum depth.
# 订单簿的最大深度。深度为 0 表示最大深度。
kwargs : dict, optional
The keyword arguments for exchange specific parameters.
# 交易所特定参数的关键字参数。
"""
...
def subscribe_quote_ticks(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to QuoteTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的报价Instrument。
"""
...
def subscribe_trade_ticks(self, instrument_id: InstrumentId) -> void:
"""
Subscribe to TradeTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to subscribe to.
# 要订阅的交易Instrument。
"""
...
def subscribed_bars(self) -> list:
"""
Return the bar types subscribed to.
Returns
-------
list[BarType]
"""
...
def subscribed_custom_data(self) -> list:
"""
Return the custom data types subscribed to.
Returns
-------
list[DataType]
"""
...
def subscribed_instrument_close(self) -> list:
"""
Return the instrument closes subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_instrument_status(self) -> list:
"""
Return the status update instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_instruments(self) -> list:
"""
Return the instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_order_book_deltas(self) -> list:
"""
Return the order book delta instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_order_book_snapshots(self) -> list:
"""
Return the order book snapshot instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_quote_ticks(self) -> list:
"""
Return the quote tick instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
def subscribed_trade_ticks(self) -> list:
"""
Return the trade tick instruments subscribed to.
Returns
-------
list[InstrumentId]
"""
...
@property
def trader_id(self) -> TraderId:
"""
The trader ID associated with the component.
Returns
-------
TraderId
"""
...
@property
def type(self) -> type:
"""
The components type.
Returns
-------
type
"""
...
def unsubscribe(self, data_type: DataType) -> void:
"""
Unsubscribe from data for the given data type.
Parameters
----------
data_type : DataType
The data type for the subscription.
# 订阅的数据类型。
"""
...
def unsubscribe_bars(self, bar_type: BarType) -> void:
"""
Unsubscribe from Bar data for the given bar type.
Parameters
----------
bar_type : BarType
The bar type to unsubscribe from.
# 要取消订阅的K线类型。
"""
...
def unsubscribe_instrument(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from Instrument data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The instrument to unsubscribe from.
# 要取消订阅的Instrument。
"""
...
def unsubscribe_instrument_close(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from InstrumentClose data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to unsubscribe from.
# 要取消订阅的报价Instrument。
"""
...
def unsubscribe_instrument_status(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from InstrumentStatus data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The instrument status updates to unsubscribe from.
# 要取消订阅的Instrument状态更新。
"""
...
def unsubscribe_instruments(self) -> void:
"""
Unsubscribe from all Instrument data.
# 取消订阅所有Instrument数据。
"""
...
def unsubscribe_order_book_deltas(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from OrderBookDeltas data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to unsubscribe from.
# 要取消订阅的订单簿Instrument。
"""
...
def unsubscribe_order_book_snapshots(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from OrderBook snapshots data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The order book instrument to unsubscribe from.
# 要取消订阅的订单簿Instrument。
"""
...
def unsubscribe_quote_ticks(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from QuoteTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to unsubscribe from.
# 要取消订阅的报价Instrument。
"""
...
def unsubscribe_trade_ticks(self, instrument_id: InstrumentId) -> void:
"""
Unsubscribe from TradeTick data for the given instrument ID.
Parameters
----------
instrument_id : InstrumentId
The tick instrument to unsubscribe from.
# 要取消订阅的交易Instrument。
"""
...
@property
def venue(self) -> Venue | None:
"""
The clients venue ID (if applicable).
Returns
-------
Venue or None
"""
...
Enums 枚举
Defines Binance Spot/Margin specific enums.
定义币安现货/保证金特定的枚举。
class BinanceSpotPermissions(Enum):
"""
Represents Binance Spot/Margin trading permissions.
# 表示币安现货/保证金交易权限。
"""
SPOT = "SPOT"
MARGIN = "MARGIN"
LEVERAGED = "LEVERAGED"
TRD_GRP_002 = "TRD_GRP_002"
TRD_GRP_003 = "TRD_GRP_003"
TRD_GRP_004 = "TRD_GRP_004"
TRD_GRP_005 = "TRD_GRP_005"
TRD_GRP_006 = "TRD_GRP_006"
TRD_GRP_007 = "TRD_GRP_007"
TRD_GRP_008 = "TRD_GRP_008"
TRD_GRP_009 = "TRD_GRP_009"
TRD_GRP_010 = "TRD_GRP_010"
TRD_GRP_011 = "TRD_GRP_011"
TRD_GRP_012 = "TRD_GRP_012"
TRD_GRP_013 = "TRD_GRP_013"
TRD_GRP_014 = "TRD_GRP_014"
TRD_GRP_015 = "TRD_GRP_015"
TRD_GRP_016 = "TRD_GRP_016"
TRD_GRP_017 = "TRD_GRP_017"
TRD_GRP_018 = "TRD_GRP_018"
TRD_GRP_019 = "TRD_GRP_019"
TRD_GRP_020 = "TRD_GRP_020"
TRD_GRP_021 = "TRD_GRP_021"
TRD_GRP_022 = "TRD_GRP_022"
TRD_GRP_023 = "TRD_GRP_023"
TRD_GRP_024 = "TRD_GRP_024"
TRD_GRP_025 = "TRD_GRP_025"
TRD_GRP_026 = "TRD_GRP_026"
TRD_GRP_027 = "TRD_GRP_027"
TRD_GRP_028 = "TRD_GRP_028"
TRD_GRP_029 = "TRD_GRP_029"
TRD_GRP_030 = "TRD_GRP_030"
TRD_GRP_031 = "TRD_GRP_031"
TRD_GRP_032 = "TRD_GRP_032"
class BinanceSpotSymbolStatus(Enum):
"""
Represents a Binance Spot/Margin symbol status.
# 表示币安现货/保证金符号状态。
"""
PRE_TRADING = "PRE_TRADING"
TRADING = "TRADING"
POST_TRADING = "POST_TRADING"
END_OF_DAY = "END_OF_DAY"
HALT = "HALT"
AUCTION_MATCH = "AUCTION_MATCH"
BREAK = "BREAK"
class BinanceSpotEventType(Enum):
"""
Represents a Binance Spot/Margin event type.
# 表示币安现货/保证金事件类型。
"""
outboundAccountPosition = "outboundAccountPosition"
balanceUpdate = "balanceUpdate"
executionReport = "executionReport"
listStatus = "listStatus"
class BinanceSpotEnumParser(BinanceEnumParser):
"""
Provides parsing methods for enums used by the ‘Binance Spot/Margin’ exchange.
# 为“币安现货/保证金”交易所使用的枚举提供解析方法。
"""
def parse_binance_order_type(self, order_type: BinanceOrderType) -> OrderType:
...
def parse_internal_order_type(self, order: Order) -> BinanceOrderType:
...
def parse_binance_bar_agg(self, bar_agg: str) -> BarAggregation:
...
def parse_binance_kline_interval_to_bar_spec(
self, kline_interval: BinanceKlineInterval
) -> BarSpecification:
...
def parse_binance_order_side(self, order_side: BinanceOrderSide) -> OrderSide:
...
def parse_binance_order_status(self, order_status: BinanceOrderStatus) -> OrderStatus:
...
def parse_binance_time_in_force(self, time_in_force: BinanceTimeInForce) -> TimeInForce:
...
def parse_binance_trigger_type(self, trigger_type: str) -> TriggerType:
...
def parse_internal_order_side(self, order_side: OrderSide) -> BinanceOrderSide:
...
def parse_internal_time_in_force(self, time_in_force: TimeInForce) -> BinanceTimeInForce:
...
def parse_nautilus_bar_aggregation(self, bar_agg: BarAggregation) -> str:
...
def parse_position_id_to_binance_futures_position_side(
self, position_id: PositionId
) -> BinanceFuturesPositionSide:
...
Execution 执行
class BinanceSpotExecutionClient 币安现货执行客户端
class BinanceSpotExecutionClient(BinanceCommonExecutionClient)
Provides an execution client for the Binance Spot/Margin exchange.
为币安现货/保证金交易所提供执行客户端。
Parameters:
loop
(asyncio.AbstractEventLoop
): The event loop for the client.loop
(asyncio.AbstractEventLoop
):客户端的事件循环。client
(BinanceHttpClient
): The binance HTTP client.client
(BinanceHttpClient
):币安 HTTP 客户端。msgbus
(MessageBus
): The message bus for the client.msgbus
(MessageBus
):客户端的消息总线。cache
(Cache
): The cache for the client.cache
(Cache
):客户端的缓存。clock
(LiveClock
): The clock for the client.clock
(LiveClock
):客户端的时钟。instrument_provider
(BinanceSpotInstrumentProvider
): The instrument provider.instrument_provider
(BinanceSpotInstrumentProvider
):Instrument适配器。base_url_ws
(str
): The base URL for the WebSocket client.base_url_ws
(str
):WebSocket 客户端的基本 URL。config
(BinanceExecClientConfig
): The configuration for the client.config
(BinanceExecClientConfig
):客户端的配置。account_type
(BinanceAccountType
, default'SPOT'
): The account type for the client.account_type
(BinanceAccountType
,默认值'SPOT'
):客户端的账户类型。name
(str
, optional): The custom client ID.name
(str
,可选):自定义客户端 ID。
@property
def account_id(self) -> AccountId | None:
"""
The clients account ID.
Returns
-------
AccountId or None
"""
...
@property
def account_type(self) -> AccountType:
"""
The clients account type.
Returns
-------
AccountType
"""
...
@property
def base_currency(self) -> Currency | None:
"""
The clients account base currency (None for multi-currency accounts).
Returns
-------
Currency or None
"""
...
def batch_cancel_orders(self, command: BatchCancelOrders) -> void:
"""
Batch cancel orders for the instrument ID contained in the given command.
Parameters
----------
command : BatchCancelOrders
The command to execute.
# 要执行的命令。
"""
...
def cancel_all_orders(self, command: CancelAllOrders) -> void:
"""
Cancel all orders for the instrument ID contained in the given command.
Parameters
----------
command : CancelAllOrders
The command to execute.
# 要执行的命令。
"""
...
def cancel_order(self, command: CancelOrder) -> void:
"""
Cancel the order with the client order ID contained in the given command.
Parameters
----------
command : CancelOrder
The command to execute.
# 要执行的命令。
"""
...
def connect(self) -> None:
"""
Connect the client.
# 连接客户端。
"""
...
def create_task(self, coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = LogColor.NORMAL) -> Task:
"""
Run the given coroutine with error handling and optional callback actions when done.
Parameters
----------
coro : Coroutine
The coroutine to run.
# 要运行的协程。
log_msg : str, optional
The log message for the task.
# 任务的日志消息。
actions : Callable, optional
The actions callback to run when the coroutine is done.
# 协程完成后要运行的操作回调。
success_msg : str, optional
The log message to write on actions success.
# 操作成功时要写入的日志消息。
success_color : str, default NORMAL
The log message color for actions success.
# 操作成功的日志消息颜色。
Returns
-------
asyncio.Task
"""
...
def degrade(self) -> void:
"""
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def disconnect(self) -> None:
"""
Disconnect the client.
# 断开客户端连接。
"""
...
def dispose(self) -> void:
"""
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def fault(self) -> void:
"""
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called,
it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a FAULTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@classmethod
def fully_qualified_name(cls) -> str:
"""
Return the fully qualified name for the components class.
Returns
-------
str
"""
...
def generate_account_state(self, balances: list, margins: list, reported: bool, ts_event: int, info: dict = None) -> void:
"""
Generate an AccountState event and publish on the message bus.
Parameters
----------
balances : list[AccountBalance]
The account balances.
# 账户余额。
margins : list[MarginBalance]
The margin balances.
# 保证金余额。
reported : bool
If the balances are reported directly from the exchange.
# 如果余额是直接从交易所报告的。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the account state event occurred.
# 账户状态事件发生时的 UNIX 时间戳(纳秒)。
info : dict[*str, object]
The additional implementation specific account information.
# 附加的特定于实现的账户信息。
"""
...
async def generate_fill_reports(self, instrument_id: InstrumentId | None = None, venue_order_id: VenueOrderId | None = None, start: Timestamp | None = None, end: Timestamp | None = None) -> list[FillReport]:
"""
Generate a list of `FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
Parameters
----------
instrument_id : InstrumentId, optional
The instrument ID query filter.
# Instrument ID 查询过滤器。
venue_order_id : VenueOrderId, optional
The venue order ID (assigned by the venue) query filter.
# 交易平台订单 ID(由交易平台分配)查询过滤器。
start : pd.Timestamp, optional
The start datetime (UTC) query filter.
# 开始日期时间(UTC)查询过滤器。
end : pd.Timestamp, optional
The end datetime (UTC) query filter.
# 结束日期时间(UTC)查询过滤器。
Returns
-------
list[FillReport]
"""
...
async def generate_mass_status(self, lookback_mins: int | None = None) -> ExecutionMassStatus | None:
"""
Generate an ExecutionMassStatus report.
Parameters
----------
lookback_mins : int, optional
The maximum lookback for querying closed orders, trades and positions.
# 查询已平仓订单、交易和头寸的最大回溯时间。
Returns
-------
ExecutionMassStatus or None
"""
...
def generate_order_accepted(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderAccepted event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order accepted event occurred.
# 订单接受事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_cancel_rejected(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, reason: str, ts_event: int) -> void:
"""
Generate an OrderCancelRejected event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
reason : str
The order cancel rejected reason.
# 订单取消被拒绝的原因。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.
# 订单取消被拒绝事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_canceled(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderCanceled event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when order canceled event occurred.
# 订单取消事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_expired(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderExpired event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order expired event occurred.
# 订单过期事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_filled(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, venue_position_id: PositionId | None, trade_id: TradeId, order_side: OrderSide, order_type: OrderType, last_qty: Quantity, last_px: Price, quote_currency: Currency, commission: Money, liquidity_side: LiquiditySide, ts_event: int) -> void:
"""
Generate an OrderFilled event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
trade_id : TradeId
The trade ID.
# 交易 ID。
venue_position_id : PositionId, optional with no default so None must be passed explicitly
The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket
then pass that here, otherwise pass None and the execution engine OMS will handle position ID resolution.
# 与订单关联的交易平台头寸 ID。如果交易平台已分配头寸 ID/票证,则在此处传递,
# 否则传递 None,执行引擎 OMS 将处理头寸 ID 解析。
order_side : OrderSide {BUY, SELL}
The execution order side.
# 执行订单方向。
order_type : OrderType
The execution order type.
# 执行订单类型。
last_qty : Quantity
The fill quantity for this execution.
# 此执行的成交数量。
last_px : Price
The fill price for this execution (not average price).
# 此执行的成交价格(非平均价格)。
quote_currency : Currency
The currency of the price.
# 价格的货币。
commission : Money
The fill commission.
# 成交佣金。
liquidity_side : LiquiditySide {NO_LIQUIDITY_SIDE, MAKER, TAKER}
The execution liquidity side.
# 执行流动性方向。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order filled event occurred.
# 订单成交事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_modify_rejected(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, reason: str, ts_event: int) -> void:
"""
Generate an OrderModifyRejected event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
reason : str
The order update rejected reason.
# 订单更新被拒绝的原因。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order update rejection event occurred.
# 订单更新拒绝事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_rejected(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, reason: str, ts_event: int) -> void:
"""
Generate an OrderRejected event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
reason : datetime
The order rejected reason.
# 订单被拒绝的原因。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order rejected event occurred.
# 订单拒绝事件发生时的 UNIX 时间戳(纳秒)。
"""
...
async def generate_order_status_report(self, instrument_id: InstrumentId, client_order_id: ClientOrderId | None = None, venue_order_id: VenueOrderId | None = None) -> OrderStatusReport | None:
"""
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns None.
Parameters
----------
instrument_id : InstrumentId
The instrument ID for the report.
# 报告的Instrument ID。
client_order_id : ClientOrderId, optional
The client order ID for the report.
# 报告的客户端订单 ID。
venue_order_id : VenueOrderId, optional
The venue order ID for the report.
# 报告的交易平台订单 ID。
Returns
-------
OrderStatusReport or None
Raises
------
ValueError
If both the client_order_id and venue_order_id are None.
"""
...
async def generate_order_status_reports(self, instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None, open_only: bool = False) -> list[OrderStatusReport]:
"""
Generate a list of `OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
Parameters
----------
instrument_id : InstrumentId, optional
The instrument ID query filter.
# Instrument ID 查询过滤器。
start : pd.Timestamp, optional
The start datetime (UTC) query filter.
# 开始日期时间(UTC)查询过滤器。
end : pd.Timestamp, optional
The end datetime (UTC) query filter.
# 结束日期时间(UTC)查询过滤器。
open_only : bool, default False
If the query is for open orders only.
# 如果查询仅针对未平仓订单。
Returns
-------
list[OrderStatusReport]
"""
...
def generate_order_submitted(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, ts_event: int) -> void:
"""
Generate an OrderSubmitted event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order submitted event occurred.
# 订单提交事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_triggered(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, ts_event: int) -> void:
"""
Generate an OrderTriggered event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order triggered event occurred.
# 订单触发事件发生时的 UNIX 时间戳(纳秒)。
"""
...
def generate_order_updated(self, strategy_id: StrategyId, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: VenueOrderId, quantity: Quantity, price: Price, trigger_price: Price, ts_event: int, venue_order_id_modified: bool = False) -> void:
"""
Generate an OrderUpdated event and send it to the ExecutionEngine.
Parameters
----------
strategy_id : StrategyId
The strategy ID associated with the event.
# 与事件关联的策略 ID。
instrument_id : InstrumentId
The instrument ID.
# Instrument ID。
client_order_id : ClientOrderId
The client order ID.
# 客户端订单 ID。
venue_order_id : VenueOrderId
The venue order ID (assigned by the venue).
# 交易平台订单 ID(由交易平台分配)。
quantity : Quantity
The orders current quantity.
# 订单的当前数量。
price : Price
The orders current price.
# 订单的当前价格。
trigger_price : Price, optional with no default so None must be passed explicitly
The orders current trigger price.
# 订单的当前触发价格。
ts_event : uint64_t
UNIX timestamp (nanoseconds) when the order update event occurred.
# 订单更新事件发生时的 UNIX 时间戳(纳秒)。
venue_order_id_modified : bool
If the ID was modified for this event.
# 如果此事件的 ID 已被修改。
"""
...
async def generate_position_status_reports(self, instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None) -> list[PositionStatusReport]:
"""
Generate a list of `PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
Parameters
----------
instrument_id : InstrumentId, optional
The instrument ID query filter.
# Instrument ID 查询过滤器。
start : pd.Timestamp, optional
The start datetime (UTC) query filter.
# 开始日期时间(UTC)查询过滤器。
end : pd.Timestamp, optional
The end datetime (UTC) query filter.
# 结束日期时间(UTC)查询过滤器。
Returns
-------
list[PositionStatusReport]
"""
...
def get_account(self) -> Account | None:
"""
Return the account for the client (if registered).
Returns
-------
Account or None
"""
...
@property
def id(self) -> ComponentId:
"""
The components ID.
Returns
-------
ComponentId
"""
...
@property
def is_connected(self) -> bool:
"""
If the client is connected.
Returns
-------
bool
"""
...
@property
def is_degraded(self) -> bool:
"""
bool
Return whether the current component state is DEGRADED.
# 返回当前组件状态是否为 DEGRADED。
Returns
-------
bool
"""
...
@property
def is_disposed(self) -> bool:
"""
bool
Return whether the current component state is DISPOSED.
# 返回当前组件状态是否为 DISPOSED。
Returns
-------
bool
"""
...
@property
def is_faulted(self) -> bool:
"""
bool
Return whether the current component state is FAULTED.
# 返回当前组件状态是否为 FAULTED。
Returns
-------
bool
"""
...
@property
def is_initialized(self) -> bool:
"""
bool
Return whether the component has been initialized (component.state >= INITIALIZED).
# 返回组件是否已初始化 (component.state >= INITIALIZED)。
Returns
-------
bool
"""
...
@property
def is_running(self) -> bool:
"""
bool
Return whether the current component state is RUNNING.
# 返回当前组件状态是否为 RUNNING。
Returns
-------
bool
"""
...
@property
def is_stopped(self) -> bool:
"""
bool
Return whether the current component state is STOPPED.
# 返回当前组件状态是否为 STOPPED。
Returns
-------
bool
"""
...
def modify_order(self, command: ModifyOrder) -> void:
"""
Modify the order with parameters contained in the command.
Parameters
----------
command : ModifyOrder
The command to execute.
# 要执行的命令。
"""
...
@property
def oms_type(self) -> OmsType:
"""
The venues order management system type.
Returns
-------
OmsType
"""
...
def query_order(self, command: QueryOrder) -> void:
"""
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
Parameters
----------
command : QueryOrder
The command to execute.
# 要执行的命令。
"""
...
def reset(self) -> void:
"""
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a RESETTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def resume(self) -> void:
"""
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
async def run_after_delay(delay: float, coro: Coroutine) -> None:
"""
Run the given coroutine after a delay.
Parameters
----------
delay : float
The delay (seconds) before running the coroutine.
# 运行协程之前的延迟(以秒为单位)。
coro : Coroutine
The coroutine to run after the initial delay.
# 初始延迟后要运行的协程。
"""
...
def start(self) -> void:
"""
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
@property
def state(self) -> ComponentState:
"""
ComponentState
Return the components current state.
# 返回组件的当前状态。
Returns
-------
ComponentState
"""
...
def stop(self) -> void:
"""
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state.
Warnings
--------
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change,
and an error will be logged.
"""
...
def submit_order(self, command: SubmitOrder) -> void:
"""
Submit the order contained in the given command for execution.
Parameters
----------
command : SubmitOrder
The command to execute.
# 要执行的命令。
"""
...
def submit_order_list(self, command: SubmitOrderList) -> void:
"""
Submit the order list contained in the given command for execution.
Parameters
----------
command : SubmitOrderList
The command to execute.
# 要执行的命令。
"""
...
@property
def trader_id(self) -> TraderId:
"""
The trader ID associated with the component.
Returns
-------
TraderId
"""
...
@property
def treat_expired_as_canceled(self) -> bool:
"""
Whether the EXPIRED execution type is treated as a CANCEL.
# EXPIRED 执行类型是否被视为 CANCEL。
Returns
-------
bool
"""
...
@property
def type(self) -> type:
"""
The components type.
Returns
-------
type
"""
...
@property
def use_position_ids(self) -> bool:
"""
Whether a position_id will be assigned to order events generated by the client.
# 是否将为客户端生成的订单事件分配 position_id。
Returns
-------
bool
"""
...
@property
def venue(self) -> Venue | None:
"""
The clients venue ID (if not a routing client).
Returns
-------
Venue or None
"""
...
Providers 提供程序
class BinanceSpotInstrumentProvider 币安现货Instrument适配器
class BinanceSpotInstrumentProvider(InstrumentProvider)
Provides a means of loading instruments from the Binance Spot/Margin exchange.
提供从币安现货/保证金交易所加载Instrument的方法。
Parameters:
client
(APIClient
): The client for the provider.client
(APIClient
):提供程序的客户端。clock
(LiveClock
): The clock for the provider.clock
(LiveClock
):提供程序的时钟。account_type
(BinanceAccountType
, defaultSPOT
): The Binance account type for the provider.account_type
(BinanceAccountType
,默认值SPOT
):提供程序的币安账户类型。is_testnet
(bool
, defaultFalse
): If the provider is for the Spot testnet.is_testnet
(bool
,默认值False
):如果提供程序用于现货测试网。config
(InstrumentProviderConfig
, optional): The configuration for the provider.config
(InstrumentProviderConfig
,可选):提供程序的配置。
async def load_all_async(self, filters: dict | None = None) -> None:
"""
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
# 异步加载最新的Instrument到提供程序中,可选地应用给定的过滤器。
"""
...
async def load_ids_async(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
"""
Load the instruments for the given IDs into the provider, optionally applying the given filters.
Parameters
----------
instrument_ids : list[InstrumentId]
The instrument IDs to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
Raises
------
ValueError
If any instrument_id.venue is not equal to self.venue.
"""
...
async def load_async(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
"""
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
Parameters
----------
instrument_id : InstrumentId
The instrument ID to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
Raises
------
ValueError
If instrument_id.venue is not equal to self.venue.
"""
...
def add(self, instrument: Instrument) -> None:
"""
Add the given instrument to the provider.
Parameters
----------
instrument : Instrument
The instrument to add.
# 要添加的Instrument。
"""
...
def add_bulk(self, instruments: list[Instrument]) -> None:
"""
Add the given instruments bulk to the provider.
Parameters
----------
instruments : list[Instrument]
The instruments to add.
# 要添加的Instrument。
"""
...
def add_currency(self, currency: Currency) -> None:
"""
Add the given currency to the provider.
Parameters
----------
currency : Currency
The currency to add.
# 要添加的货币。
"""
...
@property
def count(self) -> int:
"""
Return the count of instruments held by the provider.
Returns
-------
int
"""
...
def currencies(self) -> dict[str, Currency]:
"""
Return all currencies held by the instrument provider.
Returns
-------
dict[str, Currency]
"""
...
def currency(self, code: str) -> Currency | None:
"""
Return the currency with the given code (if found).
Parameters
----------
code : str
The currency code.
# 货币代码。
Returns
-------
Currency or None
Raises
------
ValueError
If code is not a valid string.
"""
...
def find(self, instrument_id: InstrumentId) -> Instrument | None:
"""
Return the instrument for the given instrument ID (if found).
Parameters
----------
instrument_id : InstrumentId
The ID for the instrument
# Instrument的 ID
Returns
-------
Instrument or None
"""
...
def get_all(self) -> dict[InstrumentId, Instrument]:
"""
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
Returns
-------
dict[InstrumentId, Instrument]
"""
...
async def initialize(self) -> None:
"""
Initialize the instrument provider.
If initialize() then will immediately return.
# 如果 initialize() 则将立即返回。
"""
...
def list_all(self) -> list[Instrument]:
"""
Return all loaded instruments.
Returns
-------
list[Instrument]
"""
...
def load(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
"""
Load the instrument for the given ID into the provider, optionally applying the given filters.
Parameters
----------
instrument_id : InstrumentId
The instrument ID to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
"""
...
def load_all(self, filters: dict | None = None) -> None:
"""
Load the latest instruments into the provider, optionally applying the given filters.
Parameters
----------
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
"""
...
def load_ids(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
"""
Load the instruments for the given IDs into the provider, optionally applying the given filters.
Parameters
----------
instrument_ids : list[InstrumentId]
The instrument IDs to load.
# 要加载的Instrument ID。
filters : frozendict[*str, Any] or dict[*str, Any], optional
The venue specific instrument loading filters to apply.
# 要应用的特定于交易平台的Instrument加载过滤器。
"""
...