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:
EnumRepresents a Binance account type.
- SPOT = 'SPOT'¶
- MARGIN = 'MARGIN'¶
- ISOLATED_MARGIN = 'ISOLATED_MARGIN'¶
- USDT_FUTURES = 'USDT_FUTURES'¶
- COIN_FUTURES = 'COIN_FUTURES'¶
- property is_spot¶
- property is_margin¶
- property is_spot_or_margin¶
- property is_futures: bool¶
- class BinanceDataClientConfig¶
Bases:
LiveDataClientConfigConfiguration for
BinanceDataClientinstances.- Parameters:
venue (Venue, default BINANCE_VENUE) – The venue for the client.
api_key (str, optional) – The Binance API public key. If
None, the client will work for public market data only. Providing an API key may improve rate limits.api_secret (str, optional) – The Binance API secret key. If
None, the client will work for public market data only.key_type (BinanceKeyType, default 'HMAC') – Deprecated: key type is now auto-detected from the api_secret format. Only needed for RSA keys (set explicitly to
BinanceKeyType.RSA).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.
proxy_url (str, optional) – The proxy URL for HTTP requests.
environment (BinanceEnvironment, optional) – The Binance environment (LIVE, TESTNET, or DEMO). Defaults to LIVE.
us (bool, default False) – If client is connecting to Binance US.
testnet (bool, default False) – Deprecated: use
environmentinstead.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.
- api_key: str | None¶
- api_secret: str | None¶
- key_type: BinanceKeyType¶
- account_type: BinanceAccountType¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- proxy_url: str | None¶
- environment: BinanceEnvironment | 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
References
- 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:
LiveExecClientConfigConfiguration for
BinanceExecutionClientinstances.- Parameters:
venue (Venue, default BINANCE_VENUE) – The venue for the client.
api_key (str, optional) – The Binance API public key. If
Nonethen will source from BINANCE_API_KEY (or testnet equivalent).api_secret (str, optional) – The Binance API secret key. If
Nonethen will source from BINANCE_API_SECRET (or testnet equivalent).key_type (BinanceKeyType, default 'HMAC') – Deprecated: key type is now auto-detected from the api_secret format. Only needed for RSA keys (set explicitly to
BinanceKeyType.RSA).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 API client custom endpoint override.
base_url_ws_stream (str, optional) – The WebSocket stream custom endpoint override for futures user data event delivery. Only applicable to futures account types. When
None, derived from the environment.proxy_url (str, optional) – The proxy URL for HTTP requests.
environment (BinanceEnvironment, optional) – The Binance environment (LIVE, TESTNET, or DEMO). Defaults to LIVE.
us (bool, default False) – If client is connecting to Binance US.
testnet (bool, default False) – Deprecated: use
environmentinstead.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.
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.
- api_key: str | None¶
- api_secret: str | None¶
- key_type: BinanceKeyType¶
- account_type: BinanceAccountType¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- base_url_ws_stream: str | None¶
- proxy_url: str | None¶
- environment: BinanceEnvironment | 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¶
- 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
References
- 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:
InstrumentProviderProvides 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) 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) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- 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_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.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- 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.
- 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.
- 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.
- class BinanceFuturesMarkPriceUpdate¶
Bases:
DataRepresents 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.
- 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]) BinanceFuturesMarkPriceUpdate¶
Return a Binance Futures mark price update parsed from the given values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- static to_dict(obj: BinanceFuturesMarkPriceUpdate) dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- 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
- class BinanceInstrumentProviderConfig¶
Bases:
InstrumentProviderConfigConfiguration for
BinanceInstrumentProviderinstances.- Parameters:
load_all (bool, default False) – If all venue instruments should be loaded on start.
load_ids (frozenset[InstrumentId], optional) – The list of instrument IDs to be loaded on start (if load_all is False).
filters (frozendict or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
filter_callable (str, optional) – A fully qualified path to a callable that takes a single argument, instrument and returns a bool, indicating whether the instrument should be loaded
log_warnings (bool, default True) – If parser warnings should be logged.
query_commission_rates (bool, default False) – If commission rates should be queried per symbol from the exchange. When False, uses venue fee tier tables as fallback. Recommended for market maker accounts with negative maker fees.
- query_commission_rates: bool¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- filter_callable: str | None¶
- filters: dict[str, Any] | None¶
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- 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]
- load_all: bool¶
- load_ids: frozenset[InstrumentId] | None¶
- log_warnings: bool¶
- 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
- use_gamma_markets: bool¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BinanceKeyType¶
Bases:
EnumRepresents a Binance private key cryptographic algorithm type.
- HMAC = 'HMAC'¶
- RSA = 'RSA'¶
- ED25519 = 'Ed25519'¶
- class BinanceLiveDataClientFactory¶
Bases:
LiveDataClientFactoryProvides 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:
- Raises:
ValueError – If config.account_type is not a valid BinanceAccountType.
- class BinanceLiveExecClientFactory¶
Bases:
LiveExecClientFactoryProvides 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:
objectProvides 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_sides(side: str) str¶
- classmethod map_flags(row: Series) int¶
- class BinanceSpotInstrumentProvider¶
Bases:
InstrumentProviderProvides 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.
environment (BinanceEnvironment, default LIVE) – The Binance environment.
config (InstrumentProviderConfig, optional) – The configuration for the provider.
- async load_all_async(filters: dict | None = 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) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- 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_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.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- 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.
- 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.
- 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.
- 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, environment: BinanceEnvironment = BinanceEnvironment.LIVE, is_us: bool = False, proxy_url: str | None = None) 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. If
None, the client will work for public market data only.api_secret (str, optional) – The API secret for the client. If
None, the client will work for public market data only.key_type (BinanceKeyType, default 'HMAC') – The private key cryptographic algorithm type.
base_url (str, optional) – The base URL for the API endpoints.
environment (BinanceEnvironment, default LIVE) – The Binance environment.
is_us (bool, default False) – If the client is connecting to Binance US.
proxy_url (str, optional) – The proxy URL for HTTP requests.
- Return type:
BinanceHttpClient
Config¶
- class BinanceInstrumentProviderConfig¶
Bases:
InstrumentProviderConfigConfiguration for
BinanceInstrumentProviderinstances.- Parameters:
load_all (bool, default False) – If all venue instruments should be loaded on start.
load_ids (frozenset[InstrumentId], optional) – The list of instrument IDs to be loaded on start (if load_all is False).
filters (frozendict or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
filter_callable (str, optional) – A fully qualified path to a callable that takes a single argument, instrument and returns a bool, indicating whether the instrument should be loaded
log_warnings (bool, default True) – If parser warnings should be logged.
query_commission_rates (bool, default False) – If commission rates should be queried per symbol from the exchange. When False, uses venue fee tier tables as fallback. Recommended for market maker accounts with negative maker fees.
- query_commission_rates: bool¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- filter_callable: str | None¶
- filters: dict[str, Any] | None¶
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- 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]
- load_all: bool¶
- load_ids: frozenset[InstrumentId] | None¶
- log_warnings: bool¶
- 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
- use_gamma_markets: bool¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BinanceDataClientConfig¶
Bases:
LiveDataClientConfigConfiguration for
BinanceDataClientinstances.- Parameters:
venue (Venue, default BINANCE_VENUE) – The venue for the client.
api_key (str, optional) – The Binance API public key. If
None, the client will work for public market data only. Providing an API key may improve rate limits.api_secret (str, optional) – The Binance API secret key. If
None, the client will work for public market data only.key_type (BinanceKeyType, default 'HMAC') – Deprecated: key type is now auto-detected from the api_secret format. Only needed for RSA keys (set explicitly to
BinanceKeyType.RSA).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.
proxy_url (str, optional) – The proxy URL for HTTP requests.
environment (BinanceEnvironment, optional) – The Binance environment (LIVE, TESTNET, or DEMO). Defaults to LIVE.
us (bool, default False) – If client is connecting to Binance US.
testnet (bool, default False) – Deprecated: use
environmentinstead.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.
- api_key: str | None¶
- api_secret: str | None¶
- key_type: BinanceKeyType¶
- account_type: BinanceAccountType¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- proxy_url: str | None¶
- environment: BinanceEnvironment | 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
References
- 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:
LiveExecClientConfigConfiguration for
BinanceExecutionClientinstances.- Parameters:
venue (Venue, default BINANCE_VENUE) – The venue for the client.
api_key (str, optional) – The Binance API public key. If
Nonethen will source from BINANCE_API_KEY (or testnet equivalent).api_secret (str, optional) – The Binance API secret key. If
Nonethen will source from BINANCE_API_SECRET (or testnet equivalent).key_type (BinanceKeyType, default 'HMAC') – Deprecated: key type is now auto-detected from the api_secret format. Only needed for RSA keys (set explicitly to
BinanceKeyType.RSA).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 API client custom endpoint override.
base_url_ws_stream (str, optional) – The WebSocket stream custom endpoint override for futures user data event delivery. Only applicable to futures account types. When
None, derived from the environment.proxy_url (str, optional) – The proxy URL for HTTP requests.
environment (BinanceEnvironment, optional) – The Binance environment (LIVE, TESTNET, or DEMO). Defaults to LIVE.
us (bool, default False) – If client is connecting to Binance US.
testnet (bool, default False) – Deprecated: use
environmentinstead.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.
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.
- api_key: str | None¶
- api_secret: str | None¶
- key_type: BinanceKeyType¶
- account_type: BinanceAccountType¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- base_url_ws_stream: str | None¶
- proxy_url: str | None¶
- environment: BinanceEnvironment | 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¶
- 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
References
- 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, environment: BinanceEnvironment = BinanceEnvironment.LIVE, is_us: bool = False, proxy_url: str | None = None) 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. If
None, the client will work for public market data only.api_secret (str, optional) – The API secret for the client. If
None, the client will work for public market data only.key_type (BinanceKeyType, default 'HMAC') – The private key cryptographic algorithm type.
base_url (str, optional) – The base URL for the API endpoints.
environment (BinanceEnvironment, default LIVE) – The Binance environment.
is_us (bool, default False) – If the client is connecting to Binance US.
proxy_url (str, optional) – The proxy URL for HTTP requests.
- Return type:
BinanceHttpClient
- get_cached_binance_spot_instrument_provider(client: BinanceHttpClient, clock: LiveClock, account_type: BinanceAccountType, environment: BinanceEnvironment, 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.
environment (BinanceEnvironment) – The Binance environment.
config (InstrumentProviderConfig) – The configuration for the instrument provider.
venue (Venue) – The venue for the instrument provider.
- Return type:
- get_cached_binance_futures_instrument_provider(client: BinanceHttpClient, clock: LiveClock, account_type: BinanceAccountType, config: InstrumentProviderConfig | BinanceInstrumentProviderConfig, 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 | BinanceInstrumentProviderConfig) – The configuration for the instrument provider.
venue (Venue) – The venue for the instrument provider.
- Return type:
- class BinanceLiveDataClientFactory¶
Bases:
LiveDataClientFactoryProvides 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:
- Raises:
ValueError – If config.account_type is not a valid BinanceAccountType.
- class BinanceLiveExecClientFactory¶
Bases:
LiveExecClientFactoryProvides 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.
References
https://binance-docs.github.io/apidocs/spot/en/#public-api-definitions https://binance-docs.github.io/apidocs/futures/en/#public-endpoints-info
- class BinanceKeyType¶
Bases:
EnumRepresents a Binance private key cryptographic algorithm type.
- HMAC = 'HMAC'¶
- RSA = 'RSA'¶
- ED25519 = 'Ed25519'¶
- class BinanceEnvironment¶
Bases:
EnumRepresents a Binance trading environment.
- LIVE = 'LIVE'¶
- TESTNET = 'TESTNET'¶
- DEMO = 'DEMO'¶
- property is_live: bool¶
- property is_sandbox: bool¶
True for any non-production environment (testnet or demo).
- class BinanceFuturesPositionSide¶
Bases:
EnumRepresents a Binance Futures position side.
- BOTH = 'BOTH'¶
- LONG = 'LONG'¶
- SHORT = 'SHORT'¶
- class BinanceRateLimitType¶
Bases:
EnumRepresents a Binance rate limit type.
- REQUEST_WEIGHT = 'REQUEST_WEIGHT'¶
- ORDERS = 'ORDERS'¶
- RAW_REQUESTS = 'RAW_REQUESTS'¶
- class BinanceRateLimitInterval¶
Bases:
EnumRepresents a Binance rate limit interval.
- SECOND = 'SECOND'¶
- MINUTE = 'MINUTE'¶
- DAY = 'DAY'¶
- class BinanceKlineInterval¶
Bases:
EnumRepresents 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:
EnumRepresents 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:
EnumRepresents 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_NUM_ORDER_LISTS = 'MAX_NUM_ORDER_LISTS'¶
- MAX_NUM_ORDER_AMENDS = 'MAX_NUM_ORDER_AMENDS'¶
- MAX_POSITION = 'MAX_POSITION'¶
- TRAILING_DELTA = 'TRAILING_DELTA'¶
- POSITION_RISK_CONTROL = 'POSITION_RISK_CONTROL'¶
- class BinanceAccountType¶
Bases:
EnumRepresents a Binance account type.
- SPOT = 'SPOT'¶
- MARGIN = 'MARGIN'¶
- ISOLATED_MARGIN = 'ISOLATED_MARGIN'¶
- USDT_FUTURES = 'USDT_FUTURES'¶
- COIN_FUTURES = 'COIN_FUTURES'¶
- property is_spot¶
- property is_margin¶
- property is_spot_or_margin¶
- property is_futures: bool¶
- class BinanceExecutionType¶
Bases:
EnumRepresents 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:
EnumRepresents 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'¶
- TRIGGERING = 'TRIGGERING'¶
- TRIGGERED = 'TRIGGERED'¶
- FINISHED = 'FINISHED'¶
- class BinanceTimeInForce¶
Bases:
EnumRepresents a Binance order time in force.
- GTC = 'GTC'¶
- IOC = 'IOC'¶
- FOK = 'FOK'¶
- GTX = 'GTX'¶
- GTD = 'GTD'¶
- GTE_GTC = 'GTE_GTC'¶
- class BinanceOrderType¶
Bases:
EnumRepresents 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'¶
- LIQUIDATION = 'LIQUIDATION'¶
- ADL = 'ADL'¶
- INSURANCE_FUND = 'INSURANCE_FUND'¶
- class BinanceSecurityType¶
Bases:
EnumRepresents 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:
EnumRepresents a Binance newOrderRespType.
- ACK = 'ACK'¶
- RESULT = 'RESULT'¶
- FULL = 'FULL'¶
- class BinanceErrorCode¶
Bases:
EnumRepresents 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¶
- ORDER_AMEND_KEEP_PRIORITY_FAILED = -2038¶
- ORDER_QUERY_DUAL_ID_NOT_FOUND = -2039¶
- 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¶
- INVALID_PEG_OFFSET_TYPE = 1211¶
- STOP_ORDER_SWITCH_ALGO = -4120¶
- 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:
objectProvides common parsing methods for enums used by the ‘Binance’ exchange.
Warning
This class should not be used directly, but through a concrete subclass.
- parse_binance_order_side(order_side: BinanceOrderSide) OrderSide¶
- parse_internal_order_side(order_side: OrderSide) BinanceOrderSide¶
- parse_binance_time_in_force(time_in_force: BinanceTimeInForce) TimeInForce¶
- parse_internal_time_in_force(time_in_force: TimeInForce) BinanceTimeInForce¶
- parse_binance_order_status(order_status: BinanceOrderStatus) OrderStatus¶
- parse_binance_order_type(order_type: BinanceOrderType) OrderType¶
- parse_internal_order_type(order: Order) BinanceOrderType¶
- parse_binance_bar_agg(bar_agg: str) BarAggregation¶
- parse_nautilus_bar_aggregation(bar_agg: BarAggregation) str¶
- parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval) BarSpecification¶
- parse_binance_trigger_type(trigger_type: str) TriggerType¶
- parse_position_id_to_binance_futures_position_side(position_id: PositionId) BinanceFuturesPositionSide¶
Types¶
- class BinanceBar¶
Bases:
BarRepresents 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.
References
https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-data https://binance-docs.github.io/apidocs/futures/en/#kline-candlestick-data
- static from_dict(values: dict[str, Any]) BinanceBar¶
Return a Binance bar parsed from the given values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- static to_dict(obj: BinanceBar) dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- bar_type¶
BarType
Return the bar type of bar.
- Return type:
- Type:
- static from_pyo3(pyo3_bar) Bar¶
Return a legacy Cython bar converted from the given pyo3 Rust object.
- Parameters:
pyo3_bar (nautilus_pyo3.Bar) – The pyo3 Rust bar to convert from.
- Return type:
- static from_pyo3_list(list pyo3_bars) list[Bar]¶
Return legacy Cython bars converted from the given pyo3 Rust objects.
- Parameters:
pyo3_bars (list[nautilus_pyo3.Bar]) – The pyo3 Rust bars to convert from.
- Return type:
list[Bar]
- static from_raw(BarType bar_type, PriceRaw open, PriceRaw high, PriceRaw low, PriceRaw close, uint8_t price_prec, QuantityRaw volume, uint8_t size_prec, uint64_t ts_event, uint64_t ts_init) Bar¶
Create a bar from raw fixed-point values.
Warning
This method is primarily for internal use. Most users should use
from_dict()or other higher-level construction methods instead.All raw price/size values must be valid multiples of the scale factor for the given precision. Invalid raw values will raise a
ValueError. See: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values
- static from_raw_arrays_to_list(BarType bar_type, uint8_t price_prec, uint8_t size_prec, double[: ] opens, double[: ] highs, double[: ] lows, double[: ] closes, double[: ] volumes, uint64_t[: ] ts_events, uint64_t[: ] ts_inits) list[Bar]¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- is_revision¶
If this bar is a revision for a previous bar with the same ts_event.
- Returns:
bool
- 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
- is_single_price(self) bool¶
If the OHLC are all equal to a single price.
- Return type:
bool
- to_pyo3(self) nautilus_pyo3.Bar¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.Bar
- static to_pyo3_list(list bars) list[nautilus_pyo3.Bar]¶
Return pyo3 Rust bars converted from the given legacy Cython objects.
- Parameters:
bars (list[Bar]) – The legacy Cython bars to convert from.
- Return type:
list[nautilus_pyo3.Bar]
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- volume¶
Quantity
Return the volume of the bar.
- Return type:
- Type:
- class BinanceTicker¶
Bases:
DataRepresents 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.
References
https://binance-docs.github.io/apidocs/spot/en/#24hr-ticker-price-change-statistics https://binance-docs.github.io/apidocs/futures/en/#24hr-ticker-price-change-statistics
- property ts_event: int¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- property ts_init: int¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- static from_dict(values: dict[str, Any]) BinanceTicker¶
Return a Binance Spot/Margin ticker parsed from the given values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- static to_dict(obj: BinanceTicker) dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- 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
Futures¶
Data¶
- class BinanceFuturesDataClient¶
Bases:
BinanceCommonDataClientProvides 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_FUTURES') – The account type for the client.
name (str, optional) – The custom client ID.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task | None¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (LogColor, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- 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:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- request(self, RequestData request) void¶
Request data for the given data type.
- Parameters:
request (RequestData) – The message for the data request.
- request_bars(self, RequestBars request) void¶
Request historical Bar data. To load historical data from a catalog, you can pass a list[DataCatalogConfig] to the TradingNodeConfig or the BacktestEngineConfig.
- Parameters:
request (RequestBars) – The message for the data request.
- request_funding_rates(self, RequestFundingRates request) void¶
Request historical FundingRateUpdate data.
- Parameters:
request (RequestFundingRates) – The message for the data request.
- request_instrument(self, RequestInstrument request) void¶
Request Instrument data for the given instrument ID.
- Parameters:
request (RequestInstrument) – The message for the data request.
- request_instruments(self, RequestInstruments request) void¶
Request all Instrument data for the given venue.
- Parameters:
request (RequestInstruments) – The message for the data request.
- request_order_book_deltas(self, RequestOrderBookDeltas request) void¶
Request historical OrderBookDeltas data.
- Parameters:
request (RequestOrderBookDeltas) – The message for the data request.
- request_order_book_depth(request: RequestOrderBookDepth) None¶
- request_order_book_snapshot(self, RequestOrderBookSnapshot request) void¶
Request order book snapshot data.
- Parameters:
request (RequestOrderBookSnapshot) – The message for the data request.
- request_quote_ticks(self, RequestQuoteTicks request) void¶
Request historical QuoteTick data.
- Parameters:
request (RequestQuoteTicks) – The message for the data request.
- request_trade_ticks(self, RequestTradeTicks request) void¶
Request historical TradeTick data.
- Parameters:
request (RequestTradeTicks) – The message for the data request.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.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) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.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) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.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:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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, SubscribeData command) void¶
Subscribe to data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_bars(self, SubscribeBars command) void¶
Subscribe to Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_funding_rates(self, SubscribeFundingRates command) void¶
Subscribe to FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_index_prices(self, SubscribeIndexPrices command) void¶
Subscribe to IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument(self, SubscribeInstrument command) void¶
Subscribe to the Instrument with the given instrument ID.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_close(self, SubscribeInstrumentClose command) void¶
Subscribe to InstrumentClose updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_status(self, SubscribeInstrumentStatus command) void¶
Subscribe to InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instruments(self, SubscribeInstruments command) void¶
Subscribe to all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_mark_prices(self, SubscribeMarkPrices command) void¶
Subscribe to MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_deltas(self, SubscribeOrderBook command) void¶
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.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_depth(self, SubscribeOrderBook command) void¶
Subscribe to OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
depth (int, optional) – The maximum depth for the order book (defaults to 10).
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_quote_ticks(self, SubscribeQuoteTicks command) void¶
Subscribe to QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_trade_ticks(self, SubscribeTradeTicks command) void¶
Subscribe to TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribed_custom_data(self) list¶
Return the custom data types subscribed to.
- Return type:
list[DataType]
- subscribed_funding_rates(self) list¶
Return the funding rate update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_index_prices(self) list¶
Return the index price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_close(self) list¶
Return the instrument closes subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_status(self) list¶
Return the status update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instruments(self) list¶
Return the instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_mark_prices(self) list¶
Return the mark price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_deltas(self) list¶
Return the order book delta instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_depth(self) list¶
Return the order book depth instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_quote_ticks(self) list¶
Return the quote tick instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_trade_ticks(self) list¶
Return the trade tick instruments subscribed to.
- Return type:
list[InstrumentId]
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- unsubscribe(self, UnsubscribeData command) void¶
Unsubscribe from data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_bars(self, UnsubscribeBars command) void¶
Unsubscribe from Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_funding_rates(self, UnsubscribeFundingRates command) void¶
Unsubscribe from FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_index_prices(self, UnsubscribeIndexPrices command) void¶
Unsubscribe from IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument(self, UnsubscribeInstrument command) void¶
Unsubscribe from Instrument data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_close(self, UnsubscribeInstrumentClose command) void¶
Unsubscribe from InstrumentClose data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_status(self, UnsubscribeInstrumentStatus command) void¶
Unsubscribe from InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instruments(self, UnsubscribeInstruments command) void¶
Unsubscribe from all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_mark_prices(self, UnsubscribeMarkPrices command) void¶
Unsubscribe from MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_deltas(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDeltas data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_depth(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_quote_ticks(self, UnsubscribeQuoteTicks command) void¶
Unsubscribe from QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_trade_ticks(self, UnsubscribeTradeTicks command) void¶
Unsubscribe from TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- venue¶
The clients venue ID (if applicable).
- Returns:
Venue or
None
Enums¶
Defines Binance Futures specific enums.
- class BinanceFuturesContractType¶
Bases:
EnumRepresents 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'¶
- TRADIFI_PERPETUAL = 'TRADIFI_PERPETUAL'¶
- class BinanceFuturesContractStatus¶
Bases:
EnumRepresents a Binance Futures contract status.
- PENDING_TRADING = 'PENDING_TRADING'¶
- TRADING = 'TRADING'¶
- PRE_DELIVERING = 'PRE_DELIVERING'¶
- DELIVERING = 'DELIVERING'¶
- DELIVERED = 'DELIVERED'¶
- PRE_SETTLE = 'PRE_SETTLE'¶
- SETTLING = 'SETTLING'¶
- CLOSE = 'CLOSE'¶
- class BinanceFuturesWorkingType¶
Bases:
EnumRepresents a Binance Futures working type.
- MARK_PRICE = 'MARK_PRICE'¶
- CONTRACT_PRICE = 'CONTRACT_PRICE'¶
- class BinanceFuturesMarginType¶
Bases:
EnumRepresents a Binance Futures margin type.
- ISOLATED = 'ISOLATED'¶
- CROSS = 'CROSSED'¶
- class BinanceFuturesPositionUpdateReason¶
Bases:
EnumRepresents 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:
EnumRepresents a Binance Futures event type.
- LISTEN_KEY_EXPIRED = 'listenKeyExpired'¶
- MARGIN_CALL = 'MARGIN_CALL'¶
- ACCOUNT_UPDATE = 'ACCOUNT_UPDATE'¶
- ORDER_TRADE_UPDATE = 'ORDER_TRADE_UPDATE'¶
- ACCOUNT_CONFIG_UPDATE = 'ACCOUNT_CONFIG_UPDATE'¶
- TRADE_LITE = 'TRADE_LITE'¶
- STRATEGY_UPDATE = 'STRATEGY_UPDATE'¶
- GRID_UPDATE = 'GRID_UPDATE'¶
- CONDITIONAL_ORDER_TRIGGER_REJECT = 'CONDITIONAL_ORDER_TRIGGER_REJECT'¶
- ALGO_UPDATE = 'ALGO_UPDATE'¶
- class BinanceFuturesEnumParser¶
Bases:
BinanceEnumParserProvides parsing methods for enums used by the ‘Binance Futures’ exchange.
- parse_binance_order_type(order_type: BinanceOrderType) OrderType¶
- parse_internal_order_type(order: Order) BinanceOrderType¶
- parse_binance_trigger_type(trigger_type: str) TriggerType¶
- parse_futures_position_side(net_size: Decimal) PositionSide¶
- parse_binance_bar_agg(bar_agg: str) BarAggregation¶
- parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval) BarSpecification¶
- parse_binance_order_side(order_side: BinanceOrderSide) OrderSide¶
- parse_binance_order_status(order_status: BinanceOrderStatus) OrderStatus¶
- parse_binance_time_in_force(time_in_force: BinanceTimeInForce) TimeInForce¶
- parse_internal_order_side(order_side: OrderSide) BinanceOrderSide¶
- parse_internal_time_in_force(time_in_force: TimeInForce) BinanceTimeInForce¶
- parse_nautilus_bar_aggregation(bar_agg: BarAggregation) str¶
- parse_position_id_to_binance_futures_position_side(position_id: PositionId) BinanceFuturesPositionSide¶
Execution¶
- class BinanceFuturesExecutionClient¶
Bases:
BinanceCommonExecutionClientProvides 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 (unused, kept for backward compatibility).
config (BinanceExecClientConfig) – The configuration for the client.
account_type (BinanceAccountType, default 'USDT_FUTURES') – The account type for the client.
name (str, optional) – The custom client ID.
environment (BinanceEnvironment) – The resolved Binance environment.
api_key (str) – The Binance API key.
api_secret (str) – The Binance API secret.
- async generate_order_status_report(command: GenerateOrderStatusReport) OrderStatusReport | None¶
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns
None.- Parameters:
command (GenerateOrderStatusReport) – The command to generate 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(command: GenerateOrderStatusReports) list[OrderStatusReport]¶
Generate a list of `OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
- Parameters:
command (GenerateOrderStatusReports) – The command for generating the reports.
- Return type:
list[OrderStatusReport]
- 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) void¶
Batch cancel orders for the instrument ID contained in the given command.
- Parameters:
command (BatchCancelOrders) – The command to execute.
- cancel_all_orders(self, CancelAllOrders command) void¶
Cancel all orders for the instrument ID contained in the given command.
- Parameters:
command (CancelAllOrders) – The command to execute.
- cancel_order(self, CancelOrder command) void¶
Cancel the order with the client order ID contained in the given command.
- Parameters:
command (CancelOrder) – The command to execute.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (str, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None) void¶
Generate an AccountState event and publish on the message bus.
- Parameters:
balances (list[AccountBalance]) – The account balances.
margins (list[MarginBalance]) – The margin balances.
reported (bool) – If the balances are reported directly from the exchange.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account state event occurred.
info (dict [str, object]) – The additional implementation specific account information.
- async generate_fill_reports(command: GenerateFillReports) list[FillReport]¶
Generate a list of `FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
- Parameters:
command (GenerateFillReports) – The command for generating the reports.
- Return type:
list[FillReport]
- async generate_mass_status(lookback_mins: int | None = None) ExecutionMassStatus | None¶
Generate an ExecutionMassStatus report.
- Parameters:
lookback_mins (int, optional) – The maximum lookback for querying closed orders, trades and positions.
- 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) void¶
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, str reason, uint64_t ts_event) void¶
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) void¶
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_denied(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderDenied 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 (str) – The order denied reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order denied event occurred.
- generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
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, dict info=None) void¶
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 or
None) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise passNoneand 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.
info (dict[str, object], optional) – The additional fill information.
- generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
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, str reason, uint64_t ts_event, bool due_post_only=False) void¶
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.
due_post_only (bool, default False) – If the order was rejected because it was post-only and would execute immediately as a taker.
- generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event) void¶
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) void¶
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) void¶
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 or
None) – 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(command: GeneratePositionStatusReports) list[PositionStatusReport]¶
Generate a list of `PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
- Parameters:
command (GeneratePositionStatusReports) – The command for generating the position status reports.
- Return type:
list[PositionStatusReport]
- get_account(self) Account¶
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:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- modify_order(self, ModifyOrder command) void¶
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_account(self, QueryAccount command) void¶
Query the account specified by the command which will generate an AccountState event.
- Parameters:
command (QueryAccount) – The command to execute.
- query_order(self, QueryOrder command) void¶
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
- Parameters:
command (QueryOrder) – The command to execute.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.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) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.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) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.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:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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) void¶
Submit the order contained in the given command for execution.
- Parameters:
command (SubmitOrder) – The command to execute.
- submit_order_list(self, SubmitOrderList command) void¶
Submit the order list contained in the given command for execution.
- Parameters:
command (SubmitOrderList) – The command to execute.
- 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:
InstrumentProviderProvides 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) 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) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- 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_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.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- 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.
- 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.
- 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.
Types¶
- class BinanceFuturesMarkPriceUpdate¶
Bases:
DataRepresents 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.
- 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]) BinanceFuturesMarkPriceUpdate¶
Return a Binance Futures mark price update parsed from the given values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- static to_dict(obj: BinanceFuturesMarkPriceUpdate) dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- 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
Spot¶
Data¶
- class BinanceSpotDataClient¶
Bases:
BinanceCommonDataClientProvides 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.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task | None¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (LogColor, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- 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:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- request(self, RequestData request) void¶
Request data for the given data type.
- Parameters:
request (RequestData) – The message for the data request.
- request_bars(self, RequestBars request) void¶
Request historical Bar data. To load historical data from a catalog, you can pass a list[DataCatalogConfig] to the TradingNodeConfig or the BacktestEngineConfig.
- Parameters:
request (RequestBars) – The message for the data request.
- request_funding_rates(self, RequestFundingRates request) void¶
Request historical FundingRateUpdate data.
- Parameters:
request (RequestFundingRates) – The message for the data request.
- request_instrument(self, RequestInstrument request) void¶
Request Instrument data for the given instrument ID.
- Parameters:
request (RequestInstrument) – The message for the data request.
- request_instruments(self, RequestInstruments request) void¶
Request all Instrument data for the given venue.
- Parameters:
request (RequestInstruments) – The message for the data request.
- request_order_book_deltas(self, RequestOrderBookDeltas request) void¶
Request historical OrderBookDeltas data.
- Parameters:
request (RequestOrderBookDeltas) – The message for the data request.
- request_order_book_depth(request: RequestOrderBookDepth) None¶
- request_order_book_snapshot(self, RequestOrderBookSnapshot request) void¶
Request order book snapshot data.
- Parameters:
request (RequestOrderBookSnapshot) – The message for the data request.
- request_quote_ticks(self, RequestQuoteTicks request) void¶
Request historical QuoteTick data.
- Parameters:
request (RequestQuoteTicks) – The message for the data request.
- request_trade_ticks(self, RequestTradeTicks request) void¶
Request historical TradeTick data.
- Parameters:
request (RequestTradeTicks) – The message for the data request.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.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) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.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) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.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:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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, SubscribeData command) void¶
Subscribe to data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_bars(self, SubscribeBars command) void¶
Subscribe to Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_funding_rates(self, SubscribeFundingRates command) void¶
Subscribe to FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_index_prices(self, SubscribeIndexPrices command) void¶
Subscribe to IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument(self, SubscribeInstrument command) void¶
Subscribe to the Instrument with the given instrument ID.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_close(self, SubscribeInstrumentClose command) void¶
Subscribe to InstrumentClose updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_status(self, SubscribeInstrumentStatus command) void¶
Subscribe to InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instruments(self, SubscribeInstruments command) void¶
Subscribe to all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_mark_prices(self, SubscribeMarkPrices command) void¶
Subscribe to MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_deltas(self, SubscribeOrderBook command) void¶
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.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_depth(self, SubscribeOrderBook command) void¶
Subscribe to OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
depth (int, optional) – The maximum depth for the order book (defaults to 10).
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_quote_ticks(self, SubscribeQuoteTicks command) void¶
Subscribe to QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_trade_ticks(self, SubscribeTradeTicks command) void¶
Subscribe to TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribed_custom_data(self) list¶
Return the custom data types subscribed to.
- Return type:
list[DataType]
- subscribed_funding_rates(self) list¶
Return the funding rate update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_index_prices(self) list¶
Return the index price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_close(self) list¶
Return the instrument closes subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_status(self) list¶
Return the status update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instruments(self) list¶
Return the instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_mark_prices(self) list¶
Return the mark price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_deltas(self) list¶
Return the order book delta instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_depth(self) list¶
Return the order book depth instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_quote_ticks(self) list¶
Return the quote tick instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_trade_ticks(self) list¶
Return the trade tick instruments subscribed to.
- Return type:
list[InstrumentId]
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- unsubscribe(self, UnsubscribeData command) void¶
Unsubscribe from data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_bars(self, UnsubscribeBars command) void¶
Unsubscribe from Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_funding_rates(self, UnsubscribeFundingRates command) void¶
Unsubscribe from FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_index_prices(self, UnsubscribeIndexPrices command) void¶
Unsubscribe from IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument(self, UnsubscribeInstrument command) void¶
Unsubscribe from Instrument data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_close(self, UnsubscribeInstrumentClose command) void¶
Unsubscribe from InstrumentClose data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_status(self, UnsubscribeInstrumentStatus command) void¶
Unsubscribe from InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instruments(self, UnsubscribeInstruments command) void¶
Unsubscribe from all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_mark_prices(self, UnsubscribeMarkPrices command) void¶
Unsubscribe from MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_deltas(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDeltas data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_depth(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_quote_ticks(self, UnsubscribeQuoteTicks command) void¶
Unsubscribe from QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_trade_ticks(self, UnsubscribeTradeTicks command) void¶
Unsubscribe from TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- venue¶
The clients venue ID (if applicable).
- Returns:
Venue or
None
Enums¶
Defines Binance Spot/Margin specific enums.
- class BinanceSpotPermissions¶
Bases:
EnumRepresents 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:
EnumRepresents 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:
EnumRepresents a Binance Spot/Margin event type.
- outboundAccountPosition = 'outboundAccountPosition'¶
- balanceUpdate = 'balanceUpdate'¶
- executionReport = 'executionReport'¶
- listStatus = 'listStatus'¶
- listenKeyExpired = 'listenKeyExpired'¶
- class BinanceSpotEnumParser¶
Bases:
BinanceEnumParserProvides parsing methods for enums used by the ‘Binance Spot/Margin’ exchange.
- parse_binance_order_type(order_type: BinanceOrderType) OrderType¶
- parse_internal_order_type(order: Order) BinanceOrderType¶
- parse_binance_bar_agg(bar_agg: str) BarAggregation¶
- parse_binance_kline_interval_to_bar_spec(kline_interval: BinanceKlineInterval) BarSpecification¶
- parse_binance_order_side(order_side: BinanceOrderSide) OrderSide¶
- parse_binance_order_status(order_status: BinanceOrderStatus) OrderStatus¶
- parse_binance_time_in_force(time_in_force: BinanceTimeInForce) TimeInForce¶
- parse_binance_trigger_type(trigger_type: str) TriggerType¶
- parse_internal_order_side(order_side: OrderSide) BinanceOrderSide¶
- parse_internal_time_in_force(time_in_force: TimeInForce) BinanceTimeInForce¶
- parse_nautilus_bar_aggregation(bar_agg: BarAggregation) str¶
- parse_position_id_to_binance_futures_position_side(position_id: PositionId) BinanceFuturesPositionSide¶
Execution¶
- class BinanceSpotExecutionClient¶
Bases:
BinanceCommonExecutionClientProvides 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 (unused, kept for backward compatibility).
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.
environment (BinanceEnvironment) – The resolved Binance environment.
api_key (str) – The Binance API key.
api_secret (str) – The Binance API secret.
- 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) void¶
Batch cancel orders for the instrument ID contained in the given command.
- Parameters:
command (BatchCancelOrders) – The command to execute.
- cancel_all_orders(self, CancelAllOrders command) void¶
Cancel all orders for the instrument ID contained in the given command.
- Parameters:
command (CancelAllOrders) – The command to execute.
- cancel_order(self, CancelOrder command) void¶
Cancel the order with the client order ID contained in the given command.
- Parameters:
command (CancelOrder) – The command to execute.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (str, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None) void¶
Generate an AccountState event and publish on the message bus.
- Parameters:
balances (list[AccountBalance]) – The account balances.
margins (list[MarginBalance]) – The margin balances.
reported (bool) – If the balances are reported directly from the exchange.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account state event occurred.
info (dict [str, object]) – The additional implementation specific account information.
- async generate_fill_reports(command: GenerateFillReports) list[FillReport]¶
Generate a list of `FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
- Parameters:
command (GenerateFillReports) – The command for generating the reports.
- Return type:
list[FillReport]
- async generate_mass_status(lookback_mins: int | None = None) ExecutionMassStatus | None¶
Generate an ExecutionMassStatus report.
- Parameters:
lookback_mins (int, optional) – The maximum lookback for querying closed orders, trades and positions.
- 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) void¶
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, str reason, uint64_t ts_event) void¶
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) void¶
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_denied(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderDenied 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 (str) – The order denied reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order denied event occurred.
- generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
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, dict info=None) void¶
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 or
None) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise passNoneand 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.
info (dict[str, object], optional) – The additional fill information.
- generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
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, str reason, uint64_t ts_event, bool due_post_only=False) void¶
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.
due_post_only (bool, default False) – If the order was rejected because it was post-only and would execute immediately as a taker.
- async generate_order_status_report(command: GenerateOrderStatusReport) OrderStatusReport | None¶
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns
None.- Parameters:
command (GenerateOrderStatusReport) – The command to generate 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(command: GenerateOrderStatusReports) list[OrderStatusReport]¶
Generate a list of `OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
- Parameters:
command (GenerateOrderStatusReports) – The command for generating the reports.
- Return type:
list[OrderStatusReport]
- generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event) void¶
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) void¶
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) void¶
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 or
None) – 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(command: GeneratePositionStatusReports) list[PositionStatusReport]¶
Generate a list of `PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
- Parameters:
command (GeneratePositionStatusReports) – The command for generating the position status reports.
- Return type:
list[PositionStatusReport]
- get_account(self) Account¶
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:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- modify_order(self, ModifyOrder command) void¶
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_account(self, QueryAccount command) void¶
Query the account specified by the command which will generate an AccountState event.
- Parameters:
command (QueryAccount) – The command to execute.
- query_order(self, QueryOrder command) void¶
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
- Parameters:
command (QueryOrder) – The command to execute.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.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) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.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) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.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:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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) void¶
Submit the order contained in the given command for execution.
- Parameters:
command (SubmitOrder) – The command to execute.
- submit_order_list(self, SubmitOrderList command) void¶
Submit the order list contained in the given command for execution.
- Parameters:
command (SubmitOrderList) – The command to execute.
- 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:
InstrumentProviderProvides 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.
environment (BinanceEnvironment, default LIVE) – The Binance environment.
config (InstrumentProviderConfig, optional) – The configuration for the provider.
- async load_all_async(filters: dict | None = 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) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- 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_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.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- 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.
- 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.
- 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.