Bybit
Bybit 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 Bybit’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
posei_trader.adapters.bybit
.
class BybitDataClientConfig
Bases:
LiveDataClientConfig
Configuration for
BybitDataClient
instances.
-
Parameters:
-
api_key (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_KEY or BYBIT_TESTNET_API_KEY environment variables. -
api_secret (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_SECRET or BYBIT_TESTNET_API_SECRET environment variables. - product_types (list [BybitProductType ] , optional) – The Bybit product type for the client. If not specified then will use all products.
- demo (bool , default False) – If the client is connecting to the Bybit demo API.
- testnet (bool , default False) – If the client is connecting to the Bybit testnet API.
- update_instruments_interval_mins (PositiveInt or None , default 60) – The interval (minutes) between reloading instruments from the venue.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Bybit HTTP requests.
- bars_timestamp_on_close (bool , default True) – If the ts_event timestamp for bars should be on the open or close or the bar. If True, then ts_event will be on the close of the bar.
-
api_key (str
, optional) – The Bybit
API public key. If
api_key : str | None
api_secret : str | None
bars_timestamp_on_close : bool
base_url_http : str | None
demo : bool
product_types : list[BybitProductType] | None
recv_window_ms : PositiveInt
testnet : bool
update_instruments_interval_mins : PositiveInt | None
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
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 BybitExecClientConfig
Bases:
LiveExecClientConfig
Configuration for
BybitExecutionClient
instances.
-
Parameters:
-
api_key (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_KEY or BYBIT_TESTNET_API_KEY environment variables. -
api_secret (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_KEY or BYBIT_TESTNET_API_KEY environment variables. - product_types (list [BybitProductType ] , optional) – The Bybit product type for the client. If None then will default to ‘SPOT’, you also cannot mix ‘SPOT’ with any other product type for execution, and it will use a CASH account type, vs MARGIN for the other derivative products.
- base_url_ws_private (str , optional) – The base URL for the private WebSocket client.
- base_url_ws_trade (str , optional) – The base URL for the trade WebSocket client.
- demo (bool , default False) – If the client is connecting to the Bybit demo API.
- testnet (bool , default False) – If the client is connecting to the Bybit testnet API.
- use_gtd (bool , default False) – If False, then GTD time in force will be remapped to GTC (this is useful if managing GTD orders locally).
- use_ws_execution_fast (bool , default False) – If use fast execution stream.
- use_ws_trade_api (bool , default False) – If the client is using websocket to send order requests.
- use_http_batch_api (bool , default False) – If the client is using http api to send batch order requests. Effective only when use_ws_trade_api is set to True.
- 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.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Bybit HTTP requests.
- ws_trade_timeout_secs (PositiveFloat , default 5.0) – The timeout for trade websocket messages.
- ws_auth_timeout_secs (PositiveFloat , default 5.0) – The timeout for auth websocket messages.
- futures_leverages (dict *[*BybitSymbol , PositiveInt ] , optional) – The leverages for futures.
- position_mode (dict *[*BybitSymbol , BybitPositionMode ] , optional) – The position mode for USDT perpetual and Inverse futures.
- margin_mode (BybitMarginMode , optional) – Set Margin Mode.
-
api_key (str
, optional) – The Bybit
API public key. If
WARNING
A short retry_delay with frequent retries may result in account bans.
api_key : str | None
api_secret : str | None
base_url_http : str | None
base_url_ws_private : str | None
base_url_ws_trade : str | None
demo : bool
futures_leverages : dict[BybitSymbol, PositiveInt] | None
margin_mode : BybitMarginMode | None
max_retries : PositiveInt | None
position_mode : dict[BybitSymbol, BybitPositionMode] | None
product_types : list[BybitProductType] | None
recv_window_ms : PositiveInt
retry_delay_initial_ms : PositiveInt | None
retry_delay_max_ms : PositiveInt | None
testnet : bool
use_gtd : bool
use_http_batch_api : bool
use_ws_execution_fast : bool
use_ws_trade_api : bool
ws_auth_timeout_secs : PositiveFloat | None
ws_trade_timeout_secs : PositiveFloat | None
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod 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 BybitInstrumentProvider
Bases:
InstrumentProvider
Provides Nautilus instrument definitions from Bybit.
-
Parameters:
- client (BybitHttpClient) – The Bybit HTTP client.
- clock (LiveClock) – The clock instance.
- product_types (list [BybitProductType ]) – The product types to load.
- config (InstrumentProviderConfig , optional) – The instrument provider configuration, by default None.
add(instrument: Instrument) → None
Add the given instrument to the provider.
- Parameters: instrument (Instrument) – The instrument to add.
add_bulk(instruments: list[Instrument]) → None
Add the given instruments bulk to the provider.
- Parameters: instruments (list [Instrument ]) – The instruments to add.
add_currency(currency: Currency) → None
Add the given currency to the provider.
- Parameters: currency (Currency) – The currency to add.
property count : int
Return the count of instruments held by the provider.
- Return type: int
currencies() → dict[str, Currency]
Return all currencies held by the instrument provider.
- Return type: dict[str, Currency]
currency(code: str) → Currency | None
Return the currency with the given code (if found).
- Parameters: code (str) – The currency code.
-
Return type: Currency or
None
- Raises: ValueError – If code is not a valid string.
find(instrument_id: InstrumentId) → Instrument | None
Return the instrument for the given instrument ID (if found).
- Parameters: instrument_id (InstrumentId) – The ID for the instrument
-
Return type: Instrument or
None
get_all() → dict[InstrumentId, Instrument]
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type: dict[InstrumentId, Instrument]
async initialize(reload: bool = False) → None
Initialize the instrument provider.
- Parameters: reload (bool , default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
list_all() → list[Instrument]
Return all loaded instruments.
- Return type: list[Instrument]
load(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider, optionally applying the given filters.
-
Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load_all(filters: dict | None = None) → None
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters: filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
async load_all_async(filters: dict | None = None) → None
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
async load_async(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
-
Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If instrument_id.venue is not equal to self.venue.
load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
-
Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
-
Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
class BybitLiveDataClientFactory
Bases: LiveDataClientFactory
Provides a Bybit live data client factory.
static create(loop: asyncio.AbstractEventLoop, name: str, config: BybitDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BybitDataClient
Create a new Bybit data client.
-
Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BybitDataClientConfig) – The client configuration.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the instrument provider.
- Return type: BybitDataClient
class BybitLiveExecClientFactory
Bases: LiveExecClientFactory
Provides a Bybit live execution client factory.
static create(loop: asyncio.AbstractEventLoop, name: str, config: BybitExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BybitExecutionClient
Create a new Bybit execution client.
-
Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BybitExecClientConfig) – 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: BybitExecutionClient
class BybitOrderBookDeltaDataLoader
Bases: object
Provides a means of loading Bybit order book data.
classmethod load(file_path: PathLike[str] | str, nrows: int | None = None, product_type: BybitProductType = BybitProductType.LINEAR) → pd.DataFrame
Return the deltas pandas.DataFrame loaded from the given Zip file_path.
-
Parameters:
- file_path (str , path object or file-like object) – The path to the Zip file.
- nrows (int , optional) – The maximum number of rows to load.
- product_type (BybitProductType , optional) – The product type to load.
- Return type: pd.DataFrame
classmethod map_actions(update_type: str, size: float) → str
classmethod map_flags(update_type: str) → int
classmethod map_sides(side: str) → str
class BybitProductType
Bases: Enum
property is_spot : bool
property is_linear : bool
property is_inverse : bool
property is_option : bool
SPOT = 'spot'
LINEAR = 'linear'
INVERSE = 'inverse'
OPTION = 'option'
class BybitTickerData
Bases:
Data
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the Data class.
- Return type: str
classmethod is_signal(cls, str name='') → bool
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters: name (str , optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns: True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type: bool
ts_event
int UNIX timestamp (nanoseconds) when the data event occurred.
- Return type: int
- Type: Data.ts_event
ts_init
int UNIX timestamp (nanoseconds) when the object was initialized.
- Return type: int
- Type: Data.ts_init
symbol : str
bid1Price : str
bid1Size : str
ask1Price : str
ask1Size : str
lastPrice : str
highPrice24h : str
lowPrice24h : str
turnover24h : str
volume24h : str
get_bybit_http_client(clock: LiveClock, key: str | None = None, secret: str | None = None, base_url: str | None = None, is_demo: bool = False, is_testnet: bool = False, recv_window_ms: int = 5000) → BybitHttpClient
Cache and return a Bybit 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.
- key (str , optional) – The API key for the client.
- secret (str , optional) – The API secret for the client.
- base_url (str , optional) – The base URL for the API endpoints.
- is_demo (bool , default False) – If the client is connecting to the demo API.
- is_testnet (bool , default False) – If the client is connecting to the testnet API.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Bybit HTTP requests.
- Return type: BybitHttpClient
get_bybit_instrument_provider(client: BybitHttpClient, clock: LiveClock, product_types: frozenset[BybitProductType], config: InstrumentProviderConfig) → BybitInstrumentProvider
Cache and return a Bybit instrument provider.
If a cached provider already exists, then that cached provider will be returned.
-
Parameters:
- client (BybitHttpClient) – The client for the instrument provider.
- clock (LiveClock) – The clock for the instrument provider.
- product_types (list [BybitProductType ]) – The product types to load.
- is_testnet (bool) – If the provider is for the Spot testnet.
- config (InstrumentProviderConfig) – The configuration for the instrument provider.
- Return type: BybitInstrumentProvider
Config
class BybitDataClientConfig
Bases:
LiveDataClientConfig
Configuration for
BybitDataClient
instances.
-
Parameters:
-
api_key (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_KEY or BYBIT_TESTNET_API_KEY environment variables. -
api_secret (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_SECRET or BYBIT_TESTNET_API_SECRET environment variables. - product_types (list [BybitProductType ] , optional) – The Bybit product type for the client. If not specified then will use all products.
- demo (bool , default False) – If the client is connecting to the Bybit demo API.
- testnet (bool , default False) – If the client is connecting to the Bybit testnet API.
- update_instruments_interval_mins (PositiveInt or None , default 60) – The interval (minutes) between reloading instruments from the venue.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Bybit HTTP requests.
- bars_timestamp_on_close (bool , default True) – If the ts_event timestamp for bars should be on the open or close or the bar. If True, then ts_event will be on the close of the bar.
-
api_key (str
, optional) – The Bybit
API public key. If
api_key : str | None
api_secret : str | None
product_types : list[BybitProductType] | None
base_url_http : str | None
demo : bool
testnet : bool
update_instruments_interval_mins : PositiveInt | None
recv_window_ms : PositiveInt
bars_timestamp_on_close : bool
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
handle_revised_bars : bool
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
-
Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class BybitExecClientConfig
Bases:
LiveExecClientConfig
Configuration for
BybitExecutionClient
instances.
-
Parameters:
-
api_key (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_KEY or BYBIT_TESTNET_API_KEY environment variables. -
api_secret (str
, optional) – The Bybit
API public key. If
None
then will source the BYBIT_API_KEY or BYBIT_TESTNET_API_KEY environment variables. - product_types (list [BybitProductType ] , optional) – The Bybit product type for the client. If None then will default to ‘SPOT’, you also cannot mix ‘SPOT’ with any other product type for execution, and it will use a CASH account type, vs MARGIN for the other derivative products.
- base_url_ws_private (str , optional) – The base URL for the private WebSocket client.
- base_url_ws_trade (str , optional) – The base URL for the trade WebSocket client.
- demo (bool , default False) – If the client is connecting to the Bybit demo API.
- testnet (bool , default False) – If the client is connecting to the Bybit testnet API.
- use_gtd (bool , default False) – If False, then GTD time in force will be remapped to GTC (this is useful if managing GTD orders locally).
- use_ws_execution_fast (bool , default False) – If use fast execution stream.
- use_ws_trade_api (bool , default False) – If the client is using websocket to send order requests.
- use_http_batch_api (bool , default False) – If the client is using http api to send batch order requests. Effective only when use_ws_trade_api is set to True.
- 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.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Bybit HTTP requests.
- ws_trade_timeout_secs (PositiveFloat , default 5.0) – The timeout for trade websocket messages.
- ws_auth_timeout_secs (PositiveFloat , default 5.0) – The timeout for auth websocket messages.
- futures_leverages (dict *[*BybitSymbol , PositiveInt ] , optional) – The leverages for futures.
- position_mode (dict *[*BybitSymbol , BybitPositionMode ] , optional) – The position mode for USDT perpetual and Inverse futures.
- margin_mode (BybitMarginMode , optional) – Set Margin Mode.
-
api_key (str
, optional) – The Bybit
API public key. If
WARNING
A short retry_delay with frequent retries may result in account bans.
api_key : str | None
api_secret : str | None
product_types : list[BybitProductType] | None
base_url_http : str | None
base_url_ws_private : str | None
base_url_ws_trade : str | None
demo : bool
testnet : bool
use_gtd : bool
use_ws_execution_fast : bool
use_ws_trade_api : bool
use_http_batch_api : bool
max_retries : PositiveInt | None
retry_delay_initial_ms : PositiveInt | None
retry_delay_max_ms : PositiveInt | None
recv_window_ms : PositiveInt
ws_trade_timeout_secs : PositiveFloat | None
ws_auth_timeout_secs : PositiveFloat | None
futures_leverages : dict[BybitSymbol, PositiveInt] | None
position_mode : dict[BybitSymbol, BybitPositionMode] | None
margin_mode : BybitMarginMode | None
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
instrument_provider : InstrumentProviderConfig
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod 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_bybit_http_client(clock: LiveClock, key: str | None = None, secret: str | None = None, base_url: str | None = None, is_demo: bool = False, is_testnet: bool = False, recv_window_ms: int = 5000) → BybitHttpClient
Cache and return a Bybit 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.
- key (str , optional) – The API key for the client.
- secret (str , optional) – The API secret for the client.
- base_url (str , optional) – The base URL for the API endpoints.
- is_demo (bool , default False) – If the client is connecting to the demo API.
- is_testnet (bool , default False) – If the client is connecting to the testnet API.
- recv_window_ms (PositiveInt , default 5000) – The receive window (milliseconds) for Bybit HTTP requests.
- Return type: BybitHttpClient
get_bybit_instrument_provider(client: BybitHttpClient, clock: LiveClock, product_types: frozenset[BybitProductType], config: InstrumentProviderConfig) → BybitInstrumentProvider
Cache and return a Bybit instrument provider.
If a cached provider already exists, then that cached provider will be returned.
-
Parameters:
- client (BybitHttpClient) – The client for the instrument provider.
- clock (LiveClock) – The clock for the instrument provider.
- product_types (list [BybitProductType ]) – The product types to load.
- is_testnet (bool) – If the provider is for the Spot testnet.
- config (InstrumentProviderConfig) – The configuration for the instrument provider.
- Return type: BybitInstrumentProvider
class BybitLiveDataClientFactory
Bases: LiveDataClientFactory
Provides a Bybit live data client factory.
static create(loop: asyncio.AbstractEventLoop, name: str, config: BybitDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BybitDataClient
Create a new Bybit data client.
-
Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BybitDataClientConfig) – The client configuration.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the instrument provider.
- Return type: BybitDataClient
class BybitLiveExecClientFactory
Bases: LiveExecClientFactory
Provides a Bybit live execution client factory.
static create(loop: asyncio.AbstractEventLoop, name: str, config: BybitExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → BybitExecutionClient
Create a new Bybit execution client.
-
Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (BybitExecClientConfig) – 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: BybitExecutionClient
Enums
raise_error(error)
class BybitUnifiedMarginStatus
Bases: Enum
CLASSIC_ACCOUNT = 1
UNIFIED_TRADING_ACCOUNT_1_0 = 3
UNIFIED_TRADING_ACCOUNT_1_0_PRO = 4
UNIFIED_TRADING_ACCOUNT_2_0 = 5
UNIFIED_TRADING_ACCOUNT_2_0_PRO = 6
class BybitMarginMode
Bases: Enum
ISOLATED_MARGIN = 'ISOLATED_MARGIN'
REGULAR_MARGIN = 'REGULAR_MARGIN'
PORTFOLIO_MARGIN = 'PORTFOLIO_MARGIN'
class BybitPositionMode
Bases: Enum
https://bybit-exchange.github.io/docs/v5/position/position-mode
MERGED_SINGLE = 0
BOTH_SIDES = 3
class BybitPositionIdx
Bases: Enum
ONE_WAY = 0
BUY_HEDGE = 1
SELL_HEDGE = 2
class BybitAccountType
Bases: Enum
UNIFIED = 'UNIFIED'
class BybitProductType
Bases: Enum
SPOT = 'spot'
LINEAR = 'linear'
INVERSE = 'inverse'
OPTION = 'option'
property is_spot : bool
property is_linear : bool
property is_inverse : bool
property is_option : bool
class BybitContractType
Bases: Enum
LINEAR_PERPETUAL = 'LinearPerpetual'
LINEAR_FUTURE = 'LinearFutures'
INVERSE_PERPETUAL = 'InversePerpetual'
INVERSE_FUTURE = 'InverseFutures'
class BybitOptionType
Bases: Enum
CALL = 'Call'
PUT = 'Put'
class BybitPositionSide
Bases: Enum
FLAT = ''
BUY = 'Buy'
SELL = 'Sell'
parse_to_position_side() → PositionSide
class BybitWsOrderRequestMsgOP
Bases: Enum
CREATE = 'order.create'
AMEND = 'order.amend'
CANCEL = 'order.cancel'
CREATE_BATCH = 'order.create-batch'
AMEND_BATCH = 'order.amend-batch'
CANCEL_BATCH = 'order.cancel-batch'
class BybitKlineInterval
Bases: Enum
MINUTE_1 = '1'
MINUTE_3 = '3'
MINUTE_5 = '5'
MINUTE_15 = '15'
MINUTE_30 = '30'
HOUR_1 = '60'
HOUR_2 = '120'
HOUR_4 = '240'
HOUR_6 = '360'
HOUR_12 = '720'
DAY_1 = 'D'
WEEK_1 = 'W'
MONTH_1 = 'M'
class BybitOrderStatus
Bases: Enum
CREATED = 'Created'
NEW = 'New'
REJECTED = 'Rejected'
PARTIALLY_FILLED = 'PartiallyFilled'
PARTIALLY_FILLED_CANCELED = 'PartiallyFilledCanceled'
FILLED = 'Filled'
CANCELED = 'Cancelled'
UNTRIGGERED = 'Untriggered'
TRIGGERED = 'Triggered'
DEACTIVATED = 'Deactivated'
class BybitOrderSide
Bases: Enum
UNKNOWN = ''
BUY = 'Buy'
SELL = 'Sell'
class BybitOrderType
Bases: Enum
MARKET = 'Market'
LIMIT = 'Limit'
UNKNOWN = 'UNKNOWN'
class BybitStopOrderType
Bases: Enum
https://bybit-exchange.github.io/docs/v5/enum#stopordertype
NONE = ''
UNKNOWN = 'UNKNOWN'
TAKE_PROFIT = 'TakeProfit'
STOP_LOSS = 'StopLoss'
TRAILING_STOP = 'TrailingStop'
STOP = 'Stop'
PARTIAL_TAKE_PROFIT = 'PartialTakeProfit'
PARTIAL_STOP_LOSS = 'PartialStopLoss'
TPSL_ORDER = 'tpslOrder'
OCO_ORDER = 'OcoOrder'
MM_RATE_CLOSE = 'MmRateClose'
BIDIRECTIONAL_TPSL_ORDER = 'BidirectionalTpslOrder'
class BybitTriggerType
Bases: Enum
NONE = ''
LAST_PRICE = 'LastPrice'
INDEX_PRICE = 'IndexPrice'
MARK_PRICE = 'MarkPrice'
class BybitTriggerDirection
Bases: Enum
NONE = 0
RISES_TO = 1
FALLS_TO = 2
class BybitTpSlMode
Bases: Enum
FULL = 'Full'
PARTIAL = 'Partial'
class BybitTimeInForce
Bases: Enum
GTC = 'GTC'
IOC = 'IOC'
FOK = 'FOK'
POST_ONLY = 'PostOnly'
class BybitExecType
Bases: Enum
TRADE = 'Trade'
ADL_TRADE = 'AdlTrade'
FUNDING = 'Funding'
BUST_TRADE = 'BustTrade'
DELIVERY = 'Delivery'
SETTLE = 'Settle'
BLOCK_TRADE = 'BlockTrade'
MOVE_POSITION = 'MovePosition'
UNKNOWN = 'UNKNOWN'
class BybitTransactionType
Bases: Enum
TRANSFER_IN = 'TRANSFER_IN'
TRANSFER_OUT = 'TRANSFER_OUT'
TRADE = 'TRADE'
SETTLEMENT = 'SETTLEMENT'
DELIVERY = 'DELIVERY'
LIQUIDATION = 'LIQUIDATION'
AIRDROP = 'AIRDRP'
class BybitEndpointType
Bases: Enum
NONE = 'NONE'
ASSET = 'ASSET'
MARKET = 'MARKET'
ACCOUNT = 'ACCOUNT'
TRADE = 'TRADE'
POSITION = 'POSITION'
USER = 'USER'
check_dict_keys(key, data)
class BybitEnumParser
Bases: object
parse_bybit_order_status(order_type: OrderType, order_status: BybitOrderStatus) → OrderStatus
parse_bybit_time_in_force(time_in_force: BybitTimeInForce) → TimeInForce
parse_bybit_order_side(order_side: BybitOrderSide) → OrderSide
parse_nautilus_order_side(order_side: OrderSide) → BybitOrderSide
parse_bybit_order_type(order_type: BybitOrderType, stop_order_type: BybitStopOrderType, order_side: BybitOrderSide, trigger_direction: BybitTriggerDirection) → OrderType
parse_nautilus_time_in_force(time_in_force: TimeInForce) → BybitTimeInForce
parse_nautilus_trigger_type(trigger_type: TriggerType) → BybitTriggerType
parse_bybit_trigger_type(trigger_type: BybitTriggerType) → TriggerType
parse_trigger_direction(order_type: OrderType, order_side: OrderSide) → BybitTriggerDirection | None
parse_bybit_kline(bar_type: BarType) → BybitKlineInterval
Providers
class BybitInstrumentProvider
Bases:
InstrumentProvider
Provides Nautilus instrument definitions from Bybit.
-
Parameters:
- client (BybitHttpClient) – The Bybit HTTP client.
- clock (LiveClock) – The clock instance.
- product_types (list [BybitProductType ]) – The product types to load.
- config (InstrumentProviderConfig , optional) – The instrument provider configuration, by default None.
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.
-
Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
async load_async(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
-
Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If instrument_id.venue is not equal to self.venue.
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.
Data
class BybitDataClient
Bases:
LiveMarketDataClient
Provides a data client for the Bybit centralized cypto exchange.
-
Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- client (BybitHttpClient) – The Bybit 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 (BybitInstrumentProvider) – The instrument provider.
- product_types (list [BybitProductType ]) – The product types for the client.
- ws_base_urls (dict [BybitProductType , str ]) – The product base urls for the WebSocket clients.
- config (BybitDataClientConfig) – The configuration for the client.
- name (str , optional) – The custom client ID.
async fetch_send_tickers(id: UUID4, product_type: BybitProductType, symbol: str) → None
complete_fetch_tickers_task(request: Request) → None
connect() → None
Connect the client.
create_task(coro: ~collections.abc.Coroutine, log_msg: str | None = None, actions: ~collections.abc.Callable | None = None, success_msg: str | None = None, success_color: ~posei_trader.core.rust.common.LogColor = <LogColor.NORMAL: 0>) → Task
Run the given coroutine with error handling and optional callback actions when done.
-
Parameters:
- coro (Coroutine) – The coroutine to run.
- log_msg (str , optional) – The log message for the task.
- actions (Callable , optional) – The actions callback to run when the coroutine is done.
- success_msg (str , optional) – The log message to write on actions success.
-
success_color (LogColor,
default
NORMAL
) – The log message color for actions success.
- Return type: asyncio.Task
degrade(self) → void
Degrade the component.
While executing on_degrade() any exception will be
logged and reraised, then the component will
remain in a DEGRADING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
disconnect() → None
Disconnect the client.
dispose(self) → void
Dispose of the component.
While executing on_dispose() any exception will be
logged and reraised, then the component will
remain in a DISPOSING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
fault(self) → void
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be
logged and reraised, then the component will
remain in a FAULTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the components class.
- Return type: str
id
The components ID.
- Returns: ComponentId
is_connected
If the client is connected.
- Returns: bool
is_degraded
bool Return whether the current component state is
DEGRADED
.
- Return type: bool
- Type: Component.is_degraded
is_disposed
bool Return whether the current component state is
DISPOSED
.
- Return type: bool
- Type: Component.is_disposed
is_faulted
bool Return whether the current component state is
FAULTED
.
- Return type: bool
- Type: Component.is_faulted
is_initialized
bool Return whether the component has been
initialized (component.state >=
INITIALIZED
).
- Return type: bool
- Type: Component.is_initialized
is_running
bool Return whether the current component state is
RUNNING
.
- Return type: bool
- Type: Component.is_running
is_stopped
bool Return whether the current component state is
STOPPED
.
- Return type: bool
- Type: Component.is_stopped
request(self, 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_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_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 RESETTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
resume(self) → void
Resume the component.
While executing on_resume() any exception will be
logged and reraised, then the component will
remain in a RESUMING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
async run_after_delay(delay: float, coro: Coroutine) → 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 STARTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
state
ComponentState Return the components current state.
- Return type: ComponentState
- Type: Component.state
stop(self) → void
Stop the component.
While executing on_stop() any exception will be
logged and reraised, then the component will
remain in a STOPPING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
subscribe(self, 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_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_snapshots(self, SubscribeOrderBook command) → void
Subscribe to OrderBook snapshots data for the given instrument ID.
-
Parameters:
- instrument_id (InstrumentId) – The order book instrument to subscribe to.
-
book_type (BookType
{
L1_MBP
,L2_MBP
,L3_MBO
}) – The order book level. - depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
- 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_bars(self) → list
Return the bar types subscribed to.
- Return type: list[BarType]
subscribed_custom_data(self) → list
Return the custom data types subscribed to.
- Return type: list[DataType]
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_snapshots(self) → list
Return the order book snapshot 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]