Skip to main content

HyperliquidHttpClient

Struct HyperliquidHttpClient 

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

Provides a high-level HTTP client for the Hyperliquid REST API.

This domain client wraps HyperliquidRawHttpClient and provides methods that work with Nautilus domain types. It maintains an instrument cache and handles conversions between Hyperliquid API responses and Nautilus domain models.

Implementations§

Source§

impl HyperliquidHttpClient

Source

pub fn new( is_testnet: bool, timeout_secs: u64, proxy_url: Option<String>, ) -> Result<Self, HttpClientError>

Creates a new HyperliquidHttpClient for public endpoints only.

§Errors

Returns an error if the HTTP client cannot be created.

Source

pub fn with_secrets( secrets: &Secrets, timeout_secs: u64, proxy_url: Option<String>, ) -> Result<Self, HttpClientError>

Creates a new HyperliquidHttpClient configured with a Secrets struct.

§Errors

Returns an error if the HTTP client cannot be created.

Source

pub fn set_base_info_url(&mut self, url: String)

Overrides the base info URL (for testing with mock servers).

§Panics

Panics if the inner Arc has multiple references.

Source

pub fn set_base_exchange_url(&mut self, url: String)

Overrides the base exchange URL (for testing with mock servers).

§Panics

Panics if the inner Arc has multiple references.

Source

pub fn from_env(is_testnet: bool) -> Result<Self>

Creates an authenticated client from environment variables for the specified network.

§Errors

Returns Error::Auth if required environment variables are not set.

Source

pub fn with_credentials( private_key: Option<String>, vault_address: Option<String>, account_address: Option<String>, is_testnet: bool, timeout_secs: u64, proxy_url: Option<String>, ) -> Result<Self>

Creates a new HyperliquidHttpClient configured with credentials.

If credentials are not provided, falls back to environment variables:

  • Testnet: HYPERLIQUID_TESTNET_PK, HYPERLIQUID_TESTNET_VAULT
  • Mainnet: HYPERLIQUID_PK, HYPERLIQUID_VAULT

If no credentials are provided and no environment variables are set, creates an unauthenticated client for public endpoints only.

§Errors

Returns Error::Auth if credentials are invalid.

Source

pub fn from_credentials( private_key: &str, vault_address: Option<&str>, is_testnet: bool, timeout_secs: u64, proxy_url: Option<String>, ) -> Result<Self>

Creates a new HyperliquidHttpClient configured with explicit credentials.

§Errors

Returns Error::Auth if the private key is invalid or cannot be parsed.

Source

pub fn is_testnet(&self) -> bool

Returns whether this client is configured for testnet.

Source

pub fn normalize_prices(&self) -> bool

Returns whether order price normalization is enabled.

Source

pub fn set_normalize_prices(&mut self, value: bool)

Sets whether to normalize order prices to 5 significant figures.

Source

pub fn get_user_address(&self) -> Result<String>

Gets the user address derived from the private key (if client has credentials).

§Errors

Returns Error::Auth if the client has no signer configured.

Source

pub fn has_vault_address(&self) -> bool

Returns true if a vault address is configured.

Source

pub fn get_account_address(&self) -> Result<String>

Gets the account address for queries: account_address if configured (agent wallet), then vault address, otherwise the user (EOA) address.

§Errors

Returns Error::Auth if the client has no signer configured and no account_address override is set.

Source

pub fn set_account_address(&mut self, address: Option<String>)

Sets the account address override for queries (agent wallet support).

Source

pub fn cache_instrument(&self, instrument: &InstrumentAny)

Caches a single instrument.

This is required for parsing orders, fills, and positions into reports. Any existing instrument with the same symbol will be replaced.

Source

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

Set the account ID for this client.

This is required for generating reports with the correct account ID.

Source

pub async fn request_instrument_defs( &self, ) -> Result<Vec<HyperliquidInstrumentDef>>

Fetch and parse all instrument definitions, populating the asset indices cache.

Source

pub fn convert_defs( &self, defs: Vec<HyperliquidInstrumentDef>, ) -> Vec<InstrumentAny>

Converts instrument definitions into Nautilus instruments.

Source

pub async fn request_instruments(&self) -> Result<Vec<InstrumentAny>>

Fetch and parse all available instrument definitions from Hyperliquid.

Source

pub fn get_asset_index(&self, symbol: &str) -> Option<u32>

Get asset index for a symbol from the cached map.

For perps: index in meta.universe (0, 1, 2, …). For spot: 10_000 + index in spotMeta.universe. For HIP-3: 100_000 + dex_index * 10_000 + index in dex meta.universe.

Returns None if the symbol is not found in the map.

Source

pub fn get_price_precision(&self, symbol: &str) -> Option<u8>

Get the price precision for a cached instrument by symbol.

Source

pub fn get_spot_fill_coin_mapping(&self) -> AHashMap<Ustr, Ustr>

Get mapping from spot fill coin identifiers to instrument symbols.

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 looking up the instrument from a spot fill.

This method also caches the mapping internally for use by fill parsing methods.

Source

pub async fn info_l2_book(&self, coin: &str) -> Result<HyperliquidL2Book>

Get L2 order book for a coin.

Source

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

Get user fills (trading history).

Source

pub async fn info_order_status( &self, user: &str, oid: u64, ) -> Result<HyperliquidOrderStatus>

Get order status for a user.

Source

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

Get all open orders for a user.

Source

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

Get frontend open orders (includes more detail) for a user.

Source

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

Get clearinghouse state (balances, positions, margin) for a user.

Source

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

Get user fee schedule and effective rates.

Source

pub async fn info_candle_snapshot( &self, coin: &str, interval: HyperliquidBarInterval, start_time: u64, end_time: u64, ) -> Result<HyperliquidCandleSnapshot>

Get candle/bar data for a coin.

Source

pub async fn post_action( &self, action: &ExchangeAction, ) -> Result<HyperliquidExchangeResponse>

Post an action to the exchange endpoint (low-level delegation).

Source

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

Post an execution action (low-level delegation).

Source

pub async fn info_meta(&self) -> Result<HyperliquidMeta>

Get metadata about available markets (low-level delegation).

Source

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

Cancel an order on the Hyperliquid exchange.

Can cancel either by venue order ID or client order ID. At least one ID must be provided.

§Errors

Returns an error if credentials are missing, no order ID is provided, or the API returns an error.

Source

pub async fn modify_order( &self, 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>, ) -> Result<()>

Modify an order on the Hyperliquid exchange.

The HL modify API requires a full replacement order spec plus the venue order ID. The caller must provide all order fields.

§Errors

Returns an error if the asset index is not found, the venue order ID is invalid, or the API returns an error.

Source

pub async fn request_order_status_reports( &self, user: &str, instrument_id: Option<InstrumentId>, ) -> Result<Vec<OrderStatusReport>>

Request order status reports for a user.

Fetches open orders via info_frontend_open_orders and parses them into OrderStatusReports. This method requires instruments to be added to the client cache via cache_instrument().

For vault tokens (starting with “vntls:”) that are not in the cache, synthetic instruments will be created automatically.

§Errors

Returns an error if the API request fails or parsing fails.

Source

pub async fn request_order_status_report( &self, user: &str, oid: u64, ) -> Result<Option<OrderStatusReport>>

Request a single order status report by venue order ID.

Queries info_frontend_open_orders and filters for the given oid so the result includes trigger metadata (trigger_px, tpsl, trailing_stop, etc.). Falls back to info_order_status when the order is no longer open.

§Errors

Returns an error if the API request fails or parsing fails.

Source

pub async fn request_order_status_report_by_client_order_id( &self, user: &str, client_order_id: &ClientOrderId, ) -> Result<Option<OrderStatusReport>>

Request a single order status report by client order ID.

Searches info_frontend_open_orders for an order whose cloid matches the keccak256 hash of the given client order ID. Only finds open orders.

§Errors

Returns an error if the API request fails or parsing fails.

Source

pub async fn request_fill_reports( &self, user: &str, instrument_id: Option<InstrumentId>, ) -> Result<Vec<FillReport>>

Request fill reports for a user.

Fetches user fills via info_user_fills and parses them into FillReports. This method requires instruments to be added to the client cache via cache_instrument().

For vault tokens (starting with “vntls:”) that are not in the cache, synthetic instruments will be created automatically.

§Errors

Returns an error if the API request fails or parsing fails.

Returns an error if account_id is not set on the client.

Source

pub async fn request_position_status_reports( &self, user: &str, instrument_id: Option<InstrumentId>, ) -> Result<Vec<PositionStatusReport>>

Request position status reports for a user.

Fetches clearinghouse state via info_clearinghouse_state and parses positions into PositionStatusReports. This method requires instruments to be added to the client cache via cache_instrument().

For vault tokens (starting with “vntls:”) that are not in the cache, synthetic instruments will be created automatically.

§Errors

Returns an error if the API request fails or parsing fails.

Returns an error if account_id has not been set on the client.

Source

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

Request account state (balances and margins) for a user.

Fetches clearinghouse state from Hyperliquid API and converts it to AccountState.

§Errors

Returns an error if account_id is not set or the API request fails.

Source

pub async fn request_bars( &self, bar_type: BarType, start: Option<DateTime<Utc>>, end: Option<DateTime<Utc>>, limit: Option<u32>, ) -> Result<Vec<Bar>>

Request historical bars for an instrument.

Fetches candle data from the Hyperliquid API and converts it to Nautilus bars. Incomplete bars (where end_timestamp >= current time) are filtered out.

§Errors

Returns an error if:

  • The instrument is not found in cache.
  • The bar aggregation is unsupported by Hyperliquid.
  • The API request fails.
  • Parsing fails.
§References

https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candles-snapshot

Source

pub async fn submit_order( &self, 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, ) -> Result<OrderStatusReport>

Submits an order to the exchange.

§Errors

Returns an error if credentials are missing, order validation fails, serialization fails, or the API returns an error.

Source

pub async fn submit_order_from_order_any( &self, order: &OrderAny, ) -> Result<OrderStatusReport>

Submit an order using an OrderAny object.

This is a convenience method that wraps submit_order.

Source

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

Submit multiple orders to the Hyperliquid exchange in a single request.

§Errors

Returns an error if credentials are missing, order validation fails, serialization fails, or the API returns an error.

Trait Implementations§

Source§

impl Clone for HyperliquidHttpClient

Source§

fn clone(&self) -> HyperliquidHttpClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for HyperliquidHttpClient

Source§

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

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

impl Default for HyperliquidHttpClient

Source§

fn default() -> Self

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

impl<'a, 'py> FromPyObject<'a, 'py> for HyperliquidHttpClient
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 HyperliquidHttpClient

Source§

type Target = HyperliquidHttpClient

The Python output type
Source§

type Output = Bound<'py, <HyperliquidHttpClient 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 HyperliquidHttpClient

Source§

const NAME: &str = "HyperliquidHttpClient"

Name of the class. Read more
Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for HyperliquidHttpClient

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 = /// Provides a high-level HTTP client for the [Hyperliquid](https://hyperliquid.xyz/) REST API. /// /// This domain client wraps [`HyperliquidRawHttpClient`] and provides methods that work /// with Nautilus domain types. It maintains an instrument cache and handles conversions /// between Hyperliquid API responses and Nautilus domain models.

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 = <<HyperliquidHttpClient as PyClassImpl>::BaseNativeType as PyClassBaseType>::Layout<HyperliquidHttpClient>

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

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 HyperliquidHttpClient

Source§

const TEXT_SIGNATURE: &'static str = "(private_key=None, vault_address=None, account_address=None, is_testnet=False, timeout_secs=60, proxy_url=None, normalize_prices=True)"

Source§

impl PyStubType for HyperliquidHttpClient

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 HyperliquidHttpClient

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

impl DerefToPyAny for HyperliquidHttpClient

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

impl<'py, T> FromPyObjectOwned<'py> for T
where T: for<'a> FromPyObject<'a, 'py>,

Source§

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