Binance
Provides an API integration for the Binance Crypto exchange.
Config
class BinanceDataClientConfig
Bases: LiveDataClientConfig
Configuration for BinanceDataClient
instances.
- Parameters:
- venue (Venue , default BINANCE_VENUE) – The venue for the client.
- api_key (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - api_secret (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_SECRET or BINANCE_TESTNET_API_SECRET environment variables. - key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- account_type (BinanceAccountType , default BinanceAccountType.SPOT) – The account type for the client.
- base_url_http (str , optional) – The HTTP client custom endpoint override.
- base_url_ws (str , optional) – The WebSocket client custom endpoint override.
- us (bool , default False) – If client is connecting to Binance US.
- testnet (bool , default False) – If the client is connecting to a Binance testnet.
- update_instruments_interval_mins (PositiveInt or None , default 60) – The interval (minutes) between reloading instruments from the venue.
- use_agg_trade_ticks (bool , default False) – Whether to use aggregated trade tick endpoints instead of raw trades. TradeId of ticks will be the Aggregate tradeId returned by Binance.
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
update_instruments_interval_mins : Annotated[int, msgspec.Meta(gt=0)] | None
use_agg_trade_ticks : bool
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
handle_revised_bars : bool
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod 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.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class BinanceExecClientConfig
Bases: LiveExecClientConfig
Configuration for BinanceExecutionClient
instances.
- Parameters:
- venue (Venue , default BINANCE_VENUE) – The venue for the client.
- api_key (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - api_secret (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- account_type (BinanceAccountType , default BinanceAccountType.SPOT) – The account type for the client.
- base_url_http (str , optional) – The HTTP client custom endpoint override.
- base_url_ws (str , optional) – The WebSocket client custom endpoint override.
- us (bool , default False) – If client is connecting to Binance US.
- testnet (bool , default False) – If the client is connecting to a Binance testnet.
- use_gtd (bool , default True) – If GTD orders will use the Binance GTD TIF option. If False, then GTD time in force will be remapped to GTC (this is useful if managing GTD orders locally).
- use_reduce_only (bool , default True) – If the reduce_only execution instruction on orders is sent through to the exchange. If True, then will assign the value on orders sent to the exchange, otherwise will always be False.
- use_position_ids (bool , default True) – If Binance Futures hedging position IDs should be used. If False, then order event position_id`(s) from the execution client will be `None, which allows virtual positions with OmsType.HEDGING.
- treat_expired_as_canceled (bool , default False) – If the EXPIRED execution type is semantically treated as CANCELED. 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.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Binance HTTP requests.
- max_retries (PositiveInt , optional) – The maximum number of times a submit, cancel or modify order request will be retried.
- retry_delay (PositiveFloat , optional) – The delay (seconds) between retries. Short delays with frequent retries may result in account bans.
WARNING
A short retry_delay with frequent retries may result in account bans.
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
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod 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.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
Factories
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 parameters already exists, the 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.
- Return type: BinanceHttpClient
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.
- Return type: BinanceSpotInstrumentProvider
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.
- Return type: BinanceFuturesInstrumentProvider
class BinanceLiveDataClientFactory
Bases: LiveDataClientFactory
Provides a Binance live data client factory.
static 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.
- Return type: BinanceSpotDataClient or BinanceFuturesDataClient
- Raises: ValueError – If config.account_type is not a valid BinanceAccountType.
class BinanceLiveExecClientFactory
Bases: LiveExecClientFactory
Provides a Binance live execution client factory.
static 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.
- Return type: BinanceExecutionClient
- Raises: ValueError – If config.account_type is not a valid BinanceAccountType.
Enums
Defines Binance common enums.
class BinanceKeyType
Bases: Enum
Represents a Binance private key cryptographic algorithm type.
HMAC = 'HMAC'
RSA = 'RSA'
ED25519 = 'Ed25519'
class BinanceFuturesPositionSide
Bases: Enum
Represents a Binance Futures position side.
BOTH = 'BOTH'
LONG = 'LONG'
SHORT = 'SHORT'
class BinanceRateLimitType
Bases: Enum
Represents a Binance rate limit type.
REQUEST_WEIGHT = 'REQUEST_WEIGHT'
ORDERS = 'ORDERS'
RAW_REQUESTS = 'RAW_REQUESTS'
class BinanceRateLimitInterval
Bases: Enum
Represents a Binance rate limit interval.
SECOND = 'SECOND'
MINUTE = 'MINUTE'
DAY = 'DAY'
class BinanceKlineInterval
Bases: Enum
Represents a Binance kline chart interval.
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
Bases: 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
Bases: 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
Bases: Enum
Represents a Binance account type.
SPOT = 'SPOT'
MARGIN = 'MARGIN'
ISOLATED_MARGIN = 'ISOLATED_MARGIN'
USDT_FUTURE = 'USDT_FUTURE'
COIN_FUTURE = 'COIN_FUTURE'
property is_spot
property is_margin
property is_spot_or_margin
property is_futures : bool
class BinanceOrderSide
Bases: Enum
Represents a Binance order side.
BUY = 'BUY'
SELL = 'SELL'
class BinanceExecutionType
Bases: 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
Bases: 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
Bases: Enum
Represents a Binance order time in force.
GTC = 'GTC'
IOC = 'IOC'
FOK = 'FOK'
GTX = 'GTX'
GTD = 'GTD'
GTE_GTC = 'GTE_GTC'
class BinanceOrderType
Bases: 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
Bases: 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
Bases: Enum
Represents a Binance newOrderRespType.
ACK = 'ACK'
RESULT = 'RESULT'
FULL = 'FULL'
class BinanceErrorCode
Bases: 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
Bases: object
Provides common parsing methods for enums used by the ‘Binance’ exchange.
WARNING
This class should not be used directly, but through a concrete subclass.
parse_binance_order_side(order_side: BinanceOrderSide) → OrderSide
parse_internal_order_side(order_side: OrderSide) → BinanceOrderSide
parse_binance_time_in_force(time_in_force: BinanceTimeInForce) → TimeInForce
parse_internal_time_in_force(time_in_force: TimeInForce) → BinanceTimeInForce
parse_binance_order_status(order_status: BinanceOrderStatus) → OrderStatus
parse_binance_order_type(order_type: BinanceOrderType) → OrderType
parse_internal_order_type(order: Order) → BinanceOrderType
parse_binance_bar_agg(bar_agg: str) → BarAggregation
parse_nautilus_bar_aggregation(bar_agg: BarAggregation) → str
parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval) → BarSpecification
parse_binance_trigger_type(trigger_type: str) → TriggerType
parse_position_id_to_binance_futures_position_side(position_id: PositionId) → BinanceFuturesPositionSide
Types
class BinanceBar
Bases: Bar
Represents an aggregated Binance bar.
This data type includes the raw data provided by Binance.
- Parameters:
- bar_type (BarType) – The bar type for this bar.
- open (Price) – The bars open price.
- high (Price) – The bars high price.
- low (Price) – The bars low price.
- close (Price) – The bars close price.
- volume (Quantity) – The bars volume.
- quote_volume (Decimal) – The bars quote asset volume.
- count (int) – The number of trades for the bar.
- taker_buy_base_volume (Decimal) – The liquidity taker volume on the buy side for the base asset.
- taker_buy_quote_volume (Decimal) – The liquidity taker volume on the buy side for the quote asset.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the data event occurred.
- ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
static 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.
- Return type: BinanceBar
static to_dict(obj: BinanceBar) → dict[str, Any]
Return a dictionary representation of this object.
- Return type: dict[str, Any]
bar_type
BarType
Return the bar type of bar.
- Return type: BarType
- Type: Bar.bar_type
close
Price
Return the close price of the bar.
- Return type: Price
- Type: Bar.close
static 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.
- Return type: Bar
static from_pyo3_list(list pyo3_bars) → 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.
- Return type: list[Bar]
static from_raw(BarType bar_type, int64_t open, int64_t high, int64_t low, int64_t close, uint8_t price_prec, uint64_t volume, uint8_t size_prec, uint64_t ts_event, uint64_t ts_init) → Bar
static from_raw_arrays_to_list(BarType bar_type, uint8_t price_prec, uint8_t size_prec, int64_t[:] opens, int64_t[:] highs, int64_t[:] lows, int64_t[:] closes, uint64_t[:] volumes, uint64_t[:] ts_events, uint64_t[:] ts_inits) → list[Bar]
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the Data class.
- Return type: str
high
Price
Return the high price of the bar.
- Return type: Price
- Type: Bar.high
is_revision
If this bar is a revision for a previous bar with the same ts_event.
- Returns: bool
classmethod is_signal(cls, unicode name=u'') → 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: True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type: bool
is_single_price(self) → bool
If the OHLC are all equal to a single price.
- Return type: bool
low
Price
Return the low price of the bar.
- Return type: Price
- Type: Bar.low
open
Price
Return the open price of the bar.
- Return type: Price
- Type: Bar.open
to_pyo3(self) → nautilus_pyo3.Bar
Return a pyo3 object from this legacy Cython instance.
- Return type: nautilus_pyo3.Bar
static to_pyo3_list(list bars) → list[nautilus_pyo3.Bar]
Return pyo3 Rust bars converted from the given legacy Cython objects.
- Parameters: bars (list [Bar ]) – The legacy Cython bars to convert from.
- Return type: list[nautilus_pyo3.Bar]
ts_event
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type: int
- Type: Bar.ts_event
ts_init
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type: int
- Type: Bar.ts_init
volume
Quantity
Return the volume of the bar.
- Return type: Quantity
- Type: Bar.volume
class BinanceTicker
Bases: Data
Represents a Binance 24hr statistics ticker.
This data type includes the raw data provided by Binance.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID.
- price_change (Decimal) – The price change.
- price_change_percent (Decimal) – The price change percent.
- weighted_avg_price (Decimal) – The weighted average price.
- prev_close_price (Decimal , optional) – The previous close price.
- last_price (Decimal) – The last price.
- last_qty (Decimal) – The last quantity.
- bid_price (Decimal , optional) – The bid price.
- bid_qty (Decimal , optional) – The bid quantity.
- ask_price (Decimal , optional) – The ask price.
- ask_qty (Decimal , optional) – The ask quantity.
- open_price (Decimal) – The open price.
- high_price (Decimal) – The high price.
- low_price (Decimal) – The low price.
- volume (Decimal) – The volume.
- quote_volume (Decimal) – The quote volume.
- open_time_ms (int) – UNIX timestamp (milliseconds) when the ticker opened.
- close_time_ms (int) – UNIX timestamp (milliseconds) when the ticker closed.
- first_id (int) – The first trade match ID (assigned by the venue) for the ticker.
- last_id (int) – The last trade match ID (assigned by the venue) for the ticker.
- count (int) – The count of trades over the tickers time range.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the ticker event occurred.
- ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
property ts_event : int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type: int
property ts_init : int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type: int
static 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.
- Return type: BinanceTicker
static to_dict(obj: BinanceTicker) → dict[str, Any]
Return a dictionary representation of this object.
- Return type: dict[str, Any]
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the Data class.
- Return type: str
classmethod is_signal(cls, unicode name=u'') → 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: True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type: bool
Futures
Data
class BinanceFuturesDataClient
Bases: BinanceCommonDataClient
Provides a data client for the Binance Futures exchange.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- client (BinanceHttpClient) – The Binance HTTP client.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- instrument_provider (InstrumentProvider) – The instrument provider.
- base_url_ws (str) – The base URL for the WebSocket client.
- config (BinanceDataClientConfig) – The configuration for the client.
- account_type (BinanceAccountType , default 'USDT_FUTURE') – The account type for the client.
- name (str , optional) – The custom client ID.
connect() → None
Connect the client.
create_task(coro: ~collections.abc.Coroutine, log_msg: str | None = None, actions: ~collections.abc.Callable | None = None, success_msg: str | None = None, success_color: ~nautilus_trader.core.rust.common.LogColor = <LogColor.NORMAL: 0>) → 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.
- Return type: asyncio.Task
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.
WARNING
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.
disconnect() → None
Disconnect the client.
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.
WARNING
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.
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.
WARNING
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 fully_qualified_name(cls) → str
Return the fully qualified name for the components class.
- Return type: str
id
The components ID.
- Returns: ComponentId
is_connected
If the client is connected.
- Returns: bool
is_degraded
bool
Return whether the current component state is DEGRADED
.
- Return type: bool
- Type: Component.is_degraded