Binance
Binance cryptocurreny exchange integration adapter.
This subpackage provides an instrument provider, data and execution clients, configurations, data types and constants for connecting to and interacting with Binance’s API.
For convenience, the most commonly used symbols are re-exported at the
subpackage’s top level, so downstream code can simply import from
nautilus_trader.adapters.binance
.
class BinanceAccountType
Bases: Enum
Represents a Binance account type.
property is_spot
property is_margin
property is_spot_or_margin
property is_futures : bool
SPOT = 'SPOT'
MARGIN = 'MARGIN'
ISOLATED_MARGIN = 'ISOLATED_MARGIN'
USDT_FUTURES = 'USDT_FUTURES'
COIN_FUTURES = 'COIN_FUTURES'
class BinanceDataClientConfig
Bases: LiveDataClientConfig
Configuration for BinanceDataClient
instances.
- Parameters:
- venue (Venue , default BINANCE_VENUE) – The venue for the client.
- api_key (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - api_secret (str , optional) – The Binance API secret key.
If
None
then will source the BINANCE_API_SECRET or BINANCE_TESTNET_API_SECRET environment variables. - key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- account_type (BinanceAccountType , default BinanceAccountType.SPOT) – The account type for the client.
- base_url_http (str , optional) – The HTTP client custom endpoint override.
- base_url_ws (str , optional) – The WebSocket client custom endpoint override.
- us (bool , default False) – If client is connecting to Binance US.
- testnet (bool , default False) – If the client is connecting to a Binance testnet.
- update_instruments_interval_mins (PositiveInt or None , default 60) – The interval (minutes) between reloading instruments from the venue.
- use_agg_trade_ticks (bool , default False) – Whether to use aggregated trade tick endpoints instead of raw trades. TradeId of ticks will be the Aggregate tradeId returned by Binance.
account_type : BinanceAccountType
api_key : str | None
api_secret : str | None
base_url_http : str | None
base_url_ws : str | None
key_type : BinanceKeyType
testnet : bool
update_instruments_interval_mins : Annotated[int, msgspec.Meta(gt=0)] | None
us : bool
use_agg_trade_ticks : bool
venue : Venue
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
handle_revised_bars : bool
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class BinanceExecClientConfig
Bases: LiveExecClientConfig
Configuration for BinanceExecutionClient
instances.
- Parameters:
- venue (Venue , default BINANCE_VENUE) – The venue for the client.
- api_key (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - api_secret (str , optional) – The Binance API secret key.
If
None
then will source the BINANCE_API_SECRET or BINANCE_TESTNET_API_SECRET environment variables. - key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- account_type (BinanceAccountType , default BinanceAccountType.SPOT) – The account type for the client.
- base_url_http (str , optional) – The HTTP client custom endpoint override.
- base_url_ws (str , optional) – The WebSocket client custom endpoint override.
- us (bool , default False) – If client is connecting to Binance US.
- testnet (bool , default False) – If the client is connecting to a Binance testnet.
- 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.
- use_trade_lite (bool , default False) – If TRADE_LITE events should be used. If True, commissions will be calculated based on the instrument’s details.
- treat_expired_as_canceled (bool , default False) – If the EXPIRED execution type is semantically treated as CANCELED. Binance treats cancels with certain combinations of order type and time in force as expired events. This config option allows you to treat these uniformally as cancels.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Binance HTTP requests.
- max_retries (PositiveInt , optional) – The maximum number of times a submit, cancel or modify order request will be retried.
- retry_delay_initial_ms (PositiveInt , optional) – The initial delay (milliseconds) between retries. Short delays with frequent retries may result in account bans.
- retry_delay_max_ms (PositiveInt , optional) – The maximum delay (milliseconds) between retries.
- futures_leverages (dict *[*BinanceSymbol , PositiveInt ] , optional) – The initial leverage to be used for each symbol. It’s applicable to futures only.
- futures_margin_types (dict *[*BinanceSymbol , BinanceFuturesMarginType ] , optional) – Margin type (isolated or cross) to be used for each symbol. It’s applicable to futures only.
- listen_key_ping_max_failures (PositiveInt , default 3) – The maximum number of consecutive listen key ping failures before triggering recovery.
- log_rejected_due_post_only_as_warning (bool , default True) – If order rejected events where due_post_only is True should be logged as warnings.
WARNING
A short retry_delay with frequent retries may result in account bans.
account_type : BinanceAccountType
api_key : str | None
api_secret : str | None
base_url_http : str | None
base_url_ws : str | None
futures_leverages : dict[BinanceSymbol, Annotated[int, msgspec.Meta(gt=0)]] | None
futures_margin_types : dict[BinanceSymbol, BinanceFuturesMarginType] | None
key_type : BinanceKeyType
listen_key_ping_max_failures : Annotated[int, msgspec.Meta(gt=0)]
log_rejected_due_post_only_as_warning : bool
max_retries : Annotated[int, msgspec.Meta(gt=0)] | None
recv_window_ms : Annotated[int, msgspec.Meta(gt=0)]
retry_delay_initial_ms : Annotated[int, msgspec.Meta(gt=0)] | None
retry_delay_max_ms : Annotated[int, msgspec.Meta(gt=0)] | None
testnet : bool
treat_expired_as_canceled : bool
us : bool
use_gtd : bool
use_position_ids : bool
use_reduce_only : bool
use_trade_lite : bool
venue : Venue
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class 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.
add(instrument: Instrument) → None
Add the given instrument to the provider.
- Parameters: instrument (Instrument) – The instrument to add.
add_bulk(instruments: list[Instrument]) → None
Add the given instruments bulk to the provider.
- Parameters: instruments (list [Instrument ]) – The instruments to add.
add_currency(currency: Currency) → None
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() → dict[str, Currency]
Return all currencies held by the instrument provider.
- Return type: dict[str, Currency]
currency(code: str) → Currency | None
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) → Instrument | None
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() → dict[InstrumentId, Instrument]
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type: dict[InstrumentId, Instrument]
async initialize(reload: bool = False) → None
Initialize the instrument provider.
- Parameters: reload (bool , default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
list_all() → list[Instrument]
Return all loaded instruments.
- Return type: list[Instrument]
load(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load_all(filters: dict | None = None) → None
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters: filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
async load_all_async(filters: dict | None = None) → None
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
async load_async(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If instrument_id.venue is not equal to self.venue.
load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
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.
- next_funding_ns (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.
static from_dict(values: dict[str, Any]) → BinanceFuturesMarkPriceUpdate
Return a Binance Futures mark price update parsed from the given values.
- Parameters: values (dict *[*str , Any ]) – The values for initialization.
- Return type: BinanceFuturesMarkPriceUpdate
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the Data class.
- Return type: str
classmethod is_signal(cls, str name='') → bool
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters: name (str , optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns: True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type: bool
static to_dict(obj: BinanceFuturesMarkPriceUpdate) → dict[str, Any]
Return a dictionary representation of this object.
- Return type: dict[str, Any]
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
class BinanceKeyType
Bases: Enum
Represents a Binance private key cryptographic algorithm type.
HMAC = 'HMAC'
RSA = 'RSA'
ED25519 = 'Ed25519'
class BinanceLiveDataClientFactory
Bases: LiveDataClientFactory
Provides a Binance live data client factory.
static create(loop: AbstractEventLoop, name: str, config: BinanceDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BinanceSpotDataClient | BinanceFuturesDataClient
Create a new Binance data client.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BinanceDataClientConfig) – The client configuration.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- Return type: BinanceSpotDataClient or BinanceFuturesDataClient
- Raises: ValueError – If config.account_type is not a valid BinanceAccountType.
class BinanceLiveExecClientFactory
Bases: LiveExecClientFactory
Provides a Binance live execution client factory.
static create(loop: AbstractEventLoop, name: str, config: BinanceExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BinanceSpotExecutionClient | BinanceFuturesExecutionClient
Create a new Binance execution client.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BinanceExecClientConfig) – The configuration for the client.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- Return type: BinanceExecutionClient
- Raises: ValueError – If config.account_type is not a valid BinanceAccountType.
class BinanceOrderBookDeltaDataLoader
Bases: object
Provides a means of loading Binance order book data.
classmethod load(file_path: PathLike[str] | str, nrows: int | None = None) → DataFrame
Return the deltas pandas.DataFrame loaded from the given CSV file_path.
- Parameters:
- file_path (str , path object or file-like object) – The path to the CSV file.
- nrows (int , optional) – The maximum number of rows to load.
- Return type: pd.DataFrame
classmethod map_actions(row: Series) → str
classmethod map_flags(row: Series) → int
classmethod map_sides(side: str) → str
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.
add(instrument: Instrument) → None
Add the given instrument to the provider.
- Parameters: instrument (Instrument) – The instrument to add.
add_bulk(instruments: list[Instrument]) → None
Add the given instruments bulk to the provider.
- Parameters: instruments (list [Instrument ]) – The instruments to add.
add_currency(currency: Currency) → None
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() → dict[str, Currency]
Return all currencies held by the instrument provider.
- Return type: dict[str, Currency]
currency(code: str) → Currency | None
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) → Instrument | None
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() → dict[InstrumentId, Instrument]
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type: dict[InstrumentId, Instrument]
async initialize(reload: bool = False) → None
Initialize the instrument provider.
- Parameters: reload (bool , default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
list_all() → list[Instrument]
Return all loaded instruments.
- Return type: list[Instrument]
load(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load_all(filters: dict | None = None) → None
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters: filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
async load_all_async(filters: dict | None = None) → None
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
async load_async(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If instrument_id.venue is not equal to self.venue.
load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
get_cached_binance_http_client(clock: LiveClock, account_type: BinanceAccountType, api_key: str | None = None, api_secret: str | None = None, key_type: BinanceKeyType = BinanceKeyType.HMAC, base_url: str | None = None, is_testnet: bool = False, is_us: bool = False) → BinanceHttpClient
Cache and return a Binance HTTP client with the given key and secret.
If a cached client with matching parameters already exists, the cached client will be returned.
- Parameters:
- clock (LiveClock) – The clock for the client.
- account_type (BinanceAccountType) – The account type for the client.
- api_key (str , optional) – The API key for the client.
- api_secret (str , optional) – The API secret for the client.
- key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- base_url (str , optional) – The base URL for the API endpoints.
- is_testnet (bool , default False) – If the client is connecting to the testnet API.
- is_us (bool , default False) – If the client is connecting to Binance US.
- Return type: BinanceHttpClient
Config
class BinanceDataClientConfig
Bases: LiveDataClientConfig
Configuration for BinanceDataClient
instances.
- Parameters:
- venue (Venue , default BINANCE_VENUE) – The venue for the client.
- api_key (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - api_secret (str , optional) – The Binance API secret key.
If
None
then will source the BINANCE_API_SECRET or BINANCE_TESTNET_API_SECRET environment variables. - key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- account_type (BinanceAccountType , default BinanceAccountType.SPOT) – The account type for the client.
- base_url_http (str , optional) – The HTTP client custom endpoint override.
- base_url_ws (str , optional) – The WebSocket client custom endpoint override.
- us (bool , default False) – If client is connecting to Binance US.
- testnet (bool , default False) – If the client is connecting to a Binance testnet.
- update_instruments_interval_mins (PositiveInt or None , default 60) – The interval (minutes) between reloading instruments from the venue.
- use_agg_trade_ticks (bool , default False) – Whether to use aggregated trade tick endpoints instead of raw trades. TradeId of ticks will be the Aggregate tradeId returned by Binance.
venue : Venue
api_key : str | None
api_secret : str | None
key_type : BinanceKeyType
account_type : BinanceAccountType
base_url_http : str | None
base_url_ws : str | None
us : bool
testnet : bool
update_instruments_interval_mins : Annotated[int, msgspec.Meta(gt=0)] | None
use_agg_trade_ticks : bool
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
handle_revised_bars : bool
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class BinanceExecClientConfig
Bases: LiveExecClientConfig
Configuration for BinanceExecutionClient
instances.
- Parameters:
- venue (Venue , default BINANCE_VENUE) – The venue for the client.
- api_key (str , optional) – The Binance API public key.
If
None
then will source the BINANCE_API_KEY or BINANCE_TESTNET_API_KEY environment variables. - api_secret (str , optional) – The Binance API secret key.
If
None
then will source the BINANCE_API_SECRET or BINANCE_TESTNET_API_SECRET environment variables. - key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- account_type (BinanceAccountType , default BinanceAccountType.SPOT) – The account type for the client.
- base_url_http (str , optional) – The HTTP client custom endpoint override.
- base_url_ws (str , optional) – The WebSocket client custom endpoint override.
- us (bool , default False) – If client is connecting to Binance US.
- testnet (bool , default False) – If the client is connecting to a Binance testnet.
- 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.
- use_trade_lite (bool , default False) – If TRADE_LITE events should be used. If True, commissions will be calculated based on the instrument’s details.
- treat_expired_as_canceled (bool , default False) – If the EXPIRED execution type is semantically treated as CANCELED. Binance treats cancels with certain combinations of order type and time in force as expired events. This config option allows you to treat these uniformally as cancels.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Binance HTTP requests.
- max_retries (PositiveInt , optional) – The maximum number of times a submit, cancel or modify order request will be retried.
- retry_delay_initial_ms (PositiveInt , optional) – The initial delay (milliseconds) between retries. Short delays with frequent retries may result in account bans.
- retry_delay_max_ms (PositiveInt , optional) – The maximum delay (milliseconds) between retries.
- futures_leverages (dict *[*BinanceSymbol , PositiveInt ] , optional) – The initial leverage to be used for each symbol. It’s applicable to futures only.
- futures_margin_types (dict *[*BinanceSymbol , BinanceFuturesMarginType ] , optional) – Margin type (isolated or cross) to be used for each symbol. It’s applicable to futures only.
- listen_key_ping_max_failures (PositiveInt , default 3) – The maximum number of consecutive listen key ping failures before triggering recovery.
- log_rejected_due_post_only_as_warning (bool , default True) – If order rejected events where due_post_only is True should be logged as warnings.
WARNING
A short retry_delay with frequent retries may result in account bans.
venue : Venue
api_key : str | None
api_secret : str | None
key_type : BinanceKeyType
account_type : BinanceAccountType
base_url_http : str | None
base_url_ws : str | None
us : bool
testnet : bool
use_gtd : bool
use_reduce_only : bool
use_position_ids : bool
use_trade_lite : bool
treat_expired_as_canceled : bool
recv_window_ms : Annotated[int, msgspec.Meta(gt=0)]
max_retries : Annotated[int, msgspec.Meta(gt=0)] | None
retry_delay_initial_ms : Annotated[int, msgspec.Meta(gt=0)] | None
retry_delay_max_ms : Annotated[int, msgspec.Meta(gt=0)] | None
futures_leverages : dict[BinanceSymbol, Annotated[int, msgspec.Meta(gt=0)]] | None
futures_margin_types : dict[BinanceSymbol, BinanceFuturesMarginType] | None
listen_key_ping_max_failures : Annotated[int, msgspec.Meta(gt=0)]
log_rejected_due_post_only_as_warning : bool
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
Factories
get_cached_binance_http_client(clock: LiveClock, account_type: BinanceAccountType, api_key: str | None = None, api_secret: str | None = None, key_type: BinanceKeyType = BinanceKeyType.HMAC, base_url: str | None = None, is_testnet: bool = False, is_us: bool = False) → BinanceHttpClient
Cache and return a Binance HTTP client with the given key and secret.
If a cached client with matching parameters already exists, the cached client will be returned.
- Parameters:
- clock (LiveClock) – The clock for the client.
- account_type (BinanceAccountType) – The account type for the client.
- api_key (str , optional) – The API key for the client.
- api_secret (str , optional) – The API secret for the client.
- key_type (BinanceKeyType , default 'HMAC') – The private key cryptographic algorithm type.
- base_url (str , optional) – The base URL for the API endpoints.
- is_testnet (bool , default False) – If the client is connecting to the testnet API.
- is_us (bool , default False) – If the client is connecting to Binance US.
- Return type: BinanceHttpClient
get_cached_binance_spot_instrument_provider(client: BinanceHttpClient, clock: LiveClock, account_type: BinanceAccountType, is_testnet: bool, config: InstrumentProviderConfig, venue: Venue) → BinanceSpotInstrumentProvider
Cache and return an instrument provider for the Binance Spot/Margin exchange.
If a cached provider already exists, then that provider will be returned.
- Parameters:
- client (BinanceHttpClient) – The client for the instrument provider.
- clock (LiveClock) – The clock for the instrument provider.
- account_type (BinanceAccountType) – The Binance account type for the instrument provider.
- is_testnet (bool , default False) – If the provider is for the Spot testnet.
- config (InstrumentProviderConfig) – The configuration for the instrument provider.
- venue (Venue) – The venue for the instrument provider.
- Return type: BinanceSpotInstrumentProvider
get_cached_binance_futures_instrument_provider(client: BinanceHttpClient, clock: LiveClock, account_type: BinanceAccountType, config: InstrumentProviderConfig, venue: Venue) → BinanceFuturesInstrumentProvider
Cache and return an instrument provider for the Binance Futures exchange.
If a cached provider already exists, then that provider will be returned.
- Parameters:
- client (BinanceHttpClient) – The client for the instrument provider.
- clock (LiveClock) – The clock for the instrument provider.
- account_type (BinanceAccountType) – The Binance account type for the instrument provider.
- config (InstrumentProviderConfig) – The configuration for the instrument provider.
- venue (Venue) – The venue for the instrument provider.
- Return type: BinanceFuturesInstrumentProvider
class BinanceLiveDataClientFactory
Bases: LiveDataClientFactory
Provides a Binance live data client factory.
static create(loop: AbstractEventLoop, name: str, config: BinanceDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BinanceSpotDataClient | BinanceFuturesDataClient
Create a new Binance data client.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BinanceDataClientConfig) – The client configuration.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- Return type: BinanceSpotDataClient or BinanceFuturesDataClient
- Raises: ValueError – If config.account_type is not a valid BinanceAccountType.
class BinanceLiveExecClientFactory
Bases: LiveExecClientFactory
Provides a Binance live execution client factory.
static create(loop: AbstractEventLoop, name: str, config: BinanceExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BinanceSpotExecutionClient | BinanceFuturesExecutionClient
Create a new Binance execution client.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BinanceExecClientConfig) – The configuration for the client.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- Return type: BinanceExecutionClient
- Raises: ValueError – If config.account_type is not a valid BinanceAccountType.
Enums
Defines Binance common enums.
class BinanceKeyType
Bases: Enum
Represents a Binance private key cryptographic algorithm type.
HMAC = 'HMAC'
RSA = 'RSA'
ED25519 = 'Ed25519'
class BinanceFuturesPositionSide
Bases: Enum
Represents a Binance Futures position side.
BOTH = 'BOTH'
LONG = 'LONG'
SHORT = 'SHORT'
class BinanceRateLimitType
Bases: Enum
Represents a Binance rate limit type.
REQUEST_WEIGHT = 'REQUEST_WEIGHT'
ORDERS = 'ORDERS'
RAW_REQUESTS = 'RAW_REQUESTS'
class BinanceRateLimitInterval
Bases: Enum
Represents a Binance rate limit interval.
SECOND = 'SECOND'
MINUTE = 'MINUTE'
DAY = 'DAY'
class BinanceKlineInterval
Bases: Enum
Represents a Binance kline chart interval.