Skip to main content

DeribitWebSocketClient

Struct DeribitWebSocketClient 

Source
pub struct DeribitWebSocketClient {
    pub config: Arc<WebSocketConfig>,
    pub session: Arc<WebSocketSession>,
    /* private fields */
}
Expand description

WebSocket client for Deribit

Owns a shared, optional Dispatcher that runs the send/receive loop in a dedicated tokio task. All request/response multiplexing and notification routing happens inside that task; this façade only clones an Arc<Dispatcher> out of the slot and forwards calls to it.

Fields§

§config: Arc<WebSocketConfig>

WebSocket configuration

§session: Arc<WebSocketSession>

WebSocket session

Implementations§

Source§

impl DeribitWebSocketClient

Source

pub fn new(config: &WebSocketConfig) -> Result<Self, WebSocketError>

Create a new WebSocket client

The caller’s &WebSocketConfig is deep-copied once into an Arc<WebSocketConfig> which is then shared with the inner WebSocketSession via Arc::clone — no second struct clone, no double allocation.

Source

pub fn subscription_manager(&self) -> Arc<Mutex<SubscriptionManager>>

Returns a handle to the shared subscription manager. The same handle is held by self.session, so all subscription state is observable from either side.

Source

pub fn new_with_url(ws_url: String) -> Result<Self, WebSocketError>

Create a new WebSocket client with default configuration

Source

pub fn new_testnet() -> Result<Self, WebSocketError>

Create a new WebSocket client for testnet

Source

pub fn new_production() -> Result<Self, WebSocketError>

Create a new WebSocket client for production

Source

pub async fn connect(&self) -> Result<(), WebSocketError>

Connect to the WebSocket server

Spawns the dispatcher task that owns the WebSocket stream. If a previous dispatcher is still installed, it is shut down first.

The slot lock is held across the entire shutdown + connect_async + install sequence so concurrent connect() calls are serialized. Without this, two callers could each see an empty slot, each spawn a dispatcher, and the loser’s dispatcher task would leak. While a connect is in flight, other client operations that touch the slot (send_request, disconnect, is_connected) wait on the same mutex — the desired semantics.

Source

pub async fn disconnect(&self) -> Result<(), WebSocketError>

Disconnect from the WebSocket server

Source

pub async fn is_connected(&self) -> bool

Check if connected (i.e., a dispatcher is currently installed).

Source

pub async fn authenticate( &self, client_id: &str, client_secret: &str, ) -> Result<AuthResponse, WebSocketError>

Authenticate with the server

Authenticates the connection using API credentials and returns authentication details including access token and refresh token.

§Arguments
  • client_id - API client ID
  • client_secret - API client secret
§Returns

Returns AuthResponse containing access token, token type, expiration, and scope

§Errors

Returns an error if authentication fails or credentials are invalid

Source

pub async fn subscribe( &self, channels: Vec<String>, ) -> Result<JsonRpcResponse, WebSocketError>

Subscribe to channels.

Local subscription state is reconciled against the server-confirmed channel list carried by response.result, which may be a strict subset of the requested channels when the server rejects individual entries (unknown channel, permission denied, rate limit). Only the channels the server actually acknowledged are added to the local SubscriptionManager. Transport failures and API-error responses leave the local view untouched so the caller can retry without inconsistency.

The response is parsed and validated outside the subscription_manager mutex so the lock is only held for the HashMap mutations themselves, keeping the critical section minimal under contention from get_subscriptions, concurrent subscribes, or the notification consumer.

§Errors

Returns WebSocketError::InvalidMessage if a Success response carries a result that is not a JSON array of channel strings.

Source

pub async fn unsubscribe( &self, channels: Vec<String>, ) -> Result<JsonRpcResponse, WebSocketError>

Unsubscribe from channels.

Local subscription state is reconciled against the server-confirmed channel list carried by response.result, which may be a strict subset of the requested channels. Only the channels the server actually acknowledged are removed from the local SubscriptionManager. Transport failures and API-error responses leave the local view untouched so the caller can retry without inconsistency.

The response is parsed and validated outside the subscription_manager mutex; the lock is only held for the HashMap::remove loop.

§Errors

Returns WebSocketError::InvalidMessage if a Success response carries a result that is not a JSON array of channel strings.

Source

pub async fn public_unsubscribe_all(&self) -> Result<String, WebSocketError>

Unsubscribe from all public channels

Unsubscribes from all public channels subscribed so far and clears the local subscription manager state.

§Returns

Returns "ok" on success

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn private_unsubscribe_all(&self) -> Result<String, WebSocketError>

Unsubscribe from all private channels

Unsubscribes from all private channels subscribed so far and clears the local subscription manager state. Requires authentication.

§Returns

Returns "ok" on success

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn send_request( &self, request: &JsonRpcRequest, ) -> Result<JsonRpcResponse, WebSocketError>

Send a JSON-RPC request and await the matching response.

Forwards the request to the dispatcher, which serializes it, writes it to the WebSocket sink, and routes the response back by matching on the JSON-RPC id field. Notifications arriving between the request and the response do not affect this call and are routed to the notification channel instead.

request is borrowed: callers retain ownership so they can inspect the originating request after the call (for example to build an enriched WebSocketError::ApiError) without paying for a clone on the success path.

Source

pub async fn receive_message(&self) -> Result<String, WebSocketError>

Receive the next notification (or unmatched frame) from the server.

Returns WebSocketError::ConnectionClosed if the dispatcher is not running, or if its notification channel has been drained and closed.

Source

pub async fn get_subscriptions(&self) -> Vec<String>

Get active subscriptions

Source

pub async fn test_connection(&self) -> Result<TestResponse, WebSocketError>

Test connection

Tests the WebSocket connection and returns API version information.

§Returns

Returns TestResponse containing the API version string

§Errors

Returns an error if the connection test fails

Source

pub async fn get_time(&self) -> Result<u64, WebSocketError>

Get server time

Returns the current server timestamp in milliseconds since Unix epoch.

§Returns

Returns u64 timestamp in milliseconds

§Errors

Returns an error if the request fails

Source

pub async fn set_heartbeat( &self, interval: u64, ) -> Result<String, WebSocketError>

Enable heartbeat with specified interval

The server will send a heartbeat message every interval seconds. If heartbeat is enabled, the server will also send test_request notifications which the client should respond to with public/test to keep the connection alive.

§Arguments
  • interval - Heartbeat interval in seconds (10-3600)
§Returns

Returns "ok" on success

§Errors

Returns an error if the request fails or the interval is invalid

Source

pub async fn disable_heartbeat(&self) -> Result<String, WebSocketError>

Disable heartbeat

Stops the server from sending heartbeat messages and test_request notifications.

§Returns

Returns "ok" on success

§Errors

Returns an error if the request fails

Source

pub async fn hello( &self, client_name: &str, client_version: &str, ) -> Result<HelloResponse, WebSocketError>

Send client identification to the server

This method identifies the client to the server with its name and version. It’s recommended to call this after connecting to provide debugging information.

§Arguments
  • client_name - Name of the client application
  • client_version - Version of the client application
§Returns

Returns HelloResponse containing the API version information

§Errors

Returns an error if the request fails

Source

pub async fn enable_cancel_on_disconnect( &self, ) -> Result<String, WebSocketError>

Enable automatic order cancellation on disconnect

When enabled, all open orders will be automatically cancelled if the WebSocket connection is lost. This is a safety feature to prevent unintended order execution when the client loses connectivity.

§Returns

Returns "ok" on success

§Errors

Returns an error if the request fails or requires authentication

Source

pub async fn disable_cancel_on_disconnect( &self, ) -> Result<String, WebSocketError>

Disable automatic order cancellation on disconnect

When disabled, orders will remain active even if the WebSocket connection is lost.

§Returns

Returns "ok" on success

§Errors

Returns an error if the request fails or requires authentication

Source

pub async fn get_cancel_on_disconnect(&self) -> Result<bool, WebSocketError>

Get current cancel-on-disconnect status

Returns whether automatic order cancellation on disconnect is currently enabled.

§Returns

Returns true if cancel-on-disconnect is enabled, false otherwise

§Errors

Returns an error if the request fails or requires authentication

Source

pub async fn mass_quote( &self, request: MassQuoteRequest, ) -> Result<MassQuoteResult, WebSocketError>

Place mass quotes

Source

pub async fn cancel_quotes( &self, request: CancelQuotesRequest, ) -> Result<CancelQuotesResponse, WebSocketError>

Cancel quotes

Source

pub async fn set_mmp_config( &self, config: MmpGroupConfig, ) -> Result<(), WebSocketError>

Set MMP group configuration

Source

pub async fn get_mmp_config( &self, mmp_group: Option<String>, ) -> Result<Vec<MmpGroupConfig>, WebSocketError>

Get MMP group configuration

Source

pub async fn reset_mmp( &self, mmp_group: Option<String>, ) -> Result<(), WebSocketError>

Reset MMP group

Source

pub async fn get_open_orders( &self, currency: Option<String>, kind: Option<String>, type_filter: Option<String>, ) -> Result<Vec<QuoteInfo>, WebSocketError>

Get open orders (including quotes)

Source

pub async fn buy( &self, request: OrderRequest, ) -> Result<OrderResponse, WebSocketError>

Place a buy order

§Arguments
  • request - The order request parameters
§Returns

Returns OrderResponse containing order info and any immediate trades

Source

pub async fn sell( &self, request: OrderRequest, ) -> Result<OrderResponse, WebSocketError>

Place a sell order

§Arguments
  • request - The order request parameters
§Returns

Returns OrderResponse containing order info and any immediate trades

Source

pub async fn cancel(&self, order_id: &str) -> Result<OrderInfo, WebSocketError>

Cancel an order by ID

§Arguments
  • order_id - The order ID to cancel
§Returns

Returns OrderInfo for the cancelled order

Source

pub async fn cancel_all(&self) -> Result<u32, WebSocketError>

Cancel all orders

§Returns

Returns the number of orders cancelled

Source

pub async fn cancel_all_by_currency( &self, currency: &str, ) -> Result<u32, WebSocketError>

Cancel all orders by currency

§Arguments
  • currency - Currency to cancel orders for (e.g., “BTC”, “ETH”)
§Returns

Returns the number of orders cancelled

Source

pub async fn cancel_all_by_instrument( &self, instrument_name: &str, ) -> Result<u32, WebSocketError>

Cancel all orders by instrument

§Arguments
  • instrument_name - Instrument name to cancel orders for (e.g., “BTC-PERPETUAL”)
§Returns

Returns the number of orders cancelled

Source

pub async fn edit( &self, request: EditOrderRequest, ) -> Result<OrderResponse, WebSocketError>

Edit an existing order

§Arguments
  • request - The edit order request parameters
§Returns

Returns OrderResponse containing updated order info and any trades

Source

pub async fn get_positions( &self, currency: Option<&str>, kind: Option<&str>, ) -> Result<Vec<Position>, WebSocketError>

Get positions for the specified currency and kind

Retrieves user positions filtered by currency and/or instrument kind.

§Arguments
  • currency - Currency filter (BTC, ETH, USDC, etc.) - optional
  • kind - Kind filter (future, option, spot, etc.) - optional
§Returns

A vector of positions matching the filter criteria

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn get_account_summary( &self, currency: &str, extended: Option<bool>, ) -> Result<AccountSummary, WebSocketError>

Get account summary for the specified currency

Retrieves account summary information including balance, margin, and other account details.

§Arguments
  • currency - Currency to get summary for (BTC, ETH, USDC, etc.)
  • extended - Whether to include extended information
§Returns

Account summary for the specified currency

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn get_order_state( &self, order_id: &str, ) -> Result<OrderInfo, WebSocketError>

Get the state of an order

Retrieves detailed information about a specific order.

§Arguments
  • order_id - The order ID to get state for
§Returns

Order information for the specified order

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn get_order_history_by_currency( &self, currency: &str, kind: Option<&str>, count: Option<u32>, ) -> Result<Vec<OrderInfo>, WebSocketError>

Get order history by currency

Retrieves historical orders for the specified currency.

§Arguments
  • currency - Currency to get order history for
  • kind - Kind filter (future, option, spot, etc.) - optional
  • count - Number of items to return - optional
§Returns

A vector of historical orders matching the filter criteria

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn close_position( &self, instrument_name: &str, order_type: &str, price: Option<f64>, ) -> Result<ClosePositionResponse, WebSocketError>

Close an existing position

Places a reduce-only order to close an existing position.

§Arguments
  • instrument_name - The instrument to close position for
  • order_type - Order type: “limit” or “market”
  • price - Price for limit orders (required if order_type is “limit”)
§Returns

Response containing the order and any trades executed

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub async fn move_positions( &self, currency: &str, source_uid: u64, target_uid: u64, trades: &[MovePositionTrade], ) -> Result<Vec<MovePositionResult>, WebSocketError>

Move positions between subaccounts

Transfers positions from one subaccount to another within the same main account.

§Arguments
  • currency - Currency for the positions (BTC, ETH, etc.)
  • source_uid - Source subaccount ID
  • target_uid - Target subaccount ID
  • trades - List of positions to move
§Returns

A vector of results for each position moved

§Errors

Returns an error if the request fails or the response cannot be parsed

Source

pub fn set_message_handler<F, E>( &mut self, message_callback: F, error_callback: E, )
where F: Fn(&str) -> Result<(), WebSocketError> + Send + Sync + 'static, E: Fn(&str, &WebSocketError) + Send + Sync + 'static,

Set message handler with callbacks The message_callback processes each incoming message and returns Result<(), Error> The error_callback is called only when message_callback returns an error

Source

pub fn set_message_handler_builder(&mut self, handler: MessageHandler)

Set message handler using builder pattern

Source

pub fn clear_message_handler(&mut self)

Remove the current message handler

Source

pub fn has_message_handler(&self) -> bool

Check if message handler is set

Source

pub async fn receive_and_process_message(&self) -> Result<(), WebSocketError>

Receive and process a message using the registered callbacks This method will:

  1. Receive a message from the WebSocket
  2. Call the primary callback with the message
  3. If primary callback returns error, call error callback with message and error
Source

pub async fn start_message_processing_loop(&self) -> Result<(), WebSocketError>

Start message processing loop with callbacks This will continuously receive messages and process them using the registered callbacks The loop will continue until an error occurs or the connection is closed

Trait Implementations§

Source§

impl Debug for DeribitWebSocketClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DeribitWebSocketClient

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more