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

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.

Source

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

Submit multiple orders through the Hyperliquid WebSocket post API.

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.

Source§

impl HyperliquidWebSocketClient

Source

pub fn py_url(&self) -> String

Returns the URL of this WebSocket client.

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

impl DerefToPyAny for HyperliquidWebSocketClient

Source§

impl<'a, 'py> FromPyObject<'a, 'py> for HyperliquidWebSocketClient
where Self: Clone,

Source§

type Error = PyClassGuardError<'a, 'py>

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

fn extract( obj: Borrowed<'a, 'py, PyAny>, ) -> Result<Self, <Self as FromPyObject<'a, 'py>>::Error>

Extracts Self from the bound smart pointer obj. Read more
Source§

impl<'py> IntoPyObject<'py> for HyperliquidWebSocketClient

Source§

type Target = HyperliquidWebSocketClient

The Python output type
Source§

type Output = Bound<'py, <HyperliquidWebSocketClient as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

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

fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>

Performs the conversion.
Source§

impl PyClass for HyperliquidWebSocketClient

Source§

const NAME: &str = "HyperliquidWebSocketClient"

Name of the class. Read more
Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for HyperliquidWebSocketClient

Source§

const MODULE: Option<&str>

Module which the class will be associated with. Read more
Source§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
Source§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
Source§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
Source§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
Source§

const IS_IMMUTABLE_TYPE: bool = false

#[pyclass(immutable_type)]
Source§

const RAW_DOC: &'static CStr = /// 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.

Docstring for the class provided on the struct or enum. Read more
Source§

const DOC: &'static CStr

Fully rendered class doc, including the text_signature if a constructor is defined. Read more
Source§

type Layout = <<HyperliquidWebSocketClient as PyClassImpl>::BaseNativeType as PyClassBaseType>::Layout<HyperliquidWebSocketClient>

Description of how this class is laid out in memory
Source§

type BaseType = PyAny

Base class
Source§

type ThreadChecker = NoopThreadChecker

This handles following two situations: Read more
Source§

type Inventory = Pyo3MethodsInventoryForHyperliquidWebSocketClient

Source§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
Source§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
Source§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
Source§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
Source§

fn items_iter() -> PyClassItemsIter

Source§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

Source§

fn dict_offset() -> Option<PyObjectOffset>

Used to provide the dictoffset slot (equivalent to tp_dictoffset)
Source§

fn weaklist_offset() -> Option<PyObjectOffset>

Used to provide the weaklistoffset slot (equivalent to tp_weaklistoffset
Source§

impl PyClassNewTextSignature for HyperliquidWebSocketClient

Source§

const TEXT_SIGNATURE: &'static str = "(url=None, environment=..., account_id=None, proxy_url=None)"

Source§

impl PyStubType for HyperliquidWebSocketClient

Source§

fn type_output() -> TypeInfo

The type to be used in the output signature, i.e. return type of the Python function or methods.
Source§

fn type_input() -> TypeInfo

The type to be used in the input signature, i.e. the arguments of the Python function or methods. Read more
Source§

impl PyTypeInfo for HyperliquidWebSocketClient

Source§

const NAME: &str = <Self as ::pyo3::PyClass>::NAME

👎Deprecated since 0.28.0:

prefer using ::type_object(py).name() to get the correct runtime value

Class name.
Source§

const MODULE: Option<&str> = <Self as ::pyo3::impl_::pyclass::PyClassImpl>::MODULE

👎Deprecated since 0.28.0:

prefer using ::type_object(py).module() to get the correct runtime value

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
Source§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
Source§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
Source§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.

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<'py, T> FromPyObjectOwned<'py> for T
where T: for<'a> FromPyObject<'a, 'py>,

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<'py, T> IntoPyObjectExt<'py> for T
where T: IntoPyObject<'py>,

Source§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
Source§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts self into an owned Python object, dropping type information and unbinding it from the 'py lifetime.
Source§

fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>

Converts self into a Python object. Read more
Source§

impl<'py, T> IntoPyObjectNautilusExt<'py> for T
where T: IntoPyObjectExt<'py>,

Source§

fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny>

Convert self into a Py<PyAny> while panicking if the conversion fails. 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> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

Source§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
Source§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

Source§

const NAME: &'static str = T::NAME

👎Deprecated since 0.27.0:

Use ::classinfo_object() instead and format the type name at runtime. Note that using built-in cast features is often better than manual PyTypeCheck usage.

Name of self. This is used in error messages, for example.
Source§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
Source§

fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

Returns the expected type as a possible argument for the isinstance and issubclass function. 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<T> Ungil for T
where T: Send,

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