Skip to main content
Version: latest

Binance

Provides an API integration for the Binance Crypto exchange.

Config

class BinanceDataClientConfig

Bases: LiveDataClientConfig

Configuration for BinanceDataClient instances.

  • Parameters:
    • 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.
    • 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_agg_trade_ticks (bool , default False) – Whether to use aggregated trade tick endpoints instead of raw trade ticks. TradeId of ticks will be the Aggregate tradeId returned by Binance.
    • venue (Venue , default BINANCE_VENUE) – The venue for the client.

api_key : str | None

api_secret : str | None

account_type : BinanceAccountType

base_url_http : str | None

base_url_ws : str | None

us : bool

testnet : bool

use_agg_trade_ticks : bool

venue : Venue

dict()

Return a dictionary representation of the configuration.

  • Return type: dict[str, Any]

classmethod fully_qualified_name()

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()

Return serialized JSON encoded bytes.

  • Return type: bytes

json_primitives()

Return a dictionary representation of the configuration with JSON primitive types as values.

  • Return type: dict[str, Any]

classmethod parse(raw: bytes | str)

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()

Return whether the configuration can be represented as valid JSON.

  • Return type: bool

class BinanceExecClientConfig

Bases: LiveExecClientConfig

Configuration for BinanceExecutionClient instances.

  • Parameters:
    • 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.
    • 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.
    • max_retries (PositiveInt , optional) – The maximum number of times a submit or cancel order request will be retried.
    • retry_delay (PositiveFloat , optional) – The delay (seconds) between retries.
    • venue (Venue , default BINANCE_VENUE) – The venue for the client.

api_key : str | None

api_secret : str | None

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

max_retries : int | None

retry_delay : float | None

venue : Venue

dict()

Return a dictionary representation of the configuration.

  • Return type: dict[str, Any]

classmethod fully_qualified_name()

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()

Return serialized JSON encoded bytes.

  • Return type: bytes

json_primitives()

Return a dictionary representation of the configuration with JSON primitive types as values.

  • Return type: dict[str, Any]

classmethod parse(raw: bytes | str)

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()

Return whether the configuration can be represented as valid JSON.

  • Return type: bool

Factories

get_cached_binance_http_client(clock: LiveClock, account_type: BinanceAccountType, key: str | None = None, secret: str | None = None, base_url: str | None = None, is_testnet: bool = False, is_us: bool = False)

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.
    • key (str , optional) – The API key for the client.
    • secret (str , optional) – The API secret for the client.
    • 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)

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)

Cache and return an instrument provider for the Binance Futures exchange.

If a cached provider already exists, then that provider will be returned.

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)

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)

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 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)

parse_internal_order_side(order_side: OrderSide)

parse_binance_time_in_force(time_in_force: BinanceTimeInForce)

parse_internal_time_in_force(time_in_force: TimeInForce)

parse_binance_order_status(order_status: BinanceOrderStatus)

parse_binance_order_type(order_type: BinanceOrderType)

parse_internal_order_type(order: Order)

parse_binance_bar_agg(bar_agg: str)

parse_nautilus_bar_aggregation(bar_agg: BarAggregation)

parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval)

parse_binance_trigger_type(trigger_type: str)

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])

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)

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)

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)

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)

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)

classmethod fully_qualified_name(cls)

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

is_single_price(self)

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)

Return a pyo3 object from this legacy Cython instance.

  • Return type: nautilus_pyo3.Bar

static to_pyo3_list(list bars)

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])

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)

Return a dictionary representation of this object.

  • Return type: dict[str, Any]

classmethod fully_qualified_name(cls)

Return the fully qualified name for the Data class.

  • Return type: str

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()

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>)

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)

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()

Disconnect the client.

dispose(self)

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)

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)

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

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

request(self, DataType data_type, UUID4 correlation_id)

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.

request_bars(self, BarType bar_type, int limit, UUID4 correlation_id, datetime start=None, datetime end=None)

Request historical Bar data.

  • Parameters:
    • bar_type (BarType) – The bar type for the request.
    • limit (int) – The limit for the number of returned bars.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_instrument(self, InstrumentId instrument_id, UUID4 correlation_id, datetime start=None, datetime end=None)

Request Instrument data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the request.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_instruments(self, Venue venue, UUID4 correlation_id, datetime start=None, datetime end=None)

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.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_order_book_snapshot(self, InstrumentId instrument_id, int limit, UUID4 correlation_id)

Request order book snapshot data.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
    • limit (int) – The limit on the depth of the order book snapshot.
    • correction_id (UUID4) – The correlation ID for the request.

request_quote_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start=None, datetime end=None)

Request historical QuoteTick data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • limit (int) – The limit for the number of returned ticks.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_trade_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start=None, datetime end=None)

Request historical TradeTick data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • limit (int) – The limit for the number of returned ticks.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

reset(self)

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.

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.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING 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.

async run_after_delay(delay: float, coro: Coroutine)

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.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING 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.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING 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.

subscribe(self, DataType data_type)

Subscribe to data for the given data type.

  • Parameters: data_type (DataType) – The data type for the subscription.

subscribe_bars(self, BarType bar_type)

Subscribe to Bar data for the given bar type.

  • Parameters: bar_type (BarType) – The bar type to subscribe to.

subscribe_instrument(self, InstrumentId instrument_id)

Subscribe to the Instrument with the given instrument ID.

subscribe_instrument_close(self, InstrumentId instrument_id)

Subscribe to InstrumentClose updates for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_instrument_status(self, InstrumentId instrument_id)

Subscribe to InstrumentStatus data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_instruments(self)

Subscribe to all Instrument data.

subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)

Subscribe to OrderBookDeltas data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • 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.

subscribe_order_book_snapshots(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)

Subscribe to OrderBook snapshots data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • 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.
    • kwargs (dict , optional) – The keyword arguments for exchange specific parameters.

subscribe_quote_ticks(self, InstrumentId instrument_id)

Subscribe to QuoteTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_trade_ticks(self, InstrumentId instrument_id)

Subscribe to TradeTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_venue_status(self, Venue venue)

Subscribe to InstrumentStatus data for the venue.

  • Parameters: venue (Venue) – The venue to subscribe to.

subscribed_bars(self)

Return the bar types subscribed to.

subscribed_custom_data(self)

Return the custom data types subscribed to.

subscribed_instrument_close(self)

Return the instrument closes subscribed to.

subscribed_instrument_status(self)

Return the status update instruments subscribed to.

subscribed_instruments(self)

Return the instruments subscribed to.

subscribed_order_book_deltas(self)

Return the order book delta instruments subscribed to.

subscribed_order_book_snapshots(self)

Return the order book snapshot instruments subscribed to.

subscribed_quote_ticks(self)

Return the quote tick instruments subscribed to.

subscribed_trade_ticks(self)

Return the trade tick instruments subscribed to.

subscribed_venue_status(self)

Return the status update instruments subscribed to.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

unsubscribe(self, DataType data_type)

Unsubscribe from data for the given data type.

  • Parameters: data_type (DataType) – The data type for the subscription.

unsubscribe_bars(self, BarType bar_type)

Unsubscribe from Bar data for the given bar type.

  • Parameters: bar_type (BarType) – The bar type to unsubscribe from.

unsubscribe_instrument(self, InstrumentId instrument_id)

Unsubscribe from Instrument data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The instrument to unsubscribe from.

unsubscribe_instrument_close(self, InstrumentId instrument_id)

Unsubscribe from InstrumentClose data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to unsubscribe from.

unsubscribe_instrument_status(self, InstrumentId instrument_id)

Unsubscribe from InstrumentStatus data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.

unsubscribe_instruments(self)

Unsubscribe from all Instrument data.

unsubscribe_order_book_deltas(self, InstrumentId instrument_id)

Unsubscribe from OrderBookDeltas data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The order book instrument to unsubscribe from.

unsubscribe_order_book_snapshots(self, InstrumentId instrument_id)

Unsubscribe from OrderBook snapshots data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The order book instrument to unsubscribe from.

unsubscribe_quote_ticks(self, InstrumentId instrument_id)

Unsubscribe from QuoteTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to unsubscribe from.

unsubscribe_trade_ticks(self, InstrumentId instrument_id)

Unsubscribe from TradeTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to unsubscribe from.

unsubscribe_venue_status(self, Venue venue)

Unsubscribe from InstrumentStatus data for the given venue.

  • Parameters: venue (Venue) – The venue to unsubscribe from.

venue

The clients venue ID (if applicable).

  • Returns: Venue or None

Enums

Defines Binance Futures specific enums.

class BinanceFuturesContractType

Bases: 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

Bases: 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 BinanceFuturesPositionSide

Bases: Enum

Represents a Binance Futures position side.

BOTH = 'BOTH'

LONG = 'LONG'

SHORT = 'SHORT'

class BinanceFuturesWorkingType

Bases: Enum

Represents a Binance Futures working type.

MARK_PRICE = 'MARK_PRICE'

CONTRACT_PRICE = 'CONTRACT_PRICE'

class BinanceFuturesMarginType

Bases: Enum

Represents a Binance Futures margin type.

ISOLATED = 'isolated'

CROSS = 'cross'

class BinanceFuturesPositionUpdateReason

Bases: 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

Bases: 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'

class BinanceFuturesEnumParser

Bases: BinanceEnumParser

Provides parsing methods for enums used by the ‘Binance Futures’ exchange.

parse_binance_order_type(order_type: BinanceOrderType)

parse_internal_order_type(order: Order)

parse_binance_trigger_type(trigger_type: str)

parse_futures_position_side(net_size: Decimal)

parse_binance_bar_agg(bar_agg: str)

parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval)

parse_binance_order_side(order_side: BinanceOrderSide)

parse_binance_order_status(order_status: BinanceOrderStatus)

parse_binance_time_in_force(time_in_force: BinanceTimeInForce)

parse_internal_order_side(order_side: OrderSide)

parse_internal_time_in_force(time_in_force: TimeInForce)

parse_nautilus_bar_aggregation(bar_agg: BarAggregation)

Execution

class BinanceFuturesExecutionClient

Bases: BinanceCommonExecutionClient

Provides an execution 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 (BinanceFuturesInstrumentProvider) – The instrument provider.
    • base_url_ws (str) – The base URL for the WebSocket client.
    • config (BinanceExecClientConfig) – The configuration for the client.
    • account_type (BinanceAccountType , default 'USDT_FUTURE') – The account type for the client.
    • name (str , optional) – The custom client ID.

account_id

The clients account ID.

  • Returns: AccountId or None

account_type

The clients account type.

  • Returns: AccountType

base_currency

The clients account base currency (None for multi-currency accounts).

  • Returns: Currency or None

batch_cancel_orders(self, BatchCancelOrders command)

Batch cancel orders for the instrument ID contained in the given command.

cancel_all_orders(self, CancelAllOrders command)

Cancel all orders for the instrument ID contained in the given command.

cancel_order(self, CancelOrder command)

Cancel the order with the client order ID contained in the given command.

  • Parameters: command (CancelOrder) – The command to execute.

connect()

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>)

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.
  • Return type: asyncio.Task

degrade(self)

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()

Disconnect the client.

dispose(self)

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)

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)

Return the fully qualified name for the components class.

  • Return type: str

generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None)

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.
    • info (dict *[*str , object ]) – The additional implementation specific account information.

async generate_fill_reports(instrument_id: InstrumentId | None = None, venue_order_id: VenueOrderId | None = None, start: Timestamp | None = None, end: Timestamp | None = None)

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.
    • venue_order_id (VenueOrderId , optional) – The venue order ID (assigned by the venue) query filter.
    • start (pd.Timestamp , optional) – The start datetime (UTC) query filter.
    • end (pd.Timestamp , optional) – The end datetime (UTC) query filter.
  • Return type: list[FillReport]

async generate_mass_status(lookback_mins: int | None = None)

Generate an ExecutionMassStatus report.

  • Parameters: lookback_mins (int , optional) – The maximum lookback for querying closed orders, trades and positions.
  • Return type: ExecutionMassStatus or None

generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderAccepted event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.

generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, unicode reason, uint64_t ts_event)

Generate an OrderCancelRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • reason (str) – The order cancel rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.

generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderCanceled event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.

generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderExpired event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.

generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event)

Generate an OrderFilled event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • trade_id (TradeId) – The trade 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.
    • 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.

generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, unicode reason, uint64_t ts_event)

Generate an OrderModifyRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • reason (str) – The order update rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.

generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, unicode reason, uint64_t ts_event)

Generate an OrderRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • reason (datetime) – The order rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.

async generate_order_status_report(instrument_id: InstrumentId, client_order_id: ClientOrderId | None = None, venue_order_id: VenueOrderId | None = 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.
    • client_order_id (ClientOrderId , optional) – The client order ID for the report.
    • venue_order_id (VenueOrderId , optional) – The venue order ID for the report.
  • Return type: OrderStatusReport or None
  • Raises: ValueError – If both the client_order_id and venue_order_id are None.

async generate_order_status_reports(instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None, open_only: bool = False)

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.
    • start (pd.Timestamp , optional) – The start datetime (UTC) query filter.
    • end (pd.Timestamp , optional) – The end datetime (UTC) query filter.
    • open_only (bool , default False) – If the query is for open orders only.
  • Return type: list[OrderStatusReport]

generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event)

Generate an OrderSubmitted event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.

generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderTriggered event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.

generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False)

Generate an OrderUpdated event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • 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.
    • venue_order_id_modified (bool) – If the ID was modified for this event.

async generate_position_status_reports(instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None)

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.
    • start (pd.Timestamp , optional) – The start datetime (UTC) query filter.
    • end (pd.Timestamp , optional) – The end datetime (UTC) query filter.
  • Return type: list[PositionStatusReport]

get_account(self)

Return the account for the client (if registered).

  • Return type: Account or None

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

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

modify_order(self, ModifyOrder command)

Modify the order with parameters contained in the command.

  • Parameters: command (ModifyOrder) – The command to execute.

oms_type

The venues order management system type.

  • Returns: OmsType

query_order(self, QueryOrder command)

Initiate a reconciliation for the queried order which will generate an OrderStatusReport.

  • Parameters: command (QueryOrder) – The command to execute.

reset(self)

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.

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.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING 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.

async run_after_delay(delay: float, coro: Coroutine)

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.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING 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.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING 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.

submit_order(self, SubmitOrder command)

Submit the order contained in the given command for execution.

  • Parameters: command (SubmitOrder) – The command to execute.

submit_order_list(self, SubmitOrderList command)

Submit the order list contained in the given command for execution.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

property treat_expired_as_canceled : bool

Whether the EXPIRED execution type is treated as a CANCEL.

  • Return type: bool

type

The components type.

  • Returns: type

property use_position_ids : bool

Whether a position_id will be assigned to order events generated by the client.

  • Return type: bool

venue

The clients venue ID (if not a routing client).

  • Returns: Venue or None

Providers

class BinanceFuturesInstrumentProvider

Bases: InstrumentProvider

Provides a means of loading instruments from the Binance Futures exchange.

  • Parameters:
    • client (APIClient) – The client for the provider.
    • config (InstrumentProviderConfig , optional) – The configuration for the provider.

async load_all_async(filters: dict | None = None)

Load the latest instruments into the provider asynchronously, optionally applying the given filters.

async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.
  • Raises: ValueError – If any instrument_id.venue is not equal to self.venue.

async load_async(instrument_id: InstrumentId, filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.
  • Raises: ValueError – If instrument_id.venue is not equal to self.venue.

add(instrument: Instrument)

Add the given instrument to the provider.

  • Parameters: instrument (Instrument) – The instrument to add.

add_bulk(instruments: list[Instrument])

Add the given instruments bulk to the provider.

  • Parameters: instruments (list [Instrument ]) – The instruments to add.

add_currency(currency: Currency)

Add the given currency to the provider.

  • Parameters: currency (Currency) – The currency to add.

property count : int

Return the count of instruments held by the provider.

  • Return type: int

currencies()

Return all currencies held by the instrument provider.

currency(code: str)

Return the currency with the given code (if found).

  • Parameters: code (str) – The currency code.
  • Return type: Currency or None
  • Raises: ValueError – If code is not a valid string.

find(instrument_id: InstrumentId)

Return the instrument for the given instrument ID (if found).

  • Parameters: instrument_id (InstrumentId) – The ID for the instrument
  • Return type: Instrument or None

get_all()

Return all loaded instruments as a map keyed by instrument ID.

If no instruments loaded, will return an empty dict.

async initialize()

Initialize the instrument provider.

If initialize() then will immediately return.

list_all()

Return all loaded instruments.

load(instrument_id: InstrumentId, filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.

load_all(filters: dict | None = None)

Load the latest instruments into the provider, optionally applying the given filters.

  • Parameters: filters (dict , optional) – The venue specific instrument loading filters to apply.

load_ids(instrument_ids: list[InstrumentId], filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.

Types

class BinanceFuturesMarkPriceUpdate

Bases: Data

Represents a Binance Futures mark price and funding rate update.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the update.
    • mark (Price) – The mark price for the instrument.
    • index (Price) – The index price for the instrument.
    • estimated_settle (Price) – The estimated settle price for the instrument (only useful in the last hour before the settlement starts).
    • funding_rate (Decimal) – The current funding rate for the instrument.
    • ts_next_funding (uint64_t) – UNIX timestamp (nanoseconds) when next funding will occur.
    • 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.

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])

Return a Binance Futures mark price update parsed from the given values.

static to_dict(obj: BinanceFuturesMarkPriceUpdate)

Return a dictionary representation of this object.

  • Return type: dict[str, Any]

classmethod fully_qualified_name(cls)

Return the fully qualified name for the Data class.

  • Return type: str

Spot

Data

class BinanceSpotDataClient

Bases: BinanceCommonDataClient

Provides a data client for the Binance Spot/Margin 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 'SPOT') – The account type for the client.
    • name (str , optional) – The custom client ID.

connect()

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>)

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)

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()

Disconnect the client.

dispose(self)

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)

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)

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

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

request(self, DataType data_type, UUID4 correlation_id)

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.

request_bars(self, BarType bar_type, int limit, UUID4 correlation_id, datetime start=None, datetime end=None)

Request historical Bar data.

  • Parameters:
    • bar_type (BarType) – The bar type for the request.
    • limit (int) – The limit for the number of returned bars.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_instrument(self, InstrumentId instrument_id, UUID4 correlation_id, datetime start=None, datetime end=None)

Request Instrument data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the request.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_instruments(self, Venue venue, UUID4 correlation_id, datetime start=None, datetime end=None)

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.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_order_book_snapshot(self, InstrumentId instrument_id, int limit, UUID4 correlation_id)

Request order book snapshot data.

  • Parameters:
    • instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
    • limit (int) – The limit on the depth of the order book snapshot.
    • correction_id (UUID4) – The correlation ID for the request.

request_quote_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start=None, datetime end=None)

Request historical QuoteTick data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • limit (int) – The limit for the number of returned ticks.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_trade_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start=None, datetime end=None)

Request historical TradeTick data.

  • Parameters:
    • instrument_id (InstrumentId) – The tick instrument ID for the request.
    • limit (int) – The limit for the number of returned ticks.
    • correlation_id (UUID4) – The correlation ID for the request.
    • start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
    • end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

reset(self)

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.

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.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING 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.

async run_after_delay(delay: float, coro: Coroutine)

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.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING 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.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING 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.

subscribe(self, DataType data_type)

Subscribe to data for the given data type.

  • Parameters: data_type (DataType) – The data type for the subscription.

subscribe_bars(self, BarType bar_type)

Subscribe to Bar data for the given bar type.

  • Parameters: bar_type (BarType) – The bar type to subscribe to.

subscribe_instrument(self, InstrumentId instrument_id)

Subscribe to the Instrument with the given instrument ID.

subscribe_instrument_close(self, InstrumentId instrument_id)

Subscribe to InstrumentClose updates for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_instrument_status(self, InstrumentId instrument_id)

Subscribe to InstrumentStatus data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_instruments(self)

Subscribe to all Instrument data.

subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)

Subscribe to OrderBookDeltas data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • 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.

subscribe_order_book_snapshots(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)

Subscribe to OrderBook snapshots data for the given instrument ID.

  • Parameters:
    • instrument_id (InstrumentId) – The order book instrument to subscribe to.
    • 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.
    • kwargs (dict , optional) – The keyword arguments for exchange specific parameters.

subscribe_quote_ticks(self, InstrumentId instrument_id)

Subscribe to QuoteTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_trade_ticks(self, InstrumentId instrument_id)

Subscribe to TradeTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to subscribe to.

subscribe_venue_status(self, Venue venue)

Subscribe to InstrumentStatus data for the venue.

  • Parameters: venue (Venue) – The venue to subscribe to.

subscribed_bars(self)

Return the bar types subscribed to.

subscribed_custom_data(self)

Return the custom data types subscribed to.

subscribed_instrument_close(self)

Return the instrument closes subscribed to.

subscribed_instrument_status(self)

Return the status update instruments subscribed to.

subscribed_instruments(self)

Return the instruments subscribed to.

subscribed_order_book_deltas(self)

Return the order book delta instruments subscribed to.

subscribed_order_book_snapshots(self)

Return the order book snapshot instruments subscribed to.

subscribed_quote_ticks(self)

Return the quote tick instruments subscribed to.

subscribed_trade_ticks(self)

Return the trade tick instruments subscribed to.

subscribed_venue_status(self)

Return the status update instruments subscribed to.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

type

The components type.

  • Returns: type

unsubscribe(self, DataType data_type)

Unsubscribe from data for the given data type.

  • Parameters: data_type (DataType) – The data type for the subscription.

unsubscribe_bars(self, BarType bar_type)

Unsubscribe from Bar data for the given bar type.

  • Parameters: bar_type (BarType) – The bar type to unsubscribe from.

unsubscribe_instrument(self, InstrumentId instrument_id)

Unsubscribe from Instrument data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The instrument to unsubscribe from.

unsubscribe_instrument_close(self, InstrumentId instrument_id)

Unsubscribe from InstrumentClose data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to unsubscribe from.

unsubscribe_instrument_status(self, InstrumentId instrument_id)

Unsubscribe from InstrumentStatus data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.

unsubscribe_instruments(self)

Unsubscribe from all Instrument data.

unsubscribe_order_book_deltas(self, InstrumentId instrument_id)

Unsubscribe from OrderBookDeltas data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The order book instrument to unsubscribe from.

unsubscribe_order_book_snapshots(self, InstrumentId instrument_id)

Unsubscribe from OrderBook snapshots data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The order book instrument to unsubscribe from.

unsubscribe_quote_ticks(self, InstrumentId instrument_id)

Unsubscribe from QuoteTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to unsubscribe from.

unsubscribe_trade_ticks(self, InstrumentId instrument_id)

Unsubscribe from TradeTick data for the given instrument ID.

  • Parameters: instrument_id (InstrumentId) – The tick instrument to unsubscribe from.

unsubscribe_venue_status(self, Venue venue)

Unsubscribe from InstrumentStatus data for the given venue.

  • Parameters: venue (Venue) – The venue to unsubscribe from.

venue

The clients venue ID (if applicable).

  • Returns: Venue or None

Enums

Defines Binance Spot/Margin specific enums.

class BinanceSpotPermissions

Bases: 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

Bases: 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

Bases: Enum

Represents a Binance Spot/Margin event type.

outboundAccountPosition = 'outboundAccountPosition'

balanceUpdate = 'balanceUpdate'

executionReport = 'executionReport'

listStatus = 'listStatus'

class BinanceSpotEnumParser

Bases: BinanceEnumParser

Provides parsing methods for enums used by the ‘Binance Spot/Margin’ exchange.

parse_binance_order_type(order_type: BinanceOrderType)

parse_internal_order_type(order: Order)

parse_binance_bar_agg(bar_agg: str)

parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval)

parse_binance_order_side(order_side: BinanceOrderSide)

parse_binance_order_status(order_status: BinanceOrderStatus)

parse_binance_time_in_force(time_in_force: BinanceTimeInForce)

parse_binance_trigger_type(trigger_type: str)

parse_internal_order_side(order_side: OrderSide)

parse_internal_time_in_force(time_in_force: TimeInForce)

parse_nautilus_bar_aggregation(bar_agg: BarAggregation)

Execution

class BinanceSpotExecutionClient

Bases: BinanceCommonExecutionClient

Provides an execution client for the Binance Spot/Margin 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 (BinanceSpotInstrumentProvider) – The instrument provider.
    • base_url_ws (str) – The base URL for the WebSocket client.
    • config (BinanceExecClientConfig) – The configuration for the client.
    • account_type (BinanceAccountType , default 'SPOT') – The account type for the client.
    • name (str , optional) – The custom client ID.

account_id

The clients account ID.

  • Returns: AccountId or None

account_type

The clients account type.

  • Returns: AccountType

base_currency

The clients account base currency (None for multi-currency accounts).

  • Returns: Currency or None

batch_cancel_orders(self, BatchCancelOrders command)

Batch cancel orders for the instrument ID contained in the given command.

cancel_all_orders(self, CancelAllOrders command)

Cancel all orders for the instrument ID contained in the given command.

cancel_order(self, CancelOrder command)

Cancel the order with the client order ID contained in the given command.

  • Parameters: command (CancelOrder) – The command to execute.

connect()

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>)

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.
  • Return type: asyncio.Task

degrade(self)

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()

Disconnect the client.

dispose(self)

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)

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)

Return the fully qualified name for the components class.

  • Return type: str

generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None)

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.
    • info (dict *[*str , object ]) – The additional implementation specific account information.

async generate_fill_reports(instrument_id: InstrumentId | None = None, venue_order_id: VenueOrderId | None = None, start: Timestamp | None = None, end: Timestamp | None = None)

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.
    • venue_order_id (VenueOrderId , optional) – The venue order ID (assigned by the venue) query filter.
    • start (pd.Timestamp , optional) – The start datetime (UTC) query filter.
    • end (pd.Timestamp , optional) – The end datetime (UTC) query filter.
  • Return type: list[FillReport]

async generate_mass_status(lookback_mins: int | None = None)

Generate an ExecutionMassStatus report.

  • Parameters: lookback_mins (int , optional) – The maximum lookback for querying closed orders, trades and positions.
  • Return type: ExecutionMassStatus or None

generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderAccepted event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.

generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, unicode reason, uint64_t ts_event)

Generate an OrderCancelRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • reason (str) – The order cancel rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.

generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderCanceled event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.

generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderExpired event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.

generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event)

Generate an OrderFilled event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • trade_id (TradeId) – The trade 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.
    • 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.

generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, unicode reason, uint64_t ts_event)

Generate an OrderModifyRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • reason (str) – The order update rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.

generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, unicode reason, uint64_t ts_event)

Generate an OrderRejected event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • reason (datetime) – The order rejected reason.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.

async generate_order_status_report(instrument_id: InstrumentId, client_order_id: ClientOrderId | None = None, venue_order_id: VenueOrderId | None = 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.
    • client_order_id (ClientOrderId , optional) – The client order ID for the report.
    • venue_order_id (VenueOrderId , optional) – The venue order ID for the report.
  • Return type: OrderStatusReport or None
  • Raises: ValueError – If both the client_order_id and venue_order_id are None.

async generate_order_status_reports(instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None, open_only: bool = False)

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.
    • start (pd.Timestamp , optional) – The start datetime (UTC) query filter.
    • end (pd.Timestamp , optional) – The end datetime (UTC) query filter.
    • open_only (bool , default False) – If the query is for open orders only.
  • Return type: list[OrderStatusReport]

generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event)

Generate an OrderSubmitted event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.

generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event)

Generate an OrderTriggered event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.

generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False)

Generate an OrderUpdated event and send it to the ExecutionEngine.

  • Parameters:
    • strategy_id (StrategyId) – The strategy ID associated with the event.
    • instrument_id (InstrumentId) – The instrument ID.
    • client_order_id (ClientOrderId) – The client order ID.
    • venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
    • 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.
    • venue_order_id_modified (bool) – If the ID was modified for this event.

async generate_position_status_reports(instrument_id: InstrumentId | None = None, start: Timestamp | None = None, end: Timestamp | None = None)

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.
    • start (pd.Timestamp , optional) – The start datetime (UTC) query filter.
    • end (pd.Timestamp , optional) – The end datetime (UTC) query filter.
  • Return type: list[PositionStatusReport]

get_account(self)

Return the account for the client (if registered).

  • Return type: Account or None

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

is_disposed

bool

Return whether the current component state is DISPOSED.

  • Return type: bool
  • Type: Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

  • Return type: bool
  • Type: Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED).

  • Return type: bool
  • Type: Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

  • Return type: bool
  • Type: Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

  • Return type: bool
  • Type: Component.is_stopped

modify_order(self, ModifyOrder command)

Modify the order with parameters contained in the command.

  • Parameters: command (ModifyOrder) – The command to execute.

oms_type

The venues order management system type.

  • Returns: OmsType

query_order(self, QueryOrder command)

Initiate a reconciliation for the queried order which will generate an OrderStatusReport.

  • Parameters: command (QueryOrder) – The command to execute.

reset(self)

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.

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.

resume(self)

Resume the component.

While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING 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.

async run_after_delay(delay: float, coro: Coroutine)

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.

start(self)

Start the component.

While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING 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.

state

ComponentState

Return the components current state.

  • Return type: ComponentState
  • Type: Component.state

stop(self)

Stop the component.

While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING 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.

submit_order(self, SubmitOrder command)

Submit the order contained in the given command for execution.

  • Parameters: command (SubmitOrder) – The command to execute.

submit_order_list(self, SubmitOrderList command)

Submit the order list contained in the given command for execution.

trader_id

The trader ID associated with the component.

  • Returns: TraderId

property treat_expired_as_canceled : bool

Whether the EXPIRED execution type is treated as a CANCEL.

  • Return type: bool

type

The components type.

  • Returns: type

property use_position_ids : bool

Whether a position_id will be assigned to order events generated by the client.

  • Return type: bool

venue

The clients venue ID (if not a routing client).

  • Returns: Venue or None

Providers

class BinanceSpotInstrumentProvider

Bases: InstrumentProvider

Provides a means of loading instruments from the Binance Spot/Margin exchange.

  • Parameters:
    • client (APIClient) – The client for the provider.
    • clock (LiveClock) – The clock for the provider.
    • account_type (BinanceAccountType , default SPOT) – The Binance account type for the provider.
    • is_testnet (bool , default False) – If the provider is for the Spot testnet.
    • config (InstrumentProviderConfig , optional) – The configuration for the provider.

async load_all_async(filters: dict | None = None)

Load the latest instruments into the provider asynchronously, optionally applying the given filters.

async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.
  • Raises: ValueError – If any instrument_id.venue is not equal to self.venue.

async load_async(instrument_id: InstrumentId, filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.
  • Raises: ValueError – If instrument_id.venue is not equal to self.venue.

add(instrument: Instrument)

Add the given instrument to the provider.

  • Parameters: instrument (Instrument) – The instrument to add.

add_bulk(instruments: list[Instrument])

Add the given instruments bulk to the provider.

  • Parameters: instruments (list [Instrument ]) – The instruments to add.

add_currency(currency: Currency)

Add the given currency to the provider.

  • Parameters: currency (Currency) – The currency to add.

property count : int

Return the count of instruments held by the provider.

  • Return type: int

currencies()

Return all currencies held by the instrument provider.

currency(code: str)

Return the currency with the given code (if found).

  • Parameters: code (str) – The currency code.
  • Return type: Currency or None
  • Raises: ValueError – If code is not a valid string.

find(instrument_id: InstrumentId)

Return the instrument for the given instrument ID (if found).

  • Parameters: instrument_id (InstrumentId) – The ID for the instrument
  • Return type: Instrument or None

get_all()

Return all loaded instruments as a map keyed by instrument ID.

If no instruments loaded, will return an empty dict.

async initialize()

Initialize the instrument provider.

If initialize() then will immediately return.

list_all()

Return all loaded instruments.

load(instrument_id: InstrumentId, filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.

load_all(filters: dict | None = None)

Load the latest instruments into the provider, optionally applying the given filters.

  • Parameters: filters (dict , optional) – The venue specific instrument loading filters to apply.

load_ids(instrument_ids: list[InstrumentId], filters: dict | 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.
    • filters (dict , optional) – The venue specific instrument loading filters to apply.