Skip to main content

rustrade_execution/client/hyperliquid/
mod.rs

1//! Hyperliquid ExecutionClient implementations for perpetual futures and spot trading.
2//!
3//! Uses the official `hyperliquid_rust_sdk` crate for REST and WebSocket API access.
4//! Gated behind the "hyperliquid" feature flag.
5//!
6//! # Modules
7//!
8//! - [`HyperliquidClient`]: Perpetual futures client
9//! - [`spot::HyperliquidSpotClient`]: Spot trading client
10//!
11//! # Authentication
12//!
13//! Hyperliquid uses EVM-based authentication (Ethereum private key + EIP-712 signatures)
14//! instead of traditional API key/secret. The SDK handles all signing internally.
15//!
16//! # Architecture
17//!
18//! - REST (`InfoClient`): account_snapshot, fetch_balances, fetch_open_orders, fetch_trades.
19//!   `fetch_trades` posts `userFillsByTime` to `/info` through the SDK's HTTP client but parses
20//!   the response into [`common::UserFill`] rather than the SDK's type, which drops `tid` and
21//!   `feeToken`.
22//! - REST (`ExchangeClient`): open_order, cancel_order
23//! - WebSocket (`InfoClient` with `with_reconnect`): account_stream via UserFills + OrderUpdates +
24//!   UserFundings subscriptions
25//! - REST (`InfoClient`), after each reconnect and through [`OrderStatusClient`]: how the orders
26//!   held as live ended, by `openOrders` and `orderStatus`
27//!
28//! # SDK Delegation Model
29//!
30//! This client delegates connection management to the official `hyperliquid_rust_sdk`:
31//!
32//! | Responsibility | Implementation |
33//! |----------------|----------------|
34//! | **Reconnection** | `InfoClient::with_reconnect()` handles WebSocket reconnection automatically, every 1 s with no limit on attempts (see below) |
35//! | **Heartbeat** | SDK manages WebSocket ping/pong internally |
36//! | **Deduplication** | This client's own, on the fills and funding payments. See below and [Funding](self#funding). |
37//! | **Fill recovery** | Only the recent fills the venue's `userFills` snapshot redelivers on each resubscription — use [`ExecutionClient::fetch_trades`] for older ones |
38//! | **Ended-order recovery** | This client's own, after each reconnect: see [`HyperliquidClient`]'s `account_stream` and [`OrderStatusClient`] |
39//!
40//! The SDK's reconnection has no limit, so a lost connection never ends the account stream: the
41//! SDK (`hyperliquid_rust_sdk` 0.6) retries it once a second until it succeeds, and this client
42//! sets no budget of its own. The stream ends, with
43//! [`StreamTerminated`](crate::AccountEventKind::StreamTerminated) carrying
44//! [`StreamTerminationReason::Error`], only if the SDK closes a subscription's channel. Giving up
45//! on a venue that stays unreachable is the caller's decision.
46//!
47//! **Caller responsibilities**:
48//! - If fill recovery is critical, monitor for reconnection events and call `fetch_trades()`
49//! - REST clients (`InfoClient::new()`, `ExchangeClient::new()`) do NOT auto-reconnect;
50//!   only WebSocket streams via `with_reconnect()` do
51//!
52//! # Trade identity and duplicate fills
53//!
54//! A [`Trade`]'s id is the venue's `tid`, which identifies the fill. It is deliberately **not**
55//! `hash`, which identifies the transaction: one aggressive order sweeping several resting orders
56//! produces several fills under a single hash, and keying on the hash makes them indistinguishable.
57//! Hyperliquid documents `tid` as unique per fill but qualified by coin rather than globally, so
58//! callers reconciling across instruments should qualify it the same way.
59//!
60//! The fills subscription opens with a snapshot of recent fills and the SDK resubscribes on every
61//! reconnect, so the same fill is redelivered each time the socket comes back. A trade is a delta
62//! the consumer accumulates, so this client deduplicates the stream itself — the cache is scoped to
63//! one [`ExecutionClient::account_stream`] call and survives reconnects within it.
64//!
65//! Order updates are deliberately **not** deduplicated. They assert absolute state rather than a
66//! delta, so a replayed one is idempotent while a dropped one could strand a consumer on stale
67//! state.
68//!
69//! [`ExecutionClient::fetch_trades`] does not deduplicate: it answers the window it was asked for,
70//! and its results reach the caller rather than the stream. A caller feeding both into one consumer
71//! should expect overlap and reconcile on the trade id.
72//!
73//! # Perpetual and spot coins
74//!
75//! Hyperliquid reports every market a wallet trades through the same account streams and
76//! open-order and fill endpoints, each order and fill under its *coin*. Each client keeps only its
77//! own, judged by [`CoinKind::of`](rustrade_instrument::hyperliquid::CoinKind::of):
78//! - [`HyperliquidClient`] keeps perpetuals (`BTC`, `kPEPE`, and HIP-3 perpetuals such as
79//!   `xyz:TSLA` on the DEXs it is configured with), named `{coin}-{collateral}-PERP`; see [HIP-3
80//!   perpetuals](#hip-3-perpetuals);
81//! - [`spot::HyperliquidSpotClient`] keeps spot pairs (`@107`, `PURR/USDC`), named from their
82//!   tokens; see its [Spot coins](spot#spot-coins).
83//!
84//! A coin of a kind neither recognises, such as an outcome coin (`#12`), is left out by both, and
85//! logged with `warn!` by the perpetuals client.
86//!
87//! # HIP-3 perpetuals
88//!
89//! Besides its default perpetuals DEX, Hyperliquid hosts builder-deployed (HIP-3) DEXs, each
90//! with its own perpetuals, named `{dex}:{asset}` (`xyz:TSLA`), its own margin, and its own
91//! collateral token, which need not be USDC. [`HyperliquidClient`] trades the default DEX and the
92//! HIP-3 DEXs named in [`HyperliquidConfig::dexes`], which it reads when it connects.
93//!
94//! - **Names.** Every perpetual is named after the token its DEX settles in:
95//!   `{coin}-{collateral}-PERP`, such as `BTC-USDC-PERP`, `xyz:TSLA-USDC-PERP` and
96//!   `flx:TSLA-USDH-PERP`. An order, cancel or filtered read on any other name, a perpetual on an
97//!   unconfigured DEX included, is refused with
98//!   [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid).
99//! - **Unconfigured DEXs.** Their fills and orders still arrive on the account stream and in the
100//!   venue's listings, but without the DEX's metadata they cannot be named, so they are left out,
101//!   logged at `warn` once per DEX.
102//! - **New listings.** The SDK addresses an order by the asset ids read at connect, so a
103//!   perpetual listed after that, on any DEX, cannot be ordered until the client connects again.
104//! - **Balances.** Where collateral is held depends on the account's abstraction mode; see
105//!   [`account_snapshot`](HyperliquidClient#method.account_snapshot).
106//! - **Cost.** Connecting reads `perpDexs`, `spotMeta` and each configured DEX's `meta` (weight
107//!   20 each) when any DEX is configured. Each read of open orders or positions makes one
108//!   request per DEX, the default one included: Hyperliquid lists a HIP-3 DEX's only when asked
109//!   for it. Fills need no such request.
110//!
111//! # Client order ids
112//!
113//! **Every order must be placed under a client id in
114//! [`ClientOrderId::uuid()`](crate::order::id::ClientOrderId::uuid) form**: a UUID, lowercase and
115//! hyphenated. Any other id is refused at placement with [`OrderError::Rejected`], before anything
116//! is sent.
117//!
118//! Hyperliquid tracks an order by its venue `oid` and by an optional 16-byte `cloid`, and reports
119//! the `cloid` back on every order record, REST and WebSocket alike. This client sends the client
120//! id as the `cloid` and turns the one reported back into the same id, so every account snapshot,
121//! open-order listing and order update names an order by the id it was placed with. Only that
122//! form of UUID comes back unchanged, which is why nothing else is accepted.
123//!
124//! An order placed some other way, such as the web app, has no `cloid` and is reported under its
125//! `oid`. It cannot be one of this client's orders, which is what lets an account snapshot declare
126//! its order list complete (see [`InstrumentAccountSnapshot::orders_complete`]).
127//!
128//! # Conditional Orders (Stop, TakeProfit)
129//!
130//! Hyperliquid supports conditional (trigger) orders via the `ClientOrder::Trigger` variant.
131//!
132//! **Supported order kinds**:
133//! - `Stop` → market order triggered at stop price (`tpsl: "sl"`, `is_market: true`)
134//! - `StopLimit` → limit order triggered at stop price (`tpsl: "sl"`, `is_market: false`)
135//! - `TakeProfit` → market order triggered at take-profit price (`tpsl: "tp"`, `is_market: true`)
136//! - `TakeProfitLimit` → limit order triggered at take-profit price (`tpsl: "tp"`, `is_market: false`)
137//!
138//! **Unsupported**: `TrailingStop`, `TrailingStopLimit`, `TrailingStopFixedLimit` (Hyperliquid
139//! does not support trailing stops)
140//!
141//! **SDK limitations** (hyperliquid_rust_sdk 0.6.x): neither the open orders this client reads
142//! nor `OrderUpdate` carry an order's trigger fields or time in force, so orders from both are
143//! reported as `OrderKind::Limit`, `GoodUntilCancelled`. Track `OrderKind` from the placement
144//! request.
145//!
146//! # Funding
147//!
148//! Hyperliquid settles perpetual funding every hour, as a payment into or out of the collateral
149//! that margins the position. The perpetuals account stream reports each payment, from the
150//! `userFundings` subscription, as an [`AccountEventKind::CashFlow`] of
151//! [`CashFlowKind::Funding`](crate::cash_flow::CashFlowKind::Funding):
152//! - `amount` is Hyperliquid's `usdc`, signed positive when the account received it. Its asset is
153//!   the collateral of the perpetual's DEX. Hyperliquid names the field `usdc` on every DEX, and
154//!   that it is in the collateral on a HIP-3 DEX settling in another token is this client's
155//!   reading, not documented. `rate` is `fundingRate` and `position_quantity` is the signed `szi`.
156//! - Hyperliquid gives a payment no id, so `id` is `None`. The instrument and `time_exchange`
157//!   identify it.
158//! - The subscription opens with a snapshot of recent payments, so a stream's first events can
159//!   predate it: filter on `time_exchange` to take only new ones. The SDK resubscribes on every
160//!   reconnect and the snapshot comes again, so this client sends each payment once per
161//!   [`ExecutionClient::account_stream`] call, as it does fills. Hyperliquid does not document
162//!   how far back the snapshot reaches, so payments made during a long outage can be missing;
163//!   Hyperliquid's `userFunding` history has them.
164//! - The spot client's stream carries none.
165//!
166//! Under the standard account mode a DEX's balance is its `accountValue`, which includes the
167//! funding paid and received, and the positions' unrealised PnL too, so adding payments to a
168//! balance read after them counts them twice. Under a unified account or portfolio margin a
169//! balance is the collateral token's spot balance; whether Hyperliquid books funding there at
170//! once has not been checked. The stream carries no balance: balances are read only by
171//! [`account_snapshot`](HyperliquidClient#method.account_snapshot) and
172//! [`fetch_balances`](ExecutionClient::fetch_balances).
173//!
174//! Positions report funding apart from their PnL:
175//! - A position's [`unrealized_pnl`](crate::position::Position::unrealized_pnl) is Hyperliquid's
176//!   `unrealizedPnl`, which comes from price alone.
177//! - Its [`carry`](crate::position::Position::carry) is the funding since the position opened,
178//!   from Hyperliquid's `cumFunding.sinceOpen` with the sign flipped: Hyperliquid counts funding
179//!   paid as positive, and `carry` counts it as negative, as a payment's `amount` does.
180//! - Fills carry no funding, so PnL computed from them excludes it too.
181//!
182//! # Limitations
183//!
184//! - **Order precision**: Hyperliquid limits a size to the asset's `szDecimals` decimal places,
185//!   and a price to 5 significant figures and `6 - szDecimals` decimal places (integers always
186//!   allowed). An order whose quantity, price or trigger price breaks these is refused with
187//!   [`OrderError::InvalidPrecision`] before anything is sent; the client never rounds a value,
188//!   since that would place an order other than the one requested. Read the rules with
189//!   [`HyperliquidClient::order_precision`] and round first. See [`precision`].
190
191pub mod common;
192pub mod config;
193pub mod error;
194mod funding;
195mod order_recovery;
196mod perp_account;
197mod perp_dexes;
198pub mod precision;
199pub mod spot;
200mod spot_coins;
201
202use crate::client::dedup::new_dedup_cache;
203use crate::client::order_recovery::{
204    KnownLiveOrders, OrderLookup, SharedKnownLiveOrders, fetch_ended_by_key,
205};
206use crate::{
207    AccountEvent, AccountEventKind, AccountSnapshot, InstrumentAccountSnapshot,
208    UnindexedAccountEvent, UnindexedAccountSnapshot,
209    balance::AssetBalance,
210    client::{ExecutionClient, OrderStatusClient, VenueOrderStatus},
211    emit_stream_terminated,
212    error::{
213        ConnectivityError, OrderError, StreamTerminationReason, UnindexedClientError,
214        UnindexedOrderError,
215    },
216    order::{
217        Order, OrderKey, OrderKind, TimeInForce, UnindexedInactiveOrder, UnindexedOrderKey,
218        id::{ClientOrderId, OrderId, StrategyId, VenueOrderId},
219        request::{OrderRequestCancel, OrderRequestOpen, UnindexedOrderResponseCancel},
220        state::{Filled, Open, OrderState, UnindexedOrderState},
221    },
222    position::{Position, PositionReport},
223    trade::{AssetFees, Trade, TradeId, TradeOrigin, TradesRead},
224};
225use chrono::{DateTime, Utc};
226use common::{
227    CLOID_REQUIRED, CancelOnDropStream, InstrumentFilter, OpenOrderListing, UnknownCoins,
228    cancel_outcome, cid_to_cloid, cloid_to_cid, map_tif, millis_to_datetime, open_order_to_order,
229    parse_decimal, parse_side, span_millis, user_fills_by_time, warn_unknown_coins,
230};
231pub use config::{HyperliquidConfig, HyperliquidConfigError, Network};
232pub use error::HyperliquidConnectError;
233use error::{map_order_error, order_outcome_unanswered, order_rejection};
234use ethers::signers::Signer;
235use fnv::FnvHashSet;
236use funding::{funding_cash_flow, send_fundings};
237use futures::{StreamExt, stream::BoxStream};
238use hyperliquid_rust_sdk::{ExchangeClient, InfoClient, Message, Subscription};
239use order_recovery::{
240    ReconnectWatch, fetch_order_record, listed_cids, lookup_of, remember_open, remember_snapshot,
241    send_fills, send_observed, spawn_order_checks, status_from_record, unreadable_record,
242};
243use perp_account::{account_mode, dex_states};
244use perp_dexes::{PerpDexes, UnconfiguredDexes, warn_unconfigured_dexes};
245pub use precision::OrderPrecision;
246use precision::{WireOrderError, wire_order};
247use rust_decimal::Decimal;
248use rustrade_instrument::{
249    Side,
250    asset::name::AssetNameExchange,
251    exchange::ExchangeId,
252    instrument::{kind::InstrumentKindDiscriminant, name::InstrumentNameExchange},
253};
254use smol_str::format_smolstr;
255use std::sync::{
256    Arc,
257    atomic::{AtomicBool, Ordering},
258};
259use tokio::sync::{Notify, mpsc};
260use tokio_util::sync::CancellationToken;
261use tracing::{debug, error, info, warn};
262
263/// Hyperliquid perpetual futures execution client.
264///
265/// Wraps the official `hyperliquid_rust_sdk` to implement the `ExecutionClient` trait.
266/// Supports perpetual futures trading on Hyperliquid DEX.
267#[derive(Debug, Clone)]
268pub struct HyperliquidClient {
269    config: HyperliquidConfig,
270    info_client: Arc<InfoClient>,
271    exchange_client: Arc<ExchangeClient>,
272    /// The DEXs traded, and the names of their perpetuals.
273    dexes: Arc<PerpDexes>,
274    /// The orders seen live and not yet seen end, which a reconnect asks about. Shared by every
275    /// clone and every account stream, since an order placed through one ends on any of them.
276    known_live: SharedKnownLiveOrders,
277}
278
279impl HyperliquidClient {
280    /// Create a new client asynchronously.
281    ///
282    /// Use this when calling from an async context (e.g., tokio tests).
283    /// For sync contexts, use `ExecutionClient::new()`.
284    ///
285    /// Reads the markets of each DEX in [`HyperliquidConfig::dexes`]; see [HIP-3
286    /// perpetuals](self#hip-3-perpetuals).
287    ///
288    /// # Errors
289    ///
290    /// - [`HyperliquidConnectError::Connectivity`] when the SDK clients cannot be created, or a
291    ///   request for the DEXs' markets fails in transit.
292    /// - [`HyperliquidConnectError::UnknownDex`] when Hyperliquid lists no DEX by a configured
293    ///   name on the configured network.
294    /// - [`HyperliquidConnectError::Metadata`] when a DEX's markets cannot be read.
295    ///
296    /// # Cost
297    ///
298    /// With any DEX configured: `perpDexs`, `spotMeta` and each DEX's `meta`, weight 20 each, so
299    /// `40 + 20 × dexes`, besides what the SDK reads to build its own clients.
300    pub async fn connect(config: HyperliquidConfig) -> Result<Self, HyperliquidConnectError> {
301        let base_url = config.base_url();
302
303        let info_client = InfoClient::new(None, Some(base_url))
304            .await
305            .map_err(|e| ConnectivityError::Socket(format!("InfoClient: {e}")))?;
306
307        let mut dexes = PerpDexes::fetch(&info_client, &config.dexes).await?;
308
309        let wallet = config.wallet.clone();
310        let mut exchange_client = ExchangeClient::new(None, wallet, Some(base_url), None, None)
311            .await
312            .map_err(|e| ConnectivityError::Socket(format!("ExchangeClient: {e}")))?;
313        // The SDK addresses an order by the coin's asset id, and reads only the default DEX's.
314        exchange_client.coin_to_asset.extend(dexes.asset_ids());
315        dexes.add_default_perps(&exchange_client.meta.universe);
316
317        info!(
318            network = ?config.network,
319            dexes = ?config.dexes,
320            wallet = %config.wallet_address_hex(),
321            "Created HyperliquidClient"
322        );
323
324        Ok(Self {
325            config,
326            info_client: Arc::new(info_client),
327            exchange_client: Arc::new(exchange_client),
328            dexes: Arc::new(dexes),
329            known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidPerp),
330        })
331    }
332
333    /// Returns the wallet address as a hex string (for logging/debugging).
334    pub fn wallet_address(&self) -> String {
335        self.config.wallet_address_hex()
336    }
337
338    /// The precision rules for orders on the perpetual `instrument`, from its `szDecimals`.
339    ///
340    /// [`open_order`](ExecutionClient::open_order) refuses an order that breaks them with
341    /// [`OrderError::InvalidPrecision`] and sends nothing. Round with these rules first. See
342    /// [`OrderPrecision`].
343    ///
344    /// `None` when `instrument` names no perpetual this client trades, or one listed after the
345    /// client connected: the client reads each DEX's perpetuals once, at
346    /// [`connect`](Self::connect), so a perpetual listed since needs a new client.
347    pub fn order_precision(&self, instrument: &InstrumentNameExchange) -> Option<OrderPrecision> {
348        let coin = self.dexes.coin(instrument).ok()?;
349        self.dexes.sz_decimals(coin).map(OrderPrecision::perp)
350    }
351
352    /// Returns the wallet address as ethers H160.
353    fn wallet_h160(&self) -> ethers::types::H160 {
354        self.config.wallet.address()
355    }
356
357    /// Fail with [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) on
358    /// the first of `instruments` that names no perpetual this client trades. A read filtered to
359    /// it would otherwise report it empty without having looked.
360    fn check_instruments(
361        &self,
362        instruments: &[InstrumentNameExchange],
363    ) -> Result<(), UnindexedClientError> {
364        for instrument in instruments {
365            self.dexes.coin(instrument).map_err(|reason| {
366                UnindexedClientError::Api(crate::error::ApiError::InstrumentInvalid(
367                    instrument.clone(),
368                    reason,
369                ))
370            })?;
371        }
372        Ok(())
373    }
374}
375
376impl ExecutionClient for HyperliquidClient {
377    const EXCHANGE: ExchangeId = ExchangeId::HyperliquidPerp;
378
379    // Perpetuals only — spot is served by `HyperliquidSpotClient`, which uses different coin
380    // naming, asset indices and balance endpoints.
381    const SUPPORTED_KINDS: &'static [InstrumentKindDiscriminant] =
382        &[InstrumentKindDiscriminant::Perpetual];
383
384    type Config = HyperliquidConfig;
385    type AccountStream = BoxStream<'static, UnindexedAccountEvent>;
386
387    /// Creates a new Hyperliquid client synchronously.
388    ///
389    /// # Panics
390    ///
391    /// - If no Tokio runtime is available on the current thread
392    /// - If called from within an async context (e.g., inside `async fn`, `spawn`, or `block_on`)
393    /// - Whenever [`HyperliquidClient::connect`] would fail: SDK initialization fails (network
394    ///   error, invalid credentials), or a configured DEX is unknown or unreadable
395    ///
396    /// # Recommended Usage
397    ///
398    /// Use [`HyperliquidClient::connect`] instead — it's async-safe and returns `Result`.
399    /// This method exists only for trait compliance; prefer `connect()` in all new code.
400    fn new(config: Self::Config) -> Self {
401        // SDK initialization is async; block on it since ExecutionClient::new is sync.
402        // WARNING: This will panic if called from within an async context.
403        tokio::runtime::Handle::current()
404            .block_on(Self::connect(config))
405            .unwrap_or_else(|e| panic!("Failed to create HyperliquidClient: {e}"))
406    }
407
408    /// The collateral balances, and each perpetual's open orders and position, across the default
409    /// DEX and every configured HIP-3 DEX.
410    ///
411    /// # Balances
412    ///
413    /// Read where the account's abstraction mode holds them (see [HIP-3
414    /// perpetuals](self#hip-3-perpetuals)):
415    /// - **Unified account or portfolio margin**: one balance per collateral token of the DEXs
416    ///   traded (`USDC`, `USDH`), from the spot clearinghouse, free of what is on hold. A token not
417    ///   held is reported at zero. Other tokens, which portfolio margin may also count as
418    ///   collateral, are left to [`spot::HyperliquidSpotClient`].
419    /// - **Standard** (the default for an account that never chose a mode): one balance per DEX,
420    ///   from its margin summary, as each margins separately: the default DEX's as `USDC`, each
421    ///   HIP-3 DEX's as `{dex}:{collateral}` (`xyz:USDC`, `flx:USDH`). The free balance is what
422    ///   margin does not use, never below zero.
423    ///
424    /// A mode this version does not know fails the snapshot rather than report balances read from
425    /// the wrong place.
426    ///
427    /// Positions on a HIP-3 DEX the client is not configured with are not read, and so not
428    /// reported: name the DEX in [`HyperliquidConfig::dexes`] to see them.
429    ///
430    /// # Positions
431    ///
432    /// Every requested perpetual is listed. Its position is [`PositionReport::Open`] when
433    /// Hyperliquid reports a non-zero size for it, and [`PositionReport::Flat`] otherwise, since
434    /// each DEX's state holds every open position on it. A size that does not parse is
435    /// [`PositionReport::Unreported`], with a warning.
436    ///
437    /// # Errors
438    ///
439    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for a requested
440    /// instrument that names no perpetual this client trades, such as one on a HIP-3 DEX it is not
441    /// configured with: it was not read, so nothing can be said about it.
442    ///
443    /// # Cost
444    ///
445    /// At once, `userAbstraction` (weight 20) and, for each DEX traded, the default one included,
446    /// a `clearinghouseState` (weight 2) and an `openOrders` (weight 20); then, under a unified
447    /// account or portfolio margin, `spotClearinghouseState` (weight 2). With `n` HIP-3 DEXs
448    /// that is `42 + 22n`, or `44 + 22n`, against Hyperliquid's limit of 1,200 a minute per IP
449    /// address.
450    async fn account_snapshot(
451        &self,
452        _assets: &[AssetNameExchange],
453        instruments: &[InstrumentNameExchange],
454    ) -> Result<UnindexedAccountSnapshot, UnindexedClientError> {
455        self.check_instruments(instruments)?;
456        let address = self.wallet_h160();
457        let info_client = &*self.info_client;
458        let dexes = &*self.dexes;
459
460        let (mode, states, open_orders) = tokio::try_join!(
461            account_mode(info_client, address),
462            dex_states(info_client, address, dexes),
463            perp_account::open_orders(info_client, address, dexes),
464        )?;
465        let now = Utc::now();
466        let balances =
467            perp_account::snapshot_balances(info_client, address, dexes, mode, &states, now)
468                .await?;
469
470        let instrument_filter = InstrumentFilter::new(instruments);
471
472        warn_unknown_coins(open_orders.iter().map(|order| order.coin.as_str()));
473        let mut listing = OpenOrderListing::new(
474            &open_orders,
475            ExchangeId::HyperliquidPerp,
476            instruments,
477            |coin| dexes.instrument(coin),
478        );
479
480        // Build positions from each DEX's asset_positions
481        let mut instrument_snapshots = Vec::new();
482        for asset_pos in states.iter().flat_map(|(_, state)| &state.asset_positions) {
483            let pos = &asset_pos.position;
484            let Some(instrument) = dexes.instrument(&pos.coin) else {
485                continue;
486            };
487
488            if !instrument_filter.matches(&instrument) {
489                continue;
490            }
491
492            let position = perp_position_report(pos, now);
493
494            let (orders, orders_complete) = match listing.remove(&instrument) {
495                Some(listed) => (listed.orders, listed.orders_complete),
496                // The listing has an entry for every requested instrument, so this is an
497                // unfiltered read with no open order on the instrument.
498                None => (Vec::new(), true),
499            };
500
501            instrument_snapshots.push(InstrumentAccountSnapshot {
502                instrument,
503                orders,
504                orders_complete,
505                position,
506                isolated: None,
507            });
508        }
509
510        // Every other instrument listed: open orders but no position, or requested with neither.
511        // Each DEX's `asset_positions` holds every open position on it, so these are flat.
512        instrument_snapshots.extend(listing.into_snapshots().map(|mut snapshot| {
513            snapshot.position = PositionReport::Flat;
514            snapshot
515        }));
516
517        let snapshot = AccountSnapshot {
518            exchange: ExchangeId::HyperliquidPerp,
519            balances,
520            instruments: instrument_snapshots,
521        };
522        remember_snapshot(&self.known_live, &snapshot);
523        Ok(snapshot)
524    }
525
526    /// Returns a live stream of account events (fills, order updates, funding payments).
527    ///
528    /// Funding payments arrive as [`AccountEventKind::CashFlow`]; see the [module
529    /// docs](self#funding).
530    ///
531    /// # Instrument filtering
532    ///
533    /// The `instruments` parameter is **ignored** — Hyperliquid's WebSocket API does not
534    /// support per-instrument subscriptions for user events. All fills, order updates and
535    /// funding payments across all instruments are delivered. Consumers requiring instrument
536    /// filtering must filter client-side.
537    ///
538    /// # Task lifecycle
539    ///
540    /// Spawns four background tasks (fills, orders, funding payments, and the reconnect's order
541    /// check below) that are automatically cancelled when the returned stream is dropped. The
542    /// `ws_client` is held by the orders task; when cancelled, the tasks exit and the WebSocket
543    /// connection closes.
544    ///
545    /// # Orders that ended while disconnected
546    ///
547    /// The SDK reconnects the socket underneath this stream and resubscribes, but `orderUpdates`
548    /// opens with no snapshot, so an order that ended while the socket was down is never reported
549    /// on it. After each reconnect the stream therefore reports how each order the client holds as
550    /// live ended, where it did, as an [`AccountEventKind::OrderSnapshot`] of its inactive state,
551    /// read as [`OrderStatusClient::fetch_ended_orders`] reads it: filled (without an average
552    /// price), cancelled (with what filled before) or rejected. Each carries
553    /// [`StrategyId::unknown`], since Hyperliquid records no strategy; the engine matches it to the
554    /// order it tracks by client order id.
555    ///
556    /// - **When.** The SDK tells each subscription that the socket dropped, and the venue opens
557    ///   the resubscribed `userFills` with a snapshot of recent fills. The check starts once that
558    ///   snapshot's fills have been sent on, so the fills of an order that it carries arrive before
559    ///   how the order ended. The snapshot is all the fill recovery there is (see the [module
560    ///   docs](self#sdk-delegation-model)), and Hyperliquid does not document how far back it
561    ///   reaches, so after a long outage an order can be reported filled before, or without, fills
562    ///   older than that. The SDK resubscribes in no fixed order and only logs a resubscription
563    ///   that fails: an order that ends after the check lists the open orders but before
564    ///   `orderUpdates` is subscribed again is missed, and if `userFills` is not subscribed again
565    ///   no check runs until a later reconnect.
566    /// - **Which orders.** The client holds an order as live from the response to placing it,
567    ///   from a listing of open orders ([`account_snapshot`](ExecutionClient::account_snapshot),
568    ///   [`fetch_open_orders`](ExecutionClient::fetch_open_orders)), and from its live reports on
569    ///   any of its account streams, until it sees the order end, which a successful cancel does.
570    ///   It holds up to 4,096 orders and forgets the oldest past that, logged at `warn`. An order
571    ///   placed outside this client and never listed or reported to it is not covered. Every
572    ///   instrument is checked, as the stream ignores `instruments`.
573    /// - **Cost.** One `openOrders` request (weight 20) per DEX traded, together listing every
574    ///   open order, then one `orderStatus` request (weight 2) for each held order the listing no
575    ///   longer shows, 8 at a time. Both count against Hyperliquid's REST limit of 1,200 a minute
576    ///   per IP address. The cost is per stream: a perpetuals and a spot stream on one wallet each
577    ///   make their own.
578    /// - **Failures.** Each order's lookup is settled as it ends. An instrument whose listing or
579    ///   lookup fails, or whose check is still running after 30 s, is retried while the stream is
580    ///   open 1, 2, 4, 8 and 16 minutes later, asking only about the orders still held, then given
581    ///   up, logged at `error`; its orders are asked about again at the next reconnect. A listing
582    ///   that fails charges every instrument in it. An order Hyperliquid does not know stops being
583    ///   held, logged at `warn`; one still live, or in a state this version cannot read, stays
584    ///   held.
585    ///
586    /// # Errors
587    ///
588    /// [`ConnectivityError::Socket`] if the WebSocket cannot be opened, or if any of the
589    /// `userFills`, `orderUpdates` and `userFundings` subscriptions fails: the stream is not
590    /// opened with only some of them.
591    async fn account_stream(
592        &self,
593        _assets: &[AssetNameExchange],
594        _instruments: &[InstrumentNameExchange],
595    ) -> Result<Self::AccountStream, UnindexedClientError> {
596        let user = self.wallet_h160();
597        let base_url = self.config.base_url();
598
599        // Create a dedicated InfoClient for WebSocket streaming.
600        // Using with_reconnect() enables SDK-managed reconnection.
601        let mut ws_client = InfoClient::with_reconnect(None, Some(base_url))
602            .await
603            .map_err(|e| ConnectivityError::Socket(e.to_string()))?;
604
605        // Create channels for subscriptions
606        let (fills_tx, mut fills_rx) = mpsc::unbounded_channel::<Message>();
607        let (orders_tx, mut orders_rx) = mpsc::unbounded_channel::<Message>();
608        let (fundings_tx, mut fundings_rx) = mpsc::unbounded_channel::<Message>();
609
610        // Subscribe to user fills
611        ws_client
612            .subscribe(Subscription::UserFills { user }, fills_tx)
613            .await
614            .map_err(|e| ConnectivityError::Socket(format!("UserFills subscribe: {e}")))?;
615
616        // Subscribe to order updates
617        ws_client
618            .subscribe(Subscription::OrderUpdates { user }, orders_tx)
619            .await
620            .map_err(|e| ConnectivityError::Socket(format!("OrderUpdates subscribe: {e}")))?;
621
622        // Subscribe to funding payments
623        ws_client
624            .subscribe(Subscription::UserFundings { user }, fundings_tx)
625            .await
626            .map_err(|e| ConnectivityError::Socket(format!("UserFundings subscribe: {e}")))?;
627
628        info!(%user, "Subscribed to Hyperliquid account stream");
629
630        // Create output channel for merged events
631        let (event_tx, event_rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
632
633        // CancellationToken ensures tasks exit when stream is dropped
634        let cancel_token = CancellationToken::new();
635
636        // Both tasks share `event_tx` and both observe `recv() -> None` when the SDK gives up on the
637        // socket, so guard the terminal emit with a shared flag — only the first non-cancellation
638        // terminal sends `StreamTerminated`, avoiding a double-emit. Relaxed ordering suffices: the
639        // flag has no associated payload to synchronise; the channel send is the synchronisation point.
640        let terminated = Arc::new(AtomicBool::new(false));
641
642        // Scoped to this stream rather than to the client: a fresh `account_stream` opens a fresh
643        // subscription, whose snapshot the new consumer has not seen. It must outlive a reconnect,
644        // which it does -- the SDK reconnects underneath this task, not around it.
645        let fills_dedup = new_dedup_cache();
646
647        // How the orders held as live ended while the socket was down: checked after each
648        // reconnect, once the fills snapshot that opens the resubscription has been sent on. Its
649        // own token also stops it promptly when the stream terminates.
650        let reconnected = Arc::new(Notify::new());
651        let checks_cancel = cancel_token.child_token();
652        let (list_client, lookup_client) = (self.info_client.clone(), self.info_client.clone());
653        let (list_dexes, lookup_dexes) = (self.dexes.clone(), self.dexes.clone());
654        spawn_order_checks(
655            ExchangeId::HyperliquidPerp,
656            self.known_live.clone(),
657            reconnected.clone(),
658            checks_cancel.clone(),
659            event_tx.clone(),
660            move |instruments| {
661                perp_listed_cids(list_client.clone(), list_dexes.clone(), user, instruments)
662            },
663            move |key| perp_order_lookup(lookup_client.clone(), lookup_dexes.clone(), user, key),
664        );
665
666        // Spawn task to process fills
667        let fills_event_tx = event_tx.clone();
668        let fills_cancel = cancel_token.clone();
669        let fills_terminated = terminated.clone();
670        let fills_checks_cancel = checks_cancel.clone();
671        let fills_dexes = self.dexes.clone();
672        tokio::spawn(async move {
673            let mut unknown_coins = UnknownCoins::default();
674            let mut unconfigured = UnconfiguredDexes::default();
675            let mut reconnects = ReconnectWatch::new(reconnected);
676            loop {
677                tokio::select! {
678                    biased;
679                    () = fills_cancel.cancelled() => {
680                        debug!("Fills task cancelled");
681                        return;
682                    }
683                    msg = fills_rx.recv() => {
684                        let Some(msg) = msg else {
685                            debug!("Fills receiver closed");
686                            fills_checks_cancel.cancel();
687                            // SDK gave up on the stream (channel closed). Emit a single terminal
688                            // StreamTerminated across both tasks (guarded by the shared flag).
689                            if fills_terminated
690                                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
691                                .is_ok()
692                            {
693                                emit_stream_terminated(
694                                    &fills_event_tx,
695                                    ExchangeId::HyperliquidPerp,
696                                    StreamTerminationReason::Error(
697                                        "hyperliquid account stream closed".to_string(),
698                                    ),
699                                );
700                            }
701                            return;
702                        };
703                        match msg {
704                            Message::UserFills(fills) => {
705                                let convert = |fill: &hyperliquid_rust_sdk::TradeInfo| {
706                                    unknown_coins.warn_once(&fill.coin);
707                                    unconfigured.warn_once(&fills_dexes, &fill.coin);
708                                    fill_to_account_event(fill, &fills_dexes)
709                                };
710                                if !send_fills(
711                                    &fills.data,
712                                    convert,
713                                    &fills_dedup,
714                                    &fills_event_tx,
715                                    &mut reconnects,
716                                ) {
717                                    debug!("Fills event channel closed");
718                                    return;
719                                }
720                            }
721                            Message::NoData => {
722                                warn!("UserFills WebSocket disconnected");
723                                reconnects.dropped();
724                            }
725                            Message::HyperliquidError(e) => {
726                                // Transient, non-terminal: the loop continues. Log only — no
727                                // in-band event (consumers took no action on the old StreamError).
728                                error!(%e, "UserFills WebSocket error");
729                            }
730                            _ => {}
731                        }
732                    }
733                }
734            }
735        });
736
737        // Spawn task to process funding payments. It sends no terminal event: the SDK closes every
738        // subscription's channel together, and the fills and orders tasks report that.
739        let fundings_event_tx = event_tx.clone();
740        let fundings_cancel = cancel_token.clone();
741        let fundings_dexes = self.dexes.clone();
742        // Like the fills cache, scoped to this stream and surviving reconnects within it.
743        let fundings_dedup = new_dedup_cache();
744        tokio::spawn(async move {
745            let mut unknown_coins = UnknownCoins::default();
746            let mut unconfigured = UnconfiguredDexes::default();
747            loop {
748                tokio::select! {
749                    biased;
750                    () = fundings_cancel.cancelled() => {
751                        debug!("Fundings task cancelled");
752                        return;
753                    }
754                    msg = fundings_rx.recv() => {
755                        let Some(msg) = msg else {
756                            debug!("Fundings receiver closed");
757                            return;
758                        };
759                        match msg {
760                            Message::UserFundings(fundings) => {
761                                let convert = |funding: &hyperliquid_rust_sdk::UserFunding| {
762                                    unknown_coins.warn_once(&funding.coin);
763                                    unconfigured.warn_once(&fundings_dexes, &funding.coin);
764                                    funding_cash_flow(funding, &fundings_dexes)
765                                };
766                                if !send_fundings(
767                                    &fundings.data,
768                                    convert,
769                                    &fundings_dedup,
770                                    &fundings_event_tx,
771                                ) {
772                                    debug!("Fundings event channel closed");
773                                    return;
774                                }
775                            }
776                            Message::NoData => {
777                                warn!("UserFundings WebSocket disconnected");
778                            }
779                            Message::HyperliquidError(e) => {
780                                // Transient, non-terminal: the loop continues.
781                                error!(%e, "UserFundings WebSocket error");
782                            }
783                            _ => {}
784                        }
785                    }
786                }
787            }
788        });
789
790        // Spawn task to process order updates
791        // NOTE: ws_client is moved here to keep the WebSocket alive. When this task
792        // exits (via cancellation or channel close), the WebSocket connection closes,
793        // which causes fills_rx to also close.
794        let orders_event_tx = event_tx;
795        let orders_cancel = cancel_token.clone();
796        let orders_terminated = terminated;
797        let orders_known = self.known_live.clone();
798        let orders_dexes = self.dexes.clone();
799        tokio::spawn(async move {
800            let _ws_client = ws_client;
801            let mut unknown_coins = UnknownCoins::default();
802            let mut unconfigured = UnconfiguredDexes::default();
803
804            loop {
805                tokio::select! {
806                    biased;
807                    () = orders_cancel.cancelled() => {
808                        debug!("Orders task cancelled");
809                        return;
810                    }
811                    msg = orders_rx.recv() => {
812                        let Some(msg) = msg else {
813                            debug!("Orders receiver closed");
814                            checks_cancel.cancel();
815                            // SDK gave up on the stream (channel closed). Emit a single terminal
816                            // StreamTerminated across both tasks (guarded by the shared flag).
817                            if orders_terminated
818                                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
819                                .is_ok()
820                            {
821                                emit_stream_terminated(
822                                    &orders_event_tx,
823                                    ExchangeId::HyperliquidPerp,
824                                    StreamTerminationReason::Error(
825                                        "hyperliquid account stream closed".to_string(),
826                                    ),
827                                );
828                            }
829                            return;
830                        };
831                        match msg {
832                            Message::OrderUpdates(updates) => {
833                                for update in updates.data {
834                                    unknown_coins.warn_once(&update.order.coin);
835                                    unconfigured.warn_once(&orders_dexes, &update.order.coin);
836                                    if let Some(event) =
837                                        order_update_to_account_event(&update, &orders_dexes)
838                                        && !send_observed(&orders_known, &orders_event_tx, event)
839                                    {
840                                        debug!("Orders event channel closed");
841                                        return;
842                                    }
843                                }
844                            }
845                            Message::NoData => {
846                                warn!("OrderUpdates WebSocket disconnected");
847                            }
848                            Message::HyperliquidError(e) => {
849                                // Transient, non-terminal: the loop continues. Log only — no
850                                // in-band event (consumers took no action on the old StreamError).
851                                error!(%e, "OrderUpdates WebSocket error");
852                            }
853                            _ => {}
854                        }
855                    }
856                }
857            }
858        });
859
860        // Wrap stream with drop guard that cancels tasks
861        let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(event_rx);
862        let guarded_stream = CancelOnDropStream::new(stream, cancel_token);
863        Ok(guarded_stream.boxed())
864    }
865
866    async fn cancel_order(
867        &self,
868        request: OrderRequestCancel<ExchangeId, &InstrumentNameExchange>,
869    ) -> UnindexedOrderResponseCancel {
870        use crate::order::{request::OrderResponseCancel, state::Cancelled};
871        use hyperliquid_rust_sdk::{ClientCancelRequest, ClientCancelRequestCloid};
872        use uuid::Uuid;
873
874        let coin = match self.dexes.coin(request.key.instrument) {
875            Ok(coin) => coin.to_owned(),
876            Err(reason) => {
877                warn!(%reason, cid = %request.key.cid, "Cannot cancel order on this instrument");
878                return OrderResponseCancel {
879                    key: OrderKey {
880                        exchange: ExchangeId::HyperliquidPerp,
881                        instrument: request.key.instrument.clone(),
882                        strategy: request.key.strategy.clone(),
883                        cid: request.key.cid.clone(),
884                    },
885                    state: Err(UnindexedOrderError::Rejected(
886                        crate::error::ApiError::InstrumentInvalid(
887                            request.key.instrument.clone(),
888                            reason,
889                        ),
890                    )),
891                };
892            }
893        };
894
895        enum CancelMethod {
896            ByOid(u64),
897            ByCloid(Uuid),
898        }
899
900        // How the venue addresses the order decides which endpoint cancels it. This reads the
901        // identifier's kind rather than inferring it from the string's shape: an oid and a cloid
902        // are different identifiers that happen to both be text, and telling them apart by parsing
903        // means a cloid which parses as a number gets cancelled as somebody else's oid.
904        let cancel_method = match &request.state.id {
905            Some(VenueOrderId::Assigned(id)) => {
906                id.0.parse::<u64>()
907                    .map(CancelMethod::ByOid)
908                    .map_err(|_| "venue order id is not a numeric Hyperliquid oid")
909            }
910            // The venue accepted the order without assigning an oid, so the only handle on it is
911            // the cloid it was placed with -- which placement derives from the client id the same
912            // way, and refuses the order if it cannot.
913            Some(VenueOrderId::ClientAssigned) => cid_to_cloid(&request.key.cid)
914                .map(CancelMethod::ByCloid)
915                .ok_or("order is addressable only by its client id, which is not a canonical UUID"),
916            None => Err("order is still in flight; the venue has acknowledged nothing to cancel"),
917        };
918
919        let cancel_method = match cancel_method {
920            Ok(method) => method,
921            Err(reason) => {
922                warn!(%reason, cid = %request.key.cid, "Cannot determine how to cancel order");
923                return OrderResponseCancel {
924                    key: OrderKey {
925                        exchange: ExchangeId::HyperliquidPerp,
926                        instrument: request.key.instrument.clone(),
927                        strategy: request.key.strategy.clone(),
928                        cid: request.key.cid.clone(),
929                    },
930                    state: Err(UnindexedOrderError::Rejected(
931                        crate::error::ApiError::OrderRejected(reason.to_string()),
932                    )),
933                };
934            }
935        };
936
937        // Terminal states keep a plain `OrderId`: nothing compares them for identity, so an order
938        // the venue never named records the client id it was addressed by instead.
939        let cancelled_id = match &request.state.id {
940            Some(venue_id) => venue_id.or_client_id(&request.key.cid),
941            None => OrderId(request.key.cid.0.clone()),
942        };
943
944        let response = match cancel_method {
945            CancelMethod::ByOid(oid) => {
946                debug!(oid, "Cancelling by OID");
947                let cancel_request = ClientCancelRequest { asset: coin, oid };
948                self.exchange_client.cancel(cancel_request, None).await
949            }
950            CancelMethod::ByCloid(cloid) => {
951                debug!(%cloid, "Cancelling by cloid (no oid assigned)");
952                let cancel_request = ClientCancelRequestCloid { asset: coin, cloid };
953                self.exchange_client
954                    .cancel_by_cloid(cancel_request, None)
955                    .await
956            }
957        };
958
959        let response = match response {
960            Ok(r) => r,
961            Err(e) => {
962                warn!(%e, "Cancel order failed");
963                return OrderResponseCancel {
964                    key: OrderKey {
965                        exchange: ExchangeId::HyperliquidPerp,
966                        instrument: request.key.instrument.clone(),
967                        strategy: request.key.strategy.clone(),
968                        cid: request.key.cid.clone(),
969                    },
970                    state: Err(map_order_error(e, request.key.instrument)),
971                };
972            }
973        };
974
975        match cancel_outcome(response) {
976            Ok(()) => {
977                debug!("Cancel order accepted");
978                // Hyperliquid answers a cancel once the order has left the book.
979                self.known_live.lock().ended(&request.key.cid);
980                // Hyperliquid cancel response doesn't include an exchange timestamp
981                OrderResponseCancel {
982                    key: OrderKey {
983                        exchange: ExchangeId::HyperliquidPerp,
984                        instrument: request.key.instrument.clone(),
985                        strategy: request.key.strategy.clone(),
986                        cid: request.key.cid.clone(),
987                    },
988                    state: Ok(Cancelled::new(
989                        cancelled_id.clone(),
990                        Utc::now(),
991                        None, // Cancel response doesn't include filled quantity
992                    )),
993                }
994            }
995            // Not reported ended: if the order did end, the account stream or a lookup says how.
996            Err(reason) => {
997                warn!(%reason, cid = %request.key.cid, "Cancel rejected by exchange");
998                OrderResponseCancel {
999                    key: OrderKey {
1000                        exchange: ExchangeId::HyperliquidPerp,
1001                        instrument: request.key.instrument.clone(),
1002                        strategy: request.key.strategy.clone(),
1003                        cid: request.key.cid.clone(),
1004                    },
1005                    state: Err(UnindexedOrderError::Rejected(
1006                        crate::error::ApiError::OrderRejected(reason),
1007                    )),
1008                }
1009            }
1010        }
1011    }
1012
1013    async fn open_order(
1014        &self,
1015        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
1016    ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1017        use hyperliquid_rust_sdk::{
1018            ClientOrderRequest, ExchangeDataStatus, ExchangeResponseStatus,
1019        };
1020
1021        let make_inactive =
1022            |error: UnindexedOrderError| -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1023                Order {
1024                    key: OrderKey {
1025                        exchange: ExchangeId::HyperliquidPerp,
1026                        instrument: request.key.instrument.clone(),
1027                        strategy: request.key.strategy.clone(),
1028                        cid: request.key.cid.clone(),
1029                    },
1030                    side: request.state.side,
1031                    price: request.state.price,
1032                    quantity: request.state.quantity,
1033                    kind: request.state.kind,
1034                    time_in_force: request.state.time_in_force,
1035                    state: OrderState::inactive(error),
1036                }
1037            };
1038        let make_rejected = |msg: String| {
1039            make_inactive(OrderError::Rejected(crate::error::ApiError::OrderRejected(
1040                msg,
1041            )))
1042        };
1043        let make_unsupported = |msg: String| make_inactive(OrderError::UnsupportedOrderType(msg));
1044
1045        // Hyperliquid has no order flag for borrowing, and under portfolio margin an order borrows
1046        // implicitly when it falls short, so the client cannot promise either way: no effect,
1047        // not even `NoSideEffect`, is honoured.
1048        if let Some(effect) = request.state.margin_effect {
1049            return make_inactive(OrderError::UnsupportedMarginEffect(effect));
1050        }
1051        let make_invalid_instrument = |reason: String| {
1052            make_inactive(OrderError::Rejected(
1053                crate::error::ApiError::InstrumentInvalid(request.key.instrument.clone(), reason),
1054            ))
1055        };
1056
1057        let coin = match self.dexes.coin(request.key.instrument) {
1058            Ok(coin) => coin.to_owned(),
1059            Err(reason) => return make_invalid_instrument(reason),
1060        };
1061        let is_buy = request.state.side == Side::Buy;
1062
1063        match request.state.kind {
1064            OrderKind::Market => {
1065                return make_unsupported(
1066                    "Hyperliquid does not support market orders; use Limit with IOC time-in-force"
1067                        .to_string(),
1068                );
1069            }
1070            OrderKind::TrailingStop { .. }
1071            | OrderKind::TrailingStopLimit { .. }
1072            | OrderKind::TrailingStopFixedLimit { .. } => {
1073                return make_unsupported(
1074                    "Hyperliquid does not support trailing stop orders".to_string(),
1075                );
1076            }
1077            OrderKind::Limit
1078            | OrderKind::Stop { .. }
1079            | OrderKind::StopLimit { .. }
1080            | OrderKind::TakeProfit { .. }
1081            | OrderKind::TakeProfitLimit { .. } => {}
1082        }
1083
1084        // The venue reports every order under its cloid, so an order placed without one could
1085        // not be matched to the id the caller tracks it by. See the module docs.
1086        let Some(cloid) = cid_to_cloid(&request.key.cid) else {
1087            return make_rejected(CLOID_REQUIRED.to_string());
1088        };
1089
1090        let tif = map_tif(&request.state.time_in_force).to_string();
1091
1092        let Some(precision) = self.order_precision(request.key.instrument) else {
1093            return make_invalid_instrument(format!(
1094                "{coin} was not listed when the client connected; reconnect to trade a perpetual \
1095                 listed since"
1096            ));
1097        };
1098        let wire = match wire_order(
1099            &precision,
1100            request.state.kind,
1101            tif,
1102            request.state.price,
1103            request.state.quantity,
1104        ) {
1105            Ok(wire) => wire,
1106            Err(WireOrderError::Precision(violation)) => {
1107                return make_inactive(OrderError::InvalidPrecision(violation));
1108            }
1109            Err(WireOrderError::MissingPrice) => {
1110                return make_rejected(
1111                    "Hyperliquid requires limit price for Limit/StopLimit/TakeProfitLimit orders"
1112                        .to_string(),
1113                );
1114            }
1115            Err(WireOrderError::UnsupportedKind) => {
1116                return make_unsupported(format!(
1117                    "Hyperliquid does not support {} orders",
1118                    request.state.kind
1119                ));
1120            }
1121        };
1122
1123        // Logged only for an order about to be sent.
1124        if matches!(request.state.time_in_force, TimeInForce::FillOrKill) {
1125            warn!(
1126                instrument = %request.key.instrument,
1127                "FillOrKill not supported by Hyperliquid, using ImmediateOrCancel (may result in partial fills)"
1128            );
1129        }
1130
1131        let order_request = ClientOrderRequest {
1132            asset: coin,
1133            is_buy,
1134            reduce_only: request.state.reduce_only,
1135            limit_px: wire.limit_px,
1136            sz: wire.sz,
1137            cloid: Some(cloid),
1138            order_type: wire.order_type,
1139        };
1140
1141        let response = match self.exchange_client.order(order_request, None).await {
1142            Ok(r) => r,
1143            Err(e) => {
1144                warn!(%e, "Open order failed");
1145                return Order {
1146                    key: OrderKey {
1147                        exchange: ExchangeId::HyperliquidPerp,
1148                        instrument: request.key.instrument.clone(),
1149                        strategy: request.key.strategy.clone(),
1150                        cid: request.key.cid.clone(),
1151                    },
1152                    side: request.state.side,
1153                    price: request.state.price,
1154                    quantity: request.state.quantity,
1155                    kind: request.state.kind,
1156                    time_in_force: request.state.time_in_force,
1157                    state: OrderState::inactive(map_order_error(e, request.key.instrument)),
1158                };
1159            }
1160        };
1161
1162        // Parse response
1163        let state = match response {
1164            ExchangeResponseStatus::Ok(exchange_resp) => {
1165                // Check status from response data
1166                let status = exchange_resp
1167                    .data
1168                    .and_then(|d| d.statuses.into_iter().next());
1169
1170                match status {
1171                    Some(ExchangeDataStatus::Resting(resting)) => {
1172                        debug!(oid = resting.oid, "Order resting");
1173                        OrderState::active(Open {
1174                            id: VenueOrderId::Assigned(OrderId(format_smolstr!("{}", resting.oid))),
1175                            time_exchange: Utc::now(),
1176                            filled_quantity: Decimal::ZERO,
1177                        })
1178                    }
1179                    Some(ExchangeDataStatus::Filled(filled)) => {
1180                        debug!(oid = filled.oid, avg_px = %filled.avg_px, "Order filled");
1181                        // Hyperliquid provides avg_px for filled orders
1182                        let avg_price = parse_decimal(&filled.avg_px, "avg_px");
1183                        OrderState::fully_filled(Filled::new(
1184                            OrderId(format_smolstr!("{}", filled.oid)),
1185                            Utc::now(),
1186                            parse_decimal(&filled.total_sz, "total_sz")
1187                                .unwrap_or(request.state.quantity),
1188                            avg_price,
1189                        ))
1190                    }
1191                    Some(ExchangeDataStatus::Error(msg)) => {
1192                        warn!(%msg, "Order rejected by exchange");
1193                        OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1194                    }
1195                    Some(
1196                        ExchangeDataStatus::WaitingForFill | ExchangeDataStatus::WaitingForTrigger,
1197                    ) => {
1198                        // The venue answered without an oid, so the order's only handle is the
1199                        // cloid it was placed with. A standalone trigger order is answered
1200                        // `resting` with an oid; these statuses belong to grouped orders.
1201                        debug!(cid = %request.key.cid, "Order waiting under its cloid");
1202                        OrderState::active(Open {
1203                            id: VenueOrderId::ClientAssigned,
1204                            time_exchange: Utc::now(),
1205                            filled_quantity: Decimal::ZERO,
1206                        })
1207                    }
1208                    Some(ExchangeDataStatus::Success) | None => {
1209                        // The venue took the request without saying what became of the order,
1210                        // so it may be live: the outcome is unknown, not a refusal.
1211                        warn!(cid = %request.key.cid, "Order answered without its status; outcome unknown");
1212                        OrderState::inactive(order_outcome_unanswered())
1213                    }
1214                }
1215            }
1216            ExchangeResponseStatus::Err(msg) => {
1217                warn!(%msg, "Order rejected");
1218                OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1219            }
1220        };
1221        let order = Order {
1222            key: OrderKey {
1223                exchange: ExchangeId::HyperliquidPerp,
1224                instrument: request.key.instrument.clone(),
1225                strategy: request.key.strategy.clone(),
1226                cid: request.key.cid.clone(),
1227            },
1228            side: request.state.side,
1229            price: request.state.price,
1230            quantity: request.state.quantity,
1231            kind: request.state.kind,
1232            time_in_force: request.state.time_in_force,
1233            state,
1234        };
1235        self.known_live
1236            .lock()
1237            .placed(&order.key, order.quantity, order.kind, &order.state);
1238        order
1239    }
1240
1241    /// The collateral balances, read as [`account_snapshot`](ExecutionClient::account_snapshot)
1242    /// reads them: `userAbstraction` (weight 20), then either `spotClearinghouseState` or each
1243    /// DEX's `clearinghouseState` (weight 2 each).
1244    async fn fetch_balances(
1245        &self,
1246        _assets: &[AssetNameExchange],
1247    ) -> Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError> {
1248        perp_account::fetch_balances(&self.info_client, self.wallet_h160(), &self.dexes).await
1249    }
1250
1251    /// Every open order on each DEX traded, with one `openOrders` (weight 20) per DEX.
1252    ///
1253    /// # Errors
1254    ///
1255    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an instrument
1256    /// in `instruments` that names no perpetual this client trades.
1257    async fn fetch_open_orders(
1258        &self,
1259        instruments: &[InstrumentNameExchange],
1260    ) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
1261        self.check_instruments(instruments)?;
1262        let address = self.wallet_h160();
1263
1264        let open_orders =
1265            perp_account::open_orders(&self.info_client, address, &self.dexes).await?;
1266        warn_unknown_coins(open_orders.iter().map(|order| order.coin.as_str()));
1267
1268        let instrument_filter = InstrumentFilter::new(instruments);
1269
1270        let orders: Vec<_> = open_orders
1271            .iter()
1272            .filter_map(|order| {
1273                let instrument = self.dexes.instrument(&order.coin)?;
1274                if !instrument_filter.matches(&instrument) {
1275                    return None;
1276                }
1277                open_order_to_order(order, ExchangeId::HyperliquidPerp, instrument)
1278            })
1279            .collect();
1280        remember_open(&self.known_live, &orders);
1281        Ok(orders)
1282    }
1283
1284    /// Reads the span with `userFillsByTime`, to its end within the call, so the read is always
1285    /// complete (`resume: None`). Hyperliquid keeps only each wallet's 10,000 most recent fills,
1286    /// so a span reaching further back is read only as far as those go, and
1287    /// [`held_since`](TradesRead::held_since) says where that is. One read covers every
1288    /// DEX; fills on a HIP-3 DEX this client is not configured with are left out.
1289    ///
1290    /// # Errors
1291    ///
1292    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an instrument
1293    /// in `instruments` that names no perpetual this client trades.
1294    async fn fetch_trades(
1295        &self,
1296        start: DateTime<Utc>,
1297        end: DateTime<Utc>,
1298        instruments: &[InstrumentNameExchange],
1299    ) -> Result<TradesRead<AssetNameExchange, InstrumentNameExchange>, UnindexedClientError> {
1300        self.check_instruments(instruments)?;
1301        let Some((start_ms, end_ms)) = span_millis(start, end) else {
1302            return Ok(TradesRead::complete(Vec::new()));
1303        };
1304        let address = self.wallet_h160();
1305
1306        let fills = user_fills_by_time(&self.info_client, address, start_ms, end_ms).await?;
1307        let held_since = common::held_since(&fills, start_ms);
1308        warn_unknown_coins(fills.iter().map(|fill| fill.coin.as_str()));
1309        warn_unconfigured_dexes(&self.dexes, fills.iter().map(|fill| fill.coin.as_str()));
1310
1311        let instrument_filter = InstrumentFilter::new(instruments);
1312
1313        let mut result = Vec::new();
1314        for fill in fills {
1315            let Some((instrument, collateral)) = self.dexes.perp(&fill.coin) else {
1316                continue;
1317            };
1318
1319            if !instrument_filter.matches(&instrument) {
1320                continue;
1321            }
1322
1323            let Some(side) = parse_side(&fill.side) else {
1324                continue;
1325            };
1326            let Some(price) = parse_decimal(&fill.px, "px") else {
1327                continue;
1328            };
1329            let Some(quantity) = parse_decimal(&fill.sz, "sz") else {
1330                continue;
1331            };
1332            let fee = parse_decimal(&fill.fee, "fee").unwrap_or(Decimal::ZERO);
1333
1334            let Some(time_exchange) = millis_to_datetime(fill.time) else {
1335                warn!(time = fill.time, "Invalid fill timestamp, skipping");
1336                continue;
1337            };
1338            if !(start..=end).contains(&time_exchange) {
1339                continue;
1340            }
1341
1342            result.push(Trade {
1343                id: TradeId(format_smolstr!("{}", fill.tid)),
1344                order_id: OrderId(format_smolstr!("{}", fill.oid)),
1345                instrument,
1346                strategy: StrategyId::unknown(),
1347                time_exchange,
1348                side,
1349                price,
1350                quantity,
1351                // `TradeInfo` carries no cumulative filled quantity; Hyperliquid reports order
1352                // state as its own `OrderUpdate` message.
1353                order_filled_quantity: None,
1354                fees: perp_fill_fees(fill.fee_token.as_deref(), fee, collateral),
1355                // As on the stream, whose copy of a fill usually arrives first; see `TradeOrigin`.
1356                origin: TradeOrigin::Order,
1357                position_side: None,
1358                client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1359            });
1360        }
1361
1362        Ok(TradesRead::complete(result).with_held_since(held_since))
1363    }
1364}
1365
1366/// Looks each order up with `orderStatus` (weight 2), by the cloid it was placed with, or by its
1367/// `oid` for an order placed without one, which this client reports under its `oid`. Up to 8 run
1368/// at once.
1369///
1370/// `filled` is reported as fully filled, without an average price, which the record does not
1371/// carry; every status ending in `Canceled`, and `scheduledCancel`, as cancelled with what filled
1372/// before it; and every status ending in `Rejected` as
1373/// [`OpenFailed`](crate::order::state::InactiveOrderState::OpenFailed). Hyperliquid has no expiry.
1374/// An order the venue does not know, one on another instrument than the key's, and an id that is
1375/// neither a canonical UUID nor an `oid` are unknown. An `oid` whose order carries a cloid is
1376/// unknown too, since this client reports that order under its cloid.
1377///
1378/// The account stream runs the same lookup itself after a reconnect; see
1379/// [`account_stream`](ExecutionClient::account_stream).
1380impl OrderStatusClient for HyperliquidClient {
1381    async fn fetch_ended_orders(
1382        &self,
1383        orders: &[UnindexedOrderKey],
1384    ) -> Result<Vec<UnindexedInactiveOrder>, UnindexedClientError> {
1385        let address = self.wallet_h160();
1386        fetch_ended_by_key(orders, |key| {
1387            perp_order_lookup(self.info_client.clone(), self.dexes.clone(), address, key)
1388        })
1389        .await
1390    }
1391
1392    /// One `orderStatus` (weight 2), which reports a live order as well as an ended one, read
1393    /// as [`fetch_ended_orders`](OrderStatusClient::fetch_ended_orders) reads it.
1394    ///
1395    /// # Errors
1396    ///
1397    /// When the lookup fails, or Hyperliquid's record of the order does not convert.
1398    async fn fetch_order_status(
1399        &self,
1400        key: &UnindexedOrderKey,
1401    ) -> Result<VenueOrderStatus, UnindexedClientError> {
1402        perp_order_status(
1403            self.info_client.clone(),
1404            self.dexes.clone(),
1405            self.wallet_h160(),
1406            key.clone(),
1407        )
1408        .await?
1409        .ok_or_else(|| unreadable_record(&key.cid))
1410    }
1411}
1412
1413/// Look the order under `key` up with `orderStatus`, on the perpetual its coin names.
1414async fn perp_order_lookup(
1415    info_client: Arc<InfoClient>,
1416    dexes: Arc<PerpDexes>,
1417    address: ethers::types::H160,
1418    key: UnindexedOrderKey,
1419) -> Result<OrderLookup, UnindexedClientError> {
1420    Ok(lookup_of(
1421        perp_order_status(info_client, dexes, address, key).await?,
1422    ))
1423}
1424
1425/// What `orderStatus` says of the order under `key`, on the perpetual its coin names: see
1426/// `status_from_record`.
1427async fn perp_order_status(
1428    info_client: Arc<InfoClient>,
1429    dexes: Arc<PerpDexes>,
1430    address: ethers::types::H160,
1431    key: UnindexedOrderKey,
1432) -> Result<Option<VenueOrderStatus>, UnindexedClientError> {
1433    let Some(record) = fetch_order_record(&info_client, address, &key.cid).await? else {
1434        return Ok(Some(VenueOrderStatus::Unknown));
1435    };
1436    let instrument = dexes.instrument(&record.order.coin);
1437    Ok(status_from_record(key, &record, instrument))
1438}
1439
1440/// The client order ids `openOrders` (weight 20 per DEX traded) lists on the perpetuals
1441/// `instruments`, for a reconnect's check of the orders held as live.
1442async fn perp_listed_cids(
1443    info_client: Arc<InfoClient>,
1444    dexes: Arc<PerpDexes>,
1445    address: ethers::types::H160,
1446    instruments: Vec<InstrumentNameExchange>,
1447) -> Result<FnvHashSet<ClientOrderId>, UnindexedClientError> {
1448    let rows = perp_account::open_orders(&info_client, address, &dexes).await?;
1449    Ok(listed_cids(&rows, &instruments, |coin| {
1450        dexes.instrument(coin)
1451    }))
1452}
1453
1454/// Report one perpetual position from Hyperliquid's user state.
1455///
1456/// [`PositionReport::Open`] for a non-zero size, [`PositionReport::Flat`] for zero, and
1457/// [`PositionReport::Unreported`] when the size does not parse (with a warning): an unreadable
1458/// size establishes nothing, so it must not read as flat.
1459fn perp_position_report(
1460    position: &hyperliquid_rust_sdk::PositionData,
1461    now: DateTime<Utc>,
1462) -> PositionReport {
1463    let Some(quantity) = parse_decimal(&position.szi, "szi") else {
1464        return PositionReport::Unreported;
1465    };
1466    PositionReport::from_position(Position::new(
1467        quantity,
1468        position
1469            .entry_px
1470            .as_ref()
1471            .and_then(|p| parse_decimal(p, "entry_px")),
1472        parse_decimal(&position.unrealized_pnl, "unrealized_pnl"),
1473        parse_decimal(&position.margin_used, "margin_used"),
1474        position
1475            .liquidation_px
1476            .as_ref()
1477            .and_then(|p| parse_decimal(p, "liquidation_px")),
1478        Some(Decimal::from(position.leverage.value)),
1479        // Hyperliquid counts funding paid as positive; carry counts it as negative.
1480        parse_decimal(&position.cum_funding.since_open, "cum_funding.since_open").map(|paid| -paid),
1481        now,
1482    ))
1483}
1484
1485/// The fee of a fill on a perpetual whose DEX settles in `collateral`, in the asset `fee_token`
1486/// names.
1487///
1488/// The venue's `feeToken` is read rather than assumed; only its absence, which has not been
1489/// observed, falls back to `collateral`.
1490///
1491/// The quote-equivalent is set when the fee is in `collateral`, which is the instrument's quote,
1492/// and is `None` otherwise. It serves unindexed consumers: the indexer recomputes it either way,
1493/// from the instrument's own quote and base.
1494fn perp_fill_fees(
1495    fee_token: Option<&str>,
1496    fee: Decimal,
1497    collateral: &str,
1498) -> AssetFees<AssetNameExchange> {
1499    let asset = fee_token.unwrap_or(collateral);
1500    let fees_quote = (asset == collateral).then_some(fee);
1501    AssetFees::new(AssetNameExchange::from(asset), fee, fees_quote)
1502}
1503
1504/// Convert SDK TradeInfo (fill) to AccountEvent::Trade, `None` if its coin names no perpetual
1505/// this client trades.
1506fn fill_to_account_event(
1507    fill: &hyperliquid_rust_sdk::TradeInfo,
1508    dexes: &PerpDexes,
1509) -> Option<UnindexedAccountEvent> {
1510    let (instrument, collateral) = dexes.perp(&fill.coin)?;
1511    let side = parse_side(&fill.side)?;
1512    let price = parse_decimal(&fill.px, "fill.px")?;
1513    let quantity = parse_decimal(&fill.sz, "fill.sz")?;
1514    let fee = parse_decimal(&fill.fee, "fill.fee").unwrap_or(Decimal::ZERO);
1515    let time_exchange = millis_to_datetime(fill.time)?;
1516    let order_id = OrderId(format_smolstr!("{}", fill.oid));
1517
1518    let trade = Trade {
1519        id: TradeId(format_smolstr!("{}", fill.tid)),
1520        order_id,
1521        instrument,
1522        strategy: StrategyId::unknown(),
1523        time_exchange,
1524        side,
1525        price,
1526        quantity,
1527        // `TradeInfo` carries no cumulative filled quantity, so the order's state must be learned
1528        // from an `OrderUpdate` -- which Hyperliquid sends as its own message.
1529        order_filled_quantity: None,
1530        fees: perp_fill_fees(Some(&fill.fee_token), fee, collateral),
1531        // The SDK's `TradeInfo` drops the fill's liquidation marker, so every fill is reported
1532        // as `Order`; see `TradeOrigin`.
1533        origin: TradeOrigin::Order,
1534        position_side: None,
1535        client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1536    };
1537
1538    Some(AccountEvent::new(
1539        ExchangeId::HyperliquidPerp,
1540        AccountEventKind::Trade(trade),
1541    ))
1542}
1543
1544/// Convert SDK OrderUpdate to AccountEvent::OrderSnapshot, `None` if its coin names no
1545/// perpetual this client trades.
1546fn order_update_to_account_event(
1547    update: &hyperliquid_rust_sdk::OrderUpdate,
1548    dexes: &PerpDexes,
1549) -> Option<UnindexedAccountEvent> {
1550    common::order_update_to_account_event(
1551        update,
1552        ExchangeId::HyperliquidPerp,
1553        dexes.instrument(&update.order.coin)?,
1554    )
1555}
1556
1557#[cfg(test)]
1558// Test code: panics on bad input are acceptable
1559#[allow(clippy::unwrap_used)]
1560mod tests {
1561    use super::*;
1562    use crate::client::dedup::{dedup_key_from_event, is_duplicate};
1563    use rust_decimal_macros::dec;
1564    use rustrade_integration::collection::snapshot::Snapshot;
1565    use std::collections::HashMap;
1566
1567    /// Only Hyperliquid's default DEX.
1568    fn default_dex() -> PerpDexes {
1569        PerpDexes::default()
1570    }
1571
1572    mod order_recovery {
1573        use super::super::common::info_tests::info_client_against;
1574        use super::super::order_recovery::tests::{CID, CLOID, record_json, row};
1575        use super::*;
1576        use crate::order::state::InactiveOrderState;
1577        use wiremock::matchers::{method, path};
1578        use wiremock::{Mock, MockServer, ResponseTemplate};
1579
1580        async fn serve(body: serde_json::Value) -> (MockServer, Arc<InfoClient>) {
1581            let server = MockServer::start().await;
1582            Mock::given(method("POST"))
1583                .and(path("/info"))
1584                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1585                .mount(&server)
1586                .await;
1587            let client = Arc::new(info_client_against(server.uri()).await);
1588            (server, client)
1589        }
1590
1591        fn key() -> UnindexedOrderKey {
1592            OrderKey {
1593                exchange: ExchangeId::HyperliquidPerp,
1594                instrument: InstrumentNameExchange::new("BTC-USDC-PERP"),
1595                strategy: StrategyId::new("strategy"),
1596                cid: ClientOrderId::new(CID),
1597            }
1598        }
1599
1600        fn order_status(coin: &str) -> serde_json::Value {
1601            serde_json::json!({
1602                "status": "order",
1603                "order": record_json(coin, "canceled", "0.01", Some(CLOID)),
1604            })
1605        }
1606
1607        #[test]
1608        fn a_reconnect_snapshot_wakes_the_check_once_its_fills_are_sent() {
1609            use futures::FutureExt as _;
1610            let notified = |reconnected: &Notify| reconnected.notified().now_or_never().is_some();
1611            let snapshot = |fills| hyperliquid_rust_sdk::UserFillsData {
1612                is_snapshot: Some(true),
1613                user: ethers::types::H160::zero(),
1614                fills,
1615            };
1616            let reconnected = Arc::new(Notify::new());
1617            let mut reconnects = ReconnectWatch::new(reconnected.clone());
1618            let dedup = new_dedup_cache();
1619            let (tx, mut rx) = mpsc::unbounded_channel();
1620            let tids = |rx: &mut mpsc::UnboundedReceiver<UnindexedAccountEvent>| {
1621                std::iter::from_fn(|| rx.try_recv().ok())
1622                    .map(|event| match event.kind {
1623                        AccountEventKind::Trade(trade) => trade.id.0.to_string(),
1624                        other => panic!("expected a trade, got {other:?}"),
1625                    })
1626                    .collect::<Vec<_>>()
1627            };
1628
1629            // The snapshot opening the first subscription.
1630            let first = snapshot(vec![sweep_fill(1, "60000")]);
1631            assert!(send_fills(
1632                &first,
1633                |fill| fill_to_account_event(fill, &default_dex()),
1634                &dedup,
1635                &tx,
1636                &mut reconnects
1637            ));
1638            assert_eq!(tids(&mut rx), ["1"]);
1639            assert!(!notified(&reconnected));
1640
1641            // A drop, then the resubscription's snapshot: its new fill is sent, then the check
1642            // woken.
1643            reconnects.dropped();
1644            let resubscribed = snapshot(vec![sweep_fill(1, "60000"), sweep_fill(2, "60001")]);
1645            assert!(send_fills(
1646                &resubscribed,
1647                |fill| fill_to_account_event(fill, &default_dex()),
1648                &dedup,
1649                &tx,
1650                &mut reconnects
1651            ));
1652            assert_eq!(
1653                tids(&mut rx),
1654                ["2"],
1655                "the fill already sent is not sent again"
1656            );
1657            assert!(notified(&reconnected));
1658
1659            // With the consumer gone the fills cannot be sent, and the check is not woken.
1660            drop(rx);
1661            reconnects.dropped();
1662            let unsent = snapshot(vec![sweep_fill(3, "60002")]);
1663            assert!(!send_fills(
1664                &unsent,
1665                |fill| fill_to_account_event(fill, &default_dex()),
1666                &dedup,
1667                &tx,
1668                &mut reconnects
1669            ));
1670            assert!(!notified(&reconnected));
1671        }
1672
1673        #[tokio::test]
1674        async fn a_perp_lookup_reads_how_the_order_ended() {
1675            let (_server, client) = serve(order_status("BTC")).await;
1676
1677            let lookup =
1678                perp_order_lookup(client, Arc::default(), ethers::types::H160::zero(), key())
1679                    .await
1680                    .unwrap();
1681
1682            let OrderLookup::Ended(order) = lookup else {
1683                panic!("expected an ended order, got {lookup:?}");
1684            };
1685            assert_eq!(order.key, key());
1686            assert!(matches!(order.state, InactiveOrderState::Cancelled(_)));
1687        }
1688
1689        /// One `orderStatus` answers a lookup, live, ended or unknown, without listing the open
1690        /// orders; a record that does not convert is an error, never `Unknown`.
1691        #[tokio::test]
1692        async fn a_perp_order_status_is_one_order_status_request() {
1693            let answer = |status: &str| {
1694                serde_json::json!({
1695                    "status": "order",
1696                    "order": record_json("BTC", status, "0.01", Some(CLOID)),
1697                })
1698            };
1699            for (body, expected) in [
1700                (answer("open"), "live"),
1701                (answer("canceled"), "ended"),
1702                (serde_json::json!({"status": "unknownOid"}), "unknown"),
1703                (answer("aStatusAddedLater"), "error"),
1704            ] {
1705                let server = MockServer::start().await;
1706                Mock::given(method("POST"))
1707                    .and(path("/info"))
1708                    .respond_with(ResponseTemplate::new(200).set_body_json(body))
1709                    .mount(&server)
1710                    .await;
1711                let client = client_against(&server, HashMap::new()).await;
1712
1713                let status = client.fetch_order_status(&key()).await;
1714
1715                let found = match &status {
1716                    Ok(VenueOrderStatus::Live(order)) if order.key == key() => "live",
1717                    Ok(VenueOrderStatus::Ended(order)) if order.key == key() => "ended",
1718                    Ok(VenueOrderStatus::Unknown) => "unknown",
1719                    Err(UnindexedClientError::Internal(_)) => "error",
1720                    _ => "other",
1721                };
1722                assert_eq!(found, expected, "{status:?}");
1723                assert_eq!(server.received_requests().await.unwrap().len(), 1);
1724            }
1725        }
1726
1727        #[tokio::test]
1728        async fn a_perp_lookup_of_a_spot_order_is_unknown() {
1729            let (_server, client) = serve(order_status("@107")).await;
1730
1731            let lookup =
1732                perp_order_lookup(client, Arc::default(), ethers::types::H160::zero(), key())
1733                    .await
1734                    .unwrap();
1735
1736            assert!(matches!(lookup, OrderLookup::Unknown));
1737        }
1738
1739        #[tokio::test]
1740        async fn a_perp_listing_names_only_the_orders_on_the_perpetuals_asked_about() {
1741            let rows = serde_json::json!([
1742                row("BTC", 1, Some(CLOID)),
1743                row("ETH", 2, None),
1744                row("@107", 3, None),
1745            ]);
1746            let (_server, client) = serve(rows).await;
1747
1748            let listed = perp_listed_cids(
1749                client,
1750                Arc::default(),
1751                ethers::types::H160::zero(),
1752                vec![InstrumentNameExchange::new("BTC-USDC-PERP")],
1753            )
1754            .await
1755            .unwrap();
1756
1757            assert_eq!(
1758                listed.into_iter().collect::<Vec<_>>(),
1759                [ClientOrderId::new(CID)]
1760            );
1761        }
1762    }
1763
1764    /// A client trading `xyz` and `flx` against `server`, built without the network, that places
1765    /// and cancels on the assets in `coin_to_asset`. The default DEX lists `BTC`, with
1766    /// `szDecimals` 5 as on mainnet.
1767    async fn client_against(
1768        server: &wiremock::MockServer,
1769        coin_to_asset: HashMap<String, u32>,
1770    ) -> HyperliquidClient {
1771        use super::common::info_tests::{
1772            exchange_client_against, info_client_against, test_wallet,
1773        };
1774        let mut dexes = super::perp_dexes::tests::xyz_and_flx().await;
1775        dexes.add_default_perps(&[hyperliquid_rust_sdk::AssetMeta {
1776            name: "BTC".to_owned(),
1777            sz_decimals: 5,
1778        }]);
1779        HyperliquidClient {
1780            config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
1781            info_client: Arc::new(info_client_against(server.uri()).await),
1782            exchange_client: Arc::new(exchange_client_against(server.uri(), coin_to_asset).await),
1783            dexes: Arc::new(dexes),
1784            known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidPerp),
1785        }
1786    }
1787
1788    mod open_order {
1789        use super::*;
1790        use crate::error::{ApiError, OrderField, PrecisionLimit, PrecisionViolation};
1791        use crate::order::{OrderEvent, request::RequestOpen, state::InactiveOrderState};
1792        use wiremock::matchers::{method, path};
1793        use wiremock::{Mock, MockServer, ResponseTemplate};
1794
1795        /// A server whose exchange endpoint rests every order it is sent.
1796        async fn resting_server() -> MockServer {
1797            server_responding(serde_json::json!({
1798                "status": "ok",
1799                "response": {"type": "order", "data": {"statuses": [{"resting": {"oid": 77}}]}},
1800            }))
1801            .await
1802        }
1803
1804        /// A server whose exchange endpoint answers every request with `body`.
1805        async fn server_responding(body: serde_json::Value) -> MockServer {
1806            server_with(ResponseTemplate::new(200).set_body_json(body)).await
1807        }
1808
1809        /// A server whose exchange endpoint gives `response` to every request.
1810        async fn server_with(response: ResponseTemplate) -> MockServer {
1811            let server = MockServer::start().await;
1812            Mock::given(method("POST"))
1813                .and(path("/exchange"))
1814                .respond_with(response)
1815                .mount(&server)
1816                .await;
1817            server
1818        }
1819
1820        /// Place a `BTC-USDC-PERP` limit order through a client against `server`.
1821        async fn place_on(
1822            server: &MockServer,
1823        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1824            let client = client_against(server, HashMap::from([("BTC".to_owned(), 0)])).await;
1825            place(
1826                &client,
1827                &InstrumentNameExchange::from("BTC-USDC-PERP"),
1828                OrderKind::Limit,
1829                Some(dec!(50000)),
1830                dec!(0.001),
1831            )
1832            .await
1833        }
1834
1835        /// An open the venue may have acted on keeps an unknown outcome, so the engine looks it
1836        /// up rather than ending it: a 5xx, an answer that does not parse, no answer at all, and
1837        /// an `ok` answer that does not say what became of the order.
1838        #[tokio::test]
1839        async fn an_open_the_venue_may_have_acted_on_has_an_unknown_outcome() {
1840            let no_status = serde_json::json!({"status": "ok", "response": {"type": "order"}});
1841            let success = serde_json::json!({
1842                "status": "ok",
1843                "response": {"type": "order", "data": {"statuses": ["success"]}},
1844            });
1845            for (case, response) in [
1846                (
1847                    "5xx",
1848                    ResponseTemplate::new(502).set_body_string("Bad Gateway"),
1849                ),
1850                (
1851                    "unparsable",
1852                    ResponseTemplate::new(200).set_body_string("<html>"),
1853                ),
1854                (
1855                    "no status",
1856                    ResponseTemplate::new(200).set_body_json(no_status),
1857                ),
1858                ("success", ResponseTemplate::new(200).set_body_json(success)),
1859            ] {
1860                let order = place_on(&server_with(response).await).await;
1861                assert!(
1862                    matches!(
1863                        order.state,
1864                        OrderState::Inactive(InactiveOrderState::OpenFailed(
1865                            OrderError::Connectivity(_)
1866                        ))
1867                    ),
1868                    "{case}: {:?}",
1869                    order.state
1870                );
1871                assert!(order.state.is_outcome_unknown(), "{case}");
1872            }
1873
1874            // Nothing listening: the send itself fails. A port bound and released, since a
1875            // dropped mock server goes back to wiremock's pool still listening.
1876            let server = MockServer::start().await;
1877            let mut client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
1878            let closed = std::net::TcpListener::bind("127.0.0.1:0")
1879                .and_then(|listener| listener.local_addr())
1880                .unwrap();
1881            client.exchange_client = Arc::new(
1882                super::super::common::info_tests::exchange_client_against(
1883                    format!("http://{closed}"),
1884                    HashMap::from([("BTC".to_owned(), 0)]),
1885                )
1886                .await,
1887            );
1888            let order = place(
1889                &client,
1890                &InstrumentNameExchange::from("BTC-USDC-PERP"),
1891                OrderKind::Limit,
1892                Some(dec!(50000)),
1893                dec!(0.001),
1894            )
1895            .await;
1896            assert!(order.state.is_outcome_unknown(), "{:?}", order.state);
1897        }
1898
1899        /// A 4xx turned the request away, so the open ends as refused; a 429 as rate-limited.
1900        #[tokio::test]
1901        async fn an_open_turned_away_with_a_4xx_is_refused() {
1902            let order = place_on(
1903                &server_with(ResponseTemplate::new(422).set_body_string("Failed to deserialize"))
1904                    .await,
1905            )
1906            .await;
1907            assert!(
1908                matches!(
1909                    order.state,
1910                    OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1911                        ApiError::OrderRejected(_)
1912                    )))
1913                ),
1914                "{:?}",
1915                order.state
1916            );
1917
1918            let order = place_on(&server_with(ResponseTemplate::new(429)).await).await;
1919            assert_eq!(
1920                order.state,
1921                OrderState::inactive(OrderError::Rejected(ApiError::rate_limited(None)))
1922            );
1923        }
1924
1925        /// A refusal for want of margin is a balance shortfall, as on other venues; any other
1926        /// refusal stays a rejection. Hyperliquid names no asset. The refusal is read both as an
1927        /// order's status and as the error of the whole response.
1928        #[tokio::test]
1929        async fn an_order_refused_for_margin_is_balance_insufficient() {
1930            const MARGIN: &str = "Insufficient margin to place order. asset=0";
1931            const MINIMUM: &str = "Order must have minimum value of $10. asset=0";
1932            let in_status = |error: &str| {
1933                serde_json::json!({
1934                    "status": "ok",
1935                    "response": {"type": "order", "data": {"statuses": [{"error": error}]}},
1936                })
1937            };
1938            let in_response = |error: &str| serde_json::json!({"status": "err", "response": error});
1939            for (body, expected) in [
1940                (
1941                    in_status(MARGIN),
1942                    ApiError::BalanceInsufficient(None, MARGIN.to_owned()),
1943                ),
1944                (
1945                    in_response(MARGIN),
1946                    ApiError::BalanceInsufficient(None, MARGIN.to_owned()),
1947                ),
1948                (
1949                    in_status(MINIMUM),
1950                    ApiError::OrderRejected(MINIMUM.to_owned()),
1951                ),
1952                (
1953                    in_response(MINIMUM),
1954                    ApiError::OrderRejected(MINIMUM.to_owned()),
1955                ),
1956            ] {
1957                let server = server_responding(body.clone()).await;
1958                let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
1959                let order = place(
1960                    &client,
1961                    &InstrumentNameExchange::from("BTC-USDC-PERP"),
1962                    OrderKind::Limit,
1963                    Some(dec!(50000)),
1964                    dec!(0.001),
1965                )
1966                .await;
1967                let OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1968                    reported,
1969                ))) = &order.state
1970                else {
1971                    panic!("{body}: expected a rejection, got {:?}", order.state);
1972                };
1973                assert_eq!(reported, &expected, "{body}");
1974            }
1975        }
1976
1977        async fn place(
1978            client: &HyperliquidClient,
1979            instrument: &InstrumentNameExchange,
1980            kind: OrderKind,
1981            price: Option<Decimal>,
1982            quantity: Decimal,
1983        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1984            client
1985                .open_order(OrderEvent {
1986                    key: OrderKey {
1987                        exchange: ExchangeId::HyperliquidPerp,
1988                        instrument,
1989                        strategy: StrategyId::new("strategy"),
1990                        cid: ClientOrderId::uuid(),
1991                    },
1992                    state: RequestOpen::new(
1993                        Side::Buy,
1994                        price,
1995                        quantity,
1996                        kind,
1997                        TimeInForce::GoodUntilCancelled { post_only: false },
1998                    ),
1999                })
2000                .await
2001        }
2002
2003        /// The orders the server was sent, as the SDK wrote them.
2004        async fn sent_orders(server: &MockServer) -> Vec<serde_json::Value> {
2005            server
2006                .received_requests()
2007                .await
2008                .unwrap_or_default()
2009                .into_iter()
2010                .filter(|request| request.url.path() == "/exchange")
2011                .map(|request| {
2012                    let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
2013                    body["action"]["orders"][0].clone()
2014                })
2015                .collect()
2016        }
2017
2018        #[tokio::test]
2019        async fn the_client_reports_each_perpetuals_precision() {
2020            let server = MockServer::start().await;
2021            let client = client_against(&server, HashMap::new()).await;
2022
2023            assert_eq!(
2024                client.order_precision(&InstrumentNameExchange::from("BTC-USDC-PERP")),
2025                Some(OrderPrecision::perp(5))
2026            );
2027            assert_eq!(
2028                client.order_precision(&InstrumentNameExchange::from("xyz:TSLA-USDC-PERP")),
2029                Some(OrderPrecision::perp(2)),
2030                "a HIP-3 perpetual's szDecimals come from its DEX's meta"
2031            );
2032            assert_eq!(
2033                client.order_precision(&InstrumentNameExchange::from("ETH-USDC-PERP")),
2034                None,
2035                "not listed when the client connected"
2036            );
2037            assert_eq!(
2038                client.order_precision(&InstrumentNameExchange::from("HYPE-USDC-SPOT")),
2039                None
2040            );
2041        }
2042
2043        #[tokio::test]
2044        async fn an_order_breaking_the_precision_rules_is_refused_unsent() {
2045            let server = resting_server().await;
2046            let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
2047            let btc = InstrumentNameExchange::from("BTC-USDC-PERP");
2048
2049            let cases = [
2050                (
2051                    OrderKind::Limit,
2052                    dec!(60000),
2053                    dec!(0.000001),
2054                    OrderField::Quantity,
2055                    PrecisionLimit::DecimalPlaces { max: 5 },
2056                ),
2057                (
2058                    OrderKind::Limit,
2059                    dec!(60000),
2060                    dec!(0),
2061                    OrderField::Quantity,
2062                    PrecisionLimit::NotPositive,
2063                ),
2064                (
2065                    OrderKind::Limit,
2066                    dec!(65432.1),
2067                    dec!(0.001),
2068                    OrderField::Price,
2069                    PrecisionLimit::SignificantFigures { max: 5 },
2070                ),
2071                (
2072                    OrderKind::Limit,
2073                    dec!(6543.21),
2074                    dec!(0.001),
2075                    OrderField::Price,
2076                    PrecisionLimit::DecimalPlaces { max: 1 },
2077                ),
2078                (
2079                    OrderKind::StopLimit {
2080                        trigger_price: dec!(6543.21),
2081                    },
2082                    dec!(6543),
2083                    dec!(0.001),
2084                    OrderField::TriggerPrice,
2085                    PrecisionLimit::DecimalPlaces { max: 1 },
2086                ),
2087            ];
2088            for (kind, price, quantity, field, limit) in cases {
2089                let order = place(&client, &btc, kind, Some(price), quantity).await;
2090                let expected = PrecisionViolation {
2091                    field,
2092                    value: match field {
2093                        OrderField::Quantity => quantity,
2094                        OrderField::TriggerPrice => dec!(6543.21),
2095                        _ => price,
2096                    },
2097                    limit,
2098                };
2099                assert_eq!(
2100                    order.state,
2101                    OrderState::Inactive(InactiveOrderState::OpenFailed(
2102                        OrderError::InvalidPrecision(expected)
2103                    )),
2104                    "{kind} at {price} for {quantity}"
2105                );
2106            }
2107            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
2108        }
2109
2110        #[tokio::test]
2111        async fn a_valid_order_is_sent_unchanged() {
2112            let server = resting_server().await;
2113            let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
2114            let btc = InstrumentNameExchange::from("BTC-USDC-PERP");
2115
2116            // An integer price past 5 significant figures, which the client once rounded to 123460.
2117            let order = place(
2118                &client,
2119                &btc,
2120                OrderKind::Limit,
2121                Some(dec!(123456)),
2122                dec!(0.00123),
2123            )
2124            .await;
2125            assert!(
2126                matches!(order.state, OrderState::Active(_)),
2127                "{:?}",
2128                order.state
2129            );
2130
2131            let sent = sent_orders(&server).await;
2132            assert_eq!(sent.len(), 1);
2133            assert_eq!(
2134                (&sent[0]["p"], &sent[0]["s"]),
2135                (&serde_json::json!("123456"), &serde_json::json!("0.00123"))
2136            );
2137        }
2138
2139        #[tokio::test]
2140        async fn an_order_on_a_perpetual_listed_since_connecting_is_refused_unsent() {
2141            let server = resting_server().await;
2142            let client = client_against(&server, HashMap::from([("ETH".to_owned(), 1)])).await;
2143
2144            let order = place(
2145                &client,
2146                &InstrumentNameExchange::from("ETH-USDC-PERP"),
2147                OrderKind::Limit,
2148                Some(dec!(3000)),
2149                dec!(1),
2150            )
2151            .await;
2152            let OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
2153                crate::error::ApiError::InstrumentInvalid(_, reason),
2154            ))) = &order.state
2155            else {
2156                panic!("expected InstrumentInvalid, got {:?}", order.state);
2157            };
2158            assert!(reason.contains("reconnect"), "{reason}");
2159            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
2160        }
2161    }
2162
2163    mod cancel {
2164        use super::super::common::info_tests::{CANCEL_NOT_APPLIED, cancel_answer};
2165        use super::*;
2166        use crate::error::ApiError;
2167        use crate::order::{OrderEvent, request::RequestCancel};
2168        use wiremock::matchers::{method, path};
2169        use wiremock::{Mock, MockServer, ResponseTemplate};
2170
2171        /// Cancel a live `BTC-USDC-PERP` order through a client whose exchange endpoint answers
2172        /// `answer`. Returns the response, and whether the order is still held live afterwards.
2173        async fn cancel_answered(
2174            answer: serde_json::Value,
2175        ) -> (UnindexedOrderResponseCancel, bool) {
2176            cancel_responded(ResponseTemplate::new(200).set_body_json(answer)).await
2177        }
2178
2179        /// [`cancel_answered`], with the exchange endpoint giving `response`.
2180        async fn cancel_responded(
2181            response: ResponseTemplate,
2182        ) -> (UnindexedOrderResponseCancel, bool) {
2183            let server = MockServer::start().await;
2184            Mock::given(method("POST"))
2185                .and(path("/exchange"))
2186                .respond_with(response)
2187                .mount(&server)
2188                .await;
2189            let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
2190            let instrument = InstrumentNameExchange::new("BTC-USDC-PERP");
2191            let key = OrderKey {
2192                exchange: ExchangeId::HyperliquidPerp,
2193                instrument: instrument.clone(),
2194                strategy: StrategyId::new("strategy"),
2195                cid: ClientOrderId::uuid(),
2196            };
2197            let id = VenueOrderId::Assigned(OrderId::new("7"));
2198            let open = Open {
2199                id: id.clone(),
2200                time_exchange: Utc::now(),
2201                filled_quantity: Decimal::ZERO,
2202            };
2203            client
2204                .known_live
2205                .lock()
2206                .live(&key, dec!(1), OrderKind::Limit, &open);
2207
2208            let response = client
2209                .cancel_order(OrderEvent {
2210                    key: OrderKey {
2211                        exchange: key.exchange,
2212                        instrument: &instrument,
2213                        strategy: key.strategy.clone(),
2214                        cid: key.cid.clone(),
2215                    },
2216                    state: RequestCancel { id: Some(id) },
2217                })
2218                .await;
2219            let live = client.known_live.lock().contains(&key.cid);
2220            (response, live)
2221        }
2222
2223        #[tokio::test]
2224        async fn a_success_status_cancels_the_order() {
2225            let (response, live) =
2226                cancel_answered(cancel_answer(serde_json::json!(["success"]))).await;
2227            assert!(response.state.is_ok(), "{:?}", response.state);
2228            assert!(!live, "a cancelled order is no longer held live");
2229        }
2230
2231        /// An order that filled before the cancel arrived is answered this way, so it must not be
2232        /// reported cancelled, and stays held live until the account stream or a lookup ends it.
2233        #[tokio::test]
2234        async fn an_error_status_is_a_rejected_cancel_and_the_order_stays_live() {
2235            let (response, live) = cancel_answered(cancel_answer(serde_json::json!([
2236                {"error": CANCEL_NOT_APPLIED}
2237            ])))
2238            .await;
2239            let Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(reason))) =
2240                &response.state
2241            else {
2242                panic!("expected a rejected cancel, got {:?}", response.state);
2243            };
2244            assert_eq!(reason, CANCEL_NOT_APPLIED);
2245            assert!(live, "the order is still held live");
2246        }
2247
2248        /// A cancel the venue may have acted on is not reported refused, and one turned away
2249        /// with a 4xx is. Either way the order stays held live until a report ends it.
2250        #[tokio::test]
2251        async fn a_cancel_failing_after_the_send_has_an_unknown_outcome() {
2252            let (response, live) = cancel_responded(ResponseTemplate::new(503)).await;
2253            assert!(
2254                matches!(response.state, Err(UnindexedOrderError::Connectivity(_))),
2255                "{:?}",
2256                response.state
2257            );
2258            assert!(live, "the order is still held live");
2259
2260            let (response, live) =
2261                cancel_responded(ResponseTemplate::new(422).set_body_string("bad request")).await;
2262            assert!(
2263                matches!(
2264                    response.state,
2265                    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(_)))
2266                ),
2267                "{:?}",
2268                response.state
2269            );
2270            assert!(live, "the order is still held live");
2271        }
2272
2273        #[tokio::test]
2274        async fn an_answer_without_a_status_is_a_rejected_cancel() {
2275            let (response, live) = cancel_answered(serde_json::json!({
2276                "status": "ok",
2277                "response": {"type": "cancel"},
2278            }))
2279            .await;
2280            assert!(
2281                matches!(
2282                    response.state,
2283                    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(_)))
2284                ),
2285                "{:?}",
2286                response.state
2287            );
2288            assert!(live, "the order is still held live");
2289        }
2290    }
2291
2292    mod instrument_names {
2293        use super::*;
2294        use crate::error::ApiError;
2295        use crate::order::{
2296            OrderEvent,
2297            request::{RequestCancel, RequestOpen},
2298        };
2299        use wiremock::MockServer;
2300
2301        /// A client trading `xyz` and `flx`, built without the network, against a server with
2302        /// nothing mounted: any request it sent would fail with something other than
2303        /// `InstrumentInvalid`.
2304        async fn offline_client() -> (MockServer, HyperliquidClient) {
2305            let server = MockServer::start().await;
2306            let client = client_against(&server, HashMap::new()).await;
2307            (server, client)
2308        }
2309
2310        /// Names no perpetual the client trades: the old `-USD-` name, a quote other than the
2311        /// DEX's collateral, a DEX not configured, and a spot pair.
2312        const REFUSED: [&str; 4] = [
2313            "BTC-USD-PERP",
2314            "flx:TSLA-USDC-PERP",
2315            "km:TSLA-USDH-PERP",
2316            "HYPE-USDC-SPOT",
2317        ];
2318
2319        fn is_invalid(
2320            error: &ApiError<AssetNameExchange, InstrumentNameExchange>,
2321            name: &str,
2322        ) -> bool {
2323            matches!(error, ApiError::InstrumentInvalid(instrument, _) if instrument.as_ref() == name)
2324        }
2325
2326        #[tokio::test]
2327        async fn an_order_on_a_name_the_client_does_not_trade_is_refused_unsent() {
2328            let (_server, client) = offline_client().await;
2329            for name in REFUSED {
2330                let instrument = InstrumentNameExchange::from(name);
2331                let order = client
2332                    .open_order(OrderEvent {
2333                        key: OrderKey {
2334                            exchange: ExchangeId::HyperliquidPerp,
2335                            instrument: &instrument,
2336                            strategy: StrategyId::new("strategy"),
2337                            cid: ClientOrderId::uuid(),
2338                        },
2339                        state: RequestOpen::new(
2340                            Side::Buy,
2341                            Some(dec!(1)),
2342                            dec!(1),
2343                            OrderKind::Limit,
2344                            TimeInForce::GoodUntilCancelled { post_only: false },
2345                        ),
2346                    })
2347                    .await;
2348                let OrderState::Inactive(crate::order::state::InactiveOrderState::OpenFailed(
2349                    OrderError::Rejected(error),
2350                )) = &order.state
2351                else {
2352                    panic!("{name}: expected a rejection, got {:?}", order.state);
2353                };
2354                assert!(is_invalid(error, name), "{name}: {error:?}");
2355            }
2356        }
2357
2358        #[tokio::test]
2359        async fn a_cancel_on_a_name_the_client_does_not_trade_is_refused_unsent() {
2360            let (_server, client) = offline_client().await;
2361            for name in REFUSED {
2362                let instrument = InstrumentNameExchange::from(name);
2363                let response = client
2364                    .cancel_order(OrderEvent {
2365                        key: OrderKey {
2366                            exchange: ExchangeId::HyperliquidPerp,
2367                            instrument: &instrument,
2368                            strategy: StrategyId::new("strategy"),
2369                            cid: ClientOrderId::uuid(),
2370                        },
2371                        state: RequestCancel {
2372                            id: Some(VenueOrderId::Assigned(OrderId::new("1"))),
2373                        },
2374                    })
2375                    .await;
2376                let Err(UnindexedOrderError::Rejected(error)) = &response.state else {
2377                    panic!("{name}: expected a rejection, got {:?}", response.state);
2378                };
2379                assert!(is_invalid(error, name), "{name}: {error:?}");
2380            }
2381        }
2382
2383        #[tokio::test]
2384        async fn a_read_filtered_to_a_name_the_client_does_not_trade_fails_unsent() {
2385            let (_server, client) = offline_client().await;
2386            for name in REFUSED {
2387                let instruments = [InstrumentNameExchange::from(name)];
2388                let snapshot = client.account_snapshot(&[], &instruments).await;
2389                let open = client.fetch_open_orders(&instruments).await;
2390                let trades = client
2391                    .fetch_trades(
2392                        Utc::now() - chrono::Duration::hours(1),
2393                        Utc::now(),
2394                        &instruments,
2395                    )
2396                    .await;
2397                for error in [snapshot.err(), open.err(), trades.err()] {
2398                    let Some(UnindexedClientError::Api(error)) = &error else {
2399                        panic!("{name}: expected an API error, got {error:?}");
2400                    };
2401                    assert!(is_invalid(error, name), "{name}: {error:?}");
2402                }
2403            }
2404        }
2405    }
2406
2407    fn perp_position(szi: &str) -> hyperliquid_rust_sdk::PositionData {
2408        serde_json::from_value(serde_json::json!({
2409            "coin": "BTC",
2410            "entryPx": "50000.0",
2411            "leverage": {"type": "cross", "value": 5},
2412            "liquidationPx": null,
2413            "marginUsed": "100.0",
2414            "positionValue": "500.0",
2415            "returnOnEquity": "0.0",
2416            "szi": szi,
2417            "unrealizedPnl": "1.5",
2418            "maxLeverage": 50,
2419            "cumFunding": {"allTime": "3.5", "sinceOpen": "1.25", "sinceChange": "0"}
2420        }))
2421        .unwrap()
2422    }
2423
2424    #[test]
2425    fn perp_position_report_is_open_flat_or_unreported() {
2426        let now = Utc::now();
2427        let open = perp_position_report(&perp_position("-0.01"), now);
2428        let position = open.open().unwrap();
2429        // Funding paid since open is positive on Hyperliquid and negative as carry.
2430        assert_eq!(
2431            (
2432                position.quantity,
2433                position.entry_price,
2434                position.leverage,
2435                position.carry
2436            ),
2437            (
2438                dec!(-0.01),
2439                Some(dec!(50000.0)),
2440                Some(dec!(5)),
2441                Some(dec!(-1.25))
2442            )
2443        );
2444        assert_eq!(
2445            perp_position_report(&perp_position("0.0"), now),
2446            PositionReport::Flat
2447        );
2448        assert_eq!(
2449            perp_position_report(&perp_position("not a number"), now),
2450            PositionReport::Unreported
2451        );
2452    }
2453
2454    #[test]
2455    fn test_fill_to_account_event() {
2456        let fill_json = r#"{
2457            "coin": "BTC",
2458            "side": "B",
2459            "px": "65000.5",
2460            "sz": "0.1",
2461            "time": 1714100000000,
2462            "hash": "0xabc123",
2463            "startPosition": "0",
2464            "dir": "Open Long",
2465            "closedPnl": "0",
2466            "oid": 12345,
2467            "cloid": null,
2468            "crossed": false,
2469            "fee": "0.65",
2470            "feeToken": "USDC",
2471            "tid": 99999
2472        }"#;
2473
2474        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2475        let event = fill_to_account_event(&fill, &default_dex()).unwrap();
2476
2477        assert_eq!(event.exchange, ExchangeId::HyperliquidPerp);
2478        match event.kind {
2479            AccountEventKind::Trade(trade) => {
2480                assert_eq!(trade.instrument.as_ref(), "BTC-USDC-PERP");
2481                assert_eq!(
2482                    trade.id.0, "99999",
2483                    "the id is the fill's tid, not its hash"
2484                );
2485                assert_eq!(trade.side, Side::Buy);
2486                assert_eq!(trade.price, dec!(65000.5));
2487                assert_eq!(trade.quantity, dec!(0.1));
2488                assert_eq!(trade.fees.fees, dec!(0.65));
2489                assert_eq!(trade.fees.asset.as_ref(), "USDC");
2490                assert_eq!(trade.fees.fees_quote, Some(dec!(0.65)));
2491            }
2492            _ => panic!("Expected Trade event"),
2493        }
2494    }
2495
2496    /// A fill reports its order's cloid as the client order id the order was placed under.
2497    #[tokio::test]
2498    async fn a_fill_carries_the_client_order_id_of_its_cloid() {
2499        let fill_json = r#"{
2500            "coin": "flx:TSLA", "side": "B", "px": "250", "sz": "2",
2501            "time": 1714100000000, "hash": "0xhip3", "startPosition": "0",
2502            "dir": "Open Long", "closedPnl": "0", "oid": 7,
2503            "cloid": "0x0123456789abcdef0123456789abcdef",
2504            "crossed": true, "fee": "0.2", "feeToken": "USDH", "tid": 77
2505        }"#;
2506        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2507
2508        let dexes = perp_dexes::tests::xyz_and_flx().await;
2509        let AccountEventKind::Trade(trade) = fill_to_account_event(&fill, &dexes).unwrap().kind
2510        else {
2511            panic!("Expected Trade event");
2512        };
2513        assert_eq!(
2514            trade.client_order_id,
2515            cloid_to_cid("0x0123456789abcdef0123456789abcdef")
2516        );
2517        assert!(trade.client_order_id.is_some());
2518    }
2519
2520    #[tokio::test]
2521    async fn a_builder_deployed_fill_is_named_and_charged_in_its_dex_collateral() {
2522        // A HIP-3 perpetual settles in its deployer's collateral, which is not always USDC.
2523        let fill_json = r#"{
2524            "coin": "flx:TSLA", "side": "B", "px": "250", "sz": "2",
2525            "time": 1714100000000, "hash": "0xhip3", "startPosition": "0",
2526            "dir": "Open Long", "closedPnl": "0", "oid": 7, "cloid": null,
2527            "crossed": true, "fee": "0.2", "feeToken": "USDH", "tid": 77
2528        }"#;
2529        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2530
2531        let dexes = perp_dexes::tests::xyz_and_flx().await;
2532        let AccountEventKind::Trade(trade) = fill_to_account_event(&fill, &dexes).unwrap().kind
2533        else {
2534            panic!("Expected Trade event");
2535        };
2536        assert_eq!(trade.instrument.as_ref(), "flx:TSLA-USDH-PERP");
2537        assert_eq!(trade.client_order_id, None, "placed without a cloid");
2538        assert_eq!(trade.fees.asset.as_ref(), "USDH");
2539        assert_eq!(trade.fees.fees, dec!(0.2));
2540        assert_eq!(
2541            trade.fees.fees_quote,
2542            Some(dec!(0.2)),
2543            "the fee is in the instrument's quote"
2544        );
2545
2546        // Without `flx` configured, its collateral is unknown, so the fill is left out.
2547        assert!(fill_to_account_event(&fill, &default_dex()).is_none());
2548    }
2549
2550    #[test]
2551    fn perp_fill_fees_reads_the_fee_token_and_falls_back_to_the_collateral() {
2552        assert_eq!(
2553            perp_fill_fees(Some("USDT0"), dec!(1.5), "USDC"),
2554            AssetFees::new(AssetNameExchange::from("USDT0"), dec!(1.5), None)
2555        );
2556        assert_eq!(
2557            perp_fill_fees(Some("USDC"), dec!(1.5), "USDC"),
2558            AssetFees::new(AssetNameExchange::from("USDC"), dec!(1.5), Some(dec!(1.5)))
2559        );
2560        assert_eq!(
2561            perp_fill_fees(None, dec!(1.5), "USDH"),
2562            AssetFees::new(AssetNameExchange::from("USDH"), dec!(1.5), Some(dec!(1.5))),
2563            "an absent feeToken is the DEX's collateral"
2564        );
2565    }
2566
2567    #[test]
2568    fn test_fill_to_account_event_sell() {
2569        let fill_json = r#"{
2570            "coin": "ETH",
2571            "side": "A",
2572            "px": "3200",
2573            "sz": "1.5",
2574            "time": 1714100000000,
2575            "hash": "0xdef456",
2576            "startPosition": "1.5",
2577            "dir": "Close Long",
2578            "closedPnl": "150.0",
2579            "oid": 12346,
2580            "cloid": null,
2581            "crossed": true,
2582            "fee": "4.8",
2583            "feeToken": "USDC",
2584            "tid": 100000
2585        }"#;
2586
2587        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2588        let event = fill_to_account_event(&fill, &default_dex()).unwrap();
2589
2590        match event.kind {
2591            AccountEventKind::Trade(trade) => {
2592                assert_eq!(trade.instrument.as_ref(), "ETH-USDC-PERP");
2593                assert_eq!(trade.side, Side::Sell);
2594                assert_eq!(trade.price, dec!(3200));
2595                assert_eq!(trade.quantity, dec!(1.5));
2596            }
2597            _ => panic!("Expected Trade event"),
2598        }
2599    }
2600
2601    /// Build a perp `TradeInfo` sharing one transaction hash with its siblings.
2602    fn sweep_fill(tid: u64, px: &str) -> hyperliquid_rust_sdk::TradeInfo {
2603        let json = format!(
2604            r#"{{
2605                "coin": "BTC", "side": "B", "px": "{px}", "sz": "0.1",
2606                "time": 1714100000000, "hash": "0xonesweep", "startPosition": "0",
2607                "dir": "Open Long", "closedPnl": "0", "oid": 4242, "cloid": null,
2608                "crossed": true, "fee": "0.65", "feeToken": "USDC", "tid": {tid}
2609            }}"#
2610        );
2611        serde_json::from_str(&json).unwrap()
2612    }
2613
2614    #[test]
2615    fn a_trade_id_identifies_the_fill_not_the_transaction() {
2616        // One aggressive order sweeping two resting levels: same `hash`, same `oid`, two fills.
2617        // Deriving the id from `hash` gave both the same `TradeId`, so anything reconciling on it
2618        // treated them as one fill and dropped the second -- understating filled quantity and fees.
2619        let first = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2620        let second = fill_to_account_event(&sweep_fill(222, "65001.0"), &default_dex()).unwrap();
2621
2622        let (AccountEventKind::Trade(first), AccountEventKind::Trade(second)) =
2623            (first.kind, second.kind)
2624        else {
2625            panic!("Expected Trade events");
2626        };
2627
2628        assert_eq!(first.order_id, second.order_id, "one order produced both");
2629        assert_ne!(first.id, second.id, "but they are distinct fills");
2630        assert_eq!(first.id.0, "111");
2631        assert_eq!(second.id.0, "222");
2632    }
2633
2634    #[test]
2635    fn a_replayed_fill_is_delivered_once() {
2636        // The `userFills` subscription opens with a snapshot of recent fills, and the SDK
2637        // resubscribes on reconnect -- so the same fill arrives again on every reconnect.
2638        let cache = new_dedup_cache();
2639        let event = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2640        let replay = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2641
2642        assert!(!is_duplicate(&cache, dedup_key_from_event(&event).unwrap()));
2643        assert!(is_duplicate(&cache, dedup_key_from_event(&replay).unwrap()));
2644    }
2645
2646    #[test]
2647    fn both_fills_of_one_sweep_survive_dedup() {
2648        // The guard against the fix and the dedup fighting each other: two fills of one sweep are
2649        // not duplicates of one another, and dedup must not collapse what the id now separates.
2650        let cache = new_dedup_cache();
2651        let first = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2652        let second = fill_to_account_event(&sweep_fill(222, "65001.0"), &default_dex()).unwrap();
2653
2654        assert!(!is_duplicate(&cache, dedup_key_from_event(&first).unwrap()));
2655        assert!(!is_duplicate(
2656            &cache,
2657            dedup_key_from_event(&second).unwrap()
2658        ));
2659    }
2660
2661    #[test]
2662    fn one_tid_on_two_instruments_is_two_fills() {
2663        // Hyperliquid documents `tid` as qualified by coin rather than globally unique, which is
2664        // why the dedup key carries the instrument.
2665        let cache = new_dedup_cache();
2666        let btc = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2667
2668        let eth_json = r#"{
2669            "coin": "ETH", "side": "B", "px": "3200", "sz": "1.5",
2670            "time": 1714100000000, "hash": "0xother", "startPosition": "0",
2671            "dir": "Open Long", "closedPnl": "0", "oid": 9, "cloid": null,
2672            "crossed": true, "fee": "4.8", "feeToken": "USDC", "tid": 111
2673        }"#;
2674        let eth: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(eth_json).unwrap();
2675        let eth = fill_to_account_event(&eth, &default_dex()).unwrap();
2676
2677        assert!(!is_duplicate(&cache, dedup_key_from_event(&btc).unwrap()));
2678        assert!(!is_duplicate(&cache, dedup_key_from_event(&eth).unwrap()));
2679    }
2680
2681    #[test]
2682    fn test_order_update_to_account_event_open() {
2683        let update_json = r#"{
2684            "order": {
2685                "coin": "BTC",
2686                "side": "B",
2687                "limitPx": "64000",
2688                "sz": "0.5",
2689                "oid": 12345,
2690                "timestamp": 1714100000000,
2691                "origSz": "0.5",
2692                "cloid": null
2693            },
2694            "status": "open",
2695            "statusTimestamp": 1714100000000
2696        }"#;
2697
2698        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2699        let event = order_update_to_account_event(&update, &default_dex()).unwrap();
2700
2701        assert_eq!(event.exchange, ExchangeId::HyperliquidPerp);
2702        match event.kind {
2703            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2704                assert_eq!(order.key.instrument.as_ref(), "BTC-USDC-PERP");
2705                assert_eq!(order.side, Side::Buy);
2706                assert_eq!(order.price, Some(dec!(64000)));
2707                assert_eq!(order.quantity, dec!(0.5));
2708                assert!(matches!(
2709                    order.state,
2710                    crate::order::state::OrderState::Active(_)
2711                ));
2712            }
2713            _ => panic!("Expected OrderSnapshot event"),
2714        }
2715    }
2716
2717    #[test]
2718    fn test_order_update_to_account_event_filled() {
2719        let update_json = r#"{
2720            "order": {
2721                "coin": "ETH",
2722                "side": "A",
2723                "limitPx": "3250",
2724                "sz": "0",
2725                "oid": 12346,
2726                "timestamp": 1714100000000,
2727                "origSz": "2.0",
2728                "cloid": null
2729            },
2730            "status": "filled",
2731            "statusTimestamp": 1714100001000
2732        }"#;
2733
2734        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2735        let event = order_update_to_account_event(&update, &default_dex()).unwrap();
2736
2737        match event.kind {
2738            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2739                assert_eq!(order.side, Side::Sell);
2740                assert!(matches!(
2741                    order.state,
2742                    crate::order::state::OrderState::Inactive(
2743                        crate::order::state::InactiveOrderState::FullyFilled(_)
2744                    )
2745                ));
2746            }
2747            _ => panic!("Expected OrderSnapshot event"),
2748        }
2749    }
2750
2751    #[test]
2752    fn test_order_update_to_account_event_cancelled() {
2753        let update_json = r#"{
2754            "order": {
2755                "coin": "SOL",
2756                "side": "B",
2757                "limitPx": "150",
2758                "sz": "10",
2759                "oid": 12347,
2760                "timestamp": 1714100000000,
2761                "origSz": "10",
2762                "cloid": null
2763            },
2764            "status": "canceled",
2765            "statusTimestamp": 1714100002000
2766        }"#;
2767
2768        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2769        let event = order_update_to_account_event(&update, &default_dex()).unwrap();
2770
2771        match event.kind {
2772            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2773                assert_eq!(order.key.instrument.as_ref(), "SOL-USDC-PERP");
2774                assert!(matches!(
2775                    order.state,
2776                    crate::order::state::OrderState::Inactive(
2777                        crate::order::state::InactiveOrderState::Cancelled(_)
2778                    )
2779                ));
2780            }
2781            _ => panic!("Expected OrderSnapshot event"),
2782        }
2783    }
2784
2785    #[test]
2786    fn test_order_update_unknown_status_returns_none() {
2787        let update_json = r#"{
2788            "order": {
2789                "coin": "BTC",
2790                "side": "B",
2791                "limitPx": "64000",
2792                "sz": "0.5",
2793                "oid": 12345,
2794                "timestamp": 1714100000000,
2795                "origSz": "0.5",
2796                "cloid": null
2797            },
2798            "status": "unknown_status",
2799            "statusTimestamp": 1714100000000
2800        }"#;
2801
2802        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2803        let event = order_update_to_account_event(&update, &default_dex());
2804        assert!(event.is_none());
2805    }
2806}