Skip to main content

DydxWebSocketClient

Struct DydxWebSocketClient 

Source
pub struct DydxWebSocketClient { /* private fields */ }
Expand description

WebSocket client for dYdX v4 market data and account streams.

§Authentication

dYdX v4 does not require traditional API key signatures for WebSocket connections. Public channels work without any credentials. Private channels (subaccounts) only need the wallet address included in the subscription message.

The DydxCredential stored in this client is used for:

  • Providing the wallet address for private channel subscriptions
  • Transaction signing (when placing orders via the validator node)

It is NOT used for WebSocket message signing or authentication.

§Architecture

The client owns a small pool of connection slots. Each slot has its own WebSocketClient, FeedHandler task, command channel, and [SubscriptionState]. All slots write parsed events into a single shared output channel so callers see one merged stream.

Implementations§

Source§

impl DydxWebSocketClient

Source

pub fn new_public( url: String, heartbeat: Option<u64>, proxy_url: Option<String>, ) -> Self

Creates a new public WebSocket client for market data.

This creates a new independent instrument cache. To share a cache with the HTTP client, use Self::new_public_with_cache instead.

Source

pub fn new_public_with_cache( url: String, instrument_cache: Arc<InstrumentCache>, heartbeat: Option<u64>, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new public WebSocket client with a shared instrument cache.

Use this when you want to share instrument data with the HTTP client.

Source

pub fn new_public_with_cache_and_pool( url: String, instrument_cache: Arc<InstrumentCache>, heartbeat: Option<u64>, transport_backend: TransportBackend, proxy_url: Option<String>, max_ws_connections: usize, per_channel_limit: usize, ) -> Self

Creates a new public WebSocket client with full pool configuration.

Source

pub fn new_private( url: String, credential: DydxCredential, account_id: AccountId, heartbeat: Option<u64>, proxy_url: Option<String>, ) -> Self

Creates a new private WebSocket client for account updates.

This creates a new independent instrument cache. To share a cache with the HTTP client, use Self::new_private_with_cache instead.

Source

pub fn new_private_with_cache( url: String, credential: DydxCredential, account_id: AccountId, instrument_cache: Arc<InstrumentCache>, heartbeat: Option<u64>, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new private WebSocket client with a shared instrument cache.

Use this when you want to share instrument data with the HTTP client.

Source

pub fn with_socket_factory(self, factory: SocketControlFactory) -> Self

Configures socket state reporting and reconnect control for each pool slot.

Source

pub fn credential(&self) -> Option<&Arc<DydxCredential>>

Returns the credential associated with this client, if any.

Source

pub fn is_connected(&self) -> bool

Returns true when any connection in the pool is connected.

Source

pub fn url(&self) -> &str

Returns the URL of this WebSocket client.

Source

pub fn connection_mode_atomic(&self) -> Arc<ArcSwap<AtomicU8>>

Returns a clone of the connection mode atomic reference.

With sharding, the returned atomic tracks the primary slot (slot 0) only; use Self::is_connected for a pool-wide check.

Source

pub fn pool_size(&self) -> usize

Returns the current number of active slots in the pool.

Source

pub const fn max_ws_connections(&self) -> usize

Returns the configured maximum number of pool connections.

Source

pub const fn per_channel_limit(&self) -> usize

Returns the configured per-channel subscription limit.

Source

pub fn set_account_id(&mut self, account_id: AccountId)

Sets the account ID for account message parsing.

Source

pub fn account_id(&self) -> Option<AccountId>

Returns the account ID if set.

Source

pub fn set_instrument_cache(&mut self, cache: Arc<InstrumentCache>)

Replaces the instrument cache with an externally shared one.

Use this to share the HTTP client’s cache (which includes CLOB pair ID and market ticker indices) with the WebSocket client. Must be called before connect().

Source

pub fn cache_instrument(&self, instrument: InstrumentAny)

Caches a single instrument.

Any existing instrument with the same ID will be replaced.

Source

pub fn cache_instruments(&self, instruments: Vec<InstrumentAny>)

Caches multiple instruments.

Any existing instruments with the same IDs will be replaced.

Source

pub fn instrument_cache(&self) -> &Arc<InstrumentCache>

Returns a reference to the shared instrument cache.

Source

pub fn encoder(&self) -> &Arc<ClientOrderIdEncoder>

Returns a reference to the shared client order ID encoder.

Source

pub fn bar_types(&self) -> &Arc<DashMap<String, BarType>>

Returns a reference to the bar type registrations map.

Source

pub fn ws_dispatch_state(&self) -> &Arc<DydxWsDispatchState>

Returns a reference to the shared WebSocket dispatch state.

Source

pub fn set_bars_timestamp_on_close(&self, value: bool)

Sets whether bar timestamps use the close time.

Source

pub fn bars_timestamp_on_close(&self) -> bool

Returns whether bar timestamps use the close time.

Source

pub fn all_instruments(&self) -> Vec<InstrumentAny>

Returns all cached instruments.

This is a snapshot of the current cache contents.

Source

pub fn cached_instruments_count(&self) -> usize

Returns the number of cached instruments.

Source

pub fn get_instrument( &self, instrument_id: &InstrumentId, ) -> Option<InstrumentAny>

Retrieves an instrument from the cache by InstrumentId.

Returns None if the instrument is not found.

Source

pub fn get_instrument_by_market(&self, ticker: &str) -> Option<InstrumentAny>

Retrieves an instrument from the cache by market ticker (e.g., “BTC-USD”).

Returns None if the instrument is not found.

Source

pub fn take_receiver( &mut self, ) -> Option<UnboundedReceiver<DydxWsOutputMessage>>

Takes ownership of the inbound message receiver. Returns None if the receiver has already been taken or not connected.

Source

pub fn stream( &mut self, ) -> impl Stream<Item = DydxWsOutputMessage> + Send + 'static

Returns a stream of venue-specific WebSocket messages.

Takes ownership of the message receiver and returns it as a Stream.

§Panics

Panics if the message receiver has already been taken or the client is not connected.

Source

pub async fn connect(&mut self) -> DydxWsResult<()>

Connects the websocket client and opens the primary pool slot.

Additional slots are spawned lazily by subscribe_* methods once the per-channel limit is reached on every existing slot.

§Errors

Returns an error if the connection cannot be established.

Source

pub async fn disconnect(&mut self) -> DydxWsResult<()>

Disconnects all websocket connections in the pool.

§Errors

Returns an error if the underlying clients cannot be accessed.

Source

pub fn send_command(&self, cmd: HandlerCommand) -> DydxWsResult<()>

Sends a command directly to the primary slot (slot 0).

§Errors

Returns an error if no slot exists or the handler task has terminated.

Source

pub async fn subscribe_trades( &self, instrument_id: InstrumentId, ) -> DydxWsResult<()>

Subscribes to public trade updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://docs.dydx.trade/developers/indexer/websockets#trades-channel

Source

pub async fn unsubscribe_trades( &self, instrument_id: InstrumentId, ) -> DydxWsResult<()>

Unsubscribes from public trade updates for a specific instrument.

§Errors

Returns an error if the unsubscription request fails.

Source

pub async fn subscribe_orderbook( &self, instrument_id: InstrumentId, ) -> DydxWsResult<()>

Subscribes to orderbook updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://docs.dydx.trade/developers/indexer/websockets#orderbook-channel

Source

pub async fn unsubscribe_orderbook( &self, instrument_id: InstrumentId, ) -> DydxWsResult<()>

Unsubscribes from orderbook updates for a specific instrument.

§Errors

Returns an error if the unsubscription request fails.

Source

pub async fn subscribe_candles( &self, instrument_id: InstrumentId, resolution: &str, ) -> DydxWsResult<()>

Subscribes to candle/kline updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://docs.dydx.trade/developers/indexer/websockets#candles-channel

Source

pub async fn unsubscribe_candles( &self, instrument_id: InstrumentId, resolution: &str, ) -> DydxWsResult<()>

Unsubscribes from candle/kline updates for a specific instrument.

§Errors

Returns an error if the unsubscription request fails.

Source

pub async fn subscribe_markets(&self) -> DydxWsResult<()>

Subscribes to market updates for all instruments.

§Errors

Returns an error if the subscription request fails.

§References

https://docs.dydx.trade/developers/indexer/websockets#markets-channel

Source

pub async fn unsubscribe_markets(&self) -> DydxWsResult<()>

Unsubscribes from market updates.

§Errors

Returns an error if the unsubscription request fails.

Source

pub async fn subscribe_subaccount( &self, address: &str, subaccount_number: u32, ) -> DydxWsResult<()>

Subscribes to subaccount updates (orders, fills, positions, balances).

This requires authentication and will only work for private WebSocket clients created with Self::new_private. Subaccount streams stay pinned to the primary slot: the Indexer caps them at 256 per connection, which is well above realistic per-process usage and keeps related fill/position events on a single in-order stream.

§Errors

Returns an error if the client was not created with credentials or if the subscription request fails.

§References

https://docs.dydx.trade/developers/indexer/websockets#subaccounts-channel

Source

pub async fn unsubscribe_subaccount( &self, address: &str, subaccount_number: u32, ) -> DydxWsResult<()>

Unsubscribes from subaccount updates.

§Errors

Returns an error if the unsubscription request fails.

Source

pub async fn subscribe_block_height(&self) -> DydxWsResult<()>

Subscribes to block height updates.

§Errors

Returns an error if the subscription request fails.

§References

https://docs.dydx.trade/developers/indexer/websockets#block-height-channel

Source

pub async fn unsubscribe_block_height(&self) -> DydxWsResult<()>

Unsubscribes from block height updates.

§Errors

Returns an error if the unsubscription request fails.

Trait Implementations§

Source§

impl Clone for DydxWebSocketClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DydxWebSocketClient

Source§

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

Formats the value using the given formatter. 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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

impl<T> Ungil for T
where T: Send,

§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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