Deribit

The Deribit adapter provides integration with the Deribit cryptocurrency derivatives exchange, supporting live market data ingest and order execution.

This adapter supports: - Market data streaming via WebSocket (trades, order book, quotes). - Order execution via WebSocket (market, limit, stop market, stop limit). - Instrument definitions for futures, options, spot, and combo instruments. - Multiple currencies (BTC, ETH, USDC, USDT, EURR).

class DeribitCurrency

Bases: object

Deribit currency.

ANY = <DeribitCurrency.ANY: '5'>
BTC = <DeribitCurrency.BTC: '0'>
ETH = <DeribitCurrency.ETH: '1'>
EURR = <DeribitCurrency.EURR: '4'>
USDC = <DeribitCurrency.USDC: '2'>
USDT = <DeribitCurrency.USDT: '3'>
classmethod from_str(data)
name
value
static variants()
class DeribitDataClient

Bases: LiveMarketDataClient

Provides a data client for the Deribit centralized crypto derivatives exchange.

Parameters:
  • loop (asyncio.AbstractEventLoop) – The event loop for the client.

  • client (nautilus_pyo3.DeribitHttpClient) – The Deribit 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 (DeribitInstrumentProvider) – The instrument provider.

  • config (DeribitDataClientConfig) – The configuration for the client.

  • name (str, optional) – The custom client ID.

property instrument_provider: DeribitInstrumentProvider
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 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

is_subscribed_order_book_deltas(self, InstrumentId instrument_id) bool
is_subscribed_quote_ticks(self, InstrumentId instrument_id) bool
is_subscribed_trade_ticks(self, InstrumentId instrument_id) bool
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_forward_prices(self, RequestForwardPrices request) void

Request forward prices for option chain ATM determination.

Parameters:

request (RequestForwardPrices) – 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 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_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_option_greeks(self, SubscribeOptionGreeks command) void

Subscribe to OptionGreeks data for the given instrument ID.

Parameters:

command (SubscribeOptionGreeks) – The subscribe command.

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_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_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_option_greeks(self) list

Return the option greeks 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_option_greeks(self, UnsubscribeOptionGreeks command) void

Unsubscribe from OptionGreeks data for the given instrument ID.

Parameters:

command (UnsubscribeOptionGreeks) – The unsubscribe command.

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

class DeribitDataClientConfig

Bases: LiveDataClientConfig

Configuration for DeribitDataClient instances.

Parameters:
  • api_key (str, optional) – The Deribit API public key. If None then will source the DERIBIT_API_KEY or DERIBIT_TESTNET_API_KEY environment variable based on environment.

  • api_secret (str, optional) – The Deribit API secret key. If None then will source the DERIBIT_API_SECRET or DERIBIT_TESTNET_API_SECRET environment variable based on environment.

  • product_types (tuple[DeribitProductType, ...], optional) – The Deribit product types to load. If None, defaults to Future.

  • environment (DeribitEnvironment, optional) – The Deribit environment for the client (MAINNET or TESTNET). If None then defaults to MAINNET.

  • base_url_http (str, optional) – The base URL for Deribit’s HTTP API. If None then will use default based on environment.

  • base_url_ws (str, optional) – The base URL for Deribit’s WebSocket API. If None then will use default based on environment.

  • proxy_url (str, optional) – The proxy URL for HTTP and WebSocket transports.

  • http_timeout_secs (PositiveInt, optional) – The timeout (seconds) for HTTP requests.

  • max_retries (PositiveInt, default 3) – The maximum retry attempts for requests.

  • retry_delay_initial_ms (PositiveInt, default 1_000) – The initial delay (milliseconds) between retries.

  • retry_delay_max_ms (PositiveInt, default 10_000) – The maximum delay (milliseconds) between retries.

  • update_instruments_interval_mins (PositiveInt, default 60) – The interval (minutes) between reloading instruments from the venue.

  • auto_load_missing_instruments (bool, default False) – If True, subscribes for uncached instruments lazy-load via HTTP; otherwise fail fast. See the Deribit integration guide for details.

api_key: str | None
api_secret: str | None
product_types: tuple[DeribitProductType, ...] | None
environment: DeribitEnvironment | None
base_url_http: str | None
base_url_ws: str | None
proxy_url: str | None
transport_backend: TransportBackend | None
http_timeout_secs: Annotated[int, msgspec.Meta(gt=0)] | None
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
update_instruments_interval_mins: Annotated[int, msgspec.Meta(gt=0)] | None
auto_load_missing_instruments: 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 DeribitExecClientConfig

Bases: LiveExecClientConfig

Configuration for DeribitExecutionClient instances.

Parameters:
  • api_key (str, optional) – The Deribit API public key. If None then will source the DERIBIT_API_KEY or DERIBIT_TESTNET_API_KEY environment variable based on environment.

  • api_secret (str, optional) – The Deribit API secret key. If None then will source the DERIBIT_API_SECRET or DERIBIT_TESTNET_API_SECRET environment variable based on environment.

  • product_types (tuple[DeribitProductType, ...], optional) – The Deribit product types to load. If None, defaults to Future.

  • environment (DeribitEnvironment, optional) – The Deribit environment for the client (MAINNET or TESTNET). If None then defaults to MAINNET.

  • base_url_http (str, optional) – The base URL for Deribit’s HTTP API. If None then will use default based on environment.

  • base_url_ws (str, optional) – The base URL for Deribit’s WebSocket API. If None then will use default based on environment.

  • proxy_url (str, optional) – The proxy URL for HTTP and WebSocket transports.

  • http_timeout_secs (PositiveInt, optional) – The timeout (seconds) for HTTP requests.

  • max_retries (PositiveInt, default 3) – The maximum retry attempts for requests.

  • retry_delay_initial_ms (PositiveInt, default 1_000) – The initial delay (milliseconds) between retries.

  • retry_delay_max_ms (PositiveInt, default 10_000) – The maximum delay (milliseconds) between retries.

api_key: str | None
api_secret: str | None
product_types: tuple[DeribitProductType, ...] | None
environment: DeribitEnvironment | None
base_url_http: str | None
base_url_ws: str | None
proxy_url: str | None
transport_backend: TransportBackend | None
http_timeout_secs: Annotated[int, msgspec.Meta(gt=0)] | None
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
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 DeribitExecutionClient

Bases: LiveExecutionClient

Provides an execution client for the Deribit cryptocurrency exchange.

Parameters:
  • loop (asyncio.AbstractEventLoop) – The event loop for the client.

  • http_client (nautilus_pyo3.DeribitHttpClient) – The Deribit HTTP client for REST API operations.

  • msgbus (MessageBus) – The message bus for the client.

  • cache (Cache) – The cache for the client.

  • clock (LiveClock) – The clock for the client.

  • instrument_provider (DeribitInstrumentProvider) – The instrument provider.

  • config (DeribitExecClientConfig) – The configuration for the client.

  • name (str, optional) – The custom client ID.

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]

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

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.

calculate_commission(self, Instrument instrument, Quantity last_qty, Price last_px, LiquiditySide liquidity_side) Money

Calculate the commission for a reconciliation fill.

Override this method to provide venue-specific commission logic for inferred fills generated during reconciliation.

Parameters:
  • instrument (Instrument) – The instrument for the fill.

  • last_qty (Quantity) – The fill quantity.

  • last_px (Price) – The fill price.

  • liquidity_side (LiquiditySide {NO_LIQUIDITY_SIDE, MAKER, TAKER}) – The liquidity side for the fill.

Return type:

Money or None

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

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_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 pass None and the execution engine OMS will handle position ID resolution.

  • order_side (OrderSide {BUY, SELL}) – The execution order side.

  • order_type (OrderType) – The execution order type.

  • last_qty (Quantity) – The fill quantity for this execution.

  • last_px (Price) – The fill price for this execution (not average price).

  • quote_currency (Currency) – The currency of the price.

  • commission (Money) – The fill commission.

  • liquidity_side (LiquiditySide {NO_LIQUIDITY_SIDE, MAKER, TAKER}) – The execution liquidity side.

  • ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order filled event occurred.

  • 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, is_quote_quantity=None) 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.

  • is_quote_quantity (bool, optional) – Override for the quote quantity flag. If None, preserves the existing value from the cached order.

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:

Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED.

Return type:

bool

Type:

Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED.

Return type:

bool

Type:

Component.is_faulted

is_initialized

bool

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

Return type:

bool

Type:

Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING.

Return type:

bool

Type:

Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED.

Return type:

bool

Type:

Component.is_stopped

modify_order(self, ModifyOrder command) 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 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.

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

type

The components type.

Returns:

type

venue

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

Returns:

Venue or None

class DeribitHttpClient

Bases: object

High-level Deribit HTTP client with domain-level abstractions.

This client wraps the raw HTTP client and provides methods that use Nautilus domain types. It maintains an instrument cache for efficient lookups.

cache_instrument(instrument)

# Errors

Returns a Python exception if adding the instrument to the cache fails.

cache_instruments(instruments)

Caches instruments for later retrieval.

is_initialized()
is_testnet

Returns whether this client is connected to testnet.

request_account_state(account_id)

Requests account state for all currencies.

Fetches account balance and margin information for all currencies from Deribit and converts it to Nautilus AccountState event.

# Errors

Returns an error if: - The request fails - Currency conversion fails

request_bars(bar_type, start=None, end=None, limit=None)

Requests historical bars (OHLCV) for an instrument.

Uses the public/get_tradingview_chart_data endpoint to fetch candlestick data.

# Errors

Returns an error if: - Aggregation source is not EXTERNAL - Bar aggregation type is not supported by Deribit - The instrument is not found in cache - The request fails or response cannot be parsed

# Supported Resolutions

Deribit supports: 1, 3, 5, 10, 15, 30, 60, 120, 180, 360, 720 minutes, and 1D (daily)

request_book_snapshot(instrument_id, depth=None)

Requests a snapshot of the order book for an instrument.

Fetches the order book from Deribit and converts it to a Nautilus OrderBook.

# Arguments

  • instrument_id - The instrument to fetch the order book for

  • depth - Optional depth limit (valid values: 1, 5, 10, 20, 50, 100, 1000, 10000)

# Errors

Returns an error if: - The instrument is not found in cache - The request fails - Order book parsing fails

request_fill_reports(account_id, instrument_id=None, start=None, end=None)

Requests fill reports for reconciliation.

Fetches user trades from Deribit and converts them to Nautilus FillReport. Automatically paginates through all results using time-cursor advancement.

# Strategy - Uses /private/get_user_trades_by_instrument_and_time when instrument is provided - Otherwise iterates over currencies using /private/get_user_trades_by_currency_and_time

# Errors

Returns an error if the request fails or parsing fails.

request_forward_prices(currency, instrument_id=None)

Request forward prices for option chain ATM determination.

Single-instrument path (1 HTTP call) if instrument_id is provided, otherwise bulk path via book summaries.

request_instrument(instrument_id)

Requests a specific instrument by its Nautilus instrument ID.

This is a high-level method that fetches the raw instrument data from Deribit and converts it to a Nautilus InstrumentAny type.

# Errors

Returns an error if: - The instrument name format is invalid (error code -32602) - The instrument doesn’t exist (error code 13020) - Network or API errors occur

request_instruments(currency, product_type=None)

Requests instruments for a specific currency.

# Errors

Returns an error if the request fails or instruments cannot be parsed.

request_option_expirations(currency)

Requests traded option expirations for a settlement currency.

# Errors

Returns an error if the request fails.

request_order_status_reports(account_id, instrument_id=None, start=None, end=None, open_only=True)

Requests order status reports for reconciliation.

Fetches order statuses from Deribit and converts them to Nautilus OrderStatusReport.

# Strategy - Uses /private/get_open_orders for all open orders (single efficient API call) - Uses /private/get_open_orders_by_instrument when specific instrument is provided - For historical orders (when open_only=false), iterates over currencies

# Errors

Returns an error if the request fails or parsing fails.

request_position_status_reports(account_id, instrument_id=None)

Requests position status reports for reconciliation.

Fetches positions from Deribit and converts them to Nautilus PositionStatusReport.

# Strategy - Uses currency=any to fetch all positions in one call - Filters by instrument_id if provided

# Errors

Returns an error if the request fails or parsing fails.

request_trades(instrument_id, start=None, end=None, limit=None)

Requests historical trades for an instrument within a time range.

Fetches trade ticks from Deribit and converts them to Nautilus TradeTick objects.

# Arguments

  • instrument_id - The instrument to fetch trades for

  • start - Optional start time filter

  • end - Optional end time filter

  • limit - Optional limit on number of trades (max 1000)

# Errors

Returns an error if: - The instrument is not found in cache - The request fails - Trade parsing fails

# Pagination

When limit is None, this function automatically paginates through all available trades in the time range using the has_more field from the API response. When limit is specified, pagination stops once that many trades are collected.

class DeribitInstrumentProvider

Bases: InstrumentProvider

Provides Nautilus instrument definitions from Deribit.

Parameters:
  • client (nautilus_pyo3.DeribitHttpClient) – The Deribit HTTP client.

  • product_types (tuple[DeribitProductType, ...], optional) – The product types to load.

  • config (InstrumentProviderConfig, optional) – The instrument provider configuration, by default None.

property product_types: tuple[DeribitProductType, ...] | None

Return the Deribit product types configured for the provider.

Return type:

tuple[DeribitProductType, …] | None

instruments_pyo3() list[Any]

Return all Deribit PyO3 instrument definitions held by the provider.

Return type:

list[nautilus_pyo3.Instrument]

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 DeribitLiveDataClientFactory

Bases: LiveDataClientFactory

Provides a Deribit live data client factory.

static create(loop: AbstractEventLoop, name: str, config: DeribitDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) DeribitDataClient

Create a new Deribit data client.

Parameters:
  • loop (asyncio.AbstractEventLoop) – The event loop for the client.

  • name (str) – The custom client ID.

  • config (DeribitDataClientConfig) – 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:

DeribitDataClient

class DeribitLiveExecClientFactory

Bases: LiveExecClientFactory

Provides a Deribit live execution client factory.

static create(loop: AbstractEventLoop, name: str, config: DeribitExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) DeribitExecutionClient

Create a new Deribit execution client.

Parameters:
  • loop (asyncio.AbstractEventLoop) – The event loop for the client.

  • name (str) – The custom client ID.

  • config (DeribitExecClientConfig) – 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:

DeribitExecutionClient

class DeribitProductType

Bases: object

Deribit product type.

FUTURE = <DeribitProductType.future: '0'>
FUTURE_COMBO = <DeribitProductType.future_combo: '3'>
OPTION = <DeribitProductType.option: '1'>
OPTION_COMBO = <DeribitProductType.option_combo: '4'>
SPOT = <DeribitProductType.spot: '2'>
classmethod from_str(data)
name
value
static variants()
class DeribitUpdateInterval

Bases: object

Deribit data stream update intervals.

Controls how frequently updates are sent for subscribed channels. Raw updates require authentication while aggregated updates are public.

AGG2 = <DeribitUpdateInterval.Agg2: '2'>
MS100 = <DeribitUpdateInterval.Ms100: '1'>
RAW = <DeribitUpdateInterval.Raw: '0'>
classmethod from_str(data)
name
value
static variants()
class DeribitWebSocketClient

Bases: object

WebSocket client for connecting to Deribit.

authenticate(session_name=None)

Authenticates the WebSocket session with Deribit.

Uses the client_signature grant type with HMAC-SHA256 signature. This must be called before subscribing to raw data streams.

# Arguments

  • session_name - Optional session name for session-scoped authentication. When provided, uses session:<name> scope which allows skipping access_token in subsequent private requests. When None, uses default connection scope. Recommended to use session scope for order execution compatibility.

# Errors

Returns an error if: - No credentials are configured - The authentication request fails - The authentication times out

authenticate_session(session_name)

Authenticates with session scope using the provided session name.

Use DERIBIT_DATA_SESSION_NAME for data clients and DERIBIT_EXECUTION_SESSION_NAME for execution clients.

# Errors

Returns an error if authentication fails.

cache_instrument(instrument)

Caches a single instrument.

cache_instruments(instruments)

Caches instruments for use during message parsing.

cancel_all_orders(instrument_id, order_type=None)

Cancels all orders for a specific instrument on Deribit via WebSocket.

Uses the private/cancel_all_by_instrument JSON-RPC method. Requires authentication (call authenticate_session() first).

# Errors

Returns an error if: - The client is not authenticated - The command fails to send

cancel_all_requests()

Cancel all pending WebSocket requests.

cancel_order(order_id, client_order_id, trader_id, strategy_id, instrument_id)

Cancels an existing order on Deribit via WebSocket.

The order is cancelled using the private/cancel JSON-RPC method. Requires authentication (call authenticate_session() first).

# Errors

Returns an error if: - The client is not authenticated - The command fails to send

close()

Closes the WebSocket connection.

# Errors

Returns an error if the close operation fails.

connect(loop_, instruments, callback)

Connects to the Deribit WebSocket API.

# Errors

Returns an error if the connection fails.

has_credentials()

Returns whether the client has credentials configured.

is_active()

Returns whether the client is actively connected.

is_authenticated()

Returns whether the client is authenticated.

is_closed()

Returns whether the client is closed.

is_testnet
modify_order(order_id, quantity, price, client_order_id, trader_id, strategy_id, instrument_id)

Modifies an existing order on Deribit via WebSocket.

The order parameters are sent using the private/edit JSON-RPC method. Requires authentication (call authenticate_session() first).

# Errors

Returns an error if: - The client is not authenticated - The command fails to send

static new_public(environment, proxy_url=None)

Creates a new public (unauthenticated) client.

Does NOT fall back to environment variables for credentials.

# Errors

Returns an error if initialization fails.

query_order(order_id, client_order_id, trader_id, strategy_id, instrument_id)

Queries the state of an order on Deribit via WebSocket.

Uses the private/get_order_state JSON-RPC method. Requires authentication (call authenticate_session() first).

# Errors

Returns an error if: - The client is not authenticated - The command fails to send

set_account_id(account_id)

Sets the account ID for order/fill reports.

set_bars_timestamp_on_close(value)

Sets whether bar timestamps should use the close time.

When true (default), bar ts_event is set to the bar’s close time.

submit_order(order_side, quantity, order_type, client_order_id, trader_id, strategy_id, instrument_id, price=None, time_in_force=None, post_only=False, reduce_only=False, trigger_price=None, trigger_type=None)

Submits an order to Deribit via WebSocket.

Routes to private/buy or private/sell JSON-RPC method based on order side. Requires authentication (call authenticate_session() first).

# Errors

Returns an error if: - The client is not authenticated - The command fails to send

subscribe(channels)

Subscribes to multiple channels at once.

# Errors

Returns an error if subscription fails.

subscribe_bars(bar_type)

Subscribes to bar updates for an instrument using a BarType specification.

Converts the BarType to the nearest supported Deribit resolution and subscribes to the chart channel.

# Errors

Returns an error if the subscription request fails.

subscribe_book(instrument_id, interval=None, depth=None)

Subscribes to order book updates for an instrument.

# Arguments

  • instrument_id - The instrument to subscribe to

  • interval - Update interval. Defaults to Ms100 (100ms). Raw requires authentication.

# Errors

Returns an error if subscription fails or raw is requested without authentication.

subscribe_book_grouped(instrument_id, group, depth, interval=None)

Subscribes to grouped (depth-limited) order book updates for an instrument.

Uses the Deribit grouped book channel format: book.{instrument}.{group}.{depth}.{interval}

Depth is normalized to Deribit supported values: 1, 10, or 20.

# Errors

Returns an error if subscription fails or raw is requested without authentication.

subscribe_chart(instrument_id, resolution)

Subscribes to chart/OHLC bar updates for an instrument.

# Arguments

  • instrument_id - The instrument to subscribe to

  • resolution - Bar resolution: “1”, “3”, “5”, “10”, “15”, “30”, “60”, “120”, “180”, “360”, “720”, “1D” (minutes or 1D for daily)

# Errors

Returns an error if subscription fails.

subscribe_index_prices(instrument_id, interval=None)

Subscribes to index prices for the given instrument.

Registers the instrument in the index_price_subs set so the handler emits IndexPriceUpdate from ticker messages, then subscribes to the ticker channel.

subscribe_instrument_status(instrument_id)

Subscribes to instrument status changes for lifecycle notifications.

Channel format: instrument.state.{kind}.{currency}

# Errors

Returns an error if subscription fails.

subscribe_mark_prices(instrument_id, interval=None)

Subscribes to mark prices for the given instrument.

Registers the instrument in the mark_price_subs set so the handler emits MarkPriceUpdate from ticker messages, then subscribes to the ticker channel.

subscribe_option_greeks(instrument_id, interval=None)

Subscribes to option greeks for the given instrument.

Registers the instrument in the option_greeks_subs set so the handler emits OptionGreeks from ticker messages, then subscribes to the ticker channel.

subscribe_perpetual_interest_rates(instrument_id, interval=None)
subscribe_quotes(instrument_id)

Subscribes to quote (best bid/ask) updates for an instrument.

Note: Quote channel does not support interval parameter.

# Errors

Returns an error if subscription fails.

subscribe_ticker(instrument_id, interval=None)

Subscribes to ticker updates for an instrument.

# Arguments

  • instrument_id - The instrument to subscribe to

  • interval - Update interval. Defaults to Ms100 (100ms). Raw requires authentication.

# Errors

Returns an error if subscription fails or raw is requested without authentication.

subscribe_trades(instrument_id, interval=None)

Subscribes to trade updates for an instrument.

# Arguments

  • instrument_id - The instrument to subscribe to

  • interval - Update interval. Defaults to Ms100 (100ms). Raw requires authentication.

# Errors

Returns an error if subscription fails or raw is requested without authentication.

subscribe_user_orders()

Subscribes to user order updates for all instruments.

Requires authentication. Subscribes to user.orders.any.any.raw channel.

# Errors

Returns an error if client is not authenticated or subscription fails.

subscribe_user_portfolio()

Subscribes to user portfolio updates for all currencies.

Requires authentication. Subscribes to user.portfolio.any channel which provides real-time account balance and margin updates for all currencies (BTC, ETH, USDC, USDT, etc.).

# Errors

Returns an error if client is not authenticated or subscription fails.

subscribe_user_trades()

Subscribes to user trade/fill updates for all instruments.

Requires authentication. Subscribes to user.trades.any.any.raw channel.

# Errors

Returns an error if client is not authenticated or subscription fails.

subscribe_volatility_index(index_name)

Subscribes to volatility index updates for the given index name.

Channel format: deribit_volatility_index.{index_name}

# Errors

Returns an error if subscription fails.

unsubscribe(channels)

Unsubscribes from multiple channels at once.

# Errors

Returns an error if unsubscription fails.

unsubscribe_bars(bar_type)

Unsubscribes from bar updates for an instrument using a BarType specification.

# Errors

Returns an error if the unsubscription request fails.

unsubscribe_book(instrument_id, interval=None, depth=None)

Unsubscribes from order book updates for an instrument.

# Errors

Returns an error if unsubscription fails.

unsubscribe_book_grouped(instrument_id, group, depth, interval=None)

Unsubscribes from grouped (depth-limited) order book updates for an instrument.

Depth is normalized to Deribit supported values: 1, 10, or 20.

# Errors

Returns an error if unsubscription fails.

unsubscribe_chart(instrument_id, resolution)

Unsubscribes from chart/OHLC bar updates.

# Errors

Returns an error if unsubscription fails.

unsubscribe_index_prices(instrument_id, interval=None)

Unsubscribes from index prices for the given instrument.

Removes the instrument from the index_price_subs set and unsubscribes from the ticker channel.

unsubscribe_instrument_status(instrument_id)

Unsubscribes from instrument status changes.

# Errors

Returns an error if unsubscription fails.

unsubscribe_mark_prices(instrument_id, interval=None)

Unsubscribes from mark prices for the given instrument.

Removes the instrument from the mark_price_subs set and unsubscribes from the ticker channel.

unsubscribe_option_greeks(instrument_id, interval=None)

Unsubscribes from option greeks for the given instrument.

Removes the instrument from the option_greeks_subs set and unsubscribes from the ticker channel.

unsubscribe_perpetual_interest_rates(instrument_id, interval=None)
unsubscribe_quotes(instrument_id)

Unsubscribes from quote updates for an instrument.

# Errors

Returns an error if unsubscription fails.

unsubscribe_ticker(instrument_id, interval=None)

Unsubscribes from ticker updates for an instrument.

# Errors

Returns an error if unsubscription fails.

unsubscribe_trades(instrument_id, interval=None)

Unsubscribes from trade updates for an instrument.

# Errors

Returns an error if unsubscription fails.

unsubscribe_user_orders()

Unsubscribes from user order updates for all instruments.

# Errors

Returns an error if unsubscription fails.

unsubscribe_user_portfolio()

Unsubscribes from user portfolio updates for all currencies.

# Errors

Returns an error if unsubscription fails.

unsubscribe_user_trades()

Unsubscribes from user trade/fill updates for all instruments.

# Errors

Returns an error if unsubscription fails.

unsubscribe_volatility_index(index_name)

Unsubscribes from volatility index updates for the given index name.

# Errors

Returns an error if unsubscription fails.

url

Returns the WebSocket URL.

wait_until_active(timeout_secs)

Waits until the client is active or timeout expires.

# Errors

Returns an error if the timeout expires before the client becomes active.

static with_credentials(environment, api_key=None, api_secret=None, account_id=None, proxy_url=None)

Creates an authenticated client with credentials.

Resolves each credential from the provided argument first, falling back to the environment variable for the given environment: - Testnet: DERIBIT_TESTNET_API_KEY and DERIBIT_TESTNET_API_SECRET - Mainnet: DERIBIT_API_KEY and DERIBIT_API_SECRET

# Errors

Returns an error if neither the argument nor the environment variable provides a credential.

get_cached_deribit_http_client(api_key: str | None = None, api_secret: str | None = None, base_url: str | None = None, environment: DeribitEnvironment = DeribitEnvironment.MAINNET, timeout_secs: int | None = None, max_retries: int | None = None, retry_delay_ms: int | None = None, retry_delay_max_ms: int | None = None, proxy_url: str | None = None) DeribitHttpClient

Cache and return a Deribit HTTP client with the given key and secret.

If a cached client with matching parameters already exists, the cached client will be returned.

Parameters:
  • api_key (str, optional) – The API key for the client.

  • api_secret (str, optional) – The API secret for the client.

  • base_url (str, optional) – The base URL for the API endpoints.

  • environment (DeribitEnvironment, default MAINNET) – The Deribit environment (MAINNET or TESTNET).

  • timeout_secs (int, optional) – The timeout (seconds) for HTTP requests to Deribit.

  • max_retries (int, optional) – The maximum retry attempts for requests.

  • retry_delay_ms (int, optional) – The initial delay (milliseconds) between retries.

  • retry_delay_max_ms (int, optional) – The maximum delay (milliseconds) between retries.

  • proxy_url (str, optional) – The proxy URL for HTTP requests.

Return type:

DeribitHttpClient

get_cached_deribit_instrument_provider(client: DeribitHttpClient, product_types: tuple[DeribitProductType, ...] | None = None, config: InstrumentProviderConfig | None = None) DeribitInstrumentProvider

Cache and return a Deribit instrument provider.

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

Parameters:
Return type:

DeribitInstrumentProvider