Skip to main content

HyperliquidWebSocketClient

Struct HyperliquidWebSocketClient 

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

Hyperliquid WebSocket client following the BitMEX pattern.

Orchestrates WebSocket connection and subscriptions using a command-based architecture, where the inner FeedHandler owns the WebSocketClient and handles all I/O.

Implementations§

Source§

impl HyperliquidWebSocketClient

Source

pub fn new( url: Option<String>, environment: HyperliquidEnvironment, account_id: Option<AccountId>, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new Hyperliquid WebSocket client without connecting.

If url is None, the appropriate URL will be determined from the environment:

  • Mainnet: wss://api.hyperliquid.xyz/ws
  • Testnet: wss://api.hyperliquid-testnet.xyz/ws

The connection will be established when connect() is called.

Source

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

Establishes WebSocket connection and spawns the message handler.

Source

pub fn take_task_handle(&mut self) -> Option<JoinHandle<()>>

Takes the handler task handle from this client so that another instance (e.g., the non-clone original) can await it on disconnect.

Source

pub fn set_task_handle(&mut self, handle: JoinHandle<()>)

Source

pub fn set_post_timeout(&mut self, timeout: Duration)

Source

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

Disconnects the WebSocket connection.

Source

pub async fn post_action_exec( &self, signer: &HyperliquidHttpClient, action: &HyperliquidExecAction, ) -> HyperliquidResult<HyperliquidExchangeResponse>

Send a typed exchange action through the Hyperliquid WebSocket post API.

The supplied HTTP client is used only as the canonical signer for the action envelope. The signed payload is sent over the active WebSocket connection and the response is correlated by post id.

Source

pub async fn post_action_exec_with_timeout( &self, signer: &HyperliquidHttpClient, action: &HyperliquidExecAction, timeout: Duration, expires_after: Option<u64>, ) -> HyperliquidResult<HyperliquidExchangeResponse>

Send a typed exchange action with a caller-specified timeout and optional expiry.

Source

pub async fn submit_order( &self, signer: &HyperliquidHttpClient, instrument_id: InstrumentId, client_order_id: ClientOrderId, order_side: OrderSide, order_type: OrderType, quantity: Quantity, time_in_force: TimeInForce, price: Option<Price>, trigger_price: Option<Price>, post_only: bool, reduce_only: bool, ) -> HyperliquidResult<Option<OrderStatusReport>>

Submit an order through the Hyperliquid WebSocket post API.

The HTTP client supplies signing credentials, builder attribution, and cached instrument metadata. The action itself is sent over WebSocket.

Returns an OrderStatusReport describing the venue’s immediate response (Filled for an atomic IOC fill, Accepted for a resting order), or None when the venue deferred the order without an oid (for example a waitingForFill trigger child): the order stays SUBMITTED until the user-events stream delivers the first OrderAccepted.

Source

pub async fn submit_orders( &self, signer: &HyperliquidHttpClient, orders: &[&OrderAny], ) -> HyperliquidResult<Vec<OrderStatusReport>>

Submit multiple orders through the Hyperliquid WebSocket post API.

Returns one OrderStatusReport per accepted order in submission order. Deferred trigger children of a normalTpsl bracket are absent from the result; they stay SUBMITTED until the user-events stream delivers an OrderAccepted with the real oid.

Source

pub async fn cancel_order( &self, signer: &HyperliquidHttpClient, instrument_id: InstrumentId, client_order_id: Option<ClientOrderId>, venue_order_id: Option<VenueOrderId>, ) -> HyperliquidResult<()>

Cancel an order through the Hyperliquid WebSocket post API.

Source

pub async fn cancel_orders( &self, signer: &HyperliquidHttpClient, cancels: &[(InstrumentId, ClientOrderId, Option<VenueOrderId>)], ) -> HyperliquidResult<Vec<Option<String>>>

Cancel multiple orders through one Hyperliquid WebSocket post action.

Source

pub async fn modify_order( &self, signer: &HyperliquidHttpClient, instrument_id: InstrumentId, venue_order_id: VenueOrderId, order_side: OrderSide, order_type: OrderType, price: Price, quantity: Quantity, trigger_price: Option<Price>, reduce_only: bool, post_only: bool, time_in_force: TimeInForce, client_order_id: Option<ClientOrderId>, ) -> HyperliquidResult<()>

Modify an order through the Hyperliquid WebSocket post API.

Source

pub fn is_active(&self) -> bool

Returns true if the WebSocket is actively connected.

Source

pub fn url(&self) -> &str

Returns the URL of this WebSocket client.

Source

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

Caches multiple instruments.

Clears the existing cache first, then adds all provided instruments. Instruments are keyed by their raw_symbol which is unique per instrument:

  • Perps use base currency (e.g., “BTC”)
  • Spot uses @{pair_index} format (e.g., “@107”) or slash format for PURR
Source

pub fn cache_instrument(&self, instrument: InstrumentAny)

Caches a single instrument.

Any existing instrument with the same raw_symbol will be replaced.

Source

pub fn instruments_cache(&self) -> Arc<AtomicMap<Ustr, InstrumentAny>>

Returns a shared reference to the instrument cache.

Source

pub fn cache_spot_fill_coins(&self, mapping: AHashMap<Ustr, Ustr>)

Caches spot fill coin mappings for instrument lookup.

Hyperliquid WebSocket fills for spot use @{pair_index} format (e.g., @107), while instruments are identified by full symbols (e.g., HYPE-USDC-SPOT). This mapping allows the handler to look up instruments from spot fills.

Source

pub fn cache_cloid_mapping(&self, cloid: Ustr, client_order_id: ClientOrderId)

Caches a venue CLOID to client_order_id mapping for order/fill resolution.

This mapping allows WebSocket order status and fill reports to be resolved back to the original client_order_id.

This writes directly to a shared cache that the handler reads from, avoiding any race conditions between caching and WebSocket message processing.

Source

pub fn remove_cloid_mapping(&self, cloid: &Ustr)

Removes a cloid mapping from the cache.

Called on terminal order state. The cache is FIFO-bounded so missed removals self-evict (see GH-3972 cancel-replace drain).

Source

pub fn clear_cloid_cache(&self)

Clears all cloid mappings from the cache.

Useful for cleanup during reconnection or shutdown.

Source

pub fn cloid_cache_len(&self) -> usize

Returns the number of cloid mappings in the cache.

Source

pub fn get_cloid_mapping(&self, cloid: &Ustr) -> Option<ClientOrderId>

Looks up a client_order_id by its venue CLOID.

Returns Some(ClientOrderId) if the mapping exists, None otherwise.

Source

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

Gets an instrument from the cache by ID.

Searches the cache for a matching instrument ID.

Source

pub fn get_instrument_by_symbol(&self, symbol: &Ustr) -> Option<InstrumentAny>

Gets an instrument from the cache by raw_symbol (coin).

Source

pub fn subscription_count(&self) -> usize

Returns the count of confirmed subscriptions.

Source

pub fn get_bar_type(&self, coin: &str, interval: &str) -> Option<BarType>

Gets a bar type from the cache by coin and interval.

This looks up the subscription key created when subscribing to bars.

Source

pub async fn subscribe_book(&self, instrument_id: InstrumentId) -> Result<()>

Subscribe to L2 order book for an instrument.

Source

pub async fn subscribe_book_with_options( &self, instrument_id: InstrumentId, n_sig_figs: Option<u32>, mantissa: Option<u32>, ) -> Result<()>

Subscribe to L2 order book with optional nSigFigs / mantissa precision controls passed through to the venue’s l2Book stream.

Source

pub async fn subscribe_book_depth10( &self, instrument_id: InstrumentId, ) -> Result<()>

Subscribe to order book depth-10 snapshots.

Reuses the same l2Book WebSocket subscription as Self::subscribe_book and flags the handler to additionally emit NautilusWsMessage::Depth10 for this coin.

Source

pub async fn subscribe_book_depth10_with_options( &self, instrument_id: InstrumentId, n_sig_figs: Option<u32>, mantissa: Option<u32>, ) -> Result<()>

Subscribe to depth-10 snapshots with optional nSigFigs / mantissa precision controls.

Source

pub async fn unsubscribe_book_depth10( &self, instrument_id: InstrumentId, ) -> Result<()>

Unsubscribe from order book depth-10 snapshots.

Clears the depth10 emission flag only; the underlying l2Book stream stays open so active deltas subscribers keep receiving updates. Call Self::unsubscribe_book separately to tear down the stream entirely.

Source

pub async fn subscribe_quotes(&self, instrument_id: InstrumentId) -> Result<()>

Subscribe to best bid/offer (BBO) quotes for an instrument.

Source

pub async fn subscribe_all_mids(&self) -> Result<()>

Subscribe to all mid prices across markets.

Source

pub async fn subscribe_all_dexs_asset_ctxs(&self) -> Result<()>

Subscribe to aggregate asset contexts across all perp dexes.

Source

pub async fn subscribe_all_mids_with_dex(&self, dex: Option<&str>) -> Result<()>

Subscribe to all mid prices across markets, optionally scoped to a specific dex.

Source

pub async fn unsubscribe_all_mids(&self) -> Result<()>

Unsubscribe from all mid prices across markets.

Source

pub async fn unsubscribe_all_dexs_asset_ctxs(&self) -> Result<()>

Unsubscribe from aggregate asset contexts across all perp dexes.

Source

pub async fn unsubscribe_all_mids_with_dex( &self, dex: Option<&str>, ) -> Result<()>

Unsubscribe from all mid prices across markets, optionally scoped to a specific dex.

Source

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

Subscribe to trades for an instrument.

Source

pub async fn subscribe_mark_prices( &self, instrument_id: InstrumentId, ) -> Result<()>

Subscribe to mark price updates for an instrument.

Source

pub async fn subscribe_index_prices( &self, instrument_id: InstrumentId, ) -> Result<()>

Subscribe to index/oracle price updates for an instrument.

Source

pub async fn subscribe_bars(&self, bar_type: BarType) -> Result<()>

Subscribe to candle/bar data for a specific coin and interval.

Source

pub async fn subscribe_funding_rates( &self, instrument_id: InstrumentId, ) -> Result<()>

Subscribe to funding rate updates for an instrument.

Source

pub async fn subscribe_open_interest( &self, instrument_id: InstrumentId, ) -> Result<()>

Subscribe to open interest updates for an instrument.

Source

pub async fn subscribe_order_updates(&self, user: &str) -> Result<()>

Subscribe to order updates for a specific user address.

Source

pub async fn subscribe_user_events(&self, user: &str) -> Result<()>

Subscribe to user events (fills, funding, liquidations) for a specific user address.

Source

pub async fn subscribe_user_fills(&self, user: &str) -> Result<()>

Subscribe to user fills for a specific user address.

Note: This channel is redundant with userEvents which already includes fills. Prefer using subscribe_user_events or subscribe_all_user_channels instead.

Source

pub async fn subscribe_all_user_channels(&self, user: &str) -> Result<()>

Subscribe to all user channels (order updates + user events) for convenience.

Note: userEvents already includes fills, so we don’t subscribe to userFills separately to avoid duplicate fill messages.

Source

pub async fn unsubscribe_book(&self, instrument_id: InstrumentId) -> Result<()>

Unsubscribe from L2 order book for an instrument.

Source

pub async fn unsubscribe_quotes( &self, instrument_id: InstrumentId, ) -> Result<()>

Unsubscribe from quote ticks for an instrument.

Source

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

Unsubscribe from trades for an instrument.

Source

pub async fn unsubscribe_mark_prices( &self, instrument_id: InstrumentId, ) -> Result<()>

Unsubscribe from mark price updates for an instrument.

Source

pub async fn unsubscribe_index_prices( &self, instrument_id: InstrumentId, ) -> Result<()>

Unsubscribe from index/oracle price updates for an instrument.

Source

pub async fn unsubscribe_bars(&self, bar_type: BarType) -> Result<()>

Unsubscribe from candle/bar data.

Source

pub async fn unsubscribe_funding_rates( &self, instrument_id: InstrumentId, ) -> Result<()>

Unsubscribe from funding rate updates for an instrument.

Source

pub async fn unsubscribe_open_interest( &self, instrument_id: InstrumentId, ) -> Result<()>

Unsubscribe from open interest updates for an instrument.

Source

pub fn cache_all_dex_asset_ctxs_instrument_ids( &self, mapping: AHashMap<Ustr, Vec<Option<InstrumentId>>>, )

Cache the ordered instrument IDs required to normalize allDexsAssetCtxs.

Source

pub async fn next_event(&mut self) -> Option<NautilusWsMessage>

Receives the next message from the WebSocket handler.

Returns None if the handler has disconnected or the receiver was already taken.

Trait Implementations§

Source§

impl Clone for HyperliquidWebSocketClient

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 HyperliquidWebSocketClient

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

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

Source§

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.

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

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

Source§

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

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

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