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},
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_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_from_record, remember_open,
241    remember_snapshot, send_fills, send_observed, spawn_order_checks,
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 (transport)");
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        let make_invalid_instrument = |reason: String| {
1045            make_inactive(OrderError::Rejected(
1046                crate::error::ApiError::InstrumentInvalid(request.key.instrument.clone(), reason),
1047            ))
1048        };
1049
1050        let coin = match self.dexes.coin(request.key.instrument) {
1051            Ok(coin) => coin.to_owned(),
1052            Err(reason) => return make_invalid_instrument(reason),
1053        };
1054        let is_buy = request.state.side == Side::Buy;
1055
1056        match request.state.kind {
1057            OrderKind::Market => {
1058                return make_unsupported(
1059                    "Hyperliquid does not support market orders; use Limit with IOC time-in-force"
1060                        .to_string(),
1061                );
1062            }
1063            OrderKind::TrailingStop { .. }
1064            | OrderKind::TrailingStopLimit { .. }
1065            | OrderKind::TrailingStopFixedLimit { .. } => {
1066                return make_unsupported(
1067                    "Hyperliquid does not support trailing stop orders".to_string(),
1068                );
1069            }
1070            OrderKind::Limit
1071            | OrderKind::Stop { .. }
1072            | OrderKind::StopLimit { .. }
1073            | OrderKind::TakeProfit { .. }
1074            | OrderKind::TakeProfitLimit { .. } => {}
1075        }
1076
1077        // The venue reports every order under its cloid, so an order placed without one could
1078        // not be matched to the id the caller tracks it by. See the module docs.
1079        let Some(cloid) = cid_to_cloid(&request.key.cid) else {
1080            return make_rejected(CLOID_REQUIRED.to_string());
1081        };
1082
1083        let tif = map_tif(&request.state.time_in_force).to_string();
1084
1085        let Some(precision) = self.order_precision(request.key.instrument) else {
1086            return make_invalid_instrument(format!(
1087                "{coin} was not listed when the client connected; reconnect to trade a perpetual \
1088                 listed since"
1089            ));
1090        };
1091        let wire = match wire_order(
1092            &precision,
1093            request.state.kind,
1094            tif,
1095            request.state.price,
1096            request.state.quantity,
1097        ) {
1098            Ok(wire) => wire,
1099            Err(WireOrderError::Precision(violation)) => {
1100                return make_inactive(OrderError::InvalidPrecision(violation));
1101            }
1102            Err(WireOrderError::MissingPrice) => {
1103                return make_rejected(
1104                    "Hyperliquid requires limit price for Limit/StopLimit/TakeProfitLimit orders"
1105                        .to_string(),
1106                );
1107            }
1108            Err(WireOrderError::UnsupportedKind) => {
1109                return make_unsupported(format!(
1110                    "Hyperliquid does not support {} orders",
1111                    request.state.kind
1112                ));
1113            }
1114        };
1115
1116        // Logged only for an order about to be sent.
1117        if matches!(request.state.time_in_force, TimeInForce::FillOrKill) {
1118            warn!(
1119                instrument = %request.key.instrument,
1120                "FillOrKill not supported by Hyperliquid, using ImmediateOrCancel (may result in partial fills)"
1121            );
1122        }
1123
1124        let order_request = ClientOrderRequest {
1125            asset: coin,
1126            is_buy,
1127            reduce_only: request.state.reduce_only,
1128            limit_px: wire.limit_px,
1129            sz: wire.sz,
1130            cloid: Some(cloid),
1131            order_type: wire.order_type,
1132        };
1133
1134        let response = match self.exchange_client.order(order_request, None).await {
1135            Ok(r) => r,
1136            Err(e) => {
1137                warn!(%e, "Open order failed");
1138                return Order {
1139                    key: OrderKey {
1140                        exchange: ExchangeId::HyperliquidPerp,
1141                        instrument: request.key.instrument.clone(),
1142                        strategy: request.key.strategy.clone(),
1143                        cid: request.key.cid.clone(),
1144                    },
1145                    side: request.state.side,
1146                    price: request.state.price,
1147                    quantity: request.state.quantity,
1148                    kind: request.state.kind,
1149                    time_in_force: request.state.time_in_force,
1150                    state: OrderState::inactive(map_order_error(e, request.key.instrument)),
1151                };
1152            }
1153        };
1154
1155        // Parse response
1156        let state = match response {
1157            ExchangeResponseStatus::Ok(exchange_resp) => {
1158                // Check status from response data
1159                let status = exchange_resp
1160                    .data
1161                    .and_then(|d| d.statuses.into_iter().next());
1162
1163                match status {
1164                    Some(ExchangeDataStatus::Resting(resting)) => {
1165                        debug!(oid = resting.oid, "Order resting");
1166                        OrderState::active(Open {
1167                            id: VenueOrderId::Assigned(OrderId(format_smolstr!("{}", resting.oid))),
1168                            time_exchange: Utc::now(),
1169                            filled_quantity: Decimal::ZERO,
1170                        })
1171                    }
1172                    Some(ExchangeDataStatus::Filled(filled)) => {
1173                        debug!(oid = filled.oid, avg_px = %filled.avg_px, "Order filled");
1174                        // Hyperliquid provides avg_px for filled orders
1175                        let avg_price = parse_decimal(&filled.avg_px, "avg_px");
1176                        OrderState::fully_filled(Filled::new(
1177                            OrderId(format_smolstr!("{}", filled.oid)),
1178                            Utc::now(),
1179                            parse_decimal(&filled.total_sz, "total_sz")
1180                                .unwrap_or(request.state.quantity),
1181                            avg_price,
1182                        ))
1183                    }
1184                    Some(ExchangeDataStatus::Error(msg)) => {
1185                        warn!(%msg, "Order rejected by exchange");
1186                        OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1187                    }
1188                    Some(
1189                        ExchangeDataStatus::WaitingForFill | ExchangeDataStatus::WaitingForTrigger,
1190                    ) => {
1191                        // The venue answered without an oid, so the order's only handle is the
1192                        // cloid it was placed with. A standalone trigger order is answered
1193                        // `resting` with an oid; these statuses belong to grouped orders.
1194                        debug!(cid = %request.key.cid, "Order waiting under its cloid");
1195                        OrderState::active(Open {
1196                            id: VenueOrderId::ClientAssigned,
1197                            time_exchange: Utc::now(),
1198                            filled_quantity: Decimal::ZERO,
1199                        })
1200                    }
1201                    Some(ExchangeDataStatus::Success) | None => {
1202                        // Generic success without order ID — SDK didn't return structured data.
1203                        // This shouldn't happen for limit orders; reject to avoid silent failures.
1204                        warn!("Order accepted but no order ID returned");
1205                        OrderState::inactive(OrderError::Rejected(
1206                            crate::error::ApiError::OrderRejected(
1207                                "no order ID in response".to_string(),
1208                            ),
1209                        ))
1210                    }
1211                }
1212            }
1213            ExchangeResponseStatus::Err(msg) => {
1214                warn!(%msg, "Order rejected");
1215                OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1216            }
1217        };
1218        let order = Order {
1219            key: OrderKey {
1220                exchange: ExchangeId::HyperliquidPerp,
1221                instrument: request.key.instrument.clone(),
1222                strategy: request.key.strategy.clone(),
1223                cid: request.key.cid.clone(),
1224            },
1225            side: request.state.side,
1226            price: request.state.price,
1227            quantity: request.state.quantity,
1228            kind: request.state.kind,
1229            time_in_force: request.state.time_in_force,
1230            state,
1231        };
1232        self.known_live
1233            .lock()
1234            .placed(&order.key, order.quantity, order.kind, &order.state);
1235        order
1236    }
1237
1238    /// The collateral balances, read as [`account_snapshot`](ExecutionClient::account_snapshot)
1239    /// reads them: `userAbstraction` (weight 20), then either `spotClearinghouseState` or each
1240    /// DEX's `clearinghouseState` (weight 2 each).
1241    async fn fetch_balances(
1242        &self,
1243        _assets: &[AssetNameExchange],
1244    ) -> Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError> {
1245        perp_account::fetch_balances(&self.info_client, self.wallet_h160(), &self.dexes).await
1246    }
1247
1248    /// Every open order on each DEX traded, with one `openOrders` (weight 20) per DEX.
1249    ///
1250    /// # Errors
1251    ///
1252    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an instrument
1253    /// in `instruments` that names no perpetual this client trades.
1254    async fn fetch_open_orders(
1255        &self,
1256        instruments: &[InstrumentNameExchange],
1257    ) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
1258        self.check_instruments(instruments)?;
1259        let address = self.wallet_h160();
1260
1261        let open_orders =
1262            perp_account::open_orders(&self.info_client, address, &self.dexes).await?;
1263        warn_unknown_coins(open_orders.iter().map(|order| order.coin.as_str()));
1264
1265        let instrument_filter = InstrumentFilter::new(instruments);
1266
1267        let orders: Vec<_> = open_orders
1268            .iter()
1269            .filter_map(|order| {
1270                let instrument = self.dexes.instrument(&order.coin)?;
1271                if !instrument_filter.matches(&instrument) {
1272                    return None;
1273                }
1274                open_order_to_order(order, ExchangeId::HyperliquidPerp, instrument)
1275            })
1276            .collect();
1277        remember_open(&self.known_live, &orders);
1278        Ok(orders)
1279    }
1280
1281    /// Reads the span with `userFillsByTime`, to its end within the call, so the read is always
1282    /// complete (`resume: None`). Hyperliquid keeps only each wallet's 10,000 most recent fills,
1283    /// so a span reaching further back is read only as far as those go. One read covers every
1284    /// DEX; fills on a HIP-3 DEX this client is not configured with are left out.
1285    ///
1286    /// # Errors
1287    ///
1288    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an instrument
1289    /// in `instruments` that names no perpetual this client trades.
1290    async fn fetch_trades(
1291        &self,
1292        start: DateTime<Utc>,
1293        end: DateTime<Utc>,
1294        instruments: &[InstrumentNameExchange],
1295    ) -> Result<TradesRead<AssetNameExchange, InstrumentNameExchange>, UnindexedClientError> {
1296        self.check_instruments(instruments)?;
1297        let Some((start_ms, end_ms)) = span_millis(start, end) else {
1298            return Ok(TradesRead::complete(Vec::new()));
1299        };
1300        let address = self.wallet_h160();
1301
1302        let fills = user_fills_by_time(&self.info_client, address, start_ms, end_ms).await?;
1303        warn_unknown_coins(fills.iter().map(|fill| fill.coin.as_str()));
1304        warn_unconfigured_dexes(&self.dexes, fills.iter().map(|fill| fill.coin.as_str()));
1305
1306        let instrument_filter = InstrumentFilter::new(instruments);
1307
1308        let mut result = Vec::new();
1309        for fill in fills {
1310            let Some((instrument, collateral)) = self.dexes.perp(&fill.coin) else {
1311                continue;
1312            };
1313
1314            if !instrument_filter.matches(&instrument) {
1315                continue;
1316            }
1317
1318            let Some(side) = parse_side(&fill.side) else {
1319                continue;
1320            };
1321            let Some(price) = parse_decimal(&fill.px, "px") else {
1322                continue;
1323            };
1324            let Some(quantity) = parse_decimal(&fill.sz, "sz") else {
1325                continue;
1326            };
1327            let fee = parse_decimal(&fill.fee, "fee").unwrap_or(Decimal::ZERO);
1328
1329            let Some(time_exchange) = millis_to_datetime(fill.time) else {
1330                warn!(time = fill.time, "Invalid fill timestamp, skipping");
1331                continue;
1332            };
1333            if !(start..=end).contains(&time_exchange) {
1334                continue;
1335            }
1336
1337            result.push(Trade {
1338                id: TradeId(format_smolstr!("{}", fill.tid)),
1339                order_id: OrderId(format_smolstr!("{}", fill.oid)),
1340                instrument,
1341                strategy: StrategyId::unknown(),
1342                time_exchange,
1343                side,
1344                price,
1345                quantity,
1346                // `TradeInfo` carries no cumulative filled quantity; Hyperliquid reports order
1347                // state as its own `OrderUpdate` message.
1348                order_filled_quantity: None,
1349                fees: perp_fill_fees(fill.fee_token.as_deref(), fee, collateral),
1350                // As on the stream, whose copy of a fill usually arrives first; see `TradeOrigin`.
1351                origin: TradeOrigin::Order,
1352                position_side: None,
1353                client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1354            });
1355        }
1356
1357        Ok(TradesRead::complete(result))
1358    }
1359}
1360
1361/// Looks each order up with `orderStatus` (weight 2), by the cloid it was placed with, or by its
1362/// `oid` for an order placed without one, which this client reports under its `oid`. Up to 8 run
1363/// at once.
1364///
1365/// `filled` is reported as fully filled, without an average price, which the record does not
1366/// carry; every status ending in `Canceled`, and `scheduledCancel`, as cancelled with what filled
1367/// before it; and every status ending in `Rejected` as
1368/// [`OpenFailed`](crate::order::state::InactiveOrderState::OpenFailed). Hyperliquid has no expiry.
1369/// An order the venue does not know, one on another instrument than the key's, and an id that is
1370/// neither a canonical UUID nor an `oid` are unknown. An `oid` whose order carries a cloid is
1371/// unknown too, since this client reports that order under its cloid.
1372///
1373/// The account stream runs the same lookup itself after a reconnect; see
1374/// [`account_stream`](ExecutionClient::account_stream).
1375impl OrderStatusClient for HyperliquidClient {
1376    async fn fetch_ended_orders(
1377        &self,
1378        orders: &[UnindexedOrderKey],
1379    ) -> Result<Vec<UnindexedInactiveOrder>, UnindexedClientError> {
1380        let address = self.wallet_h160();
1381        fetch_ended_by_key(orders, |key| {
1382            perp_order_lookup(self.info_client.clone(), self.dexes.clone(), address, key)
1383        })
1384        .await
1385    }
1386}
1387
1388/// Look the order under `key` up with `orderStatus`, on the perpetual its coin names.
1389async fn perp_order_lookup(
1390    info_client: Arc<InfoClient>,
1391    dexes: Arc<PerpDexes>,
1392    address: ethers::types::H160,
1393    key: UnindexedOrderKey,
1394) -> Result<OrderLookup, UnindexedClientError> {
1395    let Some(record) = fetch_order_record(&info_client, address, &key.cid).await? else {
1396        return Ok(OrderLookup::Unknown);
1397    };
1398    let instrument = dexes.instrument(&record.order.coin);
1399    Ok(lookup_from_record(key, &record, instrument))
1400}
1401
1402/// The client order ids `openOrders` (weight 20 per DEX traded) lists on the perpetuals
1403/// `instruments`, for a reconnect's check of the orders held as live.
1404async fn perp_listed_cids(
1405    info_client: Arc<InfoClient>,
1406    dexes: Arc<PerpDexes>,
1407    address: ethers::types::H160,
1408    instruments: Vec<InstrumentNameExchange>,
1409) -> Result<FnvHashSet<ClientOrderId>, UnindexedClientError> {
1410    let rows = perp_account::open_orders(&info_client, address, &dexes).await?;
1411    Ok(listed_cids(&rows, &instruments, |coin| {
1412        dexes.instrument(coin)
1413    }))
1414}
1415
1416/// Report one perpetual position from Hyperliquid's user state.
1417///
1418/// [`PositionReport::Open`] for a non-zero size, [`PositionReport::Flat`] for zero, and
1419/// [`PositionReport::Unreported`] when the size does not parse (with a warning): an unreadable
1420/// size establishes nothing, so it must not read as flat.
1421fn perp_position_report(
1422    position: &hyperliquid_rust_sdk::PositionData,
1423    now: DateTime<Utc>,
1424) -> PositionReport {
1425    let Some(quantity) = parse_decimal(&position.szi, "szi") else {
1426        return PositionReport::Unreported;
1427    };
1428    PositionReport::from_position(Position::new(
1429        quantity,
1430        position
1431            .entry_px
1432            .as_ref()
1433            .and_then(|p| parse_decimal(p, "entry_px")),
1434        parse_decimal(&position.unrealized_pnl, "unrealized_pnl"),
1435        parse_decimal(&position.margin_used, "margin_used"),
1436        position
1437            .liquidation_px
1438            .as_ref()
1439            .and_then(|p| parse_decimal(p, "liquidation_px")),
1440        Some(Decimal::from(position.leverage.value)),
1441        // Hyperliquid counts funding paid as positive; carry counts it as negative.
1442        parse_decimal(&position.cum_funding.since_open, "cum_funding.since_open").map(|paid| -paid),
1443        now,
1444    ))
1445}
1446
1447/// The fee of a fill on a perpetual whose DEX settles in `collateral`, in the asset `fee_token`
1448/// names.
1449///
1450/// The venue's `feeToken` is read rather than assumed; only its absence, which has not been
1451/// observed, falls back to `collateral`.
1452///
1453/// The quote-equivalent is set when the fee is in `collateral`, which is the instrument's quote,
1454/// and is `None` otherwise. It serves unindexed consumers: the indexer recomputes it either way,
1455/// from the instrument's own quote and base.
1456fn perp_fill_fees(
1457    fee_token: Option<&str>,
1458    fee: Decimal,
1459    collateral: &str,
1460) -> AssetFees<AssetNameExchange> {
1461    let asset = fee_token.unwrap_or(collateral);
1462    let fees_quote = (asset == collateral).then_some(fee);
1463    AssetFees::new(AssetNameExchange::from(asset), fee, fees_quote)
1464}
1465
1466/// Convert SDK TradeInfo (fill) to AccountEvent::Trade, `None` if its coin names no perpetual
1467/// this client trades.
1468fn fill_to_account_event(
1469    fill: &hyperliquid_rust_sdk::TradeInfo,
1470    dexes: &PerpDexes,
1471) -> Option<UnindexedAccountEvent> {
1472    let (instrument, collateral) = dexes.perp(&fill.coin)?;
1473    let side = parse_side(&fill.side)?;
1474    let price = parse_decimal(&fill.px, "fill.px")?;
1475    let quantity = parse_decimal(&fill.sz, "fill.sz")?;
1476    let fee = parse_decimal(&fill.fee, "fill.fee").unwrap_or(Decimal::ZERO);
1477    let time_exchange = millis_to_datetime(fill.time)?;
1478    let order_id = OrderId(format_smolstr!("{}", fill.oid));
1479
1480    let trade = Trade {
1481        id: TradeId(format_smolstr!("{}", fill.tid)),
1482        order_id,
1483        instrument,
1484        strategy: StrategyId::unknown(),
1485        time_exchange,
1486        side,
1487        price,
1488        quantity,
1489        // `TradeInfo` carries no cumulative filled quantity, so the order's state must be learned
1490        // from an `OrderUpdate` -- which Hyperliquid sends as its own message.
1491        order_filled_quantity: None,
1492        fees: perp_fill_fees(Some(&fill.fee_token), fee, collateral),
1493        // The SDK's `TradeInfo` drops the fill's liquidation marker, so every fill is reported
1494        // as `Order`; see `TradeOrigin`.
1495        origin: TradeOrigin::Order,
1496        position_side: None,
1497        client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1498    };
1499
1500    Some(AccountEvent::new(
1501        ExchangeId::HyperliquidPerp,
1502        AccountEventKind::Trade(trade),
1503    ))
1504}
1505
1506/// Convert SDK OrderUpdate to AccountEvent::OrderSnapshot, `None` if its coin names no
1507/// perpetual this client trades.
1508fn order_update_to_account_event(
1509    update: &hyperliquid_rust_sdk::OrderUpdate,
1510    dexes: &PerpDexes,
1511) -> Option<UnindexedAccountEvent> {
1512    common::order_update_to_account_event(
1513        update,
1514        ExchangeId::HyperliquidPerp,
1515        dexes.instrument(&update.order.coin)?,
1516    )
1517}
1518
1519#[cfg(test)]
1520// Test code: panics on bad input are acceptable
1521#[allow(clippy::unwrap_used)]
1522mod tests {
1523    use super::*;
1524    use crate::client::dedup::{dedup_key_from_event, is_duplicate};
1525    use rust_decimal_macros::dec;
1526    use rustrade_integration::collection::snapshot::Snapshot;
1527    use std::collections::HashMap;
1528
1529    /// Only Hyperliquid's default DEX.
1530    fn default_dex() -> PerpDexes {
1531        PerpDexes::default()
1532    }
1533
1534    mod order_recovery {
1535        use super::super::common::info_tests::info_client_against;
1536        use super::super::order_recovery::tests::{CID, CLOID, record_json, row};
1537        use super::*;
1538        use crate::order::state::InactiveOrderState;
1539        use wiremock::matchers::{method, path};
1540        use wiremock::{Mock, MockServer, ResponseTemplate};
1541
1542        async fn serve(body: serde_json::Value) -> (MockServer, Arc<InfoClient>) {
1543            let server = MockServer::start().await;
1544            Mock::given(method("POST"))
1545                .and(path("/info"))
1546                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1547                .mount(&server)
1548                .await;
1549            let client = Arc::new(info_client_against(server.uri()).await);
1550            (server, client)
1551        }
1552
1553        fn key() -> UnindexedOrderKey {
1554            OrderKey {
1555                exchange: ExchangeId::HyperliquidPerp,
1556                instrument: InstrumentNameExchange::new("BTC-USDC-PERP"),
1557                strategy: StrategyId::new("strategy"),
1558                cid: ClientOrderId::new(CID),
1559            }
1560        }
1561
1562        fn order_status(coin: &str) -> serde_json::Value {
1563            serde_json::json!({
1564                "status": "order",
1565                "order": record_json(coin, "canceled", "0.01", Some(CLOID)),
1566            })
1567        }
1568
1569        #[test]
1570        fn a_reconnect_snapshot_wakes_the_check_once_its_fills_are_sent() {
1571            use futures::FutureExt as _;
1572            let notified = |reconnected: &Notify| reconnected.notified().now_or_never().is_some();
1573            let snapshot = |fills| hyperliquid_rust_sdk::UserFillsData {
1574                is_snapshot: Some(true),
1575                user: ethers::types::H160::zero(),
1576                fills,
1577            };
1578            let reconnected = Arc::new(Notify::new());
1579            let mut reconnects = ReconnectWatch::new(reconnected.clone());
1580            let dedup = new_dedup_cache();
1581            let (tx, mut rx) = mpsc::unbounded_channel();
1582            let tids = |rx: &mut mpsc::UnboundedReceiver<UnindexedAccountEvent>| {
1583                std::iter::from_fn(|| rx.try_recv().ok())
1584                    .map(|event| match event.kind {
1585                        AccountEventKind::Trade(trade) => trade.id.0.to_string(),
1586                        other => panic!("expected a trade, got {other:?}"),
1587                    })
1588                    .collect::<Vec<_>>()
1589            };
1590
1591            // The snapshot opening the first subscription.
1592            let first = snapshot(vec![sweep_fill(1, "60000")]);
1593            assert!(send_fills(
1594                &first,
1595                |fill| fill_to_account_event(fill, &default_dex()),
1596                &dedup,
1597                &tx,
1598                &mut reconnects
1599            ));
1600            assert_eq!(tids(&mut rx), ["1"]);
1601            assert!(!notified(&reconnected));
1602
1603            // A drop, then the resubscription's snapshot: its new fill is sent, then the check
1604            // woken.
1605            reconnects.dropped();
1606            let resubscribed = snapshot(vec![sweep_fill(1, "60000"), sweep_fill(2, "60001")]);
1607            assert!(send_fills(
1608                &resubscribed,
1609                |fill| fill_to_account_event(fill, &default_dex()),
1610                &dedup,
1611                &tx,
1612                &mut reconnects
1613            ));
1614            assert_eq!(
1615                tids(&mut rx),
1616                ["2"],
1617                "the fill already sent is not sent again"
1618            );
1619            assert!(notified(&reconnected));
1620
1621            // With the consumer gone the fills cannot be sent, and the check is not woken.
1622            drop(rx);
1623            reconnects.dropped();
1624            let unsent = snapshot(vec![sweep_fill(3, "60002")]);
1625            assert!(!send_fills(
1626                &unsent,
1627                |fill| fill_to_account_event(fill, &default_dex()),
1628                &dedup,
1629                &tx,
1630                &mut reconnects
1631            ));
1632            assert!(!notified(&reconnected));
1633        }
1634
1635        #[tokio::test]
1636        async fn a_perp_lookup_reads_how_the_order_ended() {
1637            let (_server, client) = serve(order_status("BTC")).await;
1638
1639            let lookup =
1640                perp_order_lookup(client, Arc::default(), ethers::types::H160::zero(), key())
1641                    .await
1642                    .unwrap();
1643
1644            let OrderLookup::Ended(order) = lookup else {
1645                panic!("expected an ended order, got {lookup:?}");
1646            };
1647            assert_eq!(order.key, key());
1648            assert!(matches!(order.state, InactiveOrderState::Cancelled(_)));
1649        }
1650
1651        #[tokio::test]
1652        async fn a_perp_lookup_of_a_spot_order_is_unknown() {
1653            let (_server, client) = serve(order_status("@107")).await;
1654
1655            let lookup =
1656                perp_order_lookup(client, Arc::default(), ethers::types::H160::zero(), key())
1657                    .await
1658                    .unwrap();
1659
1660            assert!(matches!(lookup, OrderLookup::Unknown));
1661        }
1662
1663        #[tokio::test]
1664        async fn a_perp_listing_names_only_the_orders_on_the_perpetuals_asked_about() {
1665            let rows = serde_json::json!([
1666                row("BTC", 1, Some(CLOID)),
1667                row("ETH", 2, None),
1668                row("@107", 3, None),
1669            ]);
1670            let (_server, client) = serve(rows).await;
1671
1672            let listed = perp_listed_cids(
1673                client,
1674                Arc::default(),
1675                ethers::types::H160::zero(),
1676                vec![InstrumentNameExchange::new("BTC-USDC-PERP")],
1677            )
1678            .await
1679            .unwrap();
1680
1681            assert_eq!(
1682                listed.into_iter().collect::<Vec<_>>(),
1683                [ClientOrderId::new(CID)]
1684            );
1685        }
1686    }
1687
1688    /// A client trading `xyz` and `flx` against `server`, built without the network, that places
1689    /// and cancels on the assets in `coin_to_asset`. The default DEX lists `BTC`, with
1690    /// `szDecimals` 5 as on mainnet.
1691    async fn client_against(
1692        server: &wiremock::MockServer,
1693        coin_to_asset: HashMap<String, u32>,
1694    ) -> HyperliquidClient {
1695        use super::common::info_tests::{
1696            exchange_client_against, info_client_against, test_wallet,
1697        };
1698        let mut dexes = super::perp_dexes::tests::xyz_and_flx().await;
1699        dexes.add_default_perps(&[hyperliquid_rust_sdk::AssetMeta {
1700            name: "BTC".to_owned(),
1701            sz_decimals: 5,
1702        }]);
1703        HyperliquidClient {
1704            config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
1705            info_client: Arc::new(info_client_against(server.uri()).await),
1706            exchange_client: Arc::new(exchange_client_against(server.uri(), coin_to_asset).await),
1707            dexes: Arc::new(dexes),
1708            known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidPerp),
1709        }
1710    }
1711
1712    mod open_order {
1713        use super::*;
1714        use crate::error::{ApiError, OrderField, PrecisionLimit, PrecisionViolation};
1715        use crate::order::{OrderEvent, request::RequestOpen, state::InactiveOrderState};
1716        use wiremock::matchers::{method, path};
1717        use wiremock::{Mock, MockServer, ResponseTemplate};
1718
1719        /// A server whose exchange endpoint rests every order it is sent.
1720        async fn resting_server() -> MockServer {
1721            server_responding(serde_json::json!({
1722                "status": "ok",
1723                "response": {"type": "order", "data": {"statuses": [{"resting": {"oid": 77}}]}},
1724            }))
1725            .await
1726        }
1727
1728        /// A server whose exchange endpoint answers every request with `body`.
1729        async fn server_responding(body: serde_json::Value) -> MockServer {
1730            let server = MockServer::start().await;
1731            Mock::given(method("POST"))
1732                .and(path("/exchange"))
1733                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1734                .mount(&server)
1735                .await;
1736            server
1737        }
1738
1739        /// A refusal for want of margin is a balance shortfall, as on other venues; any other
1740        /// refusal stays a rejection. Hyperliquid names no asset. The refusal is read both as an
1741        /// order's status and as the error of the whole response.
1742        #[tokio::test]
1743        async fn an_order_refused_for_margin_is_balance_insufficient() {
1744            const MARGIN: &str = "Insufficient margin to place order. asset=0";
1745            const MINIMUM: &str = "Order must have minimum value of $10. asset=0";
1746            let in_status = |error: &str| {
1747                serde_json::json!({
1748                    "status": "ok",
1749                    "response": {"type": "order", "data": {"statuses": [{"error": error}]}},
1750                })
1751            };
1752            let in_response = |error: &str| serde_json::json!({"status": "err", "response": error});
1753            for (body, expected) in [
1754                (
1755                    in_status(MARGIN),
1756                    ApiError::BalanceInsufficient(None, MARGIN.to_owned()),
1757                ),
1758                (
1759                    in_response(MARGIN),
1760                    ApiError::BalanceInsufficient(None, MARGIN.to_owned()),
1761                ),
1762                (
1763                    in_status(MINIMUM),
1764                    ApiError::OrderRejected(MINIMUM.to_owned()),
1765                ),
1766                (
1767                    in_response(MINIMUM),
1768                    ApiError::OrderRejected(MINIMUM.to_owned()),
1769                ),
1770            ] {
1771                let server = server_responding(body.clone()).await;
1772                let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
1773                let order = place(
1774                    &client,
1775                    &InstrumentNameExchange::from("BTC-USDC-PERP"),
1776                    OrderKind::Limit,
1777                    Some(dec!(50000)),
1778                    dec!(0.001),
1779                )
1780                .await;
1781                let OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1782                    reported,
1783                ))) = &order.state
1784                else {
1785                    panic!("{body}: expected a rejection, got {:?}", order.state);
1786                };
1787                assert_eq!(reported, &expected, "{body}");
1788            }
1789        }
1790
1791        async fn place(
1792            client: &HyperliquidClient,
1793            instrument: &InstrumentNameExchange,
1794            kind: OrderKind,
1795            price: Option<Decimal>,
1796            quantity: Decimal,
1797        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1798            client
1799                .open_order(OrderEvent {
1800                    key: OrderKey {
1801                        exchange: ExchangeId::HyperliquidPerp,
1802                        instrument,
1803                        strategy: StrategyId::new("strategy"),
1804                        cid: ClientOrderId::uuid(),
1805                    },
1806                    state: RequestOpen {
1807                        side: Side::Buy,
1808                        price,
1809                        quantity,
1810                        kind,
1811                        time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
1812                        position_id: None,
1813                        reduce_only: false,
1814                        market: None,
1815                    },
1816                })
1817                .await
1818        }
1819
1820        /// The orders the server was sent, as the SDK wrote them.
1821        async fn sent_orders(server: &MockServer) -> Vec<serde_json::Value> {
1822            server
1823                .received_requests()
1824                .await
1825                .unwrap_or_default()
1826                .into_iter()
1827                .filter(|request| request.url.path() == "/exchange")
1828                .map(|request| {
1829                    let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
1830                    body["action"]["orders"][0].clone()
1831                })
1832                .collect()
1833        }
1834
1835        #[tokio::test]
1836        async fn the_client_reports_each_perpetuals_precision() {
1837            let server = MockServer::start().await;
1838            let client = client_against(&server, HashMap::new()).await;
1839
1840            assert_eq!(
1841                client.order_precision(&InstrumentNameExchange::from("BTC-USDC-PERP")),
1842                Some(OrderPrecision::perp(5))
1843            );
1844            assert_eq!(
1845                client.order_precision(&InstrumentNameExchange::from("xyz:TSLA-USDC-PERP")),
1846                Some(OrderPrecision::perp(2)),
1847                "a HIP-3 perpetual's szDecimals come from its DEX's meta"
1848            );
1849            assert_eq!(
1850                client.order_precision(&InstrumentNameExchange::from("ETH-USDC-PERP")),
1851                None,
1852                "not listed when the client connected"
1853            );
1854            assert_eq!(
1855                client.order_precision(&InstrumentNameExchange::from("HYPE-USDC-SPOT")),
1856                None
1857            );
1858        }
1859
1860        #[tokio::test]
1861        async fn an_order_breaking_the_precision_rules_is_refused_unsent() {
1862            let server = resting_server().await;
1863            let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
1864            let btc = InstrumentNameExchange::from("BTC-USDC-PERP");
1865
1866            let cases = [
1867                (
1868                    OrderKind::Limit,
1869                    dec!(60000),
1870                    dec!(0.000001),
1871                    OrderField::Quantity,
1872                    PrecisionLimit::DecimalPlaces { max: 5 },
1873                ),
1874                (
1875                    OrderKind::Limit,
1876                    dec!(60000),
1877                    dec!(0),
1878                    OrderField::Quantity,
1879                    PrecisionLimit::NotPositive,
1880                ),
1881                (
1882                    OrderKind::Limit,
1883                    dec!(65432.1),
1884                    dec!(0.001),
1885                    OrderField::Price,
1886                    PrecisionLimit::SignificantFigures { max: 5 },
1887                ),
1888                (
1889                    OrderKind::Limit,
1890                    dec!(6543.21),
1891                    dec!(0.001),
1892                    OrderField::Price,
1893                    PrecisionLimit::DecimalPlaces { max: 1 },
1894                ),
1895                (
1896                    OrderKind::StopLimit {
1897                        trigger_price: dec!(6543.21),
1898                    },
1899                    dec!(6543),
1900                    dec!(0.001),
1901                    OrderField::TriggerPrice,
1902                    PrecisionLimit::DecimalPlaces { max: 1 },
1903                ),
1904            ];
1905            for (kind, price, quantity, field, limit) in cases {
1906                let order = place(&client, &btc, kind, Some(price), quantity).await;
1907                let expected = PrecisionViolation {
1908                    field,
1909                    value: match field {
1910                        OrderField::Quantity => quantity,
1911                        OrderField::TriggerPrice => dec!(6543.21),
1912                        _ => price,
1913                    },
1914                    limit,
1915                };
1916                assert_eq!(
1917                    order.state,
1918                    OrderState::Inactive(InactiveOrderState::OpenFailed(
1919                        OrderError::InvalidPrecision(expected)
1920                    )),
1921                    "{kind} at {price} for {quantity}"
1922                );
1923            }
1924            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1925        }
1926
1927        #[tokio::test]
1928        async fn a_valid_order_is_sent_unchanged() {
1929            let server = resting_server().await;
1930            let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
1931            let btc = InstrumentNameExchange::from("BTC-USDC-PERP");
1932
1933            // An integer price past 5 significant figures, which the client once rounded to 123460.
1934            let order = place(
1935                &client,
1936                &btc,
1937                OrderKind::Limit,
1938                Some(dec!(123456)),
1939                dec!(0.00123),
1940            )
1941            .await;
1942            assert!(
1943                matches!(order.state, OrderState::Active(_)),
1944                "{:?}",
1945                order.state
1946            );
1947
1948            let sent = sent_orders(&server).await;
1949            assert_eq!(sent.len(), 1);
1950            assert_eq!(
1951                (&sent[0]["p"], &sent[0]["s"]),
1952                (&serde_json::json!("123456"), &serde_json::json!("0.00123"))
1953            );
1954        }
1955
1956        #[tokio::test]
1957        async fn an_order_on_a_perpetual_listed_since_connecting_is_refused_unsent() {
1958            let server = resting_server().await;
1959            let client = client_against(&server, HashMap::from([("ETH".to_owned(), 1)])).await;
1960
1961            let order = place(
1962                &client,
1963                &InstrumentNameExchange::from("ETH-USDC-PERP"),
1964                OrderKind::Limit,
1965                Some(dec!(3000)),
1966                dec!(1),
1967            )
1968            .await;
1969            let OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1970                crate::error::ApiError::InstrumentInvalid(_, reason),
1971            ))) = &order.state
1972            else {
1973                panic!("expected InstrumentInvalid, got {:?}", order.state);
1974            };
1975            assert!(reason.contains("reconnect"), "{reason}");
1976            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1977        }
1978    }
1979
1980    mod cancel {
1981        use super::super::common::info_tests::{CANCEL_NOT_APPLIED, cancel_answer};
1982        use super::*;
1983        use crate::error::ApiError;
1984        use crate::order::{OrderEvent, request::RequestCancel};
1985        use wiremock::matchers::{method, path};
1986        use wiremock::{Mock, MockServer, ResponseTemplate};
1987
1988        /// Cancel a live `BTC-USDC-PERP` order through a client whose exchange endpoint answers
1989        /// `answer`. Returns the response, and whether the order is still held live afterwards.
1990        async fn cancel_answered(
1991            answer: serde_json::Value,
1992        ) -> (UnindexedOrderResponseCancel, bool) {
1993            let server = MockServer::start().await;
1994            Mock::given(method("POST"))
1995                .and(path("/exchange"))
1996                .respond_with(ResponseTemplate::new(200).set_body_json(answer))
1997                .mount(&server)
1998                .await;
1999            let client = client_against(&server, HashMap::from([("BTC".to_owned(), 0)])).await;
2000            let instrument = InstrumentNameExchange::new("BTC-USDC-PERP");
2001            let key = OrderKey {
2002                exchange: ExchangeId::HyperliquidPerp,
2003                instrument: instrument.clone(),
2004                strategy: StrategyId::new("strategy"),
2005                cid: ClientOrderId::uuid(),
2006            };
2007            let id = VenueOrderId::Assigned(OrderId::new("7"));
2008            let open = Open {
2009                id: id.clone(),
2010                time_exchange: Utc::now(),
2011                filled_quantity: Decimal::ZERO,
2012            };
2013            client
2014                .known_live
2015                .lock()
2016                .live(&key, dec!(1), OrderKind::Limit, &open);
2017
2018            let response = client
2019                .cancel_order(OrderEvent {
2020                    key: OrderKey {
2021                        exchange: key.exchange,
2022                        instrument: &instrument,
2023                        strategy: key.strategy.clone(),
2024                        cid: key.cid.clone(),
2025                    },
2026                    state: RequestCancel { id: Some(id) },
2027                })
2028                .await;
2029            let live = client.known_live.lock().contains(&key.cid);
2030            (response, live)
2031        }
2032
2033        #[tokio::test]
2034        async fn a_success_status_cancels_the_order() {
2035            let (response, live) =
2036                cancel_answered(cancel_answer(serde_json::json!(["success"]))).await;
2037            assert!(response.state.is_ok(), "{:?}", response.state);
2038            assert!(!live, "a cancelled order is no longer held live");
2039        }
2040
2041        /// An order that filled before the cancel arrived is answered this way, so it must not be
2042        /// reported cancelled, and stays held live until the account stream or a lookup ends it.
2043        #[tokio::test]
2044        async fn an_error_status_is_a_rejected_cancel_and_the_order_stays_live() {
2045            let (response, live) = cancel_answered(cancel_answer(serde_json::json!([
2046                {"error": CANCEL_NOT_APPLIED}
2047            ])))
2048            .await;
2049            let Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(reason))) =
2050                &response.state
2051            else {
2052                panic!("expected a rejected cancel, got {:?}", response.state);
2053            };
2054            assert_eq!(reason, CANCEL_NOT_APPLIED);
2055            assert!(live, "the order is still held live");
2056        }
2057
2058        #[tokio::test]
2059        async fn an_answer_without_a_status_is_a_rejected_cancel() {
2060            let (response, live) = cancel_answered(serde_json::json!({
2061                "status": "ok",
2062                "response": {"type": "cancel"},
2063            }))
2064            .await;
2065            assert!(
2066                matches!(
2067                    response.state,
2068                    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(_)))
2069                ),
2070                "{:?}",
2071                response.state
2072            );
2073            assert!(live, "the order is still held live");
2074        }
2075    }
2076
2077    mod instrument_names {
2078        use super::*;
2079        use crate::error::ApiError;
2080        use crate::order::{
2081            OrderEvent,
2082            request::{RequestCancel, RequestOpen},
2083        };
2084        use wiremock::MockServer;
2085
2086        /// A client trading `xyz` and `flx`, built without the network, against a server with
2087        /// nothing mounted: any request it sent would fail with something other than
2088        /// `InstrumentInvalid`.
2089        async fn offline_client() -> (MockServer, HyperliquidClient) {
2090            let server = MockServer::start().await;
2091            let client = client_against(&server, HashMap::new()).await;
2092            (server, client)
2093        }
2094
2095        /// Names no perpetual the client trades: the old `-USD-` name, a quote other than the
2096        /// DEX's collateral, a DEX not configured, and a spot pair.
2097        const REFUSED: [&str; 4] = [
2098            "BTC-USD-PERP",
2099            "flx:TSLA-USDC-PERP",
2100            "km:TSLA-USDH-PERP",
2101            "HYPE-USDC-SPOT",
2102        ];
2103
2104        fn is_invalid(
2105            error: &ApiError<AssetNameExchange, InstrumentNameExchange>,
2106            name: &str,
2107        ) -> bool {
2108            matches!(error, ApiError::InstrumentInvalid(instrument, _) if instrument.as_ref() == name)
2109        }
2110
2111        #[tokio::test]
2112        async fn an_order_on_a_name_the_client_does_not_trade_is_refused_unsent() {
2113            let (_server, client) = offline_client().await;
2114            for name in REFUSED {
2115                let instrument = InstrumentNameExchange::from(name);
2116                let order = client
2117                    .open_order(OrderEvent {
2118                        key: OrderKey {
2119                            exchange: ExchangeId::HyperliquidPerp,
2120                            instrument: &instrument,
2121                            strategy: StrategyId::new("strategy"),
2122                            cid: ClientOrderId::uuid(),
2123                        },
2124                        state: RequestOpen {
2125                            side: Side::Buy,
2126                            price: Some(dec!(1)),
2127                            quantity: dec!(1),
2128                            kind: OrderKind::Limit,
2129                            time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
2130                            position_id: None,
2131                            reduce_only: false,
2132                            market: None,
2133                        },
2134                    })
2135                    .await;
2136                let OrderState::Inactive(crate::order::state::InactiveOrderState::OpenFailed(
2137                    OrderError::Rejected(error),
2138                )) = &order.state
2139                else {
2140                    panic!("{name}: expected a rejection, got {:?}", order.state);
2141                };
2142                assert!(is_invalid(error, name), "{name}: {error:?}");
2143            }
2144        }
2145
2146        #[tokio::test]
2147        async fn a_cancel_on_a_name_the_client_does_not_trade_is_refused_unsent() {
2148            let (_server, client) = offline_client().await;
2149            for name in REFUSED {
2150                let instrument = InstrumentNameExchange::from(name);
2151                let response = client
2152                    .cancel_order(OrderEvent {
2153                        key: OrderKey {
2154                            exchange: ExchangeId::HyperliquidPerp,
2155                            instrument: &instrument,
2156                            strategy: StrategyId::new("strategy"),
2157                            cid: ClientOrderId::uuid(),
2158                        },
2159                        state: RequestCancel {
2160                            id: Some(VenueOrderId::Assigned(OrderId::new("1"))),
2161                        },
2162                    })
2163                    .await;
2164                let Err(UnindexedOrderError::Rejected(error)) = &response.state else {
2165                    panic!("{name}: expected a rejection, got {:?}", response.state);
2166                };
2167                assert!(is_invalid(error, name), "{name}: {error:?}");
2168            }
2169        }
2170
2171        #[tokio::test]
2172        async fn a_read_filtered_to_a_name_the_client_does_not_trade_fails_unsent() {
2173            let (_server, client) = offline_client().await;
2174            for name in REFUSED {
2175                let instruments = [InstrumentNameExchange::from(name)];
2176                let snapshot = client.account_snapshot(&[], &instruments).await;
2177                let open = client.fetch_open_orders(&instruments).await;
2178                let trades = client
2179                    .fetch_trades(
2180                        Utc::now() - chrono::Duration::hours(1),
2181                        Utc::now(),
2182                        &instruments,
2183                    )
2184                    .await;
2185                for error in [snapshot.err(), open.err(), trades.err()] {
2186                    let Some(UnindexedClientError::Api(error)) = &error else {
2187                        panic!("{name}: expected an API error, got {error:?}");
2188                    };
2189                    assert!(is_invalid(error, name), "{name}: {error:?}");
2190                }
2191            }
2192        }
2193    }
2194
2195    fn perp_position(szi: &str) -> hyperliquid_rust_sdk::PositionData {
2196        serde_json::from_value(serde_json::json!({
2197            "coin": "BTC",
2198            "entryPx": "50000.0",
2199            "leverage": {"type": "cross", "value": 5},
2200            "liquidationPx": null,
2201            "marginUsed": "100.0",
2202            "positionValue": "500.0",
2203            "returnOnEquity": "0.0",
2204            "szi": szi,
2205            "unrealizedPnl": "1.5",
2206            "maxLeverage": 50,
2207            "cumFunding": {"allTime": "3.5", "sinceOpen": "1.25", "sinceChange": "0"}
2208        }))
2209        .unwrap()
2210    }
2211
2212    #[test]
2213    fn perp_position_report_is_open_flat_or_unreported() {
2214        let now = Utc::now();
2215        let open = perp_position_report(&perp_position("-0.01"), now);
2216        let position = open.open().unwrap();
2217        // Funding paid since open is positive on Hyperliquid and negative as carry.
2218        assert_eq!(
2219            (
2220                position.quantity,
2221                position.entry_price,
2222                position.leverage,
2223                position.carry
2224            ),
2225            (
2226                dec!(-0.01),
2227                Some(dec!(50000.0)),
2228                Some(dec!(5)),
2229                Some(dec!(-1.25))
2230            )
2231        );
2232        assert_eq!(
2233            perp_position_report(&perp_position("0.0"), now),
2234            PositionReport::Flat
2235        );
2236        assert_eq!(
2237            perp_position_report(&perp_position("not a number"), now),
2238            PositionReport::Unreported
2239        );
2240    }
2241
2242    #[test]
2243    fn test_fill_to_account_event() {
2244        let fill_json = r#"{
2245            "coin": "BTC",
2246            "side": "B",
2247            "px": "65000.5",
2248            "sz": "0.1",
2249            "time": 1714100000000,
2250            "hash": "0xabc123",
2251            "startPosition": "0",
2252            "dir": "Open Long",
2253            "closedPnl": "0",
2254            "oid": 12345,
2255            "cloid": null,
2256            "crossed": false,
2257            "fee": "0.65",
2258            "feeToken": "USDC",
2259            "tid": 99999
2260        }"#;
2261
2262        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2263        let event = fill_to_account_event(&fill, &default_dex()).unwrap();
2264
2265        assert_eq!(event.exchange, ExchangeId::HyperliquidPerp);
2266        match event.kind {
2267            AccountEventKind::Trade(trade) => {
2268                assert_eq!(trade.instrument.as_ref(), "BTC-USDC-PERP");
2269                assert_eq!(
2270                    trade.id.0, "99999",
2271                    "the id is the fill's tid, not its hash"
2272                );
2273                assert_eq!(trade.side, Side::Buy);
2274                assert_eq!(trade.price, dec!(65000.5));
2275                assert_eq!(trade.quantity, dec!(0.1));
2276                assert_eq!(trade.fees.fees, dec!(0.65));
2277                assert_eq!(trade.fees.asset.as_ref(), "USDC");
2278                assert_eq!(trade.fees.fees_quote, Some(dec!(0.65)));
2279            }
2280            _ => panic!("Expected Trade event"),
2281        }
2282    }
2283
2284    /// A fill reports its order's cloid as the client order id the order was placed under.
2285    #[tokio::test]
2286    async fn a_fill_carries_the_client_order_id_of_its_cloid() {
2287        let fill_json = r#"{
2288            "coin": "flx:TSLA", "side": "B", "px": "250", "sz": "2",
2289            "time": 1714100000000, "hash": "0xhip3", "startPosition": "0",
2290            "dir": "Open Long", "closedPnl": "0", "oid": 7,
2291            "cloid": "0x0123456789abcdef0123456789abcdef",
2292            "crossed": true, "fee": "0.2", "feeToken": "USDH", "tid": 77
2293        }"#;
2294        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2295
2296        let dexes = perp_dexes::tests::xyz_and_flx().await;
2297        let AccountEventKind::Trade(trade) = fill_to_account_event(&fill, &dexes).unwrap().kind
2298        else {
2299            panic!("Expected Trade event");
2300        };
2301        assert_eq!(
2302            trade.client_order_id,
2303            cloid_to_cid("0x0123456789abcdef0123456789abcdef")
2304        );
2305        assert!(trade.client_order_id.is_some());
2306    }
2307
2308    #[tokio::test]
2309    async fn a_builder_deployed_fill_is_named_and_charged_in_its_dex_collateral() {
2310        // A HIP-3 perpetual settles in its deployer's collateral, which is not always USDC.
2311        let fill_json = r#"{
2312            "coin": "flx:TSLA", "side": "B", "px": "250", "sz": "2",
2313            "time": 1714100000000, "hash": "0xhip3", "startPosition": "0",
2314            "dir": "Open Long", "closedPnl": "0", "oid": 7, "cloid": null,
2315            "crossed": true, "fee": "0.2", "feeToken": "USDH", "tid": 77
2316        }"#;
2317        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2318
2319        let dexes = perp_dexes::tests::xyz_and_flx().await;
2320        let AccountEventKind::Trade(trade) = fill_to_account_event(&fill, &dexes).unwrap().kind
2321        else {
2322            panic!("Expected Trade event");
2323        };
2324        assert_eq!(trade.instrument.as_ref(), "flx:TSLA-USDH-PERP");
2325        assert_eq!(trade.client_order_id, None, "placed without a cloid");
2326        assert_eq!(trade.fees.asset.as_ref(), "USDH");
2327        assert_eq!(trade.fees.fees, dec!(0.2));
2328        assert_eq!(
2329            trade.fees.fees_quote,
2330            Some(dec!(0.2)),
2331            "the fee is in the instrument's quote"
2332        );
2333
2334        // Without `flx` configured, its collateral is unknown, so the fill is left out.
2335        assert!(fill_to_account_event(&fill, &default_dex()).is_none());
2336    }
2337
2338    #[test]
2339    fn perp_fill_fees_reads_the_fee_token_and_falls_back_to_the_collateral() {
2340        assert_eq!(
2341            perp_fill_fees(Some("USDT0"), dec!(1.5), "USDC"),
2342            AssetFees::new(AssetNameExchange::from("USDT0"), dec!(1.5), None)
2343        );
2344        assert_eq!(
2345            perp_fill_fees(Some("USDC"), dec!(1.5), "USDC"),
2346            AssetFees::new(AssetNameExchange::from("USDC"), dec!(1.5), Some(dec!(1.5)))
2347        );
2348        assert_eq!(
2349            perp_fill_fees(None, dec!(1.5), "USDH"),
2350            AssetFees::new(AssetNameExchange::from("USDH"), dec!(1.5), Some(dec!(1.5))),
2351            "an absent feeToken is the DEX's collateral"
2352        );
2353    }
2354
2355    #[test]
2356    fn test_fill_to_account_event_sell() {
2357        let fill_json = r#"{
2358            "coin": "ETH",
2359            "side": "A",
2360            "px": "3200",
2361            "sz": "1.5",
2362            "time": 1714100000000,
2363            "hash": "0xdef456",
2364            "startPosition": "1.5",
2365            "dir": "Close Long",
2366            "closedPnl": "150.0",
2367            "oid": 12346,
2368            "cloid": null,
2369            "crossed": true,
2370            "fee": "4.8",
2371            "feeToken": "USDC",
2372            "tid": 100000
2373        }"#;
2374
2375        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2376        let event = fill_to_account_event(&fill, &default_dex()).unwrap();
2377
2378        match event.kind {
2379            AccountEventKind::Trade(trade) => {
2380                assert_eq!(trade.instrument.as_ref(), "ETH-USDC-PERP");
2381                assert_eq!(trade.side, Side::Sell);
2382                assert_eq!(trade.price, dec!(3200));
2383                assert_eq!(trade.quantity, dec!(1.5));
2384            }
2385            _ => panic!("Expected Trade event"),
2386        }
2387    }
2388
2389    /// Build a perp `TradeInfo` sharing one transaction hash with its siblings.
2390    fn sweep_fill(tid: u64, px: &str) -> hyperliquid_rust_sdk::TradeInfo {
2391        let json = format!(
2392            r#"{{
2393                "coin": "BTC", "side": "B", "px": "{px}", "sz": "0.1",
2394                "time": 1714100000000, "hash": "0xonesweep", "startPosition": "0",
2395                "dir": "Open Long", "closedPnl": "0", "oid": 4242, "cloid": null,
2396                "crossed": true, "fee": "0.65", "feeToken": "USDC", "tid": {tid}
2397            }}"#
2398        );
2399        serde_json::from_str(&json).unwrap()
2400    }
2401
2402    #[test]
2403    fn a_trade_id_identifies_the_fill_not_the_transaction() {
2404        // One aggressive order sweeping two resting levels: same `hash`, same `oid`, two fills.
2405        // Deriving the id from `hash` gave both the same `TradeId`, so anything reconciling on it
2406        // treated them as one fill and dropped the second -- understating filled quantity and fees.
2407        let first = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2408        let second = fill_to_account_event(&sweep_fill(222, "65001.0"), &default_dex()).unwrap();
2409
2410        let (AccountEventKind::Trade(first), AccountEventKind::Trade(second)) =
2411            (first.kind, second.kind)
2412        else {
2413            panic!("Expected Trade events");
2414        };
2415
2416        assert_eq!(first.order_id, second.order_id, "one order produced both");
2417        assert_ne!(first.id, second.id, "but they are distinct fills");
2418        assert_eq!(first.id.0, "111");
2419        assert_eq!(second.id.0, "222");
2420    }
2421
2422    #[test]
2423    fn a_replayed_fill_is_delivered_once() {
2424        // The `userFills` subscription opens with a snapshot of recent fills, and the SDK
2425        // resubscribes on reconnect -- so the same fill arrives again on every reconnect.
2426        let cache = new_dedup_cache();
2427        let event = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2428        let replay = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2429
2430        assert!(!is_duplicate(&cache, dedup_key_from_event(&event).unwrap()));
2431        assert!(is_duplicate(&cache, dedup_key_from_event(&replay).unwrap()));
2432    }
2433
2434    #[test]
2435    fn both_fills_of_one_sweep_survive_dedup() {
2436        // The guard against the fix and the dedup fighting each other: two fills of one sweep are
2437        // not duplicates of one another, and dedup must not collapse what the id now separates.
2438        let cache = new_dedup_cache();
2439        let first = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2440        let second = fill_to_account_event(&sweep_fill(222, "65001.0"), &default_dex()).unwrap();
2441
2442        assert!(!is_duplicate(&cache, dedup_key_from_event(&first).unwrap()));
2443        assert!(!is_duplicate(
2444            &cache,
2445            dedup_key_from_event(&second).unwrap()
2446        ));
2447    }
2448
2449    #[test]
2450    fn one_tid_on_two_instruments_is_two_fills() {
2451        // Hyperliquid documents `tid` as qualified by coin rather than globally unique, which is
2452        // why the dedup key carries the instrument.
2453        let cache = new_dedup_cache();
2454        let btc = fill_to_account_event(&sweep_fill(111, "65000.5"), &default_dex()).unwrap();
2455
2456        let eth_json = r#"{
2457            "coin": "ETH", "side": "B", "px": "3200", "sz": "1.5",
2458            "time": 1714100000000, "hash": "0xother", "startPosition": "0",
2459            "dir": "Open Long", "closedPnl": "0", "oid": 9, "cloid": null,
2460            "crossed": true, "fee": "4.8", "feeToken": "USDC", "tid": 111
2461        }"#;
2462        let eth: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(eth_json).unwrap();
2463        let eth = fill_to_account_event(&eth, &default_dex()).unwrap();
2464
2465        assert!(!is_duplicate(&cache, dedup_key_from_event(&btc).unwrap()));
2466        assert!(!is_duplicate(&cache, dedup_key_from_event(&eth).unwrap()));
2467    }
2468
2469    #[test]
2470    fn test_order_update_to_account_event_open() {
2471        let update_json = r#"{
2472            "order": {
2473                "coin": "BTC",
2474                "side": "B",
2475                "limitPx": "64000",
2476                "sz": "0.5",
2477                "oid": 12345,
2478                "timestamp": 1714100000000,
2479                "origSz": "0.5",
2480                "cloid": null
2481            },
2482            "status": "open",
2483            "statusTimestamp": 1714100000000
2484        }"#;
2485
2486        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2487        let event = order_update_to_account_event(&update, &default_dex()).unwrap();
2488
2489        assert_eq!(event.exchange, ExchangeId::HyperliquidPerp);
2490        match event.kind {
2491            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2492                assert_eq!(order.key.instrument.as_ref(), "BTC-USDC-PERP");
2493                assert_eq!(order.side, Side::Buy);
2494                assert_eq!(order.price, Some(dec!(64000)));
2495                assert_eq!(order.quantity, dec!(0.5));
2496                assert!(matches!(
2497                    order.state,
2498                    crate::order::state::OrderState::Active(_)
2499                ));
2500            }
2501            _ => panic!("Expected OrderSnapshot event"),
2502        }
2503    }
2504
2505    #[test]
2506    fn test_order_update_to_account_event_filled() {
2507        let update_json = r#"{
2508            "order": {
2509                "coin": "ETH",
2510                "side": "A",
2511                "limitPx": "3250",
2512                "sz": "0",
2513                "oid": 12346,
2514                "timestamp": 1714100000000,
2515                "origSz": "2.0",
2516                "cloid": null
2517            },
2518            "status": "filled",
2519            "statusTimestamp": 1714100001000
2520        }"#;
2521
2522        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2523        let event = order_update_to_account_event(&update, &default_dex()).unwrap();
2524
2525        match event.kind {
2526            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2527                assert_eq!(order.side, Side::Sell);
2528                assert!(matches!(
2529                    order.state,
2530                    crate::order::state::OrderState::Inactive(
2531                        crate::order::state::InactiveOrderState::FullyFilled(_)
2532                    )
2533                ));
2534            }
2535            _ => panic!("Expected OrderSnapshot event"),
2536        }
2537    }
2538
2539    #[test]
2540    fn test_order_update_to_account_event_cancelled() {
2541        let update_json = r#"{
2542            "order": {
2543                "coin": "SOL",
2544                "side": "B",
2545                "limitPx": "150",
2546                "sz": "10",
2547                "oid": 12347,
2548                "timestamp": 1714100000000,
2549                "origSz": "10",
2550                "cloid": null
2551            },
2552            "status": "canceled",
2553            "statusTimestamp": 1714100002000
2554        }"#;
2555
2556        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2557        let event = order_update_to_account_event(&update, &default_dex()).unwrap();
2558
2559        match event.kind {
2560            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2561                assert_eq!(order.key.instrument.as_ref(), "SOL-USDC-PERP");
2562                assert!(matches!(
2563                    order.state,
2564                    crate::order::state::OrderState::Inactive(
2565                        crate::order::state::InactiveOrderState::Cancelled(_)
2566                    )
2567                ));
2568            }
2569            _ => panic!("Expected OrderSnapshot event"),
2570        }
2571    }
2572
2573    #[test]
2574    fn test_order_update_unknown_status_returns_none() {
2575        let update_json = r#"{
2576            "order": {
2577                "coin": "BTC",
2578                "side": "B",
2579                "limitPx": "64000",
2580                "sz": "0.5",
2581                "oid": 12345,
2582                "timestamp": 1714100000000,
2583                "origSz": "0.5",
2584                "cloid": null
2585            },
2586            "status": "unknown_status",
2587            "statusTimestamp": 1714100000000
2588        }"#;
2589
2590        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2591        let event = order_update_to_account_event(&update, &default_dex());
2592        assert!(event.is_none());
2593    }
2594}