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
impl DydxWebSocketClient
Sourcepub fn new_public(
url: String,
heartbeat: Option<u64>,
proxy_url: Option<String>,
) -> Self
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.
Sourcepub fn new_public_with_cache(
url: String,
instrument_cache: Arc<InstrumentCache>,
heartbeat: Option<u64>,
transport_backend: TransportBackend,
proxy_url: Option<String>,
) -> Self
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.
Sourcepub 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
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.
Sourcepub fn new_private(
url: String,
credential: DydxCredential,
account_id: AccountId,
heartbeat: Option<u64>,
proxy_url: Option<String>,
) -> Self
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.
Sourcepub 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
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.
Sourcepub fn with_socket_factory(self, factory: SocketControlFactory) -> Self
pub fn with_socket_factory(self, factory: SocketControlFactory) -> Self
Configures socket state reporting and reconnect control for each pool slot.
Sourcepub fn credential(&self) -> Option<&Arc<DydxCredential>>
pub fn credential(&self) -> Option<&Arc<DydxCredential>>
Returns the credential associated with this client, if any.
Sourcepub fn is_connected(&self) -> bool
pub fn is_connected(&self) -> bool
Returns true when any connection in the pool is connected.
Sourcepub fn connection_mode_atomic(&self) -> Arc<ArcSwap<AtomicU8>> ⓘ
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.
Sourcepub const fn max_ws_connections(&self) -> usize
pub const fn max_ws_connections(&self) -> usize
Returns the configured maximum number of pool connections.
Sourcepub const fn per_channel_limit(&self) -> usize
pub const fn per_channel_limit(&self) -> usize
Returns the configured per-channel subscription limit.
Sourcepub fn set_account_id(&mut self, account_id: AccountId)
pub fn set_account_id(&mut self, account_id: AccountId)
Sets the account ID for account message parsing.
Sourcepub fn account_id(&self) -> Option<AccountId>
pub fn account_id(&self) -> Option<AccountId>
Returns the account ID if set.
Sourcepub fn set_instrument_cache(&mut self, cache: Arc<InstrumentCache>)
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().
Sourcepub fn cache_instrument(&self, instrument: InstrumentAny)
pub fn cache_instrument(&self, instrument: InstrumentAny)
Caches a single instrument.
Any existing instrument with the same ID will be replaced.
Sourcepub fn cache_instruments(&self, instruments: Vec<InstrumentAny>)
pub fn cache_instruments(&self, instruments: Vec<InstrumentAny>)
Caches multiple instruments.
Any existing instruments with the same IDs will be replaced.
Sourcepub fn instrument_cache(&self) -> &Arc<InstrumentCache> ⓘ
pub fn instrument_cache(&self) -> &Arc<InstrumentCache> ⓘ
Returns a reference to the shared instrument cache.
Sourcepub fn encoder(&self) -> &Arc<ClientOrderIdEncoder> ⓘ
pub fn encoder(&self) -> &Arc<ClientOrderIdEncoder> ⓘ
Returns a reference to the shared client order ID encoder.
Sourcepub fn bar_types(&self) -> &Arc<DashMap<String, BarType>> ⓘ
pub fn bar_types(&self) -> &Arc<DashMap<String, BarType>> ⓘ
Returns a reference to the bar type registrations map.
Sourcepub fn ws_dispatch_state(&self) -> &Arc<DydxWsDispatchState> ⓘ
pub fn ws_dispatch_state(&self) -> &Arc<DydxWsDispatchState> ⓘ
Returns a reference to the shared WebSocket dispatch state.
Sourcepub fn set_bars_timestamp_on_close(&self, value: bool)
pub fn set_bars_timestamp_on_close(&self, value: bool)
Sets whether bar timestamps use the close time.
Sourcepub fn bars_timestamp_on_close(&self) -> bool
pub fn bars_timestamp_on_close(&self) -> bool
Returns whether bar timestamps use the close time.
Sourcepub fn all_instruments(&self) -> Vec<InstrumentAny>
pub fn all_instruments(&self) -> Vec<InstrumentAny>
Returns all cached instruments.
This is a snapshot of the current cache contents.
Sourcepub fn cached_instruments_count(&self) -> usize
pub fn cached_instruments_count(&self) -> usize
Returns the number of cached instruments.
Sourcepub fn get_instrument(
&self,
instrument_id: &InstrumentId,
) -> Option<InstrumentAny>
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.
Sourcepub fn get_instrument_by_market(&self, ticker: &str) -> Option<InstrumentAny>
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.
Sourcepub fn take_receiver(
&mut self,
) -> Option<UnboundedReceiver<DydxWsOutputMessage>>
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.
Sourcepub fn stream(
&mut self,
) -> impl Stream<Item = DydxWsOutputMessage> + Send + 'static
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.
Sourcepub async fn connect(&mut self) -> DydxWsResult<()>
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.
Sourcepub async fn disconnect(&mut self) -> DydxWsResult<()>
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.
Sourcepub fn send_command(&self, cmd: HandlerCommand) -> DydxWsResult<()>
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.
Sourcepub async fn subscribe_trades(
&self,
instrument_id: InstrumentId,
) -> DydxWsResult<()>
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
Sourcepub async fn unsubscribe_trades(
&self,
instrument_id: InstrumentId,
) -> DydxWsResult<()>
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.
Sourcepub async fn subscribe_orderbook(
&self,
instrument_id: InstrumentId,
) -> DydxWsResult<()>
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
Sourcepub async fn unsubscribe_orderbook(
&self,
instrument_id: InstrumentId,
) -> DydxWsResult<()>
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.
Sourcepub async fn subscribe_candles(
&self,
instrument_id: InstrumentId,
resolution: &str,
) -> DydxWsResult<()>
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
Sourcepub async fn unsubscribe_candles(
&self,
instrument_id: InstrumentId,
resolution: &str,
) -> DydxWsResult<()>
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.
Sourcepub async fn subscribe_markets(&self) -> DydxWsResult<()>
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
Sourcepub async fn unsubscribe_markets(&self) -> DydxWsResult<()>
pub async fn unsubscribe_markets(&self) -> DydxWsResult<()>
Sourcepub async fn subscribe_subaccount(
&self,
address: &str,
subaccount_number: u32,
) -> DydxWsResult<()>
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
Sourcepub async fn unsubscribe_subaccount(
&self,
address: &str,
subaccount_number: u32,
) -> DydxWsResult<()>
pub async fn unsubscribe_subaccount( &self, address: &str, subaccount_number: u32, ) -> DydxWsResult<()>
Sourcepub async fn subscribe_block_height(&self) -> DydxWsResult<()>
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
Sourcepub async fn unsubscribe_block_height(&self) -> DydxWsResult<()>
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
impl Clone for DydxWebSocketClient
Auto Trait Implementations§
impl !RefUnwindSafe for DydxWebSocketClient
impl !UnwindSafe for DydxWebSocketClient
impl Freeze for DydxWebSocketClient
impl Send for DydxWebSocketClient
impl Sync for DydxWebSocketClient
impl Unpin for DydxWebSocketClient
impl UnsafeUnpin for DydxWebSocketClient
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].