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