Skip to main content

nautilus_hyperliquid/http/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides the HTTP client integration for the [Hyperliquid](https://hyperliquid.xyz/) REST API.
17//!
18//! This module defines and implements a [`HyperliquidHttpClient`] for sending requests to various
19//! Hyperliquid endpoints. It handles request signing (when credentials are provided), constructs
20//! valid HTTP requests using the [`HttpClient`], and parses the responses back into structured
21//! data or an [`Error`].
22
23use std::{
24    collections::HashMap,
25    num::NonZeroU32,
26    sync::{Arc, LazyLock},
27    time::Duration,
28};
29
30use ahash::{AHashMap, AHashSet};
31use anyhow::Context;
32use nautilus_common::cache::InstrumentLookupError;
33use nautilus_core::{
34    AtomicMap, UUID4, UnixNanos,
35    datetime::datetime_to_unix_nanos,
36    string::secret::SecretString,
37    time::{AtomicTime, get_atomic_clock_realtime},
38};
39use nautilus_model::{
40    data::{Bar, BarType, FundingRateUpdate},
41    enums::{
42        AccountType, BarAggregation, CurrencyType, MarketStatusAction, OrderSide, OrderStatus,
43        OrderType, TimeInForce, TriggerType,
44    },
45    events::AccountState,
46    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
47    instruments::{CurrencyPair, Instrument, InstrumentAny},
48    orders::{Order, OrderAny},
49    reports::{FillReport, OrderStatusReport, PositionStatusReport},
50    types::{AccountBalance, Currency, Price, Quantity},
51};
52use nautilus_network::{
53    http::{
54        HttpClient, HttpClientError, HttpRedirectPolicy, HttpResponse, Method,
55        create_standard_nautilus_headers, parse_retry_after,
56    },
57    ratelimiter::quota::Quota,
58};
59use parking_lot::Mutex;
60use rust_decimal::Decimal;
61use serde_json::Value;
62use ustr::Ustr;
63
64use crate::{
65    account::{normalize_account_address, resolve_execution_account_address},
66    common::{
67        consts::{
68            ASSET_INDEX_INFO_KEY, HYPERLIQUID_REST_WEIGHT_PER_MINUTE, HYPERLIQUID_VENUE,
69            NAUTILUS_BUILDER_ADDRESS, exchange_url, info_url,
70        },
71        credential::{Secrets, VaultAddress, credential_env_vars},
72        enums::{
73            HyperliquidAccountAbstraction, HyperliquidBarInterval, HyperliquidEnvironment,
74            HyperliquidOrderStatus as HyperliquidOrderStatusEnum, HyperliquidProductType,
75        },
76        parse::{
77            bar_type_to_interval, cache_alias_for_symbol, clamp_price_to_precision,
78            derive_limit_from_trigger, determine_order_list_grouping, extract_inner_error,
79            normalize_or_validate_wire_price, order_to_hyperliquid_request_with_optional_decimals,
80            parse_combined_account_balances_and_margins, parse_outcome_symbol,
81            parse_spot_account_balances, parse_trigger_order_type, parse_trigger_order_type_label,
82            round_to_sig_figs, time_in_force_to_hyperliquid_tif,
83        },
84    },
85    data::{candle_to_bar, funding_entry_to_update},
86    data_types::HyperliquidPublicTrade,
87    http::{
88        error::{Error, Result},
89        models::{
90            ClearinghouseState, Cloid, HyperliquidCandleSnapshot, HyperliquidExchangeAction,
91            HyperliquidExchangeBuilderFee, HyperliquidExchangeCancelByCloidRequest,
92            HyperliquidExchangeCancelOrderRequest, HyperliquidExchangeGrouping,
93            HyperliquidExchangeLimitParams, HyperliquidExchangeMergeOutcomeParams,
94            HyperliquidExchangeMergeQuestionParams, HyperliquidExchangeModifyOrderRequest,
95            HyperliquidExchangeModifyTarget, HyperliquidExchangeNegateOutcomeParams,
96            HyperliquidExchangeOrderKind, HyperliquidExchangeOrderResponseData,
97            HyperliquidExchangeOrderStatus, HyperliquidExchangePlaceOrderRequest,
98            HyperliquidExchangeRequest, HyperliquidExchangeResponse,
99            HyperliquidExchangeResponseData, HyperliquidExchangeSplitOutcomeParams,
100            HyperliquidExchangeTif, HyperliquidExchangeTpSl, HyperliquidExchangeTriggerParams,
101            HyperliquidExchangeUserOutcomeOp, HyperliquidFills, HyperliquidFundingHistoryEntry,
102            HyperliquidL2Book, HyperliquidMeta, HyperliquidOrderStatus,
103            HyperliquidOrderStatusEntry, HyperliquidRecentTrade, OutcomeMeta, PerpDex, PerpMeta,
104            PerpMetaAndCtxs, RESPONSE_STATUS_OK, SpotClearinghouseState, SpotMeta, SpotMetaAndCtxs,
105        },
106        parse::{
107            DEFAULT_OUTCOME_QUOTE_CURRENCY, HyperliquidInstrumentDef, create_instrument_from_def,
108            filter_recent_public_trades, get_outcome_currency, instruments_from_defs_owned,
109            parse_fill_report, parse_order_status_report_from_basic, parse_outcome_instruments,
110            parse_perp_instruments_with_collateral, parse_position_status_report,
111            parse_recent_public_trade, parse_spot_instruments, parse_spot_position_status_report,
112            parse_unlisted_outcome_instrument, resolve_perp_collateral_currency,
113        },
114        query::{ExchangeAction, InfoRequest},
115        rate_limits::{
116            RateLimitSnapshot, WeightedLimiter, backoff_full_jitter, exchange_weight,
117            exec_action_weight, info_base_weight, info_extra_weight, shared_rest_limiter,
118        },
119    },
120    signing::{
121        HyperliquidActionType, HyperliquidEip712Signer, NonceManager, SignRequest, types::SignerId,
122    },
123    websocket::messages::WsBasicOrderData,
124};
125
126fn deduplicate_historical_order_reports(reports: Vec<OrderStatusReport>) -> Vec<OrderStatusReport> {
127    let mut best_by_venue_order_id = AHashMap::new();
128
129    for candidate in reports {
130        let Some(current) = best_by_venue_order_id.remove(&candidate.venue_order_id) else {
131            best_by_venue_order_id.insert(candidate.venue_order_id, candidate);
132            continue;
133        };
134        let (mut best, other) = if historical_report_is_more_advanced(&candidate, &current) {
135            (candidate, current)
136        } else {
137            (current, candidate)
138        };
139
140        if matches!(
141            best.order_type,
142            OrderType::Limit | OrderType::StopLimit | OrderType::LimitIfTouched
143        ) {
144            best.price = best.price.or(other.price);
145        }
146        best.trigger_price = best.trigger_price.or(other.trigger_price);
147        best.trigger_type = best.trigger_type.or(other.trigger_type);
148        best_by_venue_order_id.insert(best.venue_order_id, best);
149    }
150
151    best_by_venue_order_id
152        .into_values()
153        .map(untrigger_closed_report_without_trigger_price)
154        .collect()
155}
156
157// The venue zeroes `triggerPx` on the final row of a triggered order that has filled, so when no
158// earlier row survives the order's trigger cannot be rebuilt and a conditional order type would
159// fail initialization. A closed order no longer needs its trigger: report it as the limit order it
160// executed as when a limit price survived, otherwise as a market order, so its fills reconcile.
161fn untrigger_closed_report_without_trigger_price(
162    mut report: OrderStatusReport,
163) -> OrderStatusReport {
164    let is_trigger_type = matches!(
165        report.order_type,
166        OrderType::StopMarket
167            | OrderType::StopLimit
168            | OrderType::MarketIfTouched
169            | OrderType::LimitIfTouched
170    );
171
172    if !is_trigger_type || report.trigger_price.is_some() || !report.order_status.is_closed() {
173        return report;
174    }
175
176    let order_type = match report.order_type {
177        OrderType::StopLimit | OrderType::LimitIfTouched if report.price.is_some() => {
178            OrderType::Limit
179        }
180        _ => {
181            // A market order has no price; a leftover limit price would be used to infer fills
182            report.price = None;
183            OrderType::Market
184        }
185    };
186    log::debug!(
187        "Historical {} order {} has no trigger price, reconciling as {order_type}",
188        report.order_type,
189        report.venue_order_id,
190    );
191    report.order_type = order_type;
192    report
193}
194
195fn historical_report_is_more_advanced(
196    candidate: &OrderStatusReport,
197    current: &OrderStatusReport,
198) -> bool {
199    candidate.filled_qty > current.filled_qty
200        || (candidate.filled_qty == current.filled_qty
201            && (historical_status_priority(candidate.order_status)
202                > historical_status_priority(current.order_status)
203                || (candidate.order_status == current.order_status
204                    && candidate.ts_last > current.ts_last)))
205}
206
207const fn historical_status_priority(status: OrderStatus) -> u8 {
208    match status {
209        OrderStatus::Initialized | OrderStatus::Submitted | OrderStatus::Emulated => 0,
210        OrderStatus::Released | OrderStatus::Denied => 1,
211        OrderStatus::Accepted | OrderStatus::PendingUpdate | OrderStatus::PendingCancel => 2,
212        OrderStatus::Triggered => 3,
213        OrderStatus::PartiallyFilled => 4,
214        OrderStatus::Canceled | OrderStatus::Expired | OrderStatus::Rejected => 5,
215        OrderStatus::Filled | OrderStatus::Voided => 6,
216    }
217}
218
219/// Unweighted REST quota retained for compatibility with existing callers.
220///
221/// Adapter clients use a shared weighted limiter because Hyperliquid aggregates request weights
222/// across `/info` and `/exchange`.
223pub static HYPERLIQUID_REST_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
224    Quota::per_minute(NonZeroU32::new(HYPERLIQUID_REST_WEIGHT_PER_MINUTE).unwrap())
225});
226
227pub(crate) const HYPERLIQUID_RECENT_HISTORY_LIMIT: usize = 2_000;
228const RATE_LIMIT_BACKOFF_BASE: Duration = Duration::from_millis(125);
229const RATE_LIMIT_BACKOFF_CAP: Duration = Duration::from_secs(5);
230const RATE_LIMIT_INFO_RETRIES_MAX: u32 = 3;
231const RETRY_AFTER_HEADER: &str = "retry-after";
232const VAULT_TOKEN_PREFIX: &str = "vntls:";
233
234/// Maximum rows returned per `fundingHistory` call (the venue per-response cap).
235pub const HYPERLIQUID_FUNDING_HISTORY_MAX_LIMIT: usize = 500;
236/// Seven days of hourly funding, used when a request gives no start or limit.
237const DEFAULT_FUNDING_RATES_LIMIT: usize = 7 * 24;
238
239/// Provides a raw HTTP client for low-level Hyperliquid REST API operations.
240///
241/// This client handles HTTP infrastructure, request signing, and raw API calls
242/// that closely match Hyperliquid endpoint specifications.
243#[derive(Debug, Clone)]
244#[cfg_attr(
245    feature = "python",
246    pyo3::pyclass(module = "nautilus_trader.adapters.hyperliquid", from_py_object)
247)]
248pub struct HyperliquidRawHttpClient {
249    client: HttpClient,
250    environment: HyperliquidEnvironment,
251    base_info: String,
252    base_exchange: String,
253    signer: Option<HyperliquidEip712Signer>,
254    nonce_manager: Option<Arc<NonceManager>>,
255    vault_address: Option<VaultAddress>,
256    proxy_url: Option<SecretString>,
257    info_limiter: Arc<WeightedLimiter>,
258    exchange_limiter: Arc<WeightedLimiter>,
259    info_max_retries: u32,
260    info_retry_delay_initial: Duration,
261    info_retry_delay_max: Duration,
262}
263
264impl HyperliquidRawHttpClient {
265    /// Creates a new [`HyperliquidRawHttpClient`] for public endpoints only.
266    ///
267    /// # Errors
268    ///
269    /// Returns an error if the HTTP client cannot be created.
270    pub fn new(
271        environment: HyperliquidEnvironment,
272        timeout_secs: u64,
273        proxy_url: Option<String>,
274    ) -> std::result::Result<Self, HttpClientError> {
275        let base_info = info_url(environment).to_string();
276        let base_exchange = exchange_url(environment).to_string();
277        let info_limiter = shared_rest_limiter(environment, &base_info, proxy_url.as_deref());
278        let exchange_limiter =
279            shared_rest_limiter(environment, &base_exchange, proxy_url.as_deref());
280
281        Ok(Self {
282            client: Self::build_http_client(timeout_secs, proxy_url.clone())?,
283            environment,
284            base_info,
285            base_exchange,
286            signer: None,
287            nonce_manager: None,
288            vault_address: None,
289            proxy_url: proxy_url.map(SecretString::from),
290            info_limiter,
291            exchange_limiter,
292            info_max_retries: RATE_LIMIT_INFO_RETRIES_MAX,
293            info_retry_delay_initial: RATE_LIMIT_BACKOFF_BASE,
294            info_retry_delay_max: RATE_LIMIT_BACKOFF_CAP,
295        })
296    }
297
298    /// Creates a new [`HyperliquidRawHttpClient`] configured with credentials
299    /// for authenticated requests.
300    ///
301    /// # Errors
302    ///
303    /// Returns an error if the HTTP client cannot be created.
304    pub fn with_credentials(
305        secrets: &Secrets,
306        timeout_secs: u64,
307        proxy_url: Option<String>,
308    ) -> std::result::Result<Self, HttpClientError> {
309        let signer = HyperliquidEip712Signer::new(&secrets.private_key)
310            .map_err(|e| HttpClientError::from(e.to_string()))?;
311        let nonce_manager = Arc::new(NonceManager::new());
312        let base_info = info_url(secrets.environment).to_string();
313        let base_exchange = exchange_url(secrets.environment).to_string();
314        let info_limiter =
315            shared_rest_limiter(secrets.environment, &base_info, proxy_url.as_deref());
316        let exchange_limiter =
317            shared_rest_limiter(secrets.environment, &base_exchange, proxy_url.as_deref());
318
319        Ok(Self {
320            client: Self::build_http_client(timeout_secs, proxy_url.clone())?,
321            environment: secrets.environment,
322            base_info,
323            base_exchange,
324            signer: Some(signer),
325            nonce_manager: Some(nonce_manager),
326            vault_address: secrets.vault_address,
327            proxy_url: proxy_url.map(SecretString::from),
328            info_limiter,
329            exchange_limiter,
330            info_max_retries: RATE_LIMIT_INFO_RETRIES_MAX,
331            info_retry_delay_initial: RATE_LIMIT_BACKOFF_BASE,
332            info_retry_delay_max: RATE_LIMIT_BACKOFF_CAP,
333        })
334    }
335
336    /// Overrides the base info URL (for testing with mock servers).
337    pub fn set_base_info_url(&mut self, url: String) {
338        self.info_limiter = shared_rest_limiter(
339            self.environment,
340            &url,
341            self.proxy_url.as_ref().map(|value| value.expose_secret()),
342        );
343        self.base_info = url;
344    }
345
346    /// Overrides the base exchange URL (for testing with mock servers).
347    pub fn set_base_exchange_url(&mut self, url: String) {
348        self.exchange_limiter = shared_rest_limiter(
349            self.environment,
350            &url,
351            self.proxy_url.as_ref().map(|value| value.expose_secret()),
352        );
353        self.base_exchange = url;
354    }
355
356    /// Creates an authenticated client from environment variables for the specified network.
357    ///
358    /// # Errors
359    ///
360    /// Returns an error if required environment variables are not set.
361    pub fn from_env(environment: HyperliquidEnvironment) -> Result<Self> {
362        let secrets = Secrets::from_env(environment)
363            .map_err(|e| Error::auth(format!("missing credentials in environment: {e}")))?;
364        Self::with_credentials(&secrets, 60, None)
365            .map_err(|e| Error::auth(format!("Failed to create HTTP client: {e}")))
366    }
367
368    /// Creates a new [`HyperliquidRawHttpClient`] configured with explicit credentials.
369    ///
370    /// # Errors
371    ///
372    /// Returns an error if the private key is invalid or cannot be parsed.
373    pub fn from_credentials(
374        private_key: &str,
375        vault_address: Option<&str>,
376        environment: HyperliquidEnvironment,
377        timeout_secs: u64,
378        proxy_url: Option<String>,
379    ) -> Result<Self> {
380        let secrets = Secrets::from_private_key(private_key, vault_address, environment)
381            .map_err(|e| Error::auth(format!("invalid credentials: {e}")))?;
382        Self::with_credentials(&secrets, timeout_secs, proxy_url)
383            .map_err(|e| Error::auth(format!("Failed to create HTTP client: {e}")))
384    }
385
386    /// Rebinds the client to the shared rate limits for its configured routes.
387    #[must_use]
388    pub fn with_rate_limits(mut self) -> Self {
389        let proxy_url = self.proxy_url.as_ref().map(|value| value.expose_secret());
390        self.info_limiter = shared_rest_limiter(self.environment, &self.base_info, proxy_url);
391        self.exchange_limiter =
392            shared_rest_limiter(self.environment, &self.base_exchange, proxy_url);
393        self
394    }
395
396    /// Returns the configured environment.
397    #[must_use]
398    pub fn environment(&self) -> HyperliquidEnvironment {
399        self.environment
400    }
401
402    /// Returns whether this client is configured for testnet.
403    #[must_use]
404    pub fn is_testnet(&self) -> bool {
405        self.environment == HyperliquidEnvironment::Testnet
406    }
407
408    /// Gets the user address derived from the private key (if client has credentials).
409    ///
410    /// # Errors
411    ///
412    /// Returns an error if the client has no signer configured.
413    pub fn get_user_address(&self) -> Result<String> {
414        self.signer
415            .as_ref()
416            .ok_or_else(|| Error::auth("No signer configured"))?
417            .address()
418    }
419
420    /// Returns `true` if a vault address is configured.
421    #[must_use]
422    pub fn has_vault_address(&self) -> bool {
423        self.vault_address.is_some()
424    }
425
426    /// Gets the account address for queries: vault address if configured,
427    /// otherwise the user (EOA) address.
428    ///
429    /// # Errors
430    ///
431    /// Returns an error if the client has no signer configured.
432    pub fn get_account_address(&self) -> Result<String> {
433        if let Some(vault) = &self.vault_address {
434            Ok(vault.to_hex())
435        } else {
436            self.get_user_address()
437        }
438    }
439
440    fn build_http_client(
441        timeout_secs: u64,
442        proxy_url: Option<String>,
443    ) -> std::result::Result<HttpClient, HttpClientError> {
444        HttpClient::builder()
445            .redirect_policy(HttpRedirectPolicy::Reject)
446            .headers(Self::default_headers())
447            .header_keys(vec![RETRY_AFTER_HEADER.to_string()])
448            .rate_limiters(Vec::new())
449            .timeout_secs(timeout_secs)
450            .maybe_proxy_url(proxy_url)
451            .build()
452    }
453
454    fn default_headers() -> HashMap<String, String> {
455        let mut headers: HashMap<String, String> =
456            create_standard_nautilus_headers().into_iter().collect();
457        headers.insert("Content-Type".to_string(), "application/json".to_string());
458        headers
459    }
460
461    fn signer_id(&self) -> SignerId {
462        SignerId("hyperliquid:default".into())
463    }
464
465    fn retry_after_ms(headers: &HashMap<String, String>) -> Option<u64> {
466        let retry_after = headers.get(RETRY_AFTER_HEADER)?;
467        parse_retry_after(retry_after, jiff::Timestamp::now())
468            .map(|delay| delay.as_millis().min(u128::from(u64::MAX)) as u64)
469    }
470
471    /// Get metadata about available markets.
472    pub async fn info_meta(&self) -> Result<HyperliquidMeta> {
473        let request = InfoRequest::meta();
474        let response = self.send_info_request(&request).await?;
475        serde_json::from_value(response).map_err(Error::Serde)
476    }
477
478    /// Get complete spot metadata (tokens and pairs).
479    pub async fn get_spot_meta(&self) -> Result<SpotMeta> {
480        let request = InfoRequest::spot_meta();
481        let response = self.send_info_request(&request).await?;
482        serde_json::from_value(response).map_err(Error::Serde)
483    }
484
485    /// Get perpetuals metadata with asset contexts (for price precision refinement).
486    pub async fn get_perp_meta_and_ctxs(&self) -> Result<PerpMetaAndCtxs> {
487        let request = InfoRequest::meta_and_asset_ctxs();
488        let response = self.send_info_request(&request).await?;
489        serde_json::from_value(response).map_err(Error::Serde)
490    }
491
492    /// Get spot metadata with asset contexts (for price precision refinement).
493    pub async fn get_spot_meta_and_ctxs(&self) -> Result<SpotMetaAndCtxs> {
494        let request = InfoRequest::spot_meta_and_asset_ctxs();
495        let response = self.send_info_request(&request).await?;
496        serde_json::from_value(response).map_err(Error::Serde)
497    }
498
499    /// Get outcome metadata.
500    pub async fn get_outcome_meta(&self) -> Result<OutcomeMeta> {
501        let request = InfoRequest::outcome_meta();
502        let response = self.send_info_request(&request).await?;
503        serde_json::from_value(response).map_err(Error::Serde)
504    }
505
506    pub(crate) async fn load_perp_meta(&self) -> Result<PerpMeta> {
507        let request = InfoRequest::meta();
508        let response = self.send_info_request(&request).await?;
509        serde_json::from_value(response).map_err(Error::Serde)
510    }
511
512    /// Get metadata for all perp dexes (standard + HIP-3).
513    pub(crate) async fn load_all_perp_metas(&self) -> Result<Vec<PerpMeta>> {
514        let request = InfoRequest::all_perp_metas();
515        let response = self.send_info_request(&request).await?;
516        serde_json::from_value(response).map_err(Error::Serde)
517    }
518
519    /// Get the list of perp dex names aligned by dex index.
520    pub(crate) async fn load_perp_dexs(&self) -> Result<Vec<Option<PerpDex>>> {
521        let request = InfoRequest::perp_dexs();
522        let response = self.send_info_request(&request).await?;
523        serde_json::from_value(response).map_err(Error::Serde)
524    }
525
526    /// Get L2 order book for a coin.
527    pub async fn info_l2_book(&self, coin: &str) -> Result<HyperliquidL2Book> {
528        let request = InfoRequest::l2_book(coin);
529        let response = self.send_info_request(&request).await?;
530        serde_json::from_value(response).map_err(Error::Serde)
531    }
532
533    /// Get recent public trades for a coin.
534    ///
535    /// Returns a recent snapshot (newest first) with no time range. Depends on the
536    /// Hyperliquid indexer: self-hosted `/info` nodes return HTTP 422.
537    pub async fn info_recent_trades(&self, coin: &str) -> Result<Vec<HyperliquidRecentTrade>> {
538        let request = InfoRequest::recent_trades(coin);
539        let response = self.send_info_request(&request).await?;
540        serde_json::from_value(response).map_err(Error::Serde)
541    }
542
543    /// Get user fills (trading history).
544    pub async fn info_user_fills(&self, user: &str) -> Result<HyperliquidFills> {
545        let request = InfoRequest::user_fills(user);
546        let response = self.send_info_request(&request).await?;
547        serde_json::from_value(response).map_err(Error::Serde)
548    }
549
550    /// Get order status for a user.
551    pub async fn info_order_status(&self, user: &str, oid: u64) -> Result<HyperliquidOrderStatus> {
552        let request = InfoRequest::order_status(user, oid);
553        let response = self.send_info_request(&request).await?;
554        serde_json::from_value(response).map_err(Error::Serde)
555    }
556
557    pub(crate) async fn info_order_status_by_cloid(
558        &self,
559        user: &str,
560        cloid: Cloid,
561    ) -> Result<HyperliquidOrderStatus> {
562        let request = InfoRequest::order_status_by_cloid(user, cloid);
563        let response = self.send_info_request(&request).await?;
564        serde_json::from_value(response).map_err(Error::Serde)
565    }
566
567    /// Get all open orders for a user.
568    pub async fn info_open_orders(&self, user: &str) -> Result<Value> {
569        let request = InfoRequest::open_orders(user);
570        self.send_info_request(&request).await
571    }
572
573    /// Get frontend open orders (includes more detail) for a user.
574    pub async fn info_frontend_open_orders(&self, user: &str) -> Result<Value> {
575        self.info_frontend_open_orders_for_dex(user, None).await
576    }
577
578    async fn info_frontend_open_orders_for_dex(
579        &self,
580        user: &str,
581        dex: Option<&str>,
582    ) -> Result<Value> {
583        let request = InfoRequest::frontend_open_orders_for_dex(user, dex);
584        self.send_info_request(&request).await
585    }
586
587    /// Get the most recent historical orders for a user.
588    pub async fn info_historical_orders(
589        &self,
590        user: &str,
591    ) -> Result<Vec<HyperliquidOrderStatusEntry>> {
592        let request = InfoRequest::historical_orders(user);
593        let response = self.send_info_request(&request).await?;
594        serde_json::from_value(response).map_err(Error::Serde)
595    }
596
597    /// Get clearinghouse state (balances, positions, margin) for a user.
598    pub async fn info_clearinghouse_state(&self, user: &str) -> Result<Value> {
599        self.info_clearinghouse_state_for_dex(user, None).await
600    }
601
602    async fn info_clearinghouse_state_for_dex(
603        &self,
604        user: &str,
605        dex: Option<&str>,
606    ) -> Result<Value> {
607        let request = InfoRequest::clearinghouse_state_for_dex(user, dex);
608        self.send_info_request(&request).await
609    }
610
611    /// Get spot clearinghouse state (per-token spot balances) for a user.
612    pub async fn info_spot_clearinghouse_state(&self, user: &str) -> Result<Value> {
613        let request = InfoRequest::spot_clearinghouse_state(user);
614        self.send_info_request(&request).await
615    }
616
617    /// Get the account abstraction mode for a user.
618    pub async fn info_user_abstraction(&self, user: &str) -> Result<Value> {
619        let request = InfoRequest::user_abstraction(user);
620        self.send_info_request(&request).await
621    }
622
623    /// Get user fee schedule and effective rates.
624    pub async fn info_user_fees(&self, user: &str) -> Result<Value> {
625        let request = InfoRequest::user_fees(user);
626        self.send_info_request(&request).await
627    }
628
629    /// Get candle/bar data for a coin.
630    pub async fn info_candle_snapshot(
631        &self,
632        coin: &str,
633        interval: HyperliquidBarInterval,
634        start_time: u64,
635        end_time: u64,
636    ) -> Result<HyperliquidCandleSnapshot> {
637        let request = InfoRequest::candle_snapshot(coin, interval, start_time, end_time);
638        let response = self.send_info_request(&request).await?;
639
640        log::trace!(
641            "Candle snapshot raw response (len={}): {:?}",
642            response.as_array().map_or(0, |a| a.len()),
643            response
644        );
645
646        serde_json::from_value(response).map_err(Error::Serde)
647    }
648
649    /// Get historical funding rates for a coin.
650    ///
651    /// `start_time` and `end_time` are Unix milliseconds. `end_time` is optional;
652    /// if omitted, the venue returns entries up to the most recent funding.
653    pub async fn info_funding_history(
654        &self,
655        coin: &str,
656        start_time: u64,
657        end_time: Option<u64>,
658    ) -> Result<Vec<HyperliquidFundingHistoryEntry>> {
659        let request = InfoRequest::funding_history(coin, start_time, end_time);
660        let response = self.send_info_request(&request).await?;
661        serde_json::from_value(response).map_err(Error::Serde)
662    }
663
664    /// Generic info request method that returns raw JSON (useful for new endpoints and testing).
665    pub async fn send_info_request_raw(&self, request: &InfoRequest) -> Result<Value> {
666        self.send_info_request(request).await
667    }
668
669    async fn send_info_request(&self, request: &InfoRequest) -> Result<Value> {
670        let base_w = info_base_weight(request);
671        let mut attempt = 0u32;
672
673        loop {
674            self.info_limiter.acquire(base_w).await;
675
676            let (e, retry_after_ms) = match self.http_roundtrip_info(request).await {
677                Ok(response) if response.status.is_success() => {
678                    let val: Value =
679                        serde_json::from_slice(&response.body).map_err(Error::Serde)?;
680                    let extra = info_extra_weight(request, &val);
681                    if extra > 0 {
682                        self.info_limiter.debit_extra(extra).await;
683                        log::debug!(
684                            "Info debited extra weight: endpoint={request:?}, base_w={base_w}, extra={extra}"
685                        );
686                    }
687
688                    return Ok(val);
689                }
690                Ok(response) => {
691                    let retry_after_ms = Self::retry_after_ms(&response.headers);
692                    let error = if response.status.as_u16() == 429 {
693                        Error::rate_limit("info", base_w, retry_after_ms)
694                    } else {
695                        let body = String::from_utf8_lossy(&response.body);
696                        Error::http(response.status.as_u16(), body.to_string())
697                    };
698
699                    (error, retry_after_ms)
700                }
701                Err(e) => (e, None),
702            };
703
704            if !e.is_retryable() || attempt >= self.info_max_retries {
705                return Err(e);
706            }
707
708            let delay = retry_after_ms.map_or_else(
709                || {
710                    backoff_full_jitter(
711                        attempt,
712                        self.info_retry_delay_initial,
713                        self.info_retry_delay_max,
714                    )
715                },
716                Duration::from_millis,
717            );
718
719            log::debug!(
720                "Info request failed; retrying: endpoint={request:?}, attempt={attempt}, wait_ms={}",
721                delay.as_millis()
722            );
723            attempt += 1;
724            tokio::time::sleep(delay).await;
725        }
726    }
727
728    async fn http_roundtrip_info(&self, request: &InfoRequest) -> Result<HttpResponse> {
729        let url = &self.base_info;
730        let body = serde_json::to_value(request).map_err(Error::Serde)?;
731        let body_bytes = serde_json::to_string(&body)
732            .map_err(Error::Serde)?
733            .into_bytes();
734
735        self.client
736            .request(
737                Method::POST,
738                url.clone(),
739                None,
740                None,
741                Some(body_bytes),
742                None,
743                None,
744            )
745            .await
746            .map_err(Error::from_http_client)
747    }
748
749    /// Send a signed action to the exchange.
750    pub async fn post_action(
751        &self,
752        action: &ExchangeAction,
753    ) -> Result<HyperliquidExchangeResponse> {
754        let w = exchange_weight(action);
755        self.exchange_limiter.acquire(w).await;
756
757        let signer = self
758            .signer
759            .as_ref()
760            .ok_or_else(|| Error::auth("credentials required for exchange operations"))?;
761
762        let nonce_manager = self
763            .nonce_manager
764            .as_ref()
765            .ok_or_else(|| Error::auth("nonce manager missing"))?;
766
767        let signer_id = self.signer_id();
768        let time_nonce = nonce_manager.next(signer_id)?;
769
770        // L1 signing uses `action_bytes` only; skip the JSON value to save work
771        let action_bytes = rmp_serde::to_vec_named(action)
772            .context("serialize action with MessagePack")
773            .map_err(|e| Error::bad_request(e.to_string()))?;
774
775        let sign_request = SignRequest {
776            action: None,
777            action_bytes: Some(action_bytes),
778            time_nonce,
779            action_type: HyperliquidActionType::L1,
780            is_testnet: self.is_testnet(),
781            vault_address: self.vault_address,
782            expires_after: None,
783        };
784
785        let sig = signer.sign(&sign_request)?.signature;
786
787        let nonce_u64 = time_nonce.as_millis() as u64;
788
789        let request = if let Some(vault) = self.vault_address {
790            HyperliquidExchangeRequest::with_vault(
791                action.clone(),
792                nonce_u64,
793                sig,
794                vault.to_string(),
795            )
796        } else {
797            HyperliquidExchangeRequest::new(action.clone(), nonce_u64, sig)
798        };
799
800        let response = self.http_roundtrip_exchange(&request).await?;
801
802        if response.status.is_success() {
803            let parsed_response: HyperliquidExchangeResponse =
804                serde_json::from_slice(&response.body).map_err(Error::Serde)?;
805
806            // Check if the response contains an error status
807            match &parsed_response {
808                HyperliquidExchangeResponse::Status {
809                    status,
810                    response: response_data,
811                } if status == "err" => {
812                    let error_msg = response_data
813                        .as_str()
814                        .map_or_else(|| response_data.to_string(), |s| s.to_string());
815                    log::error!("Hyperliquid API returned error: {error_msg}");
816                    Err(Error::bad_request(format!("API error: {error_msg}")))
817                }
818                HyperliquidExchangeResponse::Error { error } => {
819                    log::error!("Hyperliquid API returned error: {error}");
820                    Err(Error::bad_request(format!("API error: {error}")))
821                }
822                _ => Ok(parsed_response),
823            }
824        } else if response.status.as_u16() == 429 {
825            let ra = Self::retry_after_ms(&response.headers);
826            Err(Error::rate_limit("exchange", w, ra))
827        } else {
828            let error_body = String::from_utf8_lossy(&response.body);
829            log::error!(
830                "Exchange API error (status {}): {}",
831                response.status.as_u16(),
832                error_body
833            );
834            Err(Error::http(
835                response.status.as_u16(),
836                error_body.to_string(),
837            ))
838        }
839    }
840
841    /// Build a signed exchange request using the typed HyperliquidExchangeAction enum.
842    ///
843    /// # Errors
844    ///
845    /// Returns an error if the action is unsupported, credentials are missing, or signing fails.
846    pub fn sign_action_exec_request(
847        &self,
848        action: &HyperliquidExchangeAction,
849        expires_after: Option<u64>,
850    ) -> Result<HyperliquidExchangeRequest<HyperliquidExchangeAction>> {
851        if matches!(action, HyperliquidExchangeAction::UsdClassTransfer { .. }) {
852            return Err(Error::bad_request("Unsupported action: usdClassTransfer"));
853        }
854
855        let signer = self
856            .signer
857            .as_ref()
858            .ok_or_else(|| Error::auth("credentials required for exchange operations"))?;
859
860        let nonce_manager = self
861            .nonce_manager
862            .as_ref()
863            .ok_or_else(|| Error::auth("nonce manager missing"))?;
864
865        let signer_id = self.signer_id();
866        let time_nonce = nonce_manager.next(signer_id)?;
867        // No need to validate - next() guarantees a valid, unused nonce
868
869        // L1 signing uses `action_bytes` only; skip the JSON value to save work
870        let action_bytes = rmp_serde::to_vec_named(action)
871            .context("serialize action with MessagePack")
872            .map_err(|e| Error::bad_request(e.to_string()))?;
873
874        let sig = signer
875            .sign(&SignRequest {
876                action: None,
877                action_bytes: Some(action_bytes),
878                time_nonce,
879                action_type: HyperliquidActionType::L1,
880                is_testnet: self.is_testnet(),
881                vault_address: self.vault_address,
882                expires_after,
883            })?
884            .signature;
885
886        let mut request = if let Some(vault) = self.vault_address {
887            HyperliquidExchangeRequest::with_vault(
888                action.clone(),
889                time_nonce.as_millis() as u64,
890                sig,
891                vault.to_string(),
892            )
893        } else {
894            HyperliquidExchangeRequest::new(action.clone(), time_nonce.as_millis() as u64, sig)
895        };
896        request.expires_after = expires_after;
897        Ok(request)
898    }
899
900    /// Send a signed action to the exchange using the typed HyperliquidExchangeAction enum.
901    ///
902    /// This is the preferred method for placing orders as it uses properly typed
903    /// structures that match Hyperliquid's API expectations exactly.
904    pub async fn post_action_exec(
905        &self,
906        action: &HyperliquidExchangeAction,
907    ) -> Result<HyperliquidExchangeResponse> {
908        let w = exec_action_weight(action);
909        self.exchange_limiter.acquire(w).await;
910
911        let request = self.sign_action_exec_request(action, None)?;
912
913        let response = self.http_roundtrip_exchange(&request).await?;
914
915        if response.status.is_success() {
916            let parsed_response: HyperliquidExchangeResponse =
917                serde_json::from_slice(&response.body).map_err(Error::Serde)?;
918
919            // Check if the response contains an error status
920            match &parsed_response {
921                HyperliquidExchangeResponse::Status {
922                    status,
923                    response: response_data,
924                } if status == "err" => {
925                    let error_msg = response_data
926                        .as_str()
927                        .map_or_else(|| response_data.to_string(), |s| s.to_string());
928                    log::error!("Hyperliquid API returned error: {error_msg}");
929                    Err(Error::bad_request(format!("API error: {error_msg}")))
930                }
931                HyperliquidExchangeResponse::Error { error } => {
932                    log::error!("Hyperliquid API returned error: {error}");
933                    Err(Error::bad_request(format!("API error: {error}")))
934                }
935                _ => Ok(parsed_response),
936            }
937        } else if response.status.as_u16() == 429 {
938            let ra = Self::retry_after_ms(&response.headers);
939            Err(Error::rate_limit("exchange", w, ra))
940        } else {
941            let error_body = String::from_utf8_lossy(&response.body);
942            Err(Error::http(
943                response.status.as_u16(),
944                error_body.to_string(),
945            ))
946        }
947    }
948
949    /// Returns the current rate-limit state for the info endpoint route.
950    pub async fn rest_limiter_snapshot(&self) -> RateLimitSnapshot {
951        self.info_limiter.snapshot().await
952    }
953
954    async fn http_roundtrip_exchange<T>(
955        &self,
956        request: &HyperliquidExchangeRequest<T>,
957    ) -> Result<HttpResponse>
958    where
959        T: serde::Serialize,
960    {
961        let url = &self.base_exchange;
962        let body = serde_json::to_string(&request).map_err(Error::Serde)?;
963        let body_bytes = body.into_bytes();
964
965        let response = self
966            .client
967            .request(
968                Method::POST,
969                url.clone(),
970                None,
971                None,
972                Some(body_bytes),
973                None,
974                None,
975            )
976            .await
977            .map_err(Error::from_http_client)?;
978
979        Ok(response)
980    }
981}
982
983/// Provides a high-level HTTP client for the [Hyperliquid](https://hyperliquid.xyz/) REST API.
984///
985/// This domain client wraps [`HyperliquidRawHttpClient`] and provides methods that work
986/// with Nautilus domain types. It maintains an instrument cache and handles conversions
987/// between Hyperliquid API responses and Nautilus domain models.
988#[derive(Debug, Clone)]
989#[cfg_attr(
990    feature = "python",
991    pyo3::pyclass(module = "nautilus_trader.adapters.hyperliquid", from_py_object)
992)]
993#[cfg_attr(
994    feature = "python",
995    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.hyperliquid")
996)]
997pub struct HyperliquidHttpClient {
998    pub(crate) inner: Arc<HyperliquidRawHttpClient>,
999    clock: &'static AtomicTime,
1000    instruments: Arc<AtomicMap<Ustr, InstrumentAny>>,
1001    instruments_by_coin: Arc<AtomicMap<(Ustr, HyperliquidProductType), InstrumentAny>>,
1002    /// Mapping from symbol to asset index for order submission.
1003    asset_indices: Arc<AtomicMap<Ustr, u32>>,
1004    /// Mapping from spot fill coin (`@{pair_index}`) to instrument symbol.
1005    spot_fill_coins: Arc<AtomicMap<Ustr, Ustr>>,
1006    client_order_id_cloids: Arc<Mutex<AHashMap<ClientOrderId, Cloid>>>,
1007    account_id: Option<AccountId>,
1008    /// Optional override address for queries (agent wallet / API sub-key support).
1009    /// When set, used for balance queries, position reports, and WS subscriptions
1010    /// instead of the address derived from the private key.
1011    account_address: Option<String>,
1012    normalize_prices: bool,
1013    market_order_slippage_bps: u32,
1014    include_builder_attribution: bool,
1015    product_type_mask: u8,
1016}
1017
1018impl Default for HyperliquidHttpClient {
1019    fn default() -> Self {
1020        Self::new(HyperliquidEnvironment::Mainnet, 60, None)
1021            .expect("Failed to create default Hyperliquid HTTP client")
1022    }
1023}
1024
1025impl HyperliquidHttpClient {
1026    const ALL_PRODUCT_TYPES: u8 = Self::product_type_flag(HyperliquidProductType::Perp)
1027        | Self::product_type_flag(HyperliquidProductType::Spot)
1028        | Self::product_type_flag(HyperliquidProductType::Outcome);
1029
1030    /// Creates a new [`HyperliquidHttpClient`] for public endpoints only.
1031    ///
1032    /// # Errors
1033    ///
1034    /// Returns an error if the HTTP client cannot be created.
1035    pub fn new(
1036        environment: HyperliquidEnvironment,
1037        timeout_secs: u64,
1038        proxy_url: Option<String>,
1039    ) -> std::result::Result<Self, HttpClientError> {
1040        let raw_client = HyperliquidRawHttpClient::new(environment, timeout_secs, proxy_url)?;
1041        Ok(Self::from_raw(raw_client))
1042    }
1043
1044    /// Creates a new [`HyperliquidHttpClient`] configured with a [`Secrets`] struct.
1045    ///
1046    /// # Errors
1047    ///
1048    /// Returns an error if the HTTP client cannot be created.
1049    pub fn with_secrets(
1050        secrets: &Secrets,
1051        timeout_secs: u64,
1052        proxy_url: Option<String>,
1053    ) -> std::result::Result<Self, HttpClientError> {
1054        let raw_client =
1055            HyperliquidRawHttpClient::with_credentials(secrets, timeout_secs, proxy_url)?;
1056        Ok(Self::from_raw(raw_client))
1057    }
1058
1059    fn from_raw(raw_client: HyperliquidRawHttpClient) -> Self {
1060        Self {
1061            inner: Arc::new(raw_client),
1062            clock: get_atomic_clock_realtime(),
1063            instruments: Arc::new(AtomicMap::new()),
1064            instruments_by_coin: Arc::new(AtomicMap::new()),
1065            asset_indices: Arc::new(AtomicMap::new()),
1066            spot_fill_coins: Arc::new(AtomicMap::new()),
1067            client_order_id_cloids: Arc::new(Mutex::new(AHashMap::new())),
1068            account_id: None,
1069            account_address: None,
1070            normalize_prices: true,
1071            market_order_slippage_bps: crate::common::parse::DEFAULT_MARKET_SLIPPAGE_BPS,
1072            include_builder_attribution: true,
1073            product_type_mask: Self::ALL_PRODUCT_TYPES,
1074        }
1075    }
1076
1077    /// Returns the cached CLOID for a client order ID, or derives and caches it.
1078    #[must_use]
1079    pub fn get_or_generate_client_order_id_cloid(&self, client_order_id: ClientOrderId) -> Cloid {
1080        let mut cloids = self.client_order_id_cloids.lock();
1081        *cloids
1082            .entry(client_order_id)
1083            .or_insert_with(|| Cloid::from_client_order_id(client_order_id))
1084    }
1085
1086    /// Caches a CLOID for a client order ID if one is not already cached.
1087    pub fn cache_client_order_id_cloid(&self, client_order_id: ClientOrderId, cloid: Cloid) {
1088        self.client_order_id_cloids
1089            .lock()
1090            .entry(client_order_id)
1091            .or_insert(cloid);
1092    }
1093
1094    /// Returns the cached CLOID for a client order ID.
1095    #[must_use]
1096    pub fn cached_client_order_id_cloid(&self, client_order_id: &ClientOrderId) -> Option<Cloid> {
1097        self.client_order_id_cloids
1098            .lock()
1099            .get(client_order_id)
1100            .copied()
1101    }
1102
1103    /// Returns the cached CLOID for a client order ID when no other client
1104    /// order ID maps to the same CLOID.
1105    #[must_use]
1106    pub(crate) fn unique_cached_client_order_id_cloid(
1107        &self,
1108        client_order_id: &ClientOrderId,
1109    ) -> Option<Cloid> {
1110        let cloids = self.client_order_id_cloids.lock();
1111        let cloid = cloids.get(client_order_id).copied()?;
1112        let mapping_count = cloids
1113            .values()
1114            .filter(|cached_cloid| **cached_cloid == cloid)
1115            .count();
1116
1117        (mapping_count == 1).then_some(cloid)
1118    }
1119
1120    /// Removes the cached CLOID for a client order ID.
1121    pub fn remove_client_order_id_cloid(&self, client_order_id: &ClientOrderId) -> Option<Cloid> {
1122        self.client_order_id_cloids.lock().remove(client_order_id)
1123    }
1124
1125    /// Overrides the base info URL (for testing with mock servers).
1126    ///
1127    /// # Panics
1128    ///
1129    /// Panics if the inner `Arc` has multiple references.
1130    pub fn set_base_info_url(&mut self, url: String) {
1131        Arc::get_mut(&mut self.inner)
1132            .expect("cannot override URL: Arc has multiple references")
1133            .set_base_info_url(url);
1134    }
1135
1136    /// Overrides the base exchange URL (for testing with mock servers).
1137    ///
1138    /// # Panics
1139    ///
1140    /// Panics if the inner `Arc` has multiple references.
1141    pub fn set_base_exchange_url(&mut self, url: String) {
1142        Arc::get_mut(&mut self.inner)
1143            .expect("cannot override URL: Arc has multiple references")
1144            .set_base_exchange_url(url);
1145    }
1146
1147    pub(crate) fn set_info_retry_config(
1148        &mut self,
1149        max_retries: u32,
1150        delay_initial: Duration,
1151        delay_max: Duration,
1152    ) {
1153        let inner = Arc::make_mut(&mut self.inner);
1154        inner.info_max_retries = max_retries;
1155        inner.info_retry_delay_initial = delay_initial;
1156        inner.info_retry_delay_max = delay_max;
1157    }
1158
1159    /// Creates an authenticated client from environment variables for the specified network.
1160    ///
1161    /// # Errors
1162    ///
1163    /// Returns an error if required environment variables are not set.
1164    pub fn from_env(environment: HyperliquidEnvironment) -> Result<Self> {
1165        let raw_client = HyperliquidRawHttpClient::from_env(environment)?;
1166        Ok(Self {
1167            inner: Arc::new(raw_client),
1168            clock: get_atomic_clock_realtime(),
1169            instruments: Arc::new(AtomicMap::new()),
1170            instruments_by_coin: Arc::new(AtomicMap::new()),
1171            asset_indices: Arc::new(AtomicMap::new()),
1172            spot_fill_coins: Arc::new(AtomicMap::new()),
1173            client_order_id_cloids: Arc::new(Mutex::new(AHashMap::new())),
1174            account_id: None,
1175            account_address: None,
1176            normalize_prices: true,
1177            market_order_slippage_bps: crate::common::parse::DEFAULT_MARKET_SLIPPAGE_BPS,
1178            include_builder_attribution: true,
1179            product_type_mask: Self::ALL_PRODUCT_TYPES,
1180        })
1181    }
1182
1183    /// Creates a new [`HyperliquidHttpClient`] configured with credentials.
1184    ///
1185    /// If credentials are not provided, falls back to environment variables:
1186    /// - Testnet: `HYPERLIQUID_TESTNET_PK`, `HYPERLIQUID_TESTNET_VAULT`
1187    /// - Mainnet: `HYPERLIQUID_PK`, `HYPERLIQUID_VAULT`
1188    ///
1189    /// If no credentials are provided and no environment variables are set,
1190    /// creates an unauthenticated client for public endpoints only.
1191    ///
1192    /// # Errors
1193    ///
1194    /// Returns an error if credentials are invalid.
1195    pub fn with_credentials(
1196        private_key: Option<String>,
1197        vault_address: Option<String>,
1198        account_address: Option<&str>,
1199        environment: HyperliquidEnvironment,
1200        timeout_secs: u64,
1201        proxy_url: Option<String>,
1202    ) -> Result<Self> {
1203        let (pk_env_var, vault_env_var) = credential_env_vars(environment);
1204
1205        let resolved_account_address = resolve_execution_account_address(
1206            private_key.as_deref(),
1207            vault_address.as_deref(),
1208            account_address,
1209            environment,
1210        )?;
1211
1212        // Resolve private key: explicit value -> env var -> None (unauthenticated)
1213        let resolved_pk = private_key.or_else(|| std::env::var(pk_env_var).ok());
1214
1215        // Resolve vault address: explicit value -> env var -> None
1216        let resolved_vault = vault_address.or_else(|| std::env::var(vault_env_var).ok());
1217
1218        Self::from_resolved_credentials(
1219            resolved_pk,
1220            resolved_vault.as_deref(),
1221            resolved_account_address,
1222            environment,
1223            timeout_secs,
1224            proxy_url,
1225        )
1226    }
1227
1228    fn from_resolved_credentials(
1229        private_key: Option<String>,
1230        vault_address: Option<&str>,
1231        account_address: Option<String>,
1232        environment: HyperliquidEnvironment,
1233        timeout_secs: u64,
1234        proxy_url: Option<String>,
1235    ) -> Result<Self> {
1236        match private_key {
1237            Some(pk) => {
1238                let raw_client = HyperliquidRawHttpClient::from_credentials(
1239                    &pk,
1240                    vault_address,
1241                    environment,
1242                    timeout_secs,
1243                    proxy_url,
1244                )?;
1245                Ok(Self {
1246                    inner: Arc::new(raw_client),
1247                    clock: get_atomic_clock_realtime(),
1248                    instruments: Arc::new(AtomicMap::new()),
1249                    instruments_by_coin: Arc::new(AtomicMap::new()),
1250                    asset_indices: Arc::new(AtomicMap::new()),
1251                    spot_fill_coins: Arc::new(AtomicMap::new()),
1252                    client_order_id_cloids: Arc::new(Mutex::new(AHashMap::new())),
1253                    account_id: None,
1254                    account_address,
1255                    normalize_prices: true,
1256                    market_order_slippage_bps: crate::common::parse::DEFAULT_MARKET_SLIPPAGE_BPS,
1257                    include_builder_attribution: true,
1258                    product_type_mask: Self::ALL_PRODUCT_TYPES,
1259                })
1260            }
1261            None => {
1262                // No credentials available, create unauthenticated client
1263                let mut client = Self::new(environment, timeout_secs, proxy_url)
1264                    .map_err(|e| Error::auth(format!("Failed to create HTTP client: {e}")))?;
1265                client.set_account_address(account_address)?;
1266                Ok(client)
1267            }
1268        }
1269    }
1270
1271    /// Creates a new [`HyperliquidHttpClient`] configured with explicit credentials.
1272    ///
1273    /// # Errors
1274    ///
1275    /// Returns an error if the private key is invalid or cannot be parsed.
1276    pub fn from_credentials(
1277        private_key: &str,
1278        vault_address: Option<&str>,
1279        environment: HyperliquidEnvironment,
1280        timeout_secs: u64,
1281        proxy_url: Option<String>,
1282    ) -> Result<Self> {
1283        let raw_client = HyperliquidRawHttpClient::from_credentials(
1284            private_key,
1285            vault_address,
1286            environment,
1287            timeout_secs,
1288            proxy_url,
1289        )?;
1290        Ok(Self {
1291            inner: Arc::new(raw_client),
1292            clock: get_atomic_clock_realtime(),
1293            instruments: Arc::new(AtomicMap::new()),
1294            instruments_by_coin: Arc::new(AtomicMap::new()),
1295            asset_indices: Arc::new(AtomicMap::new()),
1296            spot_fill_coins: Arc::new(AtomicMap::new()),
1297            client_order_id_cloids: Arc::new(Mutex::new(AHashMap::new())),
1298            account_id: None,
1299            account_address: None,
1300            normalize_prices: true,
1301            market_order_slippage_bps: crate::common::parse::DEFAULT_MARKET_SLIPPAGE_BPS,
1302            include_builder_attribution: true,
1303            product_type_mask: Self::ALL_PRODUCT_TYPES,
1304        })
1305    }
1306
1307    /// Returns whether this client is configured for testnet.
1308    #[must_use]
1309    pub fn is_testnet(&self) -> bool {
1310        self.inner.is_testnet()
1311    }
1312
1313    /// Returns whether order price normalization is enabled.
1314    #[must_use]
1315    pub fn normalize_prices(&self) -> bool {
1316        self.normalize_prices
1317    }
1318
1319    /// Sets whether to normalize order prices to 5 significant figures.
1320    pub fn set_normalize_prices(&mut self, value: bool) {
1321        self.normalize_prices = value;
1322    }
1323
1324    /// Returns the MARKET-order slippage buffer in basis points.
1325    #[must_use]
1326    pub fn market_order_slippage_bps(&self) -> u32 {
1327        self.market_order_slippage_bps
1328    }
1329
1330    /// Sets the MARKET-order slippage buffer in basis points.
1331    pub fn set_market_order_slippage_bps(&mut self, value: u32) {
1332        self.market_order_slippage_bps = value;
1333    }
1334
1335    /// Returns whether eligible mainnet orders include builder attribution.
1336    #[must_use]
1337    pub fn include_builder_attribution(&self) -> bool {
1338        self.include_builder_attribution
1339    }
1340
1341    /// Sets whether eligible mainnet orders include builder attribution.
1342    pub fn set_include_builder_attribution(&mut self, value: bool) {
1343        self.include_builder_attribution = value;
1344    }
1345
1346    /// Gets the user address derived from the private key (if client has credentials).
1347    ///
1348    /// # Errors
1349    ///
1350    /// Returns an error if the client has no signer configured.
1351    pub fn get_user_address(&self) -> Result<String> {
1352        self.inner.get_user_address()
1353    }
1354
1355    /// Returns `true` if a vault address is configured.
1356    #[must_use]
1357    pub fn has_vault_address(&self) -> bool {
1358        self.inner.has_vault_address()
1359    }
1360
1361    /// Returns the builder-attribution fee to attach to outgoing orders.
1362    ///
1363    /// Returns `None` when attribution is disabled, or when Hyperliquid does
1364    /// not support it for the current request context (vault orders and testnet).
1365    #[must_use]
1366    pub fn builder_attribution(&self) -> Option<HyperliquidExchangeBuilderFee> {
1367        if !self.include_builder_attribution || self.has_vault_address() || self.is_testnet() {
1368            None
1369        } else {
1370            Some(HyperliquidExchangeBuilderFee {
1371                address: NAUTILUS_BUILDER_ADDRESS.to_string(),
1372                fee_tenths_bp: 0,
1373            })
1374        }
1375    }
1376
1377    /// Gets the account address for queries: account_address if configured
1378    /// (agent wallet), then vault address, otherwise the user (EOA) address.
1379    ///
1380    /// # Errors
1381    ///
1382    /// Returns an error if the client has no signer configured and no account_address override is
1383    /// set.
1384    pub fn get_account_address(&self) -> Result<String> {
1385        if let Some(addr) = &self.account_address {
1386            return Ok(addr.clone());
1387        }
1388        self.inner.get_account_address()
1389    }
1390
1391    /// Sets the account address override for queries (agent wallet support).
1392    ///
1393    /// Trims surrounding whitespace and stores lowercase hex. Requires a `0x`-prefixed lowercase
1394    /// or EIP-55 checksummed address.
1395    /// `None` clears the override. Invalid input leaves the current override unchanged.
1396    ///
1397    /// # Errors
1398    ///
1399    /// Returns an error if the account address is invalid.
1400    pub fn set_account_address(&mut self, address: Option<String>) -> Result<()> {
1401        self.account_address = address
1402            .map(|address| normalize_account_address(&address))
1403            .transpose()?;
1404        Ok(())
1405    }
1406
1407    /// Caches a single instrument.
1408    ///
1409    /// This is required for parsing orders, fills, and positions into reports.
1410    /// Any existing instrument with the same symbol will be replaced.
1411    ///
1412    /// The venue asset index is taken from the instrument's `info` map so an
1413    /// instrument arriving on the message bus becomes submittable without
1414    /// refetching venue metadata. An instrument without the key keeps its
1415    /// existing asset index, if any, because guessing one would route orders to
1416    /// the wrong asset.
1417    pub fn cache_instrument(&self, instrument: &InstrumentAny) {
1418        self.merge_instruments(std::slice::from_ref(instrument));
1419    }
1420
1421    pub(crate) fn merge_instruments(&self, instruments: &[InstrumentAny]) {
1422        if instruments.is_empty() {
1423            return;
1424        }
1425
1426        self.cache_asset_indices(instruments);
1427        self.instruments.rcu(|m| {
1428            for instrument in instruments {
1429                m.insert(instrument.symbol().inner(), instrument.clone());
1430                m.insert(instrument.raw_symbol().inner(), instrument.clone());
1431            }
1432        });
1433
1434        let by_coin: Vec<_> = instruments
1435            .iter()
1436            .filter_map(|instrument| {
1437                let symbol = instrument.symbol();
1438                match HyperliquidProductType::from_symbol(symbol.as_str()) {
1439                    Ok(product_type) => Some((instrument, product_type)),
1440                    Err(_) => {
1441                        log::warn!("Unable to determine product type for symbol: {symbol}");
1442                        None
1443                    }
1444                }
1445            })
1446            .collect();
1447
1448        if !by_coin.is_empty() {
1449            self.instruments_by_coin.rcu(|m| {
1450                for (instrument, product_type) in &by_coin {
1451                    cache_coin_aliases(m, instrument, *product_type);
1452                }
1453            });
1454        }
1455    }
1456
1457    fn cache_asset_indices(&self, instruments: &[InstrumentAny]) {
1458        let cached = self.asset_indices.load();
1459        let mut pending = AHashMap::new();
1460
1461        for instrument in instruments {
1462            let full_symbol = instrument.symbol().inner();
1463            let coin = instrument.raw_symbol().inner();
1464            match instrument
1465                .info()
1466                .and_then(|info| info.get_u64(ASSET_INDEX_INFO_KEY))
1467                .and_then(|value| u32::try_from(value).ok())
1468            {
1469                Some(asset_index) => {
1470                    pending.insert(full_symbol, asset_index);
1471                }
1472                // vault tokens are synthesized locally to value balances and are never
1473                // submitted, so the venue assigns them no asset index to carry
1474                None if coin.starts_with(VAULT_TOKEN_PREFIX) => {}
1475                // without an index we cannot address the asset on the wire, so a market we
1476                // have never indexed is untradable rather than merely stale
1477                None if !pending.contains_key(&full_symbol)
1478                    && !cached.contains_key(&full_symbol) =>
1479                {
1480                    log::warn!(
1481                        "Instrument '{full_symbol}' carries no '{ASSET_INDEX_INFO_KEY}' info value \
1482                         and has no cached asset index; orders for it will be rejected"
1483                    );
1484                }
1485                None => log::warn!(
1486                    "Instrument '{full_symbol}' carries no '{ASSET_INDEX_INFO_KEY}' info value; \
1487                     leaving the cached asset index unchanged"
1488                ),
1489            }
1490        }
1491
1492        drop(cached);
1493
1494        if !pending.is_empty() {
1495            self.asset_indices.rcu(|m| {
1496                m.extend(pending.iter().map(|(symbol, index)| (*symbol, *index)));
1497            });
1498        }
1499    }
1500
1501    fn get_or_create_instrument(
1502        &self,
1503        coin: &Ustr,
1504        product_type: Option<HyperliquidProductType>,
1505    ) -> Option<InstrumentAny> {
1506        if let Some(pt) = product_type
1507            && let Some(instrument) = self.instruments_by_coin.load().get(&(*coin, pt))
1508        {
1509            return Some(instrument.clone());
1510        }
1511
1512        // HTTP responses lack product type context. HIP-4 outcome coins
1513        // (`#E`/`+E`) are checked first because they never collide with
1514        // perp or spot symbols, then perp, then spot.
1515        if product_type.is_none() {
1516            let guard = self.instruments_by_coin.load();
1517
1518            if let Some(instrument) = guard.get(&(*coin, HyperliquidProductType::Outcome)) {
1519                return Some(instrument.clone());
1520            }
1521
1522            if let Some(instrument) = guard.get(&(*coin, HyperliquidProductType::Perp)) {
1523                return Some(instrument.clone());
1524            }
1525
1526            if let Some(instrument) = guard.get(&(*coin, HyperliquidProductType::Spot)) {
1527                return Some(instrument.clone());
1528            }
1529        }
1530
1531        // Spot fills use @{pair_index} format, translate to full symbol and look up
1532        if product_type.is_none_or(|product| product == HyperliquidProductType::Spot)
1533            && coin.starts_with('@')
1534            && let Some(symbol) = self.spot_fill_coins.load().get(coin)
1535        {
1536            // Look up by full symbol in instruments map (not instruments_by_coin
1537            // which uses raw_symbol)
1538            if let Some(instrument) = self.instruments.load().get(symbol) {
1539                return Some(instrument.clone());
1540            }
1541        }
1542
1543        // Settled HIP-4 outcomes drop out of `outcomeMeta`, so uncached
1544        // instruments default to USDC because the encoding lacks a quote token.
1545        if product_type.is_none_or(|product| product == HyperliquidProductType::Outcome)
1546            && let Ok(asset_id) = parse_outcome_symbol(coin)
1547            && let Ok(def) = parse_unlisted_outcome_instrument(asset_id)
1548            && let Some(instrument) = create_instrument_from_def(&def, self.clock.get_time_ns())
1549        {
1550            log::debug!("Creating instrument for unlisted outcome coin: {coin}");
1551            self.cache_instrument(&instrument);
1552            return Some(instrument);
1553        }
1554
1555        // Vault tokens aren't in standard API, create synthetic instruments
1556        if product_type.is_none_or(|product| product == HyperliquidProductType::Spot)
1557            && coin.starts_with(VAULT_TOKEN_PREFIX)
1558        {
1559            log::debug!("Creating synthetic instrument for vault token: {coin}");
1560
1561            let ts_event = self.clock.get_time_ns();
1562
1563            // Create synthetic vault token instrument
1564            let symbol_str = format!("{coin}-USDC-SPOT");
1565            let symbol = Symbol::new(&symbol_str);
1566            let venue = *HYPERLIQUID_VENUE;
1567            let instrument_id = InstrumentId::new(symbol, venue);
1568
1569            // Create currencies
1570            let base_currency = Currency::new(
1571                coin.as_str(),
1572                8, // precision
1573                0, // ISO code (not applicable)
1574                coin.as_str(),
1575                CurrencyType::Crypto,
1576            );
1577
1578            let quote_currency = Currency::new(
1579                "USDC",
1580                6, // USDC standard precision
1581                0,
1582                "USDC",
1583                CurrencyType::Crypto,
1584            );
1585
1586            let price_increment = Price::from("0.00000001");
1587            let size_increment = Quantity::from("0.00000001");
1588
1589            let instrument = InstrumentAny::CurrencyPair(
1590                CurrencyPair::builder()
1591                    .instrument_id(instrument_id)
1592                    .raw_symbol(symbol)
1593                    .base_currency(base_currency)
1594                    .quote_currency(quote_currency)
1595                    .price_precision(8)
1596                    .size_precision(8)
1597                    .price_increment(price_increment)
1598                    .size_increment(size_increment)
1599                    .ts_event(ts_event)
1600                    .ts_init(ts_event)
1601                    .build()
1602                    .unwrap(),
1603            );
1604
1605            self.cache_instrument(&instrument);
1606
1607            Some(instrument)
1608        } else {
1609            // For non-vault tokens, log warning and return None
1610            log::warn!("Instrument not found in cache: {coin}");
1611            None
1612        }
1613    }
1614
1615    pub(crate) fn set_product_types(
1616        &mut self,
1617        product_types: Vec<HyperliquidProductType>,
1618    ) -> anyhow::Result<()> {
1619        anyhow::ensure!(
1620            !product_types.is_empty(),
1621            "Execution product_types must not be empty"
1622        );
1623        self.product_type_mask = product_types
1624            .into_iter()
1625            .fold(0, |mask, product| mask | Self::product_type_flag(product));
1626        Ok(())
1627    }
1628
1629    fn allows_product(&self, product: HyperliquidProductType) -> bool {
1630        self.product_type_mask & Self::product_type_flag(product) != 0
1631    }
1632
1633    pub(crate) fn allows_instrument(&self, instrument_id: InstrumentId) -> bool {
1634        instrument_id.venue == *HYPERLIQUID_VENUE
1635            && HyperliquidProductType::from_symbol(instrument_id.symbol.as_str())
1636                .is_ok_and(|product| self.allows_product(product))
1637    }
1638
1639    const fn product_type_flag(product: HyperliquidProductType) -> u8 {
1640        match product {
1641            HyperliquidProductType::Perp => 1,
1642            HyperliquidProductType::Spot => 2,
1643            HyperliquidProductType::Outcome => 4,
1644        }
1645    }
1646
1647    /// Set the account ID for this client.
1648    ///
1649    /// This is required for generating reports with the correct account ID.
1650    pub fn set_account_id(&mut self, account_id: AccountId) {
1651        self.account_id = Some(account_id);
1652    }
1653
1654    /// Fetch and parse all instrument definitions, populating the asset indices cache.
1655    pub async fn request_instrument_defs(&self) -> Result<Vec<HyperliquidInstrumentDef>> {
1656        Ok(self.load_instrument_defs().await?.0)
1657    }
1658
1659    /// Loads all instrument definitions, together with the product types whose
1660    /// metadata loaded in full.
1661    async fn load_instrument_defs(
1662        &self,
1663    ) -> Result<(
1664        Vec<HyperliquidInstrumentDef>,
1665        AHashSet<HyperliquidProductType>,
1666    )> {
1667        let mut defs: Vec<HyperliquidInstrumentDef> = Vec::new();
1668        let mut loaded = AHashSet::new();
1669        let spot_meta = match self.inner.get_spot_meta().await {
1670            Ok(spot_meta) => Some(spot_meta),
1671            Err(e) => {
1672                log::warn!("Failed to load Hyperliquid spot metadata: {e}");
1673                None
1674            }
1675        };
1676
1677        // Load all perp dexes: index 0 = standard, index 1+ = HIP-3
1678        match self.inner.load_all_perp_metas().await {
1679            Ok(all_metas) => {
1680                for (dex_index, meta) in all_metas.iter().enumerate() {
1681                    let base = perp_dex_asset_index_base(dex_index);
1682                    let collateral_currency = match resolve_perp_collateral_currency(
1683                        meta,
1684                        spot_meta.as_ref(),
1685                    ) {
1686                        Ok(collateral_currency) => collateral_currency,
1687                        Err(e) => {
1688                            return Err(Error::decode(format!(
1689                                "failed to resolve perp collateral currency for dex {dex_index}: {e}",
1690                            )));
1691                        }
1692                    };
1693
1694                    let perp_defs = parse_perp_instruments_with_collateral(
1695                        meta,
1696                        base,
1697                        collateral_currency.as_str(),
1698                    );
1699                    log::debug!(
1700                        "Loaded Hyperliquid perp defs: dex_index={dex_index}, count={}",
1701                        perp_defs.len(),
1702                    );
1703                    defs.extend(perp_defs);
1704                }
1705                loaded.insert(HyperliquidProductType::Perp);
1706            }
1707            Err(e) => {
1708                log::warn!("Failed to load allPerpMetas, falling back to meta: {e}");
1709
1710                match self.inner.load_perp_meta().await {
1711                    Ok(perp_meta) => {
1712                        match resolve_perp_collateral_currency(&perp_meta, spot_meta.as_ref()) {
1713                            Ok(collateral_currency) => {
1714                                let perp_defs = parse_perp_instruments_with_collateral(
1715                                    &perp_meta,
1716                                    0,
1717                                    collateral_currency.as_str(),
1718                                );
1719                                log::debug!(
1720                                    "Loaded Hyperliquid perp defs via fallback: count={}",
1721                                    perp_defs.len(),
1722                                );
1723                                defs.extend(perp_defs);
1724                            }
1725                            Err(e) => {
1726                                return Err(Error::decode(format!(
1727                                    "failed to resolve fallback perp collateral currency: {e}",
1728                                )));
1729                            }
1730                        }
1731                    }
1732                    Err(e) => {
1733                        log::warn!("Failed to load Hyperliquid perp metadata: {e}");
1734                    }
1735                }
1736            }
1737        }
1738
1739        if let Some(spot_meta) = spot_meta.as_ref() {
1740            match parse_spot_instruments(spot_meta) {
1741                Ok(spot_defs) => {
1742                    log::debug!(
1743                        "Loaded Hyperliquid spot definitions: count={}",
1744                        spot_defs.len(),
1745                    );
1746                    defs.extend(spot_defs);
1747                    loaded.insert(HyperliquidProductType::Spot);
1748                }
1749                Err(e) => {
1750                    log::warn!("Failed to parse Hyperliquid spot instruments: {e}");
1751                }
1752            }
1753        }
1754
1755        // HIP-4 outcome metadata is best-effort: the venue may not expose it
1756        // and the response shape is still firming up. Treat any error as a
1757        // soft skip so missing outcomes do not break perp/spot loading.
1758        match self.inner.get_outcome_meta().await {
1759            Ok(outcome_meta) => match parse_outcome_instruments(&outcome_meta) {
1760                Ok(outcome_defs) => {
1761                    log::debug!(
1762                        "Loaded Hyperliquid outcome definitions: count={}",
1763                        outcome_defs.len(),
1764                    );
1765                    defs.extend(outcome_defs);
1766                    loaded.insert(HyperliquidProductType::Outcome);
1767                }
1768                Err(e) => {
1769                    log::warn!("Failed to parse Hyperliquid outcome instruments: {e}");
1770                }
1771            },
1772            Err(e) => {
1773                log::debug!("Skipping Hyperliquid outcome metadata: {e}");
1774            }
1775        }
1776
1777        // Drop defs whose Nautilus-internal symbol collides with one already
1778        // accepted. This guards the HIP-3 case where two distinct venue names
1779        // (e.g. `dex:FOO*` and `dex:FOO?`) sanitize onto the same internal
1780        // symbol; without this filter the second def would silently overwrite
1781        // the first in `asset_indices`, which would route orders to the wrong
1782        // asset. First-write-wins matches the spot canonical-pair ordering.
1783        let mut seen_symbols = ahash::AHashSet::with_capacity(defs.len());
1784        let mut deduped: Vec<HyperliquidInstrumentDef> = Vec::with_capacity(defs.len());
1785        for def in defs {
1786            if seen_symbols.insert(def.symbol) {
1787                deduped.push(def);
1788            } else {
1789                log::warn!(
1790                    "Dropping Hyperliquid instrument: sanitized symbol '{}' collides with an earlier def (raw_symbol='{}')",
1791                    def.symbol,
1792                    def.raw_symbol,
1793                );
1794            }
1795        }
1796        let defs = deduped;
1797
1798        // Populate asset indices for all instruments (including filtered HIP-3)
1799        self.asset_indices.rcu(|m| {
1800            for def in &defs {
1801                m.insert(def.symbol, def.asset_index);
1802            }
1803        });
1804        log::debug!(
1805            "Populated asset indices map (count={})",
1806            self.asset_indices.len()
1807        );
1808
1809        Ok((defs, loaded))
1810    }
1811
1812    /// Converts instrument definitions into Nautilus instruments.
1813    pub fn convert_defs(&self, defs: Vec<HyperliquidInstrumentDef>) -> Vec<InstrumentAny> {
1814        let ts_init = self.clock.get_time_ns();
1815        instruments_from_defs_owned(defs, ts_init)
1816    }
1817
1818    /// Fetch and parse all available instrument definitions from Hyperliquid.
1819    pub async fn request_instruments(&self) -> Result<Vec<InstrumentAny>> {
1820        let defs = self.request_instrument_defs().await?;
1821        Ok(self.convert_defs(defs))
1822    }
1823
1824    /// Fetch all available instruments together with the market status of each.
1825    pub(crate) async fn request_instruments_with_statuses(&self) -> Result<InstrumentSnapshot> {
1826        let (defs, loaded) = self.load_instrument_defs().await?;
1827        let def_statuses: AHashMap<Ustr, MarketStatusAction> = defs
1828            .iter()
1829            .map(|def| {
1830                let action = if def.active {
1831                    MarketStatusAction::Trading
1832                } else {
1833                    MarketStatusAction::Close
1834                };
1835                (def.symbol, action)
1836            })
1837            .collect();
1838        let instruments = self.convert_defs(defs);
1839
1840        // Defs that fail conversion yield no instrument, so they get no status
1841        let statuses = instruments
1842            .iter()
1843            .filter_map(|instrument| {
1844                let instrument_id = instrument.id();
1845                def_statuses
1846                    .get(&instrument_id.symbol.inner())
1847                    .map(|&action| (instrument_id, action))
1848            })
1849            .collect();
1850
1851        Ok(InstrumentSnapshot {
1852            instruments,
1853            statuses,
1854            loaded,
1855        })
1856    }
1857
1858    /// Builds the `allDexsAssetCtxs` normalization map from dex name to ordered instrument IDs.
1859    ///
1860    /// The order of instrument IDs must match the venue universe ordering for each perp dex so
1861    /// incoming `ctxs` arrays can be normalized without leaking raw positional payloads.
1862    pub async fn build_all_dex_asset_ctxs_instrument_ids(
1863        &self,
1864    ) -> Result<AHashMap<String, Vec<Option<InstrumentId>>>> {
1865        let all_metas = match self.inner.load_all_perp_metas().await {
1866            Ok(all_metas) => all_metas,
1867            Err(e) => {
1868                log::warn!("Failed to load allPerpMetas, falling back to meta: {e}");
1869                vec![self.inner.load_perp_meta().await?]
1870            }
1871        };
1872
1873        let perp_dexs = match self.inner.load_perp_dexs().await {
1874            Ok(dexs) => Some(dexs),
1875            Err(e) => {
1876                log::warn!("Failed to load perpDexs, inferring dex names from metadata: {e}");
1877                None
1878            }
1879        };
1880
1881        let raw_symbol_to_id =
1882            self.instruments
1883                .load()
1884                .values()
1885                .fold(AHashMap::new(), |mut acc, instrument| {
1886                    acc.insert(instrument.raw_symbol().to_string(), instrument.id());
1887                    acc
1888                });
1889
1890        let mut mapping = AHashMap::new();
1891
1892        for (dex_index, meta) in all_metas.iter().enumerate() {
1893            let dex_name = resolve_perp_dex_name(dex_index, meta, perp_dexs.as_deref());
1894            let mut instrument_ids = Vec::with_capacity(meta.universe.len());
1895
1896            for asset in &meta.universe {
1897                if let Some(instrument_id) = raw_symbol_to_id.get(&asset.name) {
1898                    instrument_ids.push(Some(*instrument_id));
1899                } else {
1900                    log::warn!(
1901                        "Missing cached Hyperliquid instrument for dex='{}' raw_symbol='{}'",
1902                        dex_name,
1903                        asset.name
1904                    );
1905                    instrument_ids.push(None);
1906                }
1907            }
1908
1909            mapping.insert(dex_name, instrument_ids);
1910        }
1911
1912        Ok(mapping)
1913    }
1914
1915    /// Get asset index for a symbol from the cached map.
1916    ///
1917    /// For perps: index in meta.universe (0, 1, 2, ...).
1918    /// For spot: 10_000 + index in spotMeta.universe.
1919    /// For HIP-3: 100_000 + dex_index * 10_000 + index in dex meta.universe.
1920    ///
1921    /// Returns `None` if the symbol is not found in the map.
1922    pub fn get_asset_index(&self, symbol: &str) -> Option<u32> {
1923        self.get_asset_index_for_symbol(Ustr::from(symbol))
1924    }
1925
1926    /// Get asset index for an already-interned symbol from the cached map.
1927    ///
1928    /// Returns `None` if the symbol is not found in the map.
1929    pub(crate) fn get_asset_index_for_symbol(&self, symbol: Ustr) -> Option<u32> {
1930        self.asset_indices.load().get(&symbol).copied()
1931    }
1932
1933    /// Get the price precision for a cached instrument by symbol.
1934    pub fn get_price_precision(&self, symbol: &str) -> Option<u8> {
1935        self.get_price_precision_for_symbol(Ustr::from(symbol))
1936    }
1937
1938    /// Get the price precision for a cached instrument by interned symbol.
1939    pub(crate) fn get_price_precision_for_symbol(&self, symbol: Ustr) -> Option<u8> {
1940        self.instruments
1941            .load()
1942            .get(&symbol)
1943            .map(|inst| inst.price_precision())
1944    }
1945
1946    /// Get mapping from spot fill coin identifiers to instrument symbols.
1947    ///
1948    /// Hyperliquid WebSocket fills for spot use `@{pair_index}` format (e.g., `@107`),
1949    /// while instruments are identified by full symbols (e.g., `HYPE-USDC-SPOT`).
1950    /// This mapping allows looking up the instrument from a spot fill.
1951    ///
1952    /// This method also caches the mapping internally for use by fill parsing methods.
1953    #[must_use]
1954    pub fn get_spot_fill_coin_mapping(&self) -> AHashMap<Ustr, Ustr> {
1955        const SPOT_INDEX_OFFSET: u32 = 10_000;
1956        const BUILDER_PERP_OFFSET: u32 = 100_000;
1957
1958        let guard = self.asset_indices.load();
1959
1960        let mut mapping = AHashMap::new();
1961
1962        for (symbol, &asset_index) in guard.iter() {
1963            // Spot instruments: asset_index in [10_000, 100_000)
1964            if (SPOT_INDEX_OFFSET..BUILDER_PERP_OFFSET).contains(&asset_index) {
1965                let pair_index = asset_index - SPOT_INDEX_OFFSET;
1966                let fill_coin = Ustr::from(&format!("@{pair_index}"));
1967                mapping.insert(fill_coin, *symbol);
1968            }
1969        }
1970
1971        // Cache the mapping internally for fill parsing
1972        self.spot_fill_coins.store(mapping.clone());
1973
1974        mapping
1975    }
1976
1977    /// Gets perpetuals metadata for internal use.
1978    #[allow(dead_code)]
1979    pub(crate) async fn load_perp_meta(&self) -> Result<PerpMeta> {
1980        self.inner.load_perp_meta().await
1981    }
1982
1983    /// Get metadata for all perp dexes (standard + HIP-3).
1984    #[allow(dead_code)]
1985    pub(crate) async fn load_all_perp_metas(&self) -> Result<Vec<PerpMeta>> {
1986        self.inner.load_all_perp_metas().await
1987    }
1988
1989    /// Gets spot metadata for internal use.
1990    #[allow(dead_code)]
1991    pub(crate) async fn get_spot_meta(&self) -> Result<SpotMeta> {
1992        self.inner.get_spot_meta().await
1993    }
1994
1995    /// Gets outcome metadata for internal use.
1996    pub(crate) async fn get_outcome_meta(&self) -> Result<OutcomeMeta> {
1997        self.inner.get_outcome_meta().await
1998    }
1999
2000    pub(crate) fn outcome_quote_currency(
2001        &self,
2002        instrument_id: InstrumentId,
2003        outcome_index: u32,
2004        meta: &OutcomeMeta,
2005    ) -> Currency {
2006        if let Some(instrument) = self.instruments.load().get(&instrument_id.symbol.inner()) {
2007            return instrument.quote_currency();
2008        }
2009
2010        let code = meta
2011            .outcomes
2012            .iter()
2013            .find(|market| market.outcome == outcome_index)
2014            .and_then(|market| market.quote_token.as_deref())
2015            .unwrap_or(DEFAULT_OUTCOME_QUOTE_CURRENCY);
2016        get_outcome_currency(code)
2017    }
2018
2019    /// Get L2 order book for a coin.
2020    pub async fn info_l2_book(&self, coin: &str) -> Result<HyperliquidL2Book> {
2021        self.inner.info_l2_book(coin).await
2022    }
2023
2024    /// Get recent public trades for a coin.
2025    pub async fn info_recent_trades(&self, coin: &str) -> Result<Vec<HyperliquidRecentTrade>> {
2026        self.inner.info_recent_trades(coin).await
2027    }
2028
2029    /// Get user fills (trading history).
2030    pub async fn info_user_fills(&self, user: &str) -> Result<HyperliquidFills> {
2031        self.inner.info_user_fills(user).await
2032    }
2033
2034    /// Get order status for a user.
2035    pub async fn info_order_status(&self, user: &str, oid: u64) -> Result<HyperliquidOrderStatus> {
2036        self.inner.info_order_status(user, oid).await
2037    }
2038
2039    /// Get all open orders for a user.
2040    pub async fn info_open_orders(&self, user: &str) -> Result<Value> {
2041        self.inner.info_open_orders(user).await
2042    }
2043
2044    /// Get frontend open orders (includes more detail) for a user.
2045    pub async fn info_frontend_open_orders(&self, user: &str) -> Result<Value> {
2046        self.inner.info_frontend_open_orders(user).await
2047    }
2048
2049    async fn info_frontend_open_orders_for_dex(
2050        &self,
2051        user: &str,
2052        dex: Option<&str>,
2053    ) -> Result<Value> {
2054        self.inner
2055            .info_frontend_open_orders_for_dex(user, dex)
2056            .await
2057    }
2058
2059    /// Get the most recent historical orders for a user.
2060    pub async fn info_historical_orders(
2061        &self,
2062        user: &str,
2063    ) -> Result<Vec<HyperliquidOrderStatusEntry>> {
2064        self.inner.info_historical_orders(user).await
2065    }
2066
2067    /// Get clearinghouse state (balances, positions, margin) for a user.
2068    pub async fn info_clearinghouse_state(&self, user: &str) -> Result<Value> {
2069        self.inner.info_clearinghouse_state(user).await
2070    }
2071
2072    async fn info_clearinghouse_state_for_dex(
2073        &self,
2074        user: &str,
2075        dex: Option<&str>,
2076    ) -> Result<Value> {
2077        self.inner.info_clearinghouse_state_for_dex(user, dex).await
2078    }
2079
2080    /// Get spot clearinghouse state (per-token spot balances) for a user.
2081    pub async fn info_spot_clearinghouse_state(&self, user: &str) -> Result<Value> {
2082        self.inner.info_spot_clearinghouse_state(user).await
2083    }
2084
2085    /// Get the account abstraction mode for a user.
2086    ///
2087    /// A mode string this adapter does not recognize maps to
2088    /// [`HyperliquidAccountAbstraction::Unknown`] and is logged as a warning; such accounts keep
2089    /// the perp-summary balance logic.
2090    ///
2091    /// # Errors
2092    ///
2093    /// Returns an error if the request fails or the response is not a JSON string.
2094    pub async fn info_user_abstraction(&self, user: &str) -> Result<HyperliquidAccountAbstraction> {
2095        let response = self.inner.info_user_abstraction(user).await?;
2096
2097        // Serde reads a single-key object like `{"mode": null}` as a unit variant, which
2098        // `#[serde(other)]` would map to `Unknown`, so only a bare string is accepted. Any
2099        // string decodes, to a known mode or to `Unknown`
2100        let abstraction = response
2101            .as_str()
2102            .and_then(|_| serde_json::from_value(response.clone()).ok())
2103            .ok_or_else(|| {
2104                Error::decode(format!(
2105                    "Failed to parse user abstraction: expected a mode string, was {response}"
2106                ))
2107            })?;
2108
2109        if abstraction == HyperliquidAccountAbstraction::Unknown {
2110            log::warn!(
2111                "Unrecognized Hyperliquid account abstraction {response}, using perp clearinghouse balances"
2112            );
2113        } else {
2114            log::debug!("Hyperliquid account abstraction: {abstraction}");
2115        }
2116
2117        Ok(abstraction)
2118    }
2119
2120    /// Get user fee schedule and effective rates.
2121    pub async fn info_user_fees(&self, user: &str) -> Result<Value> {
2122        self.inner.info_user_fees(user).await
2123    }
2124
2125    /// Get candle/bar data for a coin.
2126    pub async fn info_candle_snapshot(
2127        &self,
2128        coin: &str,
2129        interval: HyperliquidBarInterval,
2130        start_time: u64,
2131        end_time: u64,
2132    ) -> Result<HyperliquidCandleSnapshot> {
2133        self.inner
2134            .info_candle_snapshot(coin, interval, start_time, end_time)
2135            .await
2136    }
2137
2138    /// Get historical funding rates for a coin.
2139    pub async fn info_funding_history(
2140        &self,
2141        coin: &str,
2142        start_time: u64,
2143        end_time: Option<u64>,
2144    ) -> Result<Vec<HyperliquidFundingHistoryEntry>> {
2145        self.inner
2146            .info_funding_history(coin, start_time, end_time)
2147            .await
2148    }
2149
2150    /// Post an action to the exchange endpoint (low-level delegation).
2151    pub async fn post_action(
2152        &self,
2153        action: &ExchangeAction,
2154    ) -> Result<HyperliquidExchangeResponse> {
2155        self.inner.post_action(action).await
2156    }
2157
2158    /// Post an execution action (low-level delegation).
2159    pub async fn post_action_exec(
2160        &self,
2161        action: &HyperliquidExchangeAction,
2162    ) -> Result<HyperliquidExchangeResponse> {
2163        self.inner.post_action_exec(action).await
2164    }
2165
2166    /// Build the signed exchange request used by both HTTP and WebSocket post transports.
2167    ///
2168    /// # Errors
2169    ///
2170    /// Returns an error if the action is unsupported, credentials are missing, or signing fails.
2171    pub fn sign_action_exec_request(
2172        &self,
2173        action: &HyperliquidExchangeAction,
2174        expires_after: Option<u64>,
2175    ) -> Result<HyperliquidExchangeRequest<HyperliquidExchangeAction>> {
2176        self.inner.sign_action_exec_request(action, expires_after)
2177    }
2178
2179    /// Get metadata about available markets (low-level delegation).
2180    pub async fn info_meta(&self) -> Result<HyperliquidMeta> {
2181        self.inner.info_meta().await
2182    }
2183
2184    /// Cancel an order on the Hyperliquid exchange.
2185    ///
2186    /// Can cancel either by venue order ID or client order ID.
2187    /// At least one ID must be provided.
2188    ///
2189    /// # Errors
2190    ///
2191    /// Returns an error if credentials are missing, no order ID is provided,
2192    /// or the API returns an error.
2193    pub async fn cancel_order(
2194        &self,
2195        instrument_id: InstrumentId,
2196        client_order_id: Option<ClientOrderId>,
2197        venue_order_id: Option<VenueOrderId>,
2198    ) -> Result<()> {
2199        // Get asset ID from cached indices map
2200        let symbol = instrument_id.symbol.inner();
2201        let asset_id = self.get_asset_index_for_symbol(symbol).ok_or_else(|| {
2202            Error::bad_request(format!(
2203                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
2204            ))
2205        })?;
2206
2207        let action = if let Some(client_order_id) = client_order_id {
2208            if let Some(cloid) = self.cached_client_order_id_cloid(&client_order_id) {
2209                HyperliquidExchangeAction::CancelByCloid {
2210                    cancels: vec![HyperliquidExchangeCancelByCloidRequest {
2211                        asset: asset_id,
2212                        cloid,
2213                    }],
2214                    fast: None,
2215                }
2216            } else if let Some(oid) = venue_order_id {
2217                let oid_u64 = oid
2218                    .as_str()
2219                    .parse::<u64>()
2220                    .map_err(|_| Error::bad_request("Invalid venue order ID format"))?;
2221                HyperliquidExchangeAction::Cancel {
2222                    cancels: vec![HyperliquidExchangeCancelOrderRequest {
2223                        asset: asset_id,
2224                        oid: oid_u64,
2225                    }],
2226                    fast: None,
2227                }
2228            } else {
2229                let cloid = self.get_or_generate_client_order_id_cloid(client_order_id);
2230                HyperliquidExchangeAction::CancelByCloid {
2231                    cancels: vec![HyperliquidExchangeCancelByCloidRequest {
2232                        asset: asset_id,
2233                        cloid,
2234                    }],
2235                    fast: None,
2236                }
2237            }
2238        } else if let Some(oid) = venue_order_id {
2239            let oid_u64 = oid
2240                .as_str()
2241                .parse::<u64>()
2242                .map_err(|_| Error::bad_request("Invalid venue order ID format"))?;
2243            HyperliquidExchangeAction::Cancel {
2244                cancels: vec![HyperliquidExchangeCancelOrderRequest {
2245                    asset: asset_id,
2246                    oid: oid_u64,
2247                }],
2248                fast: None,
2249            }
2250        } else {
2251            return Err(Error::bad_request(
2252                "Either client_order_id or venue_order_id must be provided",
2253            ));
2254        };
2255
2256        // Submit cancellation
2257        let response = self.inner.post_action_exec(&action).await?;
2258
2259        // Check response - only check for error status
2260        match response {
2261            ref r @ HyperliquidExchangeResponse::Status { .. } if r.is_ok() => Ok(()),
2262            HyperliquidExchangeResponse::Status {
2263                status,
2264                response: error_data,
2265            } => Err(Error::bad_request(format!(
2266                "Cancel order failed: status={status}, error={error_data}"
2267            ))),
2268            HyperliquidExchangeResponse::Error { error } => {
2269                Err(Error::bad_request(format!("Cancel order error: {error}")))
2270            }
2271        }
2272    }
2273
2274    /// Modify an order on the Hyperliquid exchange.
2275    ///
2276    /// The HL modify API requires a full replacement order spec plus a venue
2277    /// order ID or cached CLOID target. The caller must provide all order fields.
2278    ///
2279    /// # Errors
2280    ///
2281    /// Returns an error if the asset index is not found, no safe modify target
2282    /// exists, the venue order ID is invalid, or the API returns an error.
2283    #[expect(clippy::too_many_arguments)]
2284    pub async fn modify_order(
2285        &self,
2286        instrument_id: InstrumentId,
2287        venue_order_id: Option<VenueOrderId>,
2288        order_side: OrderSide,
2289        order_type: OrderType,
2290        price: Price,
2291        quantity: Quantity,
2292        trigger_price: Option<Price>,
2293        reduce_only: bool,
2294        post_only: bool,
2295        time_in_force: TimeInForce,
2296        client_order_id: Option<ClientOrderId>,
2297    ) -> Result<()> {
2298        let symbol = instrument_id.symbol.inner();
2299        let asset_id = self.get_asset_index_for_symbol(symbol).ok_or_else(|| {
2300            Error::bad_request(format!(
2301                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
2302            ))
2303        })?;
2304
2305        let oid = match client_order_id
2306            .as_ref()
2307            .and_then(|id| self.unique_cached_client_order_id_cloid(id))
2308        {
2309            Some(cloid) => HyperliquidExchangeModifyTarget::Cloid(cloid),
2310            None => {
2311                let Some(venue_order_id) = venue_order_id.as_ref() else {
2312                    return Err(Error::bad_request(
2313                        "venue_order_id or unique cached CLOID is required for modify",
2314                    ));
2315                };
2316                HyperliquidExchangeModifyTarget::from_venue_order_id(venue_order_id)
2317                    .map_err(|_| Error::bad_request("Invalid venue order ID format"))?
2318            }
2319        };
2320
2321        let is_buy = matches!(order_side, OrderSide::Buy);
2322        let decimals = self.get_price_precision_for_symbol(symbol);
2323
2324        let normalized_price = normalize_or_validate_wire_price(
2325            price.as_decimal(),
2326            "Price",
2327            decimals,
2328            self.normalize_prices,
2329        )
2330        .map_err(|e| Error::bad_request(format!("{e}")))?;
2331
2332        let size = quantity.as_decimal().normalize();
2333
2334        let kind = match order_type {
2335            OrderType::Market => HyperliquidExchangeOrderKind::Limit {
2336                limit: HyperliquidExchangeLimitParams {
2337                    tif: HyperliquidExchangeTif::Ioc,
2338                },
2339            },
2340            OrderType::Limit => {
2341                let tif = time_in_force_to_hyperliquid_tif(time_in_force, post_only)
2342                    .map_err(|e| Error::bad_request(format!("{e}")))?;
2343                HyperliquidExchangeOrderKind::Limit {
2344                    limit: HyperliquidExchangeLimitParams { tif },
2345                }
2346            }
2347            OrderType::StopMarket
2348            | OrderType::StopLimit
2349            | OrderType::MarketIfTouched
2350            | OrderType::LimitIfTouched => {
2351                if let Some(trig_px) = trigger_price {
2352                    let trigger_price_decimal = normalize_or_validate_wire_price(
2353                        trig_px.as_decimal(),
2354                        "Trigger price",
2355                        decimals,
2356                        self.normalize_prices,
2357                    )
2358                    .map_err(|e| Error::bad_request(format!("{e}")))?;
2359                    let tpsl = match order_type {
2360                        OrderType::StopMarket | OrderType::StopLimit => HyperliquidExchangeTpSl::Sl,
2361                        _ => HyperliquidExchangeTpSl::Tp,
2362                    };
2363                    let is_market = matches!(
2364                        order_type,
2365                        OrderType::StopMarket | OrderType::MarketIfTouched
2366                    );
2367                    HyperliquidExchangeOrderKind::Trigger {
2368                        trigger: HyperliquidExchangeTriggerParams {
2369                            is_market,
2370                            trigger_px: trigger_price_decimal,
2371                            tpsl,
2372                        },
2373                    }
2374                } else {
2375                    return Err(Error::bad_request("Trigger orders require a trigger price"));
2376                }
2377            }
2378            _ => {
2379                return Err(Error::bad_request(format!(
2380                    "Order type {order_type:?} not supported for modify"
2381                )));
2382            }
2383        };
2384        let cloid = client_order_id.map(|id| self.get_or_generate_client_order_id_cloid(id));
2385
2386        let order = HyperliquidExchangePlaceOrderRequest {
2387            asset: asset_id,
2388            is_buy,
2389            price: normalized_price,
2390            size,
2391            reduce_only,
2392            kind,
2393            cloid,
2394        };
2395
2396        let action = HyperliquidExchangeAction::Modify {
2397            modify: HyperliquidExchangeModifyOrderRequest { oid, order },
2398        };
2399
2400        let response = self.inner.post_action_exec(&action).await?;
2401
2402        match response {
2403            ref r @ HyperliquidExchangeResponse::Status { .. } if r.is_ok() => {
2404                if let Some(inner_error) = extract_inner_error(&response) {
2405                    Err(Error::bad_request(format!(
2406                        "Modify order rejected: {inner_error}",
2407                    )))
2408                } else {
2409                    Ok(())
2410                }
2411            }
2412            HyperliquidExchangeResponse::Status {
2413                status,
2414                response: error_data,
2415            } => Err(Error::bad_request(format!(
2416                "Modify order failed: status={status}, error={error_data}"
2417            ))),
2418            HyperliquidExchangeResponse::Error { error } => {
2419                Err(Error::bad_request(format!("Modify order error: {error}")))
2420            }
2421        }
2422    }
2423
2424    /// Arms, replaces, or clears the account-wide scheduled cancellation of all open orders.
2425    ///
2426    /// `time` is a Unix timestamp in milliseconds, at least five seconds after the local
2427    /// clock when called. `None` clears the schedule. Allow extra time for rate limiting,
2428    /// network latency, and clock skew. The venue can still reject a delayed request.
2429    /// The schedule remains at the venue after disconnect or process exit; this method
2430    /// does not start a refresh loop or close positions.
2431    /// Convert Nautilus nanosecond timestamps to milliseconds before passing them here.
2432    /// The venue requires $1,000,000 trading volume and permits at most ten schedule triggers
2433    /// per day, resetting the trigger count at 00:00 UTC.
2434    ///
2435    /// # Errors
2436    ///
2437    /// Returns an error if:
2438    /// - The timestamp is less than five seconds ahead of the local clock.
2439    /// - Credentials are missing or the request fails.
2440    /// - The venue rejects the action or returns an unexpected acknowledgement.
2441    pub async fn schedule_cancel(&self, time: Option<u64>) -> Result<()> {
2442        if let Some(time) = time {
2443            validate_schedule_cancel_time(time, self.clock.get_time_ms())?;
2444        }
2445
2446        let action = HyperliquidExchangeAction::ScheduleCancel { time };
2447        let response = self.inner.post_action_exec(&action).await?;
2448        match response {
2449            HyperliquidExchangeResponse::Status { status, response }
2450                if status == RESPONSE_STATUS_OK =>
2451            {
2452                let data = serde_json::from_value::<HyperliquidExchangeResponseData>(response)
2453                    .map_err(Error::Serde)?;
2454
2455                if matches!(data, HyperliquidExchangeResponseData::Default) {
2456                    Ok(())
2457                } else {
2458                    Err(Error::bad_request(
2459                        "Unexpected schedule cancel acknowledgement",
2460                    ))
2461                }
2462            }
2463            response => Err(Error::bad_request(format!(
2464                "Schedule cancel failed: {response:?}"
2465            ))),
2466        }
2467    }
2468
2469    /// Split an HIP-4 outcome's quote tokens into matched Yes and No side tokens.
2470    ///
2471    /// Submits a `userOutcome` exchange action with the `splitOutcome` operation:
2472    /// debits `amount` quote tokens and credits `amount` Yes plus `amount`
2473    /// No side tokens for the given `outcome` index. Ordinary directional
2474    /// buys and sells on outcome instruments go through the standard order path
2475    /// without calling this; the action is for dual-side market making and
2476    /// inventory creation.
2477    ///
2478    /// # Errors
2479    ///
2480    /// Returns an error if credentials are missing, the venue rejects the
2481    /// action, or the response cannot be parsed.
2482    pub async fn submit_split_outcome(
2483        &self,
2484        outcome: u32,
2485        amount: Decimal,
2486    ) -> Result<HyperliquidExchangeResponse> {
2487        let action = HyperliquidExchangeAction::UserOutcome {
2488            op: HyperliquidExchangeUserOutcomeOp::SplitOutcome(
2489                HyperliquidExchangeSplitOutcomeParams { outcome, amount },
2490            ),
2491        };
2492        self.inner.post_action_exec(&action).await
2493    }
2494
2495    /// Merge matched Yes + No side-token pairs of an HIP-4 outcome back into quote tokens.
2496    ///
2497    /// Submits a `userOutcome` action with the `mergeOutcome` operation. Pass
2498    /// `amount = None` to merge the maximum mergeable balance (venue-side
2499    /// `null`).
2500    ///
2501    /// # Errors
2502    ///
2503    /// Returns an error if credentials are missing, the venue rejects the
2504    /// action, or the response cannot be parsed.
2505    pub async fn submit_merge_outcome(
2506        &self,
2507        outcome: u32,
2508        amount: Option<Decimal>,
2509    ) -> Result<HyperliquidExchangeResponse> {
2510        let action = HyperliquidExchangeAction::UserOutcome {
2511            op: HyperliquidExchangeUserOutcomeOp::MergeOutcome(
2512                HyperliquidExchangeMergeOutcomeParams { outcome, amount },
2513            ),
2514        };
2515        self.inner.post_action_exec(&action).await
2516    }
2517
2518    /// Merge `Yes` shares of every outcome in a multi-outcome question into quote tokens.
2519    ///
2520    /// Submits a `userOutcome` action with the `mergeQuestion` operation. Pass
2521    /// `amount = None` to merge the maximum balance.
2522    ///
2523    /// # Errors
2524    ///
2525    /// Returns an error if credentials are missing, the venue rejects the
2526    /// action, or the response cannot be parsed.
2527    pub async fn submit_merge_question(
2528        &self,
2529        question: u32,
2530        amount: Option<Decimal>,
2531    ) -> Result<HyperliquidExchangeResponse> {
2532        let action = HyperliquidExchangeAction::UserOutcome {
2533            op: HyperliquidExchangeUserOutcomeOp::MergeQuestion(
2534                HyperliquidExchangeMergeQuestionParams { question, amount },
2535            ),
2536        };
2537        self.inner.post_action_exec(&action).await
2538    }
2539
2540    /// Swap `No` shares of one outcome into `Yes` shares of every other outcome.
2541    ///
2542    /// Submits a `userOutcome` action with the `negateOutcome` operation. Both
2543    /// outcomes must belong to the same multi-outcome `question`.
2544    ///
2545    /// # Errors
2546    ///
2547    /// Returns an error if credentials are missing, the venue rejects the
2548    /// action, or the response cannot be parsed.
2549    pub async fn submit_negate_outcome(
2550        &self,
2551        question: u32,
2552        outcome: u32,
2553        amount: Decimal,
2554    ) -> Result<HyperliquidExchangeResponse> {
2555        let action = HyperliquidExchangeAction::UserOutcome {
2556            op: HyperliquidExchangeUserOutcomeOp::NegateOutcome(
2557                HyperliquidExchangeNegateOutcomeParams {
2558                    question,
2559                    outcome,
2560                    amount,
2561                },
2562            ),
2563        };
2564        self.inner.post_action_exec(&action).await
2565    }
2566
2567    /// Request order status reports for a user.
2568    ///
2569    /// Fetches frontend open orders from the default and all cached builder dexes when unfiltered,
2570    /// or from the dex selected by an instrument filter, then parses them into OrderStatusReports.
2571    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
2572    ///
2573    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
2574    /// will be created automatically.
2575    ///
2576    /// # Errors
2577    ///
2578    /// Returns an error if the API request fails, parsing fails, or a venue row cannot be resolved
2579    /// to an instrument or converted into a report (the snapshot is then incomplete and must not be
2580    /// treated as authoritative).
2581    pub async fn request_order_status_reports(
2582        &self,
2583        user: &str,
2584        instrument_id: Option<InstrumentId>,
2585    ) -> Result<Vec<OrderStatusReport>> {
2586        let dexes = self.reconciliation_dexes(instrument_id);
2587        let sweep = self
2588            .request_order_status_reports_for_dexes(user, instrument_id, &dexes)
2589            .await?;
2590
2591        if !sweep.complete {
2592            return Err(Error::bad_request(
2593                "Open-order snapshot incomplete: at least one venue row could not be decoded, resolved to an instrument, or converted into a report",
2594            ));
2595        }
2596
2597        Ok(sweep.reports)
2598    }
2599
2600    pub(crate) async fn request_order_status_reports_for_dexes(
2601        &self,
2602        user: &str,
2603        instrument_id: Option<InstrumentId>,
2604        dexes: &[Option<Ustr>],
2605    ) -> Result<ReportSweep<OrderStatusReport>> {
2606        if instrument_id.is_some_and(|id| !self.allows_instrument(id)) {
2607            return Err(Error::bad_request(
2608                "Instrument outside execution product scope",
2609            ));
2610        }
2611
2612        let account_id = self
2613            .account_id
2614            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
2615        let mut reports = Vec::new();
2616        let mut complete = true;
2617        let ts_init = self.clock.get_time_ns();
2618
2619        for dex in dexes {
2620            let response = self
2621                .info_frontend_open_orders_for_dex(user, dex.as_deref())
2622                .await?;
2623            let orders: Vec<serde_json::Value> = serde_json::from_value(response)
2624                .map_err(|e| Error::bad_request(format!("Failed to parse orders: {e}")))?;
2625
2626            for order_value in orders {
2627                let order: WsBasicOrderData = match serde_json::from_value(order_value) {
2628                    Ok(order) => order,
2629                    Err(e) => {
2630                        log::warn!("Failed to parse order: {e}");
2631                        complete = false;
2632                        continue;
2633                    }
2634                };
2635
2636                let product_type = self.product_type_for_venue_coin(&order.coin);
2637                if !self.allows_product(product_type) {
2638                    continue;
2639                }
2640
2641                let instrument =
2642                    match self.get_or_create_instrument(&order.coin, Some(product_type)) {
2643                        Some(instrument) => instrument,
2644                        // get_or_create_instrument warns with the coin
2645                        None => {
2646                            complete = false;
2647                            continue;
2648                        }
2649                    };
2650
2651                if instrument_id.is_some_and(|filter_id| instrument.id() != filter_id) {
2652                    continue;
2653                }
2654
2655                match parse_order_status_report_from_basic(
2656                    &order,
2657                    &HyperliquidOrderStatusEnum::Open,
2658                    &instrument,
2659                    account_id,
2660                    ts_init,
2661                ) {
2662                    Ok(report) => reports.push(report),
2663                    Err(e) => {
2664                        log::error!("Failed to parse order status report: {e}");
2665                        complete = false;
2666                    }
2667                }
2668            }
2669        }
2670
2671        Ok(ReportSweep { reports, complete })
2672    }
2673
2674    /// Request historical order status reports for a user.
2675    ///
2676    /// The venue bounds this endpoint to its 2,000 most recent historical
2677    /// orders. Mass-status reconciliation narrows these reports to venue order
2678    /// IDs represented by the retained fill window.
2679    ///
2680    /// # Errors
2681    ///
2682    /// Returns an error if the API request fails or a venue row cannot be resolved to an
2683    /// instrument or converted into a report (the snapshot is then incomplete and must not be
2684    /// treated as authoritative).
2685    pub async fn request_historical_order_status_reports(
2686        &self,
2687        user: &str,
2688        instrument_id: Option<InstrumentId>,
2689    ) -> Result<Vec<OrderStatusReport>> {
2690        let entries = self.info_historical_orders(user).await?;
2691        let sweep = self.historical_order_status_reports_from_response(entries, instrument_id)?;
2692
2693        if !sweep.complete {
2694            return Err(Error::bad_request(
2695                "Historical-order snapshot incomplete: at least one venue row could not be decoded, resolved to an instrument, or converted into a report",
2696            ));
2697        }
2698
2699        Ok(sweep.reports)
2700    }
2701
2702    pub(crate) fn historical_order_status_reports_from_response(
2703        &self,
2704        entries: Vec<HyperliquidOrderStatusEntry>,
2705        instrument_id: Option<InstrumentId>,
2706    ) -> Result<ReportSweep<OrderStatusReport>> {
2707        if instrument_id.is_some_and(|id| !self.allows_instrument(id)) {
2708            return Err(Error::bad_request(
2709                "Instrument outside execution product scope",
2710            ));
2711        }
2712
2713        let account_id = self
2714            .account_id
2715            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
2716        let mut reports = Vec::new();
2717        let mut complete = true;
2718        let ts_init = self.clock.get_time_ns();
2719
2720        for entry in entries {
2721            let product_type = self.product_type_for_venue_coin(&entry.order.coin);
2722            if !self.allows_product(product_type) {
2723                continue;
2724            }
2725
2726            let instrument =
2727                match self.get_or_create_instrument(&entry.order.coin, Some(product_type)) {
2728                    // get_or_create_instrument warns with the coin
2729                    Some(instrument) => instrument,
2730                    None => {
2731                        complete = false;
2732                        continue;
2733                    }
2734                };
2735
2736            if instrument_id.is_some_and(|filter_id| instrument.id() != filter_id) {
2737                continue;
2738            }
2739
2740            let label = entry.order.order_type.as_deref().unwrap_or_default();
2741            let tpsl = parse_trigger_order_type_label(label).map(|(tpsl, _)| tpsl);
2742            let is_market = label.ends_with("Market");
2743            let historical_order_type = match tpsl.as_ref() {
2744                Some(tpsl) => parse_trigger_order_type(is_market, tpsl),
2745                None if is_market => OrderType::Market,
2746                None => OrderType::Limit,
2747            };
2748            let order = WsBasicOrderData {
2749                coin: entry.order.coin,
2750                side: entry.order.side,
2751                limit_px: entry.order.limit_px,
2752                sz: entry.order.sz,
2753                oid: entry.order.oid,
2754                timestamp: entry.order.timestamp,
2755                orig_sz: entry.order.orig_sz,
2756                cloid: entry.order.cloid,
2757                tif: entry.order.tif,
2758                reduce_only: entry.order.reduce_only,
2759                trigger_px: entry
2760                    .order
2761                    .trigger_px
2762                    .filter(|price| *price != Decimal::ZERO),
2763                is_market: tpsl.is_some().then_some(is_market),
2764                tpsl,
2765                trigger_activated: None,
2766                trailing_stop: None,
2767                order_type: None,
2768            };
2769
2770            match parse_order_status_report_from_basic(
2771                &order,
2772                &entry.status,
2773                &instrument,
2774                account_id,
2775                ts_init,
2776            ) {
2777                Ok(mut report) => {
2778                    report.order_type = historical_order_type;
2779                    report.ts_last = UnixNanos::from(entry.status_timestamp * 1_000_000);
2780                    reports.push(report);
2781                }
2782                Err(e) => {
2783                    log::error!("Failed to parse historical order status report: {e}");
2784                    complete = false;
2785                }
2786            }
2787        }
2788
2789        Ok(ReportSweep {
2790            reports: deduplicate_historical_order_reports(reports),
2791            complete,
2792        })
2793    }
2794
2795    /// Request a single order status report by venue order ID.
2796    ///
2797    /// Queries `info_frontend_open_orders` and filters for the given oid so the
2798    /// result includes trigger metadata (trigger_px, tpsl, trailing_stop, etc.).
2799    /// Falls back to `info_order_status` when the order is no longer open.
2800    ///
2801    /// # Errors
2802    ///
2803    /// Returns an error if the API request fails, parsing fails, or the matched venue row cannot be
2804    /// resolved to an instrument or converted into a report. A genuinely absent order returns
2805    /// `Ok(None)`.
2806    pub async fn request_order_status_report(
2807        &self,
2808        user: &str,
2809        oid: u64,
2810    ) -> Result<Option<OrderStatusReport>> {
2811        let account_id = self
2812            .account_id
2813            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
2814
2815        let ts_init = self.clock.get_time_ns();
2816
2817        // Try open orders first (returns full WsBasicOrderData with trigger fields).
2818        // A transport error here must not abort the call: the oid fallback to
2819        // info_order_status below still covers closed orders, so a transient
2820        // frontendOpenOrders outage is downgraded to a warning.
2821        let orders: Vec<WsBasicOrderData> = match self.info_frontend_open_orders(user).await {
2822            Ok(response) => match serde_json::from_value(response) {
2823                Ok(v) => v,
2824                Err(e) => {
2825                    log::warn!("Failed to parse frontend open orders response: {e}");
2826                    Vec::new()
2827                }
2828            },
2829            Err(e) => {
2830                log::warn!(
2831                    "Failed to fetch frontendOpenOrders for oid {oid}: {e}; falling back to orderStatus"
2832                );
2833                Vec::new()
2834            }
2835        };
2836
2837        if let Some(order) = orders.into_iter().find(|o| o.oid == oid) {
2838            let product_type = self.product_type_for_venue_coin(&order.coin);
2839            if !self.allows_product(product_type) {
2840                return Err(Error::bad_request("Order outside execution product scope"));
2841            }
2842
2843            let instrument = match self.get_or_create_instrument(&order.coin, Some(product_type)) {
2844                Some(inst) => inst,
2845                None => {
2846                    return Err(Error::bad_request(format!(
2847                        "Failed to resolve instrument for open order oid {oid} with coin {}",
2848                        order.coin,
2849                    )));
2850                }
2851            };
2852
2853            let status = if order.trigger_activated == Some(true) {
2854                HyperliquidOrderStatusEnum::Triggered
2855            } else {
2856                HyperliquidOrderStatusEnum::Open
2857            };
2858
2859            return parse_order_status_report_from_basic(
2860                &order,
2861                &status,
2862                &instrument,
2863                account_id,
2864                ts_init,
2865            )
2866            .map(Some)
2867            .map_err(|e| {
2868                Error::bad_request(format!(
2869                    "Failed to parse order status report for oid {oid}: {e}"
2870                ))
2871            });
2872        }
2873
2874        // Order not in open set: query by oid (returns limited HyperliquidOrderInfo)
2875        let response = self.info_order_status(user, oid).await?;
2876        let entry = match response.into_order() {
2877            Some(e) => e,
2878            None => return Ok(None),
2879        };
2880
2881        self.order_status_report_from_entry(entry, account_id, ts_init)
2882            .map(Some)
2883    }
2884
2885    // Queries `orderStatus`, which also returns closed orders, unlike the open-order search
2886    pub(crate) async fn request_order_status_report_by_cloid(
2887        &self,
2888        user: &str,
2889        client_order_id: &ClientOrderId,
2890    ) -> Result<Option<OrderStatusReport>> {
2891        let account_id = self
2892            .account_id
2893            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
2894
2895        let ts_init = self.clock.get_time_ns();
2896
2897        let cloid = self
2898            .cached_client_order_id_cloid(client_order_id)
2899            .unwrap_or_else(|| Cloid::from_client_order_id(*client_order_id));
2900
2901        let response = self.inner.info_order_status_by_cloid(user, cloid).await?;
2902        let entry = match response.into_order() {
2903            Some(e) => e,
2904            None => return Ok(None),
2905        };
2906
2907        let mut report = self.order_status_report_from_entry(entry, account_id, ts_init)?;
2908        report.client_order_id = Some(*client_order_id);
2909        Ok(Some(report))
2910    }
2911
2912    fn order_status_report_from_entry(
2913        &self,
2914        entry: HyperliquidOrderStatusEntry,
2915        account_id: AccountId,
2916        ts_init: UnixNanos,
2917    ) -> Result<OrderStatusReport> {
2918        let oid = entry.order.oid;
2919        let product_type = self.product_type_for_venue_coin(&entry.order.coin);
2920        if !self.allows_product(product_type) {
2921            return Err(Error::bad_request("Order outside execution product scope"));
2922        }
2923
2924        let instrument = match self.get_or_create_instrument(&entry.order.coin, Some(product_type))
2925        {
2926            Some(inst) => inst,
2927            None => {
2928                return Err(Error::bad_request(format!(
2929                    "Failed to resolve instrument for order oid {oid} with coin {}",
2930                    entry.order.coin,
2931                )));
2932            }
2933        };
2934
2935        // The info_order_status endpoint returns limited HyperliquidOrderInfo
2936        // without trigger fields (trigger_px, tpsl, is_market, trailing_stop).
2937        // Closed trigger orders will report as Limit type. This is an exchange
2938        // API limitation: trigger metadata is only available on open orders.
2939        // The reduce-only flag is carried through so reconciliation can clamp a
2940        // reduce-only fill to its fills.
2941        let basic = WsBasicOrderData {
2942            coin: entry.order.coin,
2943            side: entry.order.side,
2944            limit_px: entry.order.limit_px,
2945            sz: entry.order.sz,
2946            oid: entry.order.oid,
2947            timestamp: entry.order.timestamp,
2948            orig_sz: entry.order.orig_sz,
2949            cloid: entry.order.cloid,
2950            tif: None,
2951            reduce_only: entry.order.reduce_only,
2952            trigger_px: None,
2953            is_market: None,
2954            tpsl: None,
2955            trigger_activated: None,
2956            trailing_stop: None,
2957            order_type: None,
2958        };
2959
2960        let mut report = parse_order_status_report_from_basic(
2961            &basic,
2962            &entry.status,
2963            &instrument,
2964            account_id,
2965            ts_init,
2966        )
2967        .map_err(|e| {
2968            Error::bad_request(format!(
2969                "Failed to parse order status report for oid {oid}: {e}"
2970            ))
2971        })?;
2972
2973        // Use status_timestamp for ts_last when available (more accurate
2974        // than the order creation timestamp for filled/canceled orders)
2975        if entry.status_timestamp > 0 {
2976            report.ts_last = UnixNanos::from(entry.status_timestamp * 1_000_000);
2977        }
2978
2979        Ok(report)
2980    }
2981
2982    /// Request a single order status report by client order ID.
2983    ///
2984    /// Searches `info_frontend_open_orders` for an order whose cloid matches the
2985    /// cached CLOID or the generated CLOID. Only finds open orders.
2986    ///
2987    /// # Errors
2988    ///
2989    /// Returns an error if the API request fails, the response cannot be decoded, or the matched
2990    /// venue row cannot be resolved to an instrument or converted into a report. A genuinely
2991    /// absent order returns `Ok(None)`.
2992    pub async fn request_order_status_report_by_client_order_id(
2993        &self,
2994        user: &str,
2995        client_order_id: &ClientOrderId,
2996    ) -> Result<Option<OrderStatusReport>> {
2997        let account_id = self
2998            .account_id
2999            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
3000
3001        let ts_init = self.clock.get_time_ns();
3002
3003        let cached_cloid_hex = self
3004            .cached_client_order_id_cloid(client_order_id)
3005            .map(|cloid| cloid.to_hex());
3006        let cloid = Cloid::from_client_order_id(*client_order_id);
3007        let cloid_hex = cloid.to_hex();
3008
3009        let response = self.info_frontend_open_orders(user).await?;
3010
3011        let orders: Vec<WsBasicOrderData> = serde_json::from_value(response).map_err(|e| {
3012            Error::bad_request(format!("Failed to parse open orders response: {e}"))
3013        })?;
3014
3015        let order = match orders.into_iter().find(|o| {
3016            o.cloid
3017                .as_ref()
3018                .is_some_and(|c| cached_cloid_hex.as_ref() == Some(c) || c == &cloid_hex)
3019        }) {
3020            Some(o) => o,
3021            None => return Ok(None),
3022        };
3023
3024        let product_type = self.product_type_for_venue_coin(&order.coin);
3025        if !self.allows_product(product_type) {
3026            return Err(Error::bad_request("Order outside execution product scope"));
3027        }
3028
3029        let instrument = match self.get_or_create_instrument(&order.coin, Some(product_type)) {
3030            Some(inst) => inst,
3031            None => {
3032                return Err(Error::bad_request(format!(
3033                    "Failed to resolve instrument for open order with cloid {cloid_hex} and coin {}",
3034                    order.coin,
3035                )));
3036            }
3037        };
3038
3039        let status = if order.trigger_activated == Some(true) {
3040            HyperliquidOrderStatusEnum::Triggered
3041        } else {
3042            HyperliquidOrderStatusEnum::Open
3043        };
3044
3045        let mut report =
3046            parse_order_status_report_from_basic(&order, &status, &instrument, account_id, ts_init)
3047                .map_err(|e| {
3048                    Error::bad_request(format!(
3049                        "Failed to parse order status report for cloid {cloid_hex}: {e}"
3050                    ))
3051                })?;
3052
3053        report.client_order_id = Some(*client_order_id);
3054        Ok(Some(report))
3055    }
3056
3057    /// Request fill reports for a user.
3058    ///
3059    /// Fetches user fills via `info_user_fills` and parses them into FillReports.
3060    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
3061    ///
3062    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
3063    /// will be created automatically.
3064    ///
3065    /// # Errors
3066    ///
3067    /// Returns an error if the API request fails, parsing fails, or a venue row cannot be resolved
3068    /// to an instrument or converted into a report (the snapshot is then incomplete and must not be
3069    /// treated as authoritative).
3070    ///
3071    /// Returns an error if `account_id` is not set on the client.
3072    pub async fn request_fill_reports(
3073        &self,
3074        user: &str,
3075        instrument_id: Option<InstrumentId>,
3076    ) -> Result<Vec<FillReport>> {
3077        let fills_response = self.info_user_fills(user).await?;
3078        let sweep = self.fill_reports_from_response(fills_response, instrument_id)?;
3079
3080        if !sweep.complete {
3081            return Err(Error::bad_request(
3082                "Fill snapshot incomplete: at least one venue row could not be decoded, resolved to an instrument, or converted into a report",
3083            ));
3084        }
3085
3086        Ok(sweep.reports)
3087    }
3088
3089    pub(crate) fn fill_reports_from_response(
3090        &self,
3091        fills_response: HyperliquidFills,
3092        instrument_id: Option<InstrumentId>,
3093    ) -> Result<ReportSweep<FillReport>> {
3094        if instrument_id.is_some_and(|id| !self.allows_instrument(id)) {
3095            return Err(Error::bad_request(
3096                "Instrument outside execution product scope",
3097            ));
3098        }
3099
3100        let account_id = self
3101            .account_id
3102            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
3103
3104        let mut reports = Vec::new();
3105        let mut complete = true;
3106        let ts_init = self.clock.get_time_ns();
3107
3108        for fill in fills_response {
3109            let product_type = self.product_type_for_venue_coin(&fill.coin);
3110            if !self.allows_product(product_type) {
3111                continue;
3112            }
3113
3114            // Get instrument from cache or create synthetic for vault tokens
3115            let instrument = match self.get_or_create_instrument(&fill.coin, Some(product_type)) {
3116                Some(inst) => inst,
3117                // get_or_create_instrument warns with the coin
3118                None => {
3119                    complete = false;
3120                    continue;
3121                }
3122            };
3123
3124            // Filter by instrument_id if specified
3125            if let Some(filter_id) = instrument_id
3126                && instrument.id() != filter_id
3127            {
3128                continue;
3129            }
3130
3131            // Parse to FillReport
3132            match parse_fill_report(&fill, &instrument, account_id, ts_init) {
3133                Ok(report) => reports.push(report),
3134                Err(e) => {
3135                    log::error!("Failed to parse fill report: {e}");
3136                    complete = false;
3137                }
3138            }
3139        }
3140
3141        Ok(ReportSweep { reports, complete })
3142    }
3143
3144    /// Request position status reports for a user.
3145    ///
3146    /// Fetches clearinghouse state from the default and all cached builder dexes when unfiltered,
3147    /// plus spot clearinghouse state, then returns the union of perp asset positions (short/long
3148    /// with PnL) and spot holdings (long only). This method requires instruments to be added to the
3149    /// client cache via `cache_instrument()`.
3150    ///
3151    /// When `instrument_id` resolves to a specific product type, the opposite
3152    /// product's endpoint is skipped to avoid wasted round trips and make
3153    /// filtered queries independent of the unused endpoint's availability.
3154    /// HIP-4 outcomes live in `spotClearinghouseState`, so an outcome filter
3155    /// is routed like a spot filter (perp leg skipped).
3156    ///
3157    /// For vault tokens (starting with "vntls:") that are not in the cache,
3158    /// synthetic instruments will be created automatically.
3159    ///
3160    /// # Errors
3161    ///
3162    /// Returns an error if any clearinghouse request fails (when that product or dex is in scope),
3163    /// parsing fails, or a venue row cannot be resolved to an instrument or converted into a
3164    /// report (the snapshot is then incomplete and must not be treated as authoritative).
3165    ///
3166    /// Returns an error if `account_id` has not been set on the client.
3167    pub async fn request_position_status_reports(
3168        &self,
3169        user: &str,
3170        instrument_id: Option<InstrumentId>,
3171    ) -> Result<Vec<PositionStatusReport>> {
3172        let dexes = self.reconciliation_dexes(instrument_id);
3173        let sweep = self
3174            .request_position_status_reports_for_dexes(user, instrument_id, &dexes)
3175            .await?;
3176
3177        if !sweep.complete {
3178            return Err(Error::bad_request(
3179                "Position snapshot incomplete: at least one venue row could not be decoded, resolved to an instrument, or converted into a report",
3180            ));
3181        }
3182
3183        Ok(sweep.reports)
3184    }
3185
3186    pub(crate) async fn request_position_status_reports_for_dexes(
3187        &self,
3188        user: &str,
3189        instrument_id: Option<InstrumentId>,
3190        dexes: &[Option<Ustr>],
3191    ) -> Result<ReportSweep<PositionStatusReport>> {
3192        let account_id = self
3193            .account_id
3194            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
3195
3196        let filter_product = instrument_id
3197            .and_then(|id| HyperliquidProductType::from_symbol(id.symbol.as_str()).ok());
3198
3199        if instrument_id.is_some_and(|id| !self.allows_instrument(id)) {
3200            return Err(Error::bad_request(
3201                "Instrument outside execution product scope",
3202            ));
3203        }
3204
3205        let fetch_perp = self.allows_product(HyperliquidProductType::Perp)
3206            && !matches!(
3207                filter_product,
3208                Some(HyperliquidProductType::Spot | HyperliquidProductType::Outcome)
3209            );
3210        let fetch_spot = filter_product != Some(HyperliquidProductType::Perp)
3211            && (self.allows_product(HyperliquidProductType::Spot)
3212                || self.allows_product(HyperliquidProductType::Outcome));
3213
3214        let mut reports = Vec::new();
3215        let mut complete = true;
3216        let ts_init = self.clock.get_time_ns();
3217
3218        if !fetch_perp {
3219            return self
3220                .request_spot_position_status_reports_sweep(user, instrument_id)
3221                .await;
3222        }
3223
3224        for dex in dexes {
3225            let state_response = self
3226                .info_clearinghouse_state_for_dex(user, dex.as_deref())
3227                .await?;
3228            let asset_positions: Vec<serde_json::Value> = state_response
3229                .get("assetPositions")
3230                .and_then(|value| value.as_array())
3231                .ok_or_else(|| {
3232                    Error::bad_request("assetPositions not found in clearinghouse state")
3233                })?
3234                .clone();
3235
3236            for position_value in asset_positions {
3237                let coin = position_value
3238                    .get("position")
3239                    .and_then(|position| position.get("coin"))
3240                    .and_then(|coin| coin.as_str())
3241                    .ok_or_else(|| Error::bad_request("coin not found in position"))?;
3242
3243                let instrument = match self
3244                    .get_or_create_instrument(&Ustr::from(coin), Some(HyperliquidProductType::Perp))
3245                {
3246                    Some(instrument) => instrument,
3247                    // get_or_create_instrument warns with the coin
3248                    None => {
3249                        complete = false;
3250                        continue;
3251                    }
3252                };
3253
3254                if instrument_id.is_some_and(|filter_id| instrument.id() != filter_id) {
3255                    continue;
3256                }
3257
3258                match parse_position_status_report(
3259                    &position_value,
3260                    &instrument,
3261                    account_id,
3262                    ts_init,
3263                ) {
3264                    Ok(report) => reports.push(report),
3265                    Err(e) => {
3266                        log::error!("Failed to parse position status report: {e}");
3267                        complete = false;
3268                    }
3269                }
3270            }
3271        }
3272
3273        // Spot positions are part of the report truth; propagate fetch errors
3274        // rather than silently omitting spot holdings from reconciliation.
3275        if fetch_spot {
3276            let spot_sweep = self
3277                .request_spot_position_status_reports_sweep(user, instrument_id)
3278                .await?;
3279            reports.extend(spot_sweep.reports);
3280            complete &= spot_sweep.complete;
3281        }
3282
3283        Ok(ReportSweep { reports, complete })
3284    }
3285
3286    /// Request account state (balances and margins) for a user.
3287    ///
3288    /// Fetches perp and spot clearinghouse state and the account abstraction mode from
3289    /// Hyperliquid and merges them into a single [`AccountState`]. For unified and portfolio
3290    /// margin accounts, balances come from the spot state alone and spot USDC `hold` is the
3291    /// account-wide margin. Otherwise USDC comes from the perp margin summary only when that
3292    /// summary reflects non-zero collateral, margin used, or withdrawable balance; if the
3293    /// summary is absent or zeroed, spot USDC is used instead. Non-USDC tokens are always
3294    /// appended from the spot balances. Spot tokens the venue lists at zero are reported at
3295    /// zero, and USDC is reported at zero when there is no USDC balance, so a previous balance
3296    /// is cleared. On accounts without spot collateral this needs a perp summary in the response.
3297    ///
3298    /// # Errors
3299    ///
3300    /// Returns an error if `account_id` is not set, or if the perp clearinghouse, spot
3301    /// clearinghouse, or user abstraction request fails. Spot and abstraction failures are
3302    /// propagated so the caller sees real API errors instead of a silently truncated or
3303    /// misread snapshot.
3304    pub async fn request_account_state(&self, user: &str) -> Result<AccountState> {
3305        let account_id = self
3306            .account_id
3307            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
3308        let state_response = self.info_clearinghouse_state(user).await?;
3309        let ts_init = self.clock.get_time_ns();
3310
3311        log::trace!("Clearinghouse state response: {state_response}");
3312
3313        let perp_state: ClearinghouseState = serde_json::from_value(state_response.clone())
3314            .map_err(|e| {
3315                log::error!("Failed to parse clearinghouse state: {e}");
3316                log::debug!("Raw response: {state_response}");
3317                Error::bad_request(format!("Failed to parse clearinghouse state: {e}"))
3318            })?;
3319
3320        // Spot must not be silently dropped: a 429 or parse error would
3321        // otherwise make non-USDC holdings look like they vanished.
3322        let spot_response = self.info_spot_clearinghouse_state(user).await?;
3323        let spot_state: SpotClearinghouseState = serde_json::from_value(spot_response.clone())
3324            .map_err(|e| {
3325                log::error!("Failed to parse spot clearinghouse state: {e}");
3326                log::debug!("Raw spot response: {spot_response}");
3327                Error::bad_request(format!("Failed to parse spot clearinghouse state: {e}"))
3328            })?;
3329
3330        // Without the mode a unified account would be read from the default-dex perp summary.
3331        let abstraction = self.info_user_abstraction(user).await?;
3332
3333        let (balances, margins) =
3334            parse_combined_account_balances_and_margins(&perp_state, &spot_state, abstraction)
3335                .map_err(|e| Error::decode(e.to_string()))?;
3336
3337        Ok(AccountState::new(
3338            account_id,
3339            AccountType::Margin,
3340            balances,
3341            margins,
3342            true, // reported
3343            UUID4::new(),
3344            ts_init,
3345            ts_init,
3346            None,
3347        ))
3348    }
3349
3350    /// Request spot token balances for a user.
3351    ///
3352    /// Fetches `spotClearinghouseState` and returns one [`AccountBalance`] per
3353    /// non-zero token. USDC is included as a separate balance entry when present;
3354    /// callers that also report perp margin state must dedupe currencies before
3355    /// emitting an [`AccountState`].
3356    ///
3357    /// # Errors
3358    ///
3359    /// Returns an error if the API request fails or the response cannot be parsed.
3360    pub async fn request_spot_balances(&self, user: &str) -> Result<Vec<AccountBalance>> {
3361        let response = self.info_spot_clearinghouse_state(user).await?;
3362
3363        log::trace!("Spot clearinghouse state response: {response}");
3364
3365        let state: SpotClearinghouseState =
3366            serde_json::from_value(response.clone()).map_err(|e| {
3367                log::error!("Failed to parse spot clearinghouse state: {e}");
3368                log::debug!("Raw response: {response}");
3369                Error::bad_request(format!("Failed to parse spot clearinghouse state: {e}"))
3370            })?;
3371
3372        parse_spot_account_balances(&state).map_err(|e| Error::decode(e.to_string()))
3373    }
3374
3375    /// Request spot position status reports for a user.
3376    ///
3377    /// Each non-zero spot balance is reported as a Long position against its
3378    /// `{BASE}-{QUOTE}-SPOT` instrument. HIP-4 outcome side tokens arrive on
3379    /// this same endpoint with `coin` set to the `+<encoding>` token form;
3380    /// those balances are resolved against the matching Outcome instrument so
3381    /// outcome holdings surface as positions through the standard reconcile
3382    /// path.
3383    ///
3384    /// # Errors
3385    ///
3386    /// Returns an error if `account_id` has not been set, the API request fails,
3387    /// or a non-zero balance cannot be resolved to an instrument or converted
3388    /// into a report (the snapshot is then incomplete and must not be treated
3389    /// as authoritative).
3390    pub async fn request_spot_position_status_reports(
3391        &self,
3392        user: &str,
3393        instrument_id: Option<InstrumentId>,
3394    ) -> Result<Vec<PositionStatusReport>> {
3395        let sweep = self
3396            .request_spot_position_status_reports_sweep(user, instrument_id)
3397            .await?;
3398
3399        if !sweep.complete {
3400            return Err(Error::bad_request(
3401                "Spot position snapshot incomplete: at least one venue row could not be decoded, resolved to an instrument, or converted into a report",
3402            ));
3403        }
3404
3405        Ok(sweep.reports)
3406    }
3407
3408    pub(crate) async fn request_spot_position_status_reports_sweep(
3409        &self,
3410        user: &str,
3411        instrument_id: Option<InstrumentId>,
3412    ) -> Result<ReportSweep<PositionStatusReport>> {
3413        if instrument_id.is_some_and(|id| !self.allows_instrument(id)) {
3414            return Err(Error::bad_request(
3415                "Instrument outside execution product scope",
3416            ));
3417        }
3418
3419        let account_id = self
3420            .account_id
3421            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
3422        let response = self.info_spot_clearinghouse_state(user).await?;
3423
3424        let state: SpotClearinghouseState = serde_json::from_value(response).map_err(|e| {
3425            log::error!("Failed to parse spot clearinghouse state: {e}");
3426            Error::bad_request(format!("Failed to parse spot clearinghouse state: {e}"))
3427        })?;
3428
3429        let ts_init = self.clock.get_time_ns();
3430        let mut reports = Vec::with_capacity(state.balances.len());
3431        let mut complete = true;
3432
3433        for balance in &state.balances {
3434            if balance.total.is_zero() {
3435                continue;
3436            }
3437
3438            // USDC is the universal quote for Hyperliquid spot: it funds every
3439            // pair and has no `USDC-*-SPOT` instrument. Skip it so the loop
3440            // does not trigger a misleading cache-miss WARN. Revisit if
3441            // Hyperliquid ever introduces a USDC-base spot pair.
3442            if balance.coin == "USDC" {
3443                continue;
3444            }
3445
3446            let product_type = match HyperliquidProductType::from_symbol(balance.coin.as_str()) {
3447                Ok(HyperliquidProductType::Outcome) => HyperliquidProductType::Outcome,
3448                _ => HyperliquidProductType::Spot,
3449            };
3450
3451            if !self.allows_product(product_type) {
3452                continue;
3453            }
3454
3455            let instrument = match self.get_or_create_instrument(&balance.coin, Some(product_type))
3456            {
3457                Some(inst) => inst,
3458                // get_or_create_instrument warns with the coin
3459                None => {
3460                    complete = false;
3461                    continue;
3462                }
3463            };
3464
3465            if let Some(filter_id) = instrument_id
3466                && instrument.id() != filter_id
3467            {
3468                continue;
3469            }
3470
3471            match parse_spot_position_status_report(balance, &instrument, account_id, ts_init) {
3472                Ok(report) => reports.push(report),
3473                Err(e) => {
3474                    log::error!(
3475                        "Failed to parse spot position status report for {}: {e}",
3476                        balance.coin,
3477                    );
3478                    complete = false;
3479                }
3480            }
3481        }
3482
3483        Ok(ReportSweep { reports, complete })
3484    }
3485
3486    /// Request historical bars for an instrument.
3487    ///
3488    /// Fetches candle data from the Hyperliquid API and converts it to Nautilus bars.
3489    /// Incomplete bars (where end_timestamp >= current time) are filtered out.
3490    ///
3491    /// # Errors
3492    ///
3493    /// Returns an error if:
3494    /// - The instrument is not found in cache.
3495    /// - The bar aggregation is unsupported by Hyperliquid.
3496    /// - The API request fails.
3497    /// - Parsing fails.
3498    ///
3499    /// # References
3500    ///
3501    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candles-snapshot>
3502    pub async fn request_bars(
3503        &self,
3504        bar_type: BarType,
3505        start: Option<jiff::Timestamp>,
3506        end: Option<jiff::Timestamp>,
3507        limit: Option<u32>,
3508    ) -> Result<Vec<Bar>> {
3509        let instrument_id = bar_type.instrument_id();
3510        let symbol = instrument_id.symbol;
3511
3512        let product_type = HyperliquidProductType::from_symbol(symbol.as_str()).ok();
3513
3514        // `cache_alias_for_symbol` mirrors how `cache_instrument` stores the
3515        // secondary key (token form `+<encoding>` for outcomes, leading
3516        // segment for perps / spots), so this lookup stays in sync.
3517        let alias = cache_alias_for_symbol(symbol.as_str())
3518            .map(|alias| Ustr::from(alias.as_str()))
3519            .ok_or_else(|| Error::bad_request("Invalid instrument symbol"))?;
3520
3521        let instrument = self
3522            .get_or_create_instrument(&alias, product_type)
3523            .ok_or_else(|| {
3524                Error::bad_request(InstrumentLookupError::not_found(instrument_id).to_string())
3525            })?;
3526
3527        // Use raw_symbol which has the correct Hyperliquid API format:
3528        // - Perps: base currency (e.g., "BTC")
3529        // - Spot PURR: slash format (e.g., "PURR/USDC")
3530        // - Spot others: @{index} format (e.g., "@107")
3531        let coin = instrument.raw_symbol().inner();
3532
3533        let price_precision = instrument.price_precision();
3534        let size_precision = instrument.size_precision();
3535
3536        let interval =
3537            bar_type_to_interval(&bar_type).map_err(|e| Error::bad_request(e.to_string()))?;
3538
3539        // Hyperliquid uses millisecond timestamps
3540        let now = jiff::Timestamp::now();
3541        let end_time = end.unwrap_or(now).as_millisecond() as u64;
3542        let start_time = if let Some(start) = start {
3543            start.as_millisecond() as u64
3544        } else {
3545            // Default to 1000 bars before end_time
3546            let spec = bar_type.spec();
3547            let step_ms = match spec.aggregation {
3548                BarAggregation::Minute => spec.step.get() as u64 * 60_000,
3549                BarAggregation::Hour => spec.step.get() as u64 * 3_600_000,
3550                BarAggregation::Day => spec.step.get() as u64 * 86_400_000,
3551                BarAggregation::Week => spec.step.get() as u64 * 604_800_000,
3552                BarAggregation::Month => spec.step.get() as u64 * 2_592_000_000,
3553                _ => 60_000,
3554            };
3555            end_time.saturating_sub(1000 * step_ms)
3556        };
3557
3558        let candles = self
3559            .info_candle_snapshot(coin.as_str(), interval, start_time, end_time)
3560            .await?;
3561
3562        // Filter out incomplete bars where end_timestamp >= current time
3563        let now_ms = now.as_millisecond() as u64;
3564
3565        let mut bars: Vec<Bar> = candles
3566            .iter()
3567            .filter(|candle| candle.end_timestamp < now_ms)
3568            .enumerate()
3569            .filter_map(|(i, candle)| {
3570                candle_to_bar(candle, bar_type, price_precision, size_precision)
3571                    .map_err(|e| {
3572                        log::error!("Failed to convert candle {i} to bar: {candle:?} error: {e}");
3573                        e
3574                    })
3575                    .ok()
3576            })
3577            .collect();
3578
3579        // 0 means no limit
3580        if let Some(limit) = limit
3581            && limit > 0
3582            && bars.len() > limit as usize
3583        {
3584            bars.truncate(limit as usize);
3585        }
3586
3587        log::debug!(
3588            "Received {} bars for {} (filtered {} incomplete)",
3589            bars.len(),
3590            bar_type,
3591            candles.len() - bars.len()
3592        );
3593        Ok(bars)
3594    }
3595
3596    /// Request the recent public trade snapshot for an instrument.
3597    ///
3598    /// Hyperliquid's `recentTrades` endpoint is a bounded newest-first snapshot,
3599    /// rather than a range-query endpoint. The returned trades are normalized to
3600    /// ascending event time and then constrained to the requested window.
3601    ///
3602    /// A self-hosted node without the indexer responds with HTTP 422. This is
3603    /// treated as no available coverage so requests can still complete.
3604    pub async fn request_public_trades(
3605        &self,
3606        instrument_id: InstrumentId,
3607        start: Option<jiff::Timestamp>,
3608        end: Option<jiff::Timestamp>,
3609        limit: Option<usize>,
3610    ) -> Result<Vec<HyperliquidPublicTrade>> {
3611        let symbol = instrument_id.symbol;
3612        let product_type = HyperliquidProductType::from_symbol(symbol.as_str()).ok();
3613        let alias = cache_alias_for_symbol(symbol.as_str())
3614            .map(|alias| Ustr::from(alias.as_str()))
3615            .ok_or_else(|| Error::bad_request("Invalid instrument symbol"))?;
3616        let instrument = self
3617            .get_or_create_instrument(&alias, product_type)
3618            .ok_or_else(|| {
3619                Error::bad_request(InstrumentLookupError::not_found(instrument_id).to_string())
3620            })?;
3621
3622        let raw_trades = match self
3623            .info_recent_trades(instrument.raw_symbol().as_ref())
3624            .await
3625        {
3626            Ok(trades) => trades,
3627            Err(e) if e.is_unprocessable_entity() => {
3628                log::warn!(
3629                    "Recent public trades endpoint unavailable for {instrument_id} \
3630                     (requires the Hyperliquid indexer); returning empty response"
3631                );
3632                Vec::new()
3633            }
3634            Err(e) => return Err(e),
3635        };
3636
3637        let mut trades: Vec<HyperliquidPublicTrade> = raw_trades
3638            .iter()
3639            .filter_map(|raw| match parse_recent_public_trade(raw, &instrument) {
3640                Ok(trade) => Some(trade),
3641                Err(e) => {
3642                    log::warn!("Skipping recent public trade for {instrument_id}: {e}");
3643                    None
3644                }
3645            })
3646            .collect();
3647        trades.sort_by_key(|trade| trade.ts_event);
3648
3649        Ok(filter_recent_public_trades(
3650            trades,
3651            datetime_to_unix_nanos(start),
3652            datetime_to_unix_nanos(end),
3653            limit.filter(|limit| *limit > 0),
3654            instrument_id,
3655        ))
3656    }
3657
3658    /// Requests funding rate history for a perpetual, paging past the venue's
3659    /// per-response cap.
3660    ///
3661    /// With `start`, returns up to `limit` rows from `start` onward. Without it,
3662    /// returns the most recent `limit` rows (default seven days).
3663    ///
3664    /// # Errors
3665    ///
3666    /// Returns an error if the instrument is not a perpetual, `start` is not
3667    /// before `end`, or a request fails.
3668    pub async fn request_funding_rates(
3669        &self,
3670        instrument: &InstrumentAny,
3671        start: Option<jiff::Timestamp>,
3672        end: Option<jiff::Timestamp>,
3673        limit: Option<usize>,
3674    ) -> Result<Vec<FundingRateUpdate>> {
3675        let instrument_id = instrument.id();
3676
3677        if !matches!(instrument, InstrumentAny::CryptoPerpetual(_)) {
3678            return Err(Error::bad_request(format!(
3679                "funding rates are only available for perpetual instruments: {instrument_id}",
3680            )));
3681        }
3682
3683        let coin = instrument.raw_symbol().inner();
3684
3685        if let (Some(start), Some(end)) = (start, end)
3686            && start >= end
3687        {
3688            return Err(Error::bad_request(format!(
3689                "invalid funding request range: start={start}, end={end}",
3690            )));
3691        }
3692
3693        let now = jiff::Timestamp::now();
3694        let end = end.unwrap_or(now).min(now);
3695
3696        if let Some(start) = start
3697            && start >= end
3698        {
3699            return Ok(Vec::new());
3700        }
3701
3702        let requested_limit = limit.filter(|n| *n > 0);
3703        let target_limit = requested_limit.unwrap_or(DEFAULT_FUNDING_RATES_LIMIT);
3704        let start_was_unspecified = start.is_none();
3705        let end_ms = end.as_millisecond().max(0) as u64;
3706
3707        let start_ms = start.map_or_else(
3708            || {
3709                let lookback_rows = target_limit.saturating_add(1) as u64;
3710                // Hyperliquid funding interval is 1h
3711                end_ms.saturating_sub((60 * 60 * 1_000_u64).saturating_mul(lookback_rows))
3712            },
3713            |dt| dt.as_millisecond().max(0) as u64,
3714        );
3715
3716        let mut funding_rates = Vec::new();
3717        let mut cursor_ms = start_ms;
3718
3719        'pages: while cursor_ms <= end_ms {
3720            let entries = self
3721                .info_funding_history(coin.as_str(), cursor_ms, Some(end_ms))
3722                .await?;
3723            let Some(last_time_ms) = entries.iter().map(|entry| entry.time).max() else {
3724                break;
3725            };
3726
3727            let mut page: Vec<FundingRateUpdate> = entries
3728                .iter()
3729                .filter(|entry| (cursor_ms..=end_ms).contains(&entry.time))
3730                .map(|entry| funding_entry_to_update(entry, instrument_id))
3731                .collect();
3732            page.sort_by_key(|rate| rate.ts_event);
3733
3734            for update in page {
3735                if funding_rates
3736                    .last()
3737                    .is_some_and(|last: &FundingRateUpdate| last.ts_event == update.ts_event)
3738                {
3739                    continue;
3740                }
3741                funding_rates.push(update);
3742
3743                if !start_was_unspecified
3744                    && requested_limit.is_some_and(|limit| funding_rates.len() >= limit)
3745                {
3746                    break 'pages;
3747                }
3748            }
3749
3750            if entries.len() < HYPERLIQUID_FUNDING_HISTORY_MAX_LIMIT {
3751                break;
3752            }
3753
3754            // `startTime` is inclusive, so step past the last row
3755            let next_cursor_ms = last_time_ms.saturating_add(1);
3756            if next_cursor_ms <= cursor_ms {
3757                break;
3758            }
3759            cursor_ms = next_cursor_ms;
3760        }
3761
3762        if start_was_unspecified && funding_rates.len() > target_limit {
3763            funding_rates = funding_rates.split_off(funding_rates.len() - target_limit);
3764        }
3765
3766        Ok(funding_rates)
3767    }
3768
3769    /// Submits an order to the exchange.
3770    ///
3771    /// # Errors
3772    ///
3773    /// Returns an error if credentials are missing, order validation fails, serialization fails,
3774    /// or the API returns an error.
3775    #[expect(clippy::too_many_arguments)]
3776    pub async fn submit_order(
3777        &self,
3778        instrument_id: InstrumentId,
3779        client_order_id: ClientOrderId,
3780        order_side: OrderSide,
3781        order_type: OrderType,
3782        quantity: Quantity,
3783        time_in_force: TimeInForce,
3784        price: Option<Price>,
3785        trigger_price: Option<Price>,
3786        post_only: bool,
3787        reduce_only: bool,
3788    ) -> Result<OrderStatusReport> {
3789        let symbol = instrument_id.symbol.inner();
3790        let asset = self.get_asset_index_for_symbol(symbol).ok_or_else(|| {
3791            Error::bad_request(format!(
3792                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
3793            ))
3794        })?;
3795
3796        let is_buy = matches!(order_side, OrderSide::Buy);
3797        let price_precision = self.get_price_precision_for_symbol(symbol);
3798
3799        let price_decimal = match price {
3800            Some(px) => normalize_or_validate_wire_price(
3801                px.as_decimal(),
3802                "Price",
3803                price_precision,
3804                self.normalize_prices,
3805            )
3806            .map_err(|e| Error::bad_request(format!("{e}")))?,
3807            None if matches!(order_type, OrderType::Market) => Decimal::ZERO,
3808            None if matches!(
3809                order_type,
3810                OrderType::StopMarket | OrderType::MarketIfTouched
3811            ) =>
3812            {
3813                match trigger_price {
3814                    Some(tp) => {
3815                        let derived = derive_limit_from_trigger(
3816                            tp.as_decimal().normalize(),
3817                            is_buy,
3818                            self.market_order_slippage_bps,
3819                        );
3820                        let sig_rounded = round_to_sig_figs(derived, 5);
3821                        clamp_price_to_precision(sig_rounded, price_precision.unwrap_or(2), is_buy)
3822                            .normalize()
3823                    }
3824                    None => Decimal::ZERO,
3825                }
3826            }
3827            None => return Err(Error::bad_request("Limit orders require a price")),
3828        };
3829
3830        let size_decimal = quantity.as_decimal().normalize();
3831
3832        let kind = match order_type {
3833            OrderType::Market => HyperliquidExchangeOrderKind::Limit {
3834                limit: HyperliquidExchangeLimitParams {
3835                    tif: HyperliquidExchangeTif::Ioc,
3836                },
3837            },
3838            OrderType::Limit => {
3839                let tif = if post_only {
3840                    HyperliquidExchangeTif::Alo
3841                } else {
3842                    match time_in_force {
3843                        TimeInForce::Gtc => HyperliquidExchangeTif::Gtc,
3844                        TimeInForce::Ioc => HyperliquidExchangeTif::Ioc,
3845                        TimeInForce::Fok
3846                        | TimeInForce::Day
3847                        | TimeInForce::Gtd
3848                        | TimeInForce::AtTheOpen
3849                        | TimeInForce::AtTheClose => {
3850                            return Err(Error::bad_request(format!(
3851                                "Time in force {time_in_force:?} not supported"
3852                            )));
3853                        }
3854                    }
3855                };
3856                HyperliquidExchangeOrderKind::Limit {
3857                    limit: HyperliquidExchangeLimitParams { tif },
3858                }
3859            }
3860            OrderType::StopMarket
3861            | OrderType::StopLimit
3862            | OrderType::MarketIfTouched
3863            | OrderType::LimitIfTouched => {
3864                if let Some(trig_px) = trigger_price {
3865                    let trigger_price_decimal = normalize_or_validate_wire_price(
3866                        trig_px.as_decimal(),
3867                        "Trigger price",
3868                        price_precision,
3869                        self.normalize_prices,
3870                    )
3871                    .map_err(|e| Error::bad_request(format!("{e}")))?;
3872
3873                    // Determine TP/SL type based on order type
3874                    // StopMarket/StopLimit are always Sl (protective stops)
3875                    // MarketIfTouched/LimitIfTouched are always Tp (profit-taking/entry)
3876                    let tpsl = match order_type {
3877                        OrderType::StopMarket | OrderType::StopLimit => HyperliquidExchangeTpSl::Sl,
3878                        OrderType::MarketIfTouched | OrderType::LimitIfTouched => {
3879                            HyperliquidExchangeTpSl::Tp
3880                        }
3881                        _ => unreachable!(),
3882                    };
3883
3884                    let is_market = matches!(
3885                        order_type,
3886                        OrderType::StopMarket | OrderType::MarketIfTouched
3887                    );
3888
3889                    HyperliquidExchangeOrderKind::Trigger {
3890                        trigger: HyperliquidExchangeTriggerParams {
3891                            is_market,
3892                            trigger_px: trigger_price_decimal,
3893                            tpsl,
3894                        },
3895                    }
3896                } else {
3897                    return Err(Error::bad_request("Trigger orders require a trigger price"));
3898                }
3899            }
3900            _ => {
3901                return Err(Error::bad_request(format!(
3902                    "Order type {order_type:?} not supported"
3903                )));
3904            }
3905        };
3906
3907        let cloid = self.get_or_generate_client_order_id_cloid(client_order_id);
3908        let hyperliquid_order = HyperliquidExchangePlaceOrderRequest {
3909            asset,
3910            is_buy,
3911            price: price_decimal,
3912            size: size_decimal,
3913            reduce_only,
3914            kind,
3915            cloid: Some(cloid),
3916        };
3917
3918        let builder = self.builder_attribution();
3919
3920        let action = HyperliquidExchangeAction::Order {
3921            orders: vec![hyperliquid_order],
3922            grouping: HyperliquidExchangeGrouping::Na,
3923            builder,
3924        };
3925
3926        let response = self.inner.post_action_exec(&action).await?;
3927
3928        // A single (non-bracket) order should return an actionable status;
3929        // `None` (a deferred `Tag` child) is unexpected on this HTTP path.
3930        self.build_submit_order_report(
3931            instrument_id,
3932            client_order_id,
3933            order_side,
3934            order_type,
3935            quantity,
3936            time_in_force,
3937            price,
3938            trigger_price,
3939            response,
3940        )?
3941        .ok_or_else(|| {
3942            Error::bad_request(
3943                "Single-order submission returned no actionable status (deferred trigger child)",
3944            )
3945        })
3946    }
3947
3948    /// Submit an order using an OrderAny object.
3949    ///
3950    /// This is a convenience method that wraps submit_order.
3951    ///
3952    /// # Errors
3953    ///
3954    /// Returns an error if the quantity is quote-denominated: this raw path has no cached market
3955    /// data for a quote-to-base conversion, so the order must be submitted through the execution
3956    /// client instead.
3957    pub async fn submit_order_from_order_any(&self, order: &OrderAny) -> Result<OrderStatusReport> {
3958        if order.is_quote_quantity() {
3959            return Err(Error::bad_request(
3960                "Quote-denominated quantity orders must submit through the execution client \
3961                 for quote-to-base conversion",
3962            ));
3963        }
3964
3965        self.submit_order(
3966            order.instrument_id(),
3967            order.client_order_id(),
3968            order.order_side(),
3969            order.order_type(),
3970            order.quantity(),
3971            order.time_in_force(),
3972            order.price(),
3973            order.trigger_price(),
3974            order.is_post_only(),
3975            order.is_reduce_only(),
3976        )
3977        .await
3978    }
3979
3980    #[expect(clippy::too_many_arguments)]
3981    fn create_order_status_report(
3982        &self,
3983        instrument_id: InstrumentId,
3984        client_order_id: Option<ClientOrderId>,
3985        venue_order_id: VenueOrderId,
3986        order_side: OrderSide,
3987        order_type: OrderType,
3988        quantity: Quantity,
3989        time_in_force: TimeInForce,
3990        price: Option<Price>,
3991        trigger_price: Option<Price>,
3992        order_status: OrderStatus,
3993        filled_qty: Quantity,
3994        _instrument: &InstrumentAny,
3995        account_id: AccountId,
3996        ts_init: UnixNanos,
3997    ) -> OrderStatusReport {
3998        let ts_accepted = self.clock.get_time_ns();
3999        let ts_last = ts_accepted;
4000        let report_id = UUID4::new();
4001
4002        let mut report = OrderStatusReport::new(
4003            account_id,
4004            instrument_id,
4005            client_order_id,
4006            venue_order_id,
4007            order_side.into(),
4008            order_type,
4009            time_in_force,
4010            order_status,
4011            quantity,
4012            filled_qty,
4013            ts_accepted,
4014            ts_last,
4015            ts_init,
4016            Some(report_id),
4017        );
4018
4019        if let Some(px) = price {
4020            report = report.with_price(px);
4021        }
4022
4023        if let Some(trig_px) = trigger_price {
4024            report = report
4025                .with_trigger_price(trig_px)
4026                .with_trigger_type(TriggerType::Default);
4027        }
4028
4029        report
4030    }
4031
4032    /// Submit multiple orders to the Hyperliquid exchange in a single request.
4033    ///
4034    /// # Errors
4035    ///
4036    /// Returns an error if credentials are missing, order validation fails, serialization fails,
4037    /// or the API returns an error. Also returns an error for any quote-denominated quantity:
4038    /// this raw path has no cached market data for a quote-to-base conversion, so such orders
4039    /// must be submitted through the execution client instead.
4040    pub async fn submit_orders(&self, orders: &[&OrderAny]) -> Result<Vec<OrderStatusReport>> {
4041        // Convert orders using asset indices from the cached map
4042        let mut hyperliquid_orders = Vec::with_capacity(orders.len());
4043        let mut client_order_ids = Vec::with_capacity(orders.len());
4044
4045        for order in orders {
4046            if order.is_quote_quantity() {
4047                return Err(Error::bad_request(format!(
4048                    "Quote-denominated quantity order {} must submit through the execution \
4049                     client for quote-to-base conversion",
4050                    order.client_order_id()
4051                )));
4052            }
4053
4054            let instrument_id = order.instrument_id();
4055            let symbol = instrument_id.symbol.inner();
4056            let asset = self.get_asset_index_for_symbol(symbol).ok_or_else(|| {
4057                Error::bad_request(format!(
4058                    "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
4059                ))
4060            })?;
4061            let price_decimals = self.get_price_precision_for_symbol(symbol);
4062            let request = order_to_hyperliquid_request_with_optional_decimals(
4063                order,
4064                asset,
4065                price_decimals,
4066                self.normalize_prices,
4067                self.market_order_slippage_bps,
4068                None,
4069            )
4070            .map_err(|e| Error::bad_request(format!("Failed to convert order: {e}")))?;
4071            client_order_ids.push(order.client_order_id());
4072            hyperliquid_orders.push(request);
4073        }
4074
4075        for (request, client_order_id) in hyperliquid_orders.iter_mut().zip(client_order_ids) {
4076            request.cloid = Some(self.get_or_generate_client_order_id_cloid(client_order_id));
4077        }
4078
4079        let builder = self.builder_attribution();
4080
4081        let grouping =
4082            determine_order_list_grouping(&orders.iter().copied().cloned().collect::<Vec<_>>());
4083
4084        let action = HyperliquidExchangeAction::Order {
4085            orders: hyperliquid_orders,
4086            grouping,
4087            builder,
4088        };
4089
4090        // Submit to exchange using the typed exec endpoint
4091        let response = self.inner.post_action_exec(&action).await?;
4092
4093        self.build_submit_orders_reports(orders, grouping, response)
4094    }
4095
4096    /// Parses a Hyperliquid exchange order response for a single-order submit
4097    /// into an [`OrderStatusReport`].
4098    ///
4099    /// Returns `Ok(None)` when the venue returned an empty `statuses` array or
4100    /// when the only status is a deferred `Tag` child (for example
4101    /// `waitingForFill`): the venue accepted the order but has not assigned an
4102    /// oid yet, so the order stays `SUBMITTED` until the user-events stream
4103    /// drives the first `OrderAccepted` with the real oid.
4104    ///
4105    /// Shared by the HTTP and WebSocket single-submit paths.
4106    ///
4107    /// # Errors
4108    ///
4109    /// Returns an error if account credentials are missing, the response is
4110    /// malformed, or the order returned an `error` status.
4111    #[expect(clippy::too_many_arguments)]
4112    pub fn build_submit_order_report(
4113        &self,
4114        instrument_id: InstrumentId,
4115        client_order_id: ClientOrderId,
4116        order_side: OrderSide,
4117        order_type: OrderType,
4118        quantity: Quantity,
4119        time_in_force: TimeInForce,
4120        price: Option<Price>,
4121        trigger_price: Option<Price>,
4122        response: HyperliquidExchangeResponse,
4123    ) -> Result<Option<OrderStatusReport>> {
4124        let order_response = parse_order_response(response)?;
4125
4126        let Some(order_status) = order_response.statuses.first() else {
4127            return Ok(None);
4128        };
4129
4130        let account_id = self
4131            .account_id
4132            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
4133        let ts_init = self.clock.get_time_ns();
4134
4135        self.build_status_report(
4136            instrument_id,
4137            client_order_id,
4138            order_side,
4139            order_type,
4140            quantity,
4141            time_in_force,
4142            price,
4143            trigger_price,
4144            order_status,
4145            account_id,
4146            ts_init,
4147        )
4148    }
4149
4150    /// Parses a Hyperliquid exchange order response into per-order
4151    /// [`OrderStatusReport`]s, paired positionally with `orders`.
4152    ///
4153    /// Shared by the HTTP and WebSocket batch-submit paths since the response
4154    /// envelope is identical regardless of transport. Deferred `Tag` children
4155    /// (for example `waitingForFill`) are elided from the result; those orders
4156    /// stay `SUBMITTED` until the user-events stream delivers an `OrderAccepted`
4157    /// with the real oid.
4158    ///
4159    /// # Errors
4160    ///
4161    /// Returns an error if account credentials are missing, the response is
4162    /// malformed, an order returned an `error` status, or, for ungrouped
4163    /// submissions, the response status count diverges from the order count.
4164    pub fn build_submit_orders_reports(
4165        &self,
4166        orders: &[&OrderAny],
4167        grouping: HyperliquidExchangeGrouping,
4168        response: HyperliquidExchangeResponse,
4169    ) -> Result<Vec<OrderStatusReport>> {
4170        let order_response = parse_order_response(response)?;
4171
4172        let account_id = self
4173            .account_id
4174            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
4175        let ts_init = self.clock.get_time_ns();
4176
4177        // For grouped orders (NormalTpsl/PositionTpsl) the exchange returns a
4178        // single status for the whole group, so only enforce 1:1 matching for
4179        // ungrouped (Na) submissions.
4180        if grouping == HyperliquidExchangeGrouping::Na
4181            && order_response.statuses.len() != orders.len()
4182        {
4183            return Err(Error::bad_request(format!(
4184                "Mismatch between submitted orders ({}) and response statuses ({})",
4185                orders.len(),
4186                order_response.statuses.len()
4187            )));
4188        }
4189
4190        // The exchange returns statuses in submission order, so pair each order
4191        // with its status positionally.
4192        let mut reports = Vec::with_capacity(order_response.statuses.len());
4193        for (order, order_status) in orders.iter().zip(order_response.statuses.iter()) {
4194            if let Some(report) = self.build_status_report(
4195                order.instrument_id(),
4196                order.client_order_id(),
4197                order.order_side(),
4198                order.order_type(),
4199                order.quantity(),
4200                order.time_in_force(),
4201                order.price(),
4202                order.trigger_price(),
4203                order_status,
4204                account_id,
4205                ts_init,
4206            )? {
4207                reports.push(report);
4208            }
4209        }
4210
4211        Ok(reports)
4212    }
4213
4214    /// Builds an [`OrderStatusReport`] from a single venue status, or `Ok(None)`
4215    /// for a deferred `Tag` child that has no oid yet.
4216    ///
4217    /// `Tag` rows are elided rather than given a synthetic placeholder venue id:
4218    /// an earlier placeholder accept was deduped against the later real accept,
4219    /// so the cache never picked up the real oid and cancel/modify by venue id
4220    /// broke on bracket children.
4221    #[expect(clippy::too_many_arguments)]
4222    fn build_status_report(
4223        &self,
4224        instrument_id: InstrumentId,
4225        client_order_id: ClientOrderId,
4226        order_side: OrderSide,
4227        order_type: OrderType,
4228        quantity: Quantity,
4229        time_in_force: TimeInForce,
4230        price: Option<Price>,
4231        trigger_price: Option<Price>,
4232        order_status: &HyperliquidExchangeOrderStatus,
4233        account_id: AccountId,
4234        ts_init: UnixNanos,
4235    ) -> Result<Option<OrderStatusReport>> {
4236        if matches!(order_status, HyperliquidExchangeOrderStatus::Tag(_)) {
4237            return Ok(None);
4238        }
4239
4240        let symbol = instrument_id.symbol.as_str();
4241        let product_type = HyperliquidProductType::from_symbol(symbol).ok();
4242
4243        // Mirror the alias `cache_instrument` stored (token form for outcomes,
4244        // leading segment for perps / spots).
4245        let asset = cache_alias_for_symbol(symbol).unwrap_or_else(|| symbol.to_string());
4246        let instrument = self
4247            .get_or_create_instrument(&Ustr::from(asset.as_str()), product_type)
4248            .ok_or_else(|| {
4249                Error::bad_request(InstrumentLookupError::not_found(instrument_id).to_string())
4250            })?;
4251
4252        let report = match order_status {
4253            HyperliquidExchangeOrderStatus::Resting { resting } => self.create_order_status_report(
4254                instrument_id,
4255                Some(client_order_id),
4256                VenueOrderId::new(resting.oid.to_string()),
4257                order_side,
4258                order_type,
4259                quantity,
4260                time_in_force,
4261                price,
4262                trigger_price,
4263                OrderStatus::Accepted,
4264                Quantity::zero(instrument.size_precision()),
4265                &instrument,
4266                account_id,
4267                ts_init,
4268            ),
4269            HyperliquidExchangeOrderStatus::Filled { filled } => {
4270                let filled_qty =
4271                    Quantity::from_decimal_dp(filled.total_sz, instrument.size_precision())
4272                        .map_err(|e| {
4273                            Error::bad_request(format!(
4274                                "Invalid filled size {}: {e}",
4275                                filled.total_sz
4276                            ))
4277                        })?;
4278                self.create_order_status_report(
4279                    instrument_id,
4280                    Some(client_order_id),
4281                    VenueOrderId::new(filled.oid.to_string()),
4282                    order_side,
4283                    order_type,
4284                    quantity,
4285                    time_in_force,
4286                    price,
4287                    trigger_price,
4288                    OrderStatus::Filled,
4289                    filled_qty,
4290                    &instrument,
4291                    account_id,
4292                    ts_init,
4293                )
4294            }
4295            HyperliquidExchangeOrderStatus::Error { error } => {
4296                return Err(Error::bad_request(format!(
4297                    "Order {client_order_id} rejected: {error}"
4298                )));
4299            }
4300            HyperliquidExchangeOrderStatus::Tag(_) => unreachable!("handled above"),
4301        };
4302
4303        Ok(Some(report))
4304    }
4305
4306    pub(crate) fn allows_venue_coin(&self, coin: &Ustr) -> bool {
4307        self.allows_product(self.product_type_for_venue_coin(coin))
4308    }
4309
4310    fn product_type_for_venue_coin(&self, coin: &Ustr) -> HyperliquidProductType {
4311        // A cached base alias such as BTC for BTC/USDC does not identify a Spot wire coin.
4312        // Venue coin names can themselves end in -SPOT or -OUTCOME.
4313        let cached = self.instruments_by_coin.load();
4314        for product in [
4315            HyperliquidProductType::Outcome,
4316            HyperliquidProductType::Perp,
4317            HyperliquidProductType::Spot,
4318        ] {
4319            if cached
4320                .get(&(*coin, product))
4321                .is_some_and(|instrument| instrument.raw_symbol().as_str() == coin.as_str())
4322            {
4323                return product;
4324            }
4325        }
4326
4327        if coin.starts_with('#') || coin.starts_with('+') {
4328            HyperliquidProductType::Outcome
4329        } else if coin.starts_with('@')
4330            || coin.contains('/')
4331            || coin.starts_with(VAULT_TOKEN_PREFIX)
4332        {
4333            HyperliquidProductType::Spot
4334        } else {
4335            HyperliquidProductType::Perp
4336        }
4337    }
4338
4339    fn reconciliation_dexes(&self, instrument_id: Option<InstrumentId>) -> Vec<Option<Ustr>> {
4340        if !self.allows_product(HyperliquidProductType::Perp) {
4341            return vec![None];
4342        }
4343
4344        if let Some(instrument_id) = instrument_id {
4345            return vec![perp_dex_from_symbol(instrument_id.symbol.as_str())];
4346        }
4347
4348        let cached = self.instruments.load();
4349        reconciliation_dexes_from_builders(
4350            cached
4351                .keys()
4352                .filter_map(|symbol| perp_dex_from_symbol(symbol.as_str())),
4353        )
4354    }
4355
4356    pub(crate) async fn reconciliation_dexes_from_activity(
4357        &self,
4358        historical_orders: &[HyperliquidOrderStatusEntry],
4359        fills: &HyperliquidFills,
4360    ) -> Result<Vec<Option<Ustr>>> {
4361        if !self.allows_product(HyperliquidProductType::Perp) {
4362            return Ok(vec![None]);
4363        }
4364
4365        if historical_orders.len() >= HYPERLIQUID_RECENT_HISTORY_LIMIT
4366            || fills.len() >= HYPERLIQUID_RECENT_HISTORY_LIMIT
4367        {
4368            let builder_dexes = self
4369                .inner
4370                .load_perp_dexs()
4371                .await?
4372                .into_iter()
4373                .flatten()
4374                .filter(|dex| !dex.name.is_empty())
4375                .map(|dex| Ustr::from(dex.name.as_str()));
4376            return Ok(reconciliation_dexes_from_builders(builder_dexes));
4377        }
4378
4379        let builder_dexes = historical_orders
4380            .iter()
4381            .map(|entry| entry.order.coin.as_str())
4382            .chain(fills.iter().map(|fill| fill.coin.as_str()))
4383            .filter_map(perp_dex_from_activity_coin);
4384
4385        Ok(reconciliation_dexes_from_builders(builder_dexes))
4386    }
4387}
4388
4389// A reconciliation snapshot with its completeness flag: `complete` is false when
4390// at least one venue row could not be decoded, resolved to an instrument, or
4391// converted into a report. Callers whose contract cannot carry the flag fail
4392// closed; mass-status reconciliation preserves the valid rows and reports the
4393// incompleteness via `ExecutionMassStatus::set_report_window`.
4394#[derive(Debug)]
4395pub(crate) struct ReportSweep<T> {
4396    pub reports: Vec<T>,
4397    pub complete: bool,
4398}
4399
4400/// The instrument universe with the market status of each instrument.
4401#[derive(Debug)]
4402pub(crate) struct InstrumentSnapshot {
4403    pub instruments: Vec<InstrumentAny>,
4404    pub statuses: AHashMap<InstrumentId, MarketStatusAction>,
4405    /// Product types whose metadata loaded in full.
4406    pub loaded: AHashSet<HyperliquidProductType>,
4407}
4408
4409fn reconciliation_dexes_from_builders(
4410    builder_dexes: impl IntoIterator<Item = Ustr>,
4411) -> Vec<Option<Ustr>> {
4412    let mut builder_dexes = builder_dexes.into_iter().collect::<Vec<_>>();
4413    builder_dexes.sort_unstable();
4414    builder_dexes.dedup();
4415
4416    let mut dexes = Vec::with_capacity(builder_dexes.len() + 1);
4417    dexes.push(None);
4418    dexes.extend(builder_dexes.into_iter().map(Some));
4419    dexes
4420}
4421
4422fn perp_dex_from_activity_coin(coin: &str) -> Option<Ustr> {
4423    if coin.starts_with(VAULT_TOKEN_PREFIX) {
4424        return None;
4425    }
4426
4427    let (dex, _) = coin.split_once(':')?;
4428    (!dex.is_empty()).then(|| Ustr::from(dex))
4429}
4430
4431fn perp_dex_from_symbol(symbol: &str) -> Option<Ustr> {
4432    symbol
4433        .strip_suffix("-PERP")?
4434        .split_once(':')
4435        .map(|(dex, _)| Ustr::from(dex))
4436}
4437
4438/// Extracts the order-status payload from an exchange response.
4439///
4440/// The newer response format nests the statuses under `data`; the older format
4441/// places them directly in the response body.
4442fn parse_order_response(
4443    response: HyperliquidExchangeResponse,
4444) -> Result<HyperliquidExchangeOrderResponseData> {
4445    let response_data = match response {
4446        HyperliquidExchangeResponse::Status {
4447            status,
4448            response: response_data,
4449        } if status == RESPONSE_STATUS_OK => response_data,
4450        HyperliquidExchangeResponse::Error { error } => {
4451            return Err(Error::bad_request(format!(
4452                "Order submission failed: {error}"
4453            )));
4454        }
4455        _ => return Err(Error::bad_request("Unexpected response format")),
4456    };
4457
4458    let data_value = if let Some(data) = response_data.get("data") {
4459        data.clone()
4460    } else {
4461        response_data
4462    };
4463
4464    serde_json::from_value(data_value)
4465        .map_err(|e| Error::bad_request(format!("Failed to parse order response: {e}")))
4466}
4467
4468fn resolve_perp_dex_name(
4469    dex_index: usize,
4470    meta: &PerpMeta,
4471    perp_dexs: Option<&[Option<PerpDex>]>,
4472) -> String {
4473    if dex_index == 0 {
4474        return String::new();
4475    }
4476
4477    if let Some(dex_name) = perp_dexs
4478        .and_then(|dexs| dexs.get(dex_index))
4479        .and_then(|dex| dex.as_ref())
4480        .map(|dex| dex.name.clone())
4481    {
4482        return dex_name;
4483    }
4484
4485    meta.universe
4486        .iter()
4487        .find_map(|asset| asset.name.split_once(':').map(|(dex, _)| dex.to_string()))
4488        .unwrap_or_default()
4489}
4490
4491/// Returns the asset index base for a perp dex.
4492///
4493/// Standard perps (dex 0) start at 0. HIP-3 dexes start at
4494/// 100_000 + dex_index * 10_000.
4495fn perp_dex_asset_index_base(dex_index: usize) -> u32 {
4496    if dex_index == 0 {
4497        0
4498    } else {
4499        100_000 + dex_index as u32 * 10_000
4500    }
4501}
4502
4503fn cache_coin_aliases(
4504    cache: &mut AHashMap<(Ustr, HyperliquidProductType), InstrumentAny>,
4505    instrument: &InstrumentAny,
4506    product_type: HyperliquidProductType,
4507) {
4508    let full_symbol = instrument.symbol().inner();
4509    let coin = instrument.raw_symbol().inner();
4510
4511    // Composite key allows disambiguating same coin across PERP and SPOT
4512    cache.insert((coin, product_type), instrument.clone());
4513
4514    // Secondary alias key for two distinct callers:
4515    //
4516    // * Spot raw_symbols are either `@{pair_index}` or slash format
4517    //   (e.g., "PURR/USDC"); spot balance/position reconciliation
4518    //   maps the venue token name (e.g., "PURR") to instruments via
4519    //   this alias.
4520    // * Order submission paths split `instrument_id.symbol` on `-`
4521    //   to derive a coin key. For HIP-3 perps with wildcard-bearing
4522    //   venue names, the sanitized base in `instrument_id.symbol`
4523    //   (e.g., "dex:STREAMABCDxxxx") differs from `raw_symbol` /
4524    //   `coin` (e.g., "dex:STREAMABCD****"), so an alias on the
4525    //   sanitized base lets that lookup resolve.
4526    //
4527    // For outcomes the alias is the `+<encoding>` token form
4528    // (matching the `coin` field on `spotClearinghouseState`);
4529    // for perps / spots it is the leading symbol segment.
4530    // `cache_alias_for_symbol` keeps the two rules co-located so
4531    // every caller derives the same key.
4532    //
4533    // Keep aliases on their original venue market while refreshing
4534    // its definition, canonical spot pairs are cached first.
4535    if let Some(alias_ustr) =
4536        cache_alias_for_symbol(full_symbol.as_str()).map(|alias| Ustr::from(alias.as_str()))
4537    {
4538        let key = (alias_ustr, product_type);
4539        if alias_ustr != coin
4540            && cache
4541                .get(&key)
4542                .is_none_or(|cached| cached.raw_symbol() == instrument.raw_symbol())
4543        {
4544            cache.insert(key, instrument.clone());
4545        }
4546    }
4547}
4548
4549fn validate_schedule_cancel_time(time: u64, now: u64) -> Result<()> {
4550    if time.checked_sub(now).is_none_or(|delay| delay < 5_000) {
4551        return Err(Error::bad_request(
4552            "Schedule cancel time must be at least 5000 ms after the current time",
4553        ));
4554    }
4555
4556    Ok(())
4557}
4558
4559#[cfg(test)]
4560mod tests {
4561    use std::{
4562        collections::HashMap,
4563        net::SocketAddr,
4564        sync::{
4565            Arc,
4566            atomic::{AtomicUsize, Ordering},
4567        },
4568        time::Duration,
4569    };
4570
4571    use axum::{
4572        Router,
4573        extract::State,
4574        http::StatusCode,
4575        response::{IntoResponse, Json, Response},
4576        routing::post,
4577    };
4578    use nautilus_core::{Params, UUID4, UnixNanos, hex, time::get_atomic_clock_realtime};
4579    use nautilus_model::{
4580        currencies::CURRENCY_MAP,
4581        enums::{CurrencyType, OrderSide, OrderStatus, OrderType, TimeInForce, TriggerType},
4582        events::{OrderEventAny, OrderInitialized},
4583        identifiers::{
4584            AccountId, ClientOrderId, InstrumentId, StrategyId, Symbol, TraderId, VenueOrderId,
4585        },
4586        instruments::{CryptoPerpetual, CurrencyPair, Instrument, InstrumentAny},
4587        orders::OrderAny,
4588        reports::OrderStatusReport,
4589        types::{Currency, Price, Quantity},
4590    };
4591    use nautilus_testkit::http::assert_http_redirect_rejected;
4592    use rstest::rstest;
4593    use rust_decimal_macros::dec;
4594    use serde_json::{Value, json};
4595    use ustr::Ustr;
4596
4597    use super::{
4598        HyperliquidHttpClient, HyperliquidRawHttpClient, RETRY_AFTER_HEADER, resolve_perp_dex_name,
4599        validate_schedule_cancel_time,
4600    };
4601    use crate::{
4602        common::{
4603            consts::{ASSET_INDEX_INFO_KEY, HYPERLIQUID_VENUE, NAUTILUS_BUILDER_ADDRESS},
4604            credential::EvmPrivateKey,
4605            enums::{HyperliquidEnvironment, HyperliquidProductType},
4606        },
4607        http::{
4608            error::Error,
4609            models::{
4610                Cloid, HyperliquidExchangeAction, HyperliquidExchangeResponse,
4611                HyperliquidOrderStatusEntry, PerpAsset, PerpDex, PerpMeta,
4612            },
4613            query::InfoRequest,
4614        },
4615        signing::{HyperliquidActionType, HyperliquidEip712Signer, SignRequest, nonce::TimeNonce},
4616    };
4617
4618    const TEST_PRIVATE_KEY: &str =
4619        "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
4620
4621    #[rstest]
4622    #[case::perp(vec![HyperliquidProductType::Perp])]
4623    #[case::spot(vec![HyperliquidProductType::Spot])]
4624    #[case::outcome(vec![HyperliquidProductType::Outcome])]
4625    #[case::perp_spot(vec![HyperliquidProductType::Perp, HyperliquidProductType::Spot])]
4626    #[case::perp_outcome(vec![HyperliquidProductType::Perp, HyperliquidProductType::Outcome])]
4627    #[case::spot_outcome(vec![HyperliquidProductType::Spot, HyperliquidProductType::Outcome])]
4628    #[case::all(vec![HyperliquidProductType::Perp, HyperliquidProductType::Spot, HyperliquidProductType::Outcome])]
4629    #[case::duplicates(vec![HyperliquidProductType::Perp, HyperliquidProductType::Perp])]
4630    fn test_execution_product_scope_compiles_configuration_and_preserves_clones(
4631        #[case] products: Vec<HyperliquidProductType>,
4632    ) {
4633        let mut client = HyperliquidHttpClient::default();
4634        client.set_product_types(products.clone()).unwrap();
4635        let cloned = client.clone();
4636        assert!(client.set_product_types(vec![]).is_err());
4637        let instruments = [
4638            (
4639                HyperliquidProductType::Perp,
4640                InstrumentId::from("BTC-USD-PERP.HYPERLIQUID"),
4641            ),
4642            (
4643                HyperliquidProductType::Spot,
4644                InstrumentId::from("BTC-USDC-SPOT.HYPERLIQUID"),
4645            ),
4646            (
4647                HyperliquidProductType::Outcome,
4648                InstrumentId::from("1-YES-OUTCOME.HYPERLIQUID"),
4649            ),
4650        ];
4651
4652        for (product, instrument_id) in instruments {
4653            assert_eq!(
4654                client.allows_instrument(instrument_id),
4655                products.contains(&product)
4656            );
4657            assert_eq!(
4658                cloned.allows_instrument(instrument_id),
4659                products.contains(&product)
4660            );
4661        }
4662
4663        client
4664            .set_product_types(vec![HyperliquidProductType::Spot])
4665            .unwrap();
4666
4667        for (product, instrument_id) in instruments {
4668            assert_eq!(
4669                client.allows_instrument(instrument_id),
4670                product == HyperliquidProductType::Spot
4671            );
4672            assert_eq!(
4673                cloned.allows_instrument(instrument_id),
4674                products.contains(&product)
4675            );
4676        }
4677        assert!(!cloned.allows_instrument(InstrumentId::from("BTC-USD-PERP.BINANCE")));
4678    }
4679
4680    #[rstest]
4681    #[case("#200", HyperliquidProductType::Perp, HyperliquidProductType::Outcome)]
4682    #[case(
4683        "vntls:SCOPE",
4684        HyperliquidProductType::Outcome,
4685        HyperliquidProductType::Spot
4686    )]
4687    fn test_execution_product_scope_respects_explicit_product_resolution(
4688        #[case] coin: &str,
4689        #[case] wrong: HyperliquidProductType,
4690        #[case] correct: HyperliquidProductType,
4691    ) {
4692        let client = HyperliquidHttpClient::default();
4693        let coin = Ustr::from(coin);
4694
4695        assert!(
4696            client
4697                .get_or_create_instrument(&coin, Some(wrong))
4698                .is_none()
4699        );
4700        assert!(client.instruments_by_coin.load().is_empty());
4701        assert!(
4702            client
4703                .get_or_create_instrument(&coin, Some(correct))
4704                .is_some()
4705        );
4706    }
4707
4708    #[rstest]
4709    #[case("xyz:ASSET-SPOT")]
4710    #[case("xyz:ASSET-OUTCOME")]
4711    fn test_execution_product_scope_uses_venue_coin_identity(#[case] coin: &str) {
4712        let mut client = HyperliquidHttpClient::default();
4713        let meta = perp_meta_with_assets(&[coin]);
4714        let defs = crate::http::parse::parse_perp_instruments(&meta, 0).unwrap();
4715        let instrument =
4716            crate::http::parse::create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
4717        client.cache_instrument(&instrument);
4718        client
4719            .set_product_types(vec![HyperliquidProductType::Perp])
4720            .unwrap();
4721
4722        assert!(client.allows_instrument(instrument.id()));
4723        assert!(client.allows_venue_coin(&Ustr::from(coin)));
4724
4725        client
4726            .set_product_types(vec![
4727                HyperliquidProductType::Spot,
4728                HyperliquidProductType::Outcome,
4729            ])
4730            .unwrap();
4731        assert!(!client.allows_venue_coin(&Ustr::from(coin)));
4732    }
4733
4734    #[rstest]
4735    #[case::spot(HyperliquidProductType::Spot, true)]
4736    #[case::perp(HyperliquidProductType::Perp, false)]
4737    #[tokio::test]
4738    async fn test_execution_product_scope_cached_cloid_query(
4739        #[case] product: HyperliquidProductType,
4740        #[case] allowed: bool,
4741    ) {
4742        let coid = ClientOrderId::from("O-CACHED-CLOID-SCOPE");
4743        let cloid = Cloid::from_hex("0x000000000000000000000000000000ab").unwrap();
4744        assert_ne!(cloid, Cloid::from_client_order_id(coid));
4745        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4746        let addr = listener.local_addr().unwrap();
4747        let router = Router::new().route(
4748            "/info",
4749            post(move |Json(request): Json<Value>| async move {
4750                assert_eq!(request["type"], "frontendOpenOrders");
4751                Json(json!([{
4752                    "coin": "vntls:SCOPE", "side": "B", "limitPx": "1", "sz": "2",
4753                    "oid": 101, "timestamp": 1_700_000_000_000u64, "origSz": "2",
4754                    "cloid": cloid.to_hex(),
4755                }]))
4756            }),
4757        );
4758
4759        let server = tokio::spawn(async move {
4760            axum::serve(listener, router).await.unwrap();
4761        });
4762        let mut client = HyperliquidHttpClient::default();
4763        client.set_base_info_url(format!("http://{addr}/info"));
4764        client.set_account_id(AccountId::from("HYPERLIQUID-001"));
4765        client.set_product_types(vec![product]).unwrap();
4766        client.cache_client_order_id_cloid(coid, cloid);
4767        let cloned = client.clone();
4768        let result = cloned
4769            .request_order_status_report_by_client_order_id(
4770                "0x0000000000000000000000000000000000000001",
4771                &coid,
4772            )
4773            .await;
4774
4775        if allowed {
4776            let report = result.unwrap().unwrap();
4777            assert_eq!(report.client_order_id, Some(coid));
4778            assert_eq!(report.venue_order_id, VenueOrderId::from("101"));
4779            assert!(client.allows_instrument(report.instrument_id));
4780            assert_eq!(report.order_status, OrderStatus::Accepted);
4781        } else {
4782            assert!(
4783                result
4784                    .unwrap_err()
4785                    .to_string()
4786                    .contains("outside execution product scope")
4787            );
4788        }
4789        server.abort();
4790    }
4791
4792    #[rstest]
4793    #[case(10_000, 9_999, false)]
4794    #[case(10_000, 10_000, false)]
4795    #[case(10_000, 14_999, false)]
4796    #[case(10_000, 15_000, true)]
4797    #[case(10_000, 15_001, true)]
4798    #[case(u64::MAX - 4_999, u64::MAX, false)]
4799    #[case(u64::MAX - 5_000, u64::MAX, true)]
4800    fn test_schedule_cancel_timestamp(#[case] now: u64, #[case] time: u64, #[case] valid: bool) {
4801        assert_eq!(validate_schedule_cancel_time(time, now).is_ok(), valid);
4802    }
4803
4804    #[rstest]
4805    fn test_usd_class_transfer_rejected_without_credentials(
4806        #[values(HyperliquidEnvironment::Mainnet, HyperliquidEnvironment::Testnet)]
4807        environment: HyperliquidEnvironment,
4808    ) {
4809        let client = HyperliquidRawHttpClient::new(environment, 5, None).unwrap();
4810
4811        let action = HyperliquidExchangeAction::UsdClassTransfer {
4812            from: "spot".to_string(),
4813            to: "perp".to_string(),
4814            amount: dec!(1.25),
4815        };
4816
4817        let error = client.sign_action_exec_request(&action, None).unwrap_err();
4818
4819        assert!(matches!(error, Error::BadRequest(_)));
4820        assert_eq!(
4821            error.to_string(),
4822            "bad request: Unsupported action: usdClassTransfer"
4823        );
4824    }
4825
4826    #[rstest]
4827    fn test_usd_class_transfer_rejected_before_nonce_allocation(
4828        #[values(HyperliquidEnvironment::Mainnet, HyperliquidEnvironment::Testnet)]
4829        environment: HyperliquidEnvironment,
4830        #[values(None, Some("0x1234567890123456789012345678901234567890"))] vault: Option<&str>,
4831        #[values(None, Some(1_900_000_000_000))] expires_after: Option<u64>,
4832    ) {
4833        let mut client =
4834            HyperliquidHttpClient::from_credentials(TEST_PRIVATE_KEY, vault, environment, 5, None)
4835                .unwrap();
4836        Arc::get_mut(&mut client.inner).unwrap().nonce_manager = None;
4837
4838        let action = HyperliquidExchangeAction::UsdClassTransfer {
4839            from: "perp".to_string(),
4840            to: "spot".to_string(),
4841            amount: dec!(2.75),
4842        };
4843
4844        let error = client
4845            .sign_action_exec_request(&action, expires_after)
4846            .unwrap_err();
4847
4848        assert!(matches!(error, Error::BadRequest(_)));
4849        assert_eq!(
4850            error.to_string(),
4851            "bad request: Unsupported action: usdClassTransfer"
4852        );
4853    }
4854
4855    #[rstest]
4856    #[tokio::test]
4857    async fn test_usd_class_transfer_rejected_without_dispatch(
4858        #[values(HyperliquidEnvironment::Mainnet, HyperliquidEnvironment::Testnet)]
4859        environment: HyperliquidEnvironment,
4860    ) {
4861        let (addr, count, server) =
4862            start_retry_server(RetryFailure::Response(400), usize::MAX, None).await;
4863        let mut client =
4864            HyperliquidHttpClient::from_credentials(TEST_PRIVATE_KEY, None, environment, 5, None)
4865                .unwrap();
4866        client.set_base_exchange_url(format!("http://{addr}/exchange"));
4867
4868        let action = HyperliquidExchangeAction::UsdClassTransfer {
4869            from: "spot".to_string(),
4870            to: "perp".to_string(),
4871            amount: dec!(3.125),
4872        };
4873
4874        let error = client.post_action_exec(&action).await.unwrap_err();
4875
4876        server.abort();
4877
4878        assert!(matches!(error, Error::BadRequest(_)));
4879        assert_eq!(
4880            error.to_string(),
4881            "bad request: Unsupported action: usdClassTransfer"
4882        );
4883        assert_eq!(count.load(Ordering::Relaxed), 0);
4884    }
4885
4886    #[rstest]
4887    #[case(0)]
4888    #[case(1)]
4889    #[case(2)]
4890    #[case(3)]
4891    fn test_leverage_margin_signed_request(
4892        #[case] case_index: usize,
4893        #[values(HyperliquidEnvironment::Mainnet, HyperliquidEnvironment::Testnet)]
4894        environment: HyperliquidEnvironment,
4895    ) {
4896        let fixture: Value =
4897            serde_json::from_str(include_str!("../../test_data/leverage_margin_actions.json"))
4898                .unwrap();
4899        let case = &fixture["cases"][case_index];
4900        let action: HyperliquidExchangeAction =
4901            serde_json::from_str(case["json"].as_str().unwrap()).unwrap();
4902        let client =
4903            HyperliquidHttpClient::from_credentials(TEST_PRIVATE_KEY, None, environment, 60, None)
4904                .unwrap();
4905        let expires_after = Some(1_900_000_000_000);
4906        let request = client
4907            .sign_action_exec_request(&action, expires_after)
4908            .unwrap();
4909        let key = EvmPrivateKey::new(TEST_PRIVATE_KEY).unwrap();
4910        let signer = HyperliquidEip712Signer::new(&key).unwrap();
4911        let expected_bytes = hex::decode(case["msgpack"].as_str().unwrap()).unwrap();
4912
4913        let expected_signature = signer
4914            .sign(&SignRequest {
4915                action: None,
4916                action_bytes: Some(expected_bytes),
4917                time_nonce: TimeNonce::from_millis(i128::from(request.nonce)),
4918                action_type: HyperliquidActionType::L1,
4919                is_testnet: environment == HyperliquidEnvironment::Testnet,
4920                vault_address: None,
4921                expires_after,
4922            })
4923            .unwrap()
4924            .signature;
4925
4926        let expected_action: Value = serde_json::from_str(case["json"].as_str().unwrap()).unwrap();
4927
4928        assert_eq!(
4929            serde_json::to_value(&request).unwrap(),
4930            json!({
4931                "action": expected_action,
4932                "nonce": request.nonce,
4933                "signature": expected_signature,
4934                "expiresAfter": expires_after,
4935            })
4936        );
4937    }
4938
4939    #[tokio::test]
4940    async fn test_authenticated_client_rejects_redirects() {
4941        let client = HyperliquidRawHttpClient::build_http_client(3, None).unwrap();
4942        assert_http_redirect_rejected(|url| async move {
4943            client
4944                .get(url, None, None, Some(3), None)
4945                .await
4946                .unwrap()
4947                .status
4948                .as_u16()
4949        })
4950        .await;
4951    }
4952
4953    #[rstest]
4954    fn raw_clients_share_rest_limit_for_one_route() {
4955        let mut first =
4956            HyperliquidRawHttpClient::new(HyperliquidEnvironment::Testnet, 60, None).unwrap();
4957        let mut second =
4958            HyperliquidRawHttpClient::new(HyperliquidEnvironment::Testnet, 60, None).unwrap();
4959        first.set_base_info_url("https://shared-http-limit.test/info".to_string());
4960        second.set_base_exchange_url("https://shared-http-limit.test/exchange".to_string());
4961
4962        assert!(Arc::ptr_eq(&first.info_limiter, &second.exchange_limiter));
4963    }
4964
4965    #[rstest]
4966    #[case::seconds("3", Some(3_000))]
4967    #[case::zero("0", Some(0))]
4968    #[case::past_date("Sun, 06 Nov 1994 08:49:36 GMT", Some(0))]
4969    #[case::overflow("18446744073709551615", Some(u64::MAX))]
4970    #[case::invalid("soon", None)]
4971    #[case::negative("-1", None)]
4972    fn retry_after_ms_parses_header(#[case] value: &str, #[case] expected: Option<u64>) {
4973        let headers = HashMap::from([(RETRY_AFTER_HEADER.to_string(), value.to_string())]);
4974
4975        assert_eq!(HyperliquidRawHttpClient::retry_after_ms(&headers), expected);
4976    }
4977
4978    #[rstest]
4979    #[case::transport(RetryFailure::Transport)]
4980    #[case::timeout(RetryFailure::Timeout)]
4981    #[case::request_timeout(RetryFailure::Response(408))]
4982    #[case::rate_limit(RetryFailure::Response(429))]
4983    #[case::server_error(RetryFailure::Response(500))]
4984    #[case::unavailable(RetryFailure::Response(503))]
4985    #[tokio::test]
4986    async fn info_retry_recovers(#[case] failure: RetryFailure) {
4987        let (addr, count, server) = start_retry_server(failure, 1, None).await;
4988        let mut client =
4989            HyperliquidRawHttpClient::new(HyperliquidEnvironment::Testnet, 1, None).unwrap();
4990        client.set_base_info_url(format!("http://{addr}/info"));
4991
4992        let result = client
4993            .send_info_request_raw(&InfoRequest::meta())
4994            .await
4995            .unwrap();
4996        let expected: Value =
4997            serde_json::from_str(include_str!("../../test_data/http_meta_perp_sample.json"))
4998                .unwrap();
4999
5000        server.abort();
5001        assert_eq!(result, expected);
5002        assert_eq!(count.load(Ordering::Relaxed), 2);
5003    }
5004
5005    #[rstest]
5006    #[case::transport(RetryFailure::Transport)]
5007    #[case::timeout(RetryFailure::Timeout)]
5008    #[case::request_timeout(RetryFailure::Response(408))]
5009    #[case::rate_limit(RetryFailure::Response(429))]
5010    #[case::server_error(RetryFailure::Response(503))]
5011    #[tokio::test]
5012    async fn info_retry_exhausts_budget(#[case] failure: RetryFailure) {
5013        let (addr, count, server) = start_retry_server(failure, usize::MAX, Some("0")).await;
5014        let mut client =
5015            HyperliquidRawHttpClient::new(HyperliquidEnvironment::Testnet, 1, None).unwrap();
5016        client.set_base_info_url(format!("http://{addr}/info"));
5017
5018        let error = client.info_meta().await.unwrap_err();
5019
5020        server.abort();
5021        assert_retry_failure(error, failure, ("info", 20, Some(0)));
5022        assert_eq!(count.load(Ordering::Relaxed), 4);
5023    }
5024
5025    #[rstest]
5026    #[case::bad_request(RetryFailure::Response(400))]
5027    #[case::unauthorized(RetryFailure::Response(401))]
5028    #[case::forbidden(RetryFailure::Response(403))]
5029    #[case::unprocessable(RetryFailure::Response(422))]
5030    #[case::invalid_json(RetryFailure::InvalidJson)]
5031    #[tokio::test]
5032    async fn info_retry_rejects_permanent_failures(#[case] failure: RetryFailure) {
5033        let (addr, count, server) = start_retry_server(failure, usize::MAX, Some("0")).await;
5034        let mut client =
5035            HyperliquidRawHttpClient::new(HyperliquidEnvironment::Testnet, 1, None).unwrap();
5036        client.set_base_info_url(format!("http://{addr}/info"));
5037
5038        let error = client.info_meta().await.unwrap_err();
5039
5040        server.abort();
5041        assert_retry_failure(error, failure, ("info", 20, Some(0)));
5042        assert_eq!(count.load(Ordering::Relaxed), 1);
5043    }
5044
5045    #[rstest]
5046    #[case(0)]
5047    #[case(1)]
5048    #[case(2)]
5049    #[tokio::test]
5050    async fn info_retry_uses_configured_budget(#[case] max_retries: u32) {
5051        let failure = RetryFailure::Response(503);
5052        let (addr, count, server) = start_retry_server(failure, usize::MAX, Some("invalid")).await;
5053        let mut client =
5054            HyperliquidHttpClient::new(HyperliquidEnvironment::Testnet, 1, None).unwrap();
5055        client.set_base_info_url(format!("http://{addr}/info"));
5056        client.set_info_retry_config(max_retries, Duration::ZERO, Duration::ZERO);
5057
5058        let error = client.info_meta().await.unwrap_err();
5059
5060        server.abort();
5061        assert_retry_failure(error, failure, ("info", 20, None));
5062        assert_eq!(count.load(Ordering::Relaxed), max_retries as usize + 1);
5063    }
5064
5065    #[rstest]
5066    #[case::rate_limit(429)]
5067    #[case::unavailable(503)]
5068    #[tokio::test]
5069    async fn info_retry_honors_retry_after_above_backoff_cap(#[case] status: u16) {
5070        let (addr, count, server) =
5071            start_retry_server(RetryFailure::Response(status), 1, Some("1")).await;
5072        let mut client =
5073            HyperliquidHttpClient::new(HyperliquidEnvironment::Testnet, 2, None).unwrap();
5074        client.set_base_info_url(format!("http://{addr}/info"));
5075        client.set_info_retry_config(1, Duration::ZERO, Duration::ZERO);
5076        let started = tokio::time::Instant::now();
5077
5078        let result = client.info_meta().await;
5079        let elapsed = started.elapsed();
5080
5081        server.abort();
5082        assert!(result.is_ok(), "{result:?}");
5083        assert_eq!(count.load(Ordering::Relaxed), 2);
5084        assert!(elapsed >= Duration::from_secs(1), "{elapsed:?}");
5085    }
5086
5087    #[rstest]
5088    #[case::transport(RetryFailure::Transport)]
5089    #[case::timeout(RetryFailure::Timeout)]
5090    #[case::rate_limit(RetryFailure::Response(429))]
5091    #[case::server_error(RetryFailure::Response(503))]
5092    #[tokio::test]
5093    async fn exchange_does_not_retry_unknown_outcome(
5094        #[case] failure: RetryFailure,
5095        #[values("submit", "modify", "cancel")] operation: &str,
5096    ) {
5097        let (addr, count, server) = start_retry_server(failure, usize::MAX, Some("0")).await;
5098        let mut client = HyperliquidHttpClient::from_credentials(
5099            TEST_PRIVATE_KEY,
5100            None,
5101            HyperliquidEnvironment::Testnet,
5102            1,
5103            None,
5104        )
5105        .unwrap();
5106        client.set_base_exchange_url(format!("http://{addr}/exchange"));
5107        client.set_info_retry_config(9, Duration::ZERO, Duration::ZERO);
5108        let signing: Value =
5109            serde_json::from_str(include_str!("../../test_data/order_decimal_signing.json"))
5110                .unwrap();
5111
5112        let action = match operation {
5113            "submit" => serde_json::from_value(signing["cases"][0]["action"].clone()).unwrap(),
5114            "modify" => HyperliquidExchangeAction::Modify {
5115                modify: serde_json::from_value(
5116                    signing["cases"][2]["action"]["modifies"][0].clone(),
5117                )
5118                .unwrap(),
5119            },
5120            "cancel" => {
5121                let cancels: Value =
5122                    serde_json::from_str(include_str!("../../test_data/cancel_actions.json"))
5123                        .unwrap();
5124                serde_json::from_value(cancels["cancel"]["normal"]["json"].clone()).unwrap()
5125            }
5126            _ => unreachable!(),
5127        };
5128
5129        let error = client.post_action_exec(&action).await.unwrap_err();
5130
5131        server.abort();
5132
5133        assert_retry_failure(error, failure, ("exchange", 1, Some(0)));
5134        assert_eq!(count.load(Ordering::Relaxed), 1);
5135    }
5136
5137    #[derive(Debug, Clone, Copy)]
5138    enum RetryFailure {
5139        Transport,
5140        Timeout,
5141        Response(u16),
5142        InvalidJson,
5143    }
5144
5145    async fn start_retry_server(
5146        failure: RetryFailure,
5147        failures: usize,
5148        retry_after: Option<&'static str>,
5149    ) -> (SocketAddr, Arc<AtomicUsize>, tokio::task::JoinHandle<()>) {
5150        let count = Arc::new(AtomicUsize::new(0));
5151        let requests = count.clone();
5152        let handler = post(move |_body: axum::body::Bytes| {
5153            let count = requests.clone();
5154            async move {
5155                if count.fetch_add(1, Ordering::Relaxed) >= failures {
5156                    return include_str!("../../test_data/http_meta_perp_sample.json")
5157                        .into_response();
5158                }
5159
5160                let mut response = match failure {
5161                    RetryFailure::Transport => {
5162                        let stream = futures_util::stream::once(async {
5163                            Err::<axum::body::Bytes, _>(std::io::Error::other("connection dropped"))
5164                        });
5165
5166                        Response::new(axum::body::Body::from_stream(stream))
5167                    }
5168                    RetryFailure::Timeout => {
5169                        tokio::time::sleep(Duration::from_secs(2)).await;
5170                        "delayed response".into_response()
5171                    }
5172                    RetryFailure::Response(status) => {
5173                        (StatusCode::from_u16(status).unwrap(), "retry failure").into_response()
5174                    }
5175                    RetryFailure::InvalidJson => "invalid json".into_response(),
5176                };
5177
5178                if let Some(value) = retry_after {
5179                    response
5180                        .headers_mut()
5181                        .insert(RETRY_AFTER_HEADER, value.parse().unwrap());
5182                }
5183
5184                response
5185            }
5186        });
5187
5188        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5189        let addr = listener.local_addr().unwrap();
5190        let router = Router::new()
5191            .route("/info", handler.clone())
5192            .route("/exchange", handler);
5193
5194        let server = tokio::spawn(async move {
5195            axum::serve(listener, router).await.unwrap();
5196        });
5197
5198        (addr, count, server)
5199    }
5200
5201    fn assert_retry_failure(
5202        error: Error,
5203        failure: RetryFailure,
5204        rate_limit: (&str, u32, Option<u64>),
5205    ) {
5206        match (failure, error) {
5207            (RetryFailure::Transport, Error::Transport(_))
5208            | (RetryFailure::Timeout, Error::Timeout)
5209            | (RetryFailure::InvalidJson, Error::Serde(_)) => {}
5210            (
5211                RetryFailure::Response(429),
5212                Error::RateLimit {
5213                    scope,
5214                    weight,
5215                    retry_after_ms,
5216                },
5217            ) => {
5218                assert_eq!((scope, weight, retry_after_ms), rate_limit);
5219            }
5220            (
5221                RetryFailure::Response(status),
5222                Error::Http {
5223                    status: actual,
5224                    message,
5225                },
5226            ) => {
5227                assert_eq!((actual, message.as_str()), (status, "retry failure"));
5228            }
5229            (_, e) => panic!("unexpected info failure: {e:?}"),
5230        }
5231    }
5232
5233    fn perp_meta_with_assets(names: &[&str]) -> PerpMeta {
5234        PerpMeta {
5235            universe: names
5236                .iter()
5237                .map(|name| PerpAsset {
5238                    name: (*name).to_string(),
5239                    ..Default::default()
5240                })
5241                .collect(),
5242            margin_tables: Vec::new(),
5243            collateral_token: None,
5244        }
5245    }
5246
5247    #[rstest]
5248    fn resolve_perp_dex_name_uses_empty_string_for_default_dex() {
5249        let meta = perp_meta_with_assets(&["BTC", "ETH"]);
5250        assert_eq!(resolve_perp_dex_name(0, &meta, None), "");
5251    }
5252
5253    #[rstest]
5254    fn resolve_perp_dex_name_prefers_perp_dexs_entry() {
5255        let meta = perp_meta_with_assets(&["xyz:TSLA"]);
5256        let perp_dexs = vec![
5257            None,
5258            Some(PerpDex {
5259                name: "xyz".to_string(),
5260            }),
5261        ];
5262        assert_eq!(resolve_perp_dex_name(1, &meta, Some(&perp_dexs)), "xyz");
5263    }
5264
5265    #[rstest]
5266    fn resolve_perp_dex_name_infers_from_asset_name_when_perp_dexs_missing() {
5267        let meta = perp_meta_with_assets(&["abc:TSLA", "abc:NVDA"]);
5268        assert_eq!(resolve_perp_dex_name(1, &meta, None), "abc");
5269    }
5270
5271    #[rstest]
5272    fn test_build_submit_order_report_elides_waiting_for_fill_tag() {
5273        // A `Tag` status (for example the `waitingForFill` trigger child of a
5274        // `normalTpsl` bracket) must surface as `Ok(None)` so the caller leaves
5275        // the order SUBMITTED until the user-events stream confirms a real oid.
5276        let mut client =
5277            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5278        client.set_account_id(AccountId::from("HYPERLIQUID-001"));
5279
5280        let response: HyperliquidExchangeResponse = serde_json::from_value(json!({
5281            "status": "ok",
5282            "response": {
5283                "type": "order",
5284                "data": {
5285                    "statuses": ["waitingForFill"]
5286                }
5287            }
5288        }))
5289        .unwrap();
5290
5291        let result = client
5292            .build_submit_order_report(
5293                InstrumentId::from("ARB-USD-PERP.HYPERLIQUID"),
5294                ClientOrderId::from("O-WAITING-CHILD"),
5295                OrderSide::Buy,
5296                OrderType::StopMarket,
5297                Quantity::from("100"),
5298                TimeInForce::Gtc,
5299                None,
5300                Some(Price::from("0.16136")),
5301                response,
5302            )
5303            .unwrap();
5304
5305        assert!(
5306            result.is_none(),
5307            "Tag status must elide so the order stays SUBMITTED, was {result:?}"
5308        );
5309    }
5310
5311    #[rstest]
5312    fn test_build_submit_order_report_filled_uses_total_sz_decimal() {
5313        // An atomic `filled` submit response must surface as a FILLED report
5314        // carrying the venue oid and the total filled size built from the
5315        // Decimal `totalSz` at the instrument's size precision.
5316        let mut client =
5317            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5318        client.set_account_id(AccountId::from("HYPERLIQUID-001"));
5319
5320        let base = Currency::new("ARB", 8, 0, "ARB", CurrencyType::Crypto);
5321        let usd = Currency::new("USD", 8, 0, "USD", CurrencyType::Crypto);
5322        let usdc = Currency::new("USDC", 6, 0, "USDC", CurrencyType::Crypto);
5323        let clock = get_atomic_clock_realtime();
5324        let ts = clock.get_time_ns();
5325        let perp = InstrumentAny::CryptoPerpetual(
5326            CryptoPerpetual::builder()
5327                .instrument_id(InstrumentId::new(
5328                    Symbol::new("ARB-USD-PERP"),
5329                    *HYPERLIQUID_VENUE,
5330                ))
5331                .raw_symbol(Symbol::new("ARB"))
5332                .base_currency(base)
5333                .quote_currency(usd)
5334                .settlement_currency(usdc)
5335                .is_inverse(false)
5336                .price_precision(5)
5337                .size_precision(2)
5338                .price_increment(Price::from("0.00001"))
5339                .size_increment(Quantity::from("0.01"))
5340                .ts_event(ts)
5341                .ts_init(ts)
5342                .build()
5343                .unwrap(),
5344        );
5345        client.cache_instrument(&perp);
5346
5347        let response: HyperliquidExchangeResponse = serde_json::from_value(json!({
5348            "status": "ok",
5349            "response": {
5350                "type": "order",
5351                "data": {
5352                    "statuses": [{
5353                        "filled": {"totalSz": "0.5", "avgPx": "1.2345", "oid": 778899}
5354                    }]
5355                }
5356            }
5357        }))
5358        .unwrap();
5359
5360        let report = client
5361            .build_submit_order_report(
5362                InstrumentId::from("ARB-USD-PERP.HYPERLIQUID"),
5363                ClientOrderId::from("O-FILLED-001"),
5364                OrderSide::Buy,
5365                OrderType::Market,
5366                Quantity::from("0.5"),
5367                TimeInForce::Ioc,
5368                None,
5369                None,
5370                response,
5371            )
5372            .unwrap()
5373            .expect("filled status must produce a report");
5374
5375        assert_eq!(report.order_status, OrderStatus::Filled);
5376        assert_eq!(report.venue_order_id.as_str(), "778899");
5377        assert_eq!(report.filled_qty.as_decimal(), dec!(0.5));
5378    }
5379
5380    #[derive(Clone, Default)]
5381    struct OutcomeMetaServerState {
5382        last_request_body: Arc<tokio::sync::Mutex<Option<Value>>>,
5383    }
5384
5385    async fn handle_outcome_meta_info(
5386        State(state): State<OutcomeMetaServerState>,
5387        body: axum::body::Bytes,
5388    ) -> Response {
5389        let Ok(request_body): Result<Value, _> = serde_json::from_slice(&body) else {
5390            return (
5391                StatusCode::BAD_REQUEST,
5392                Json(json!({"error": "Invalid JSON body"})),
5393            )
5394                .into_response();
5395        };
5396
5397        *state.last_request_body.lock().await = Some(request_body.clone());
5398
5399        if request_body.get("type").and_then(|value| value.as_str()) != Some("outcomeMeta") {
5400            return (
5401                StatusCode::BAD_REQUEST,
5402                Json(json!({"error": "Expected outcomeMeta request"})),
5403            )
5404                .into_response();
5405        }
5406
5407        Json(json!({
5408            "outcomes": [
5409                {
5410                    "outcome": 123,
5411                    "quoteToken": "USDC",
5412                    "name": "Recurring",
5413                    "description": "class:priceBinary|underlying:HYPE|expiry:20260310-1100|targetPrice:34.5|period:3m",
5414                    "sideSpecs": [
5415                        {"name": "Yes"},
5416                        {"name": "No"}
5417                    ]
5418                }
5419            ]
5420        }))
5421        .into_response()
5422    }
5423
5424    async fn start_outcome_meta_server(state: OutcomeMetaServerState) -> SocketAddr {
5425        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5426        let addr = listener.local_addr().unwrap();
5427        let router = Router::new()
5428            .route("/info", post(handle_outcome_meta_info))
5429            .with_state(state);
5430
5431        tokio::spawn(async move {
5432            axum::serve(listener, router).await.unwrap();
5433        });
5434
5435        addr
5436    }
5437
5438    async fn handle_unresolved_collateral_info(body: axum::body::Bytes) -> Response {
5439        let Ok(request_body): Result<Value, _> = serde_json::from_slice(&body) else {
5440            return (
5441                StatusCode::BAD_REQUEST,
5442                Json(json!({"error": "Invalid JSON body"})),
5443            )
5444                .into_response();
5445        };
5446
5447        match request_body.get("type").and_then(|value| value.as_str()) {
5448            Some("spotMeta") => (
5449                StatusCode::INTERNAL_SERVER_ERROR,
5450                Json(json!({"error": "spot metadata unavailable"})),
5451            )
5452                .into_response(),
5453            Some("allPerpMetas") => Json(json!([
5454                {
5455                    "collateralToken": 360,
5456                    "marginTables": [],
5457                    "universe": [
5458                        {
5459                            "maxLeverage": 20,
5460                            "name": "km:US500",
5461                            "szDecimals": 3
5462                        }
5463                    ]
5464                }
5465            ]))
5466            .into_response(),
5467            _ => Json(json!({"universe": [], "marginTables": []})).into_response(),
5468        }
5469    }
5470
5471    async fn start_unresolved_collateral_server() -> SocketAddr {
5472        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5473        let addr = listener.local_addr().unwrap();
5474        let router = Router::new().route("/info", post(handle_unresolved_collateral_info));
5475
5476        tokio::spawn(async move {
5477            axum::serve(listener, router).await.unwrap();
5478        });
5479
5480        addr
5481    }
5482
5483    #[rstest]
5484    fn stable_json_roundtrips() {
5485        let v = serde_json::json!({"type":"l2Book","coin":"BTC"});
5486        let s = serde_json::to_string(&v).unwrap();
5487        // Parse back to ensure JSON structure is correct, regardless of field order
5488        let parsed: serde_json::Value = serde_json::from_str(&s).unwrap();
5489        assert_eq!(parsed["type"], "l2Book");
5490        assert_eq!(parsed["coin"], "BTC");
5491        assert_eq!(parsed, v);
5492    }
5493
5494    #[rstest]
5495    fn info_pretty_shape() {
5496        let r = InfoRequest::l2_book("BTC");
5497        let val = serde_json::to_value(&r).unwrap();
5498        let pretty = serde_json::to_string_pretty(&val).unwrap();
5499        assert!(pretty.contains("\"type\": \"l2Book\""));
5500        assert!(pretty.contains("\"coin\": \"BTC\""));
5501    }
5502
5503    #[rstest]
5504    fn test_client_order_id_cloid_cache_is_stable_and_first_write_wins() {
5505        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5506        let client_order_id = ClientOrderId::new("O-CLOID-CACHE");
5507        let other_client_order_id = ClientOrderId::new("O-CLOID-CACHE-OTHER");
5508        let duplicate_client_order_id = ClientOrderId::new("O-CLOID-CACHE-DUPLICATE");
5509        let explicit_cloid = Cloid::from_hex("0x1234567890abcdef1234567890abcdef").unwrap();
5510
5511        let first = client.get_or_generate_client_order_id_cloid(client_order_id);
5512        let second = client.get_or_generate_client_order_id_cloid(client_order_id);
5513        client.cache_client_order_id_cloid(client_order_id, explicit_cloid);
5514        client.cache_client_order_id_cloid(other_client_order_id, explicit_cloid);
5515        client.cache_client_order_id_cloid(duplicate_client_order_id, explicit_cloid);
5516
5517        assert_eq!(first, Cloid::from_client_order_id(client_order_id));
5518        assert_eq!(first, second);
5519        assert_eq!(
5520            client.cached_client_order_id_cloid(&client_order_id),
5521            Some(first),
5522            "cache insert must not overwrite an existing generated CLOID",
5523        );
5524        assert_eq!(
5525            client.unique_cached_client_order_id_cloid(&client_order_id),
5526            Some(first),
5527        );
5528        assert_eq!(
5529            client.cached_client_order_id_cloid(&other_client_order_id),
5530            Some(explicit_cloid),
5531        );
5532        assert_eq!(
5533            client.unique_cached_client_order_id_cloid(&other_client_order_id),
5534            None,
5535            "duplicate CLOID mappings are not safe modify targets",
5536        );
5537        assert_eq!(
5538            client.remove_client_order_id_cloid(&client_order_id),
5539            Some(first),
5540        );
5541        assert_eq!(client.cached_client_order_id_cloid(&client_order_id), None);
5542    }
5543
5544    #[rstest]
5545    fn test_builder_attribution_defaults_to_mainnet_builder() {
5546        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5547        let builder = client
5548            .builder_attribution()
5549            .expect("mainnet client should include builder attribution by default");
5550
5551        assert!(client.include_builder_attribution());
5552        assert_eq!(builder.address, NAUTILUS_BUILDER_ADDRESS);
5553        assert_eq!(builder.fee_tenths_bp, 0);
5554    }
5555
5556    #[rstest]
5557    fn test_builder_attribution_disabled_returns_none() {
5558        let mut client =
5559            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5560        client.set_include_builder_attribution(false);
5561
5562        assert!(!client.include_builder_attribution());
5563        assert!(client.builder_attribution().is_none());
5564    }
5565
5566    #[rstest]
5567    fn test_builder_attribution_omitted_on_testnet() {
5568        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Testnet, 60, None).unwrap();
5569
5570        assert!(client.include_builder_attribution());
5571        assert!(client.builder_attribution().is_none());
5572    }
5573
5574    #[rstest]
5575    #[tokio::test]
5576    async fn test_production_client_get_outcome_meta_uses_outcome_meta_request() {
5577        let state = OutcomeMetaServerState::default();
5578        let addr = start_outcome_meta_server(state.clone()).await;
5579        let mut client =
5580            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5581        client.set_base_info_url(format!("http://{addr}/info"));
5582
5583        let meta = client.get_outcome_meta().await.unwrap();
5584        let request_body = state.last_request_body.lock().await.clone().unwrap();
5585
5586        assert_eq!(request_body, json!({"type": "outcomeMeta"}));
5587        assert_eq!(meta.outcomes.len(), 1);
5588        assert_eq!(meta.outcomes[0].outcome, 123);
5589        assert_eq!(meta.outcomes[0].quote_token.as_deref(), Some("USDC"));
5590        assert_eq!(meta.outcomes[0].name, "Recurring");
5591        assert_eq!(meta.outcomes[0].side_specs.len(), 2);
5592        assert_eq!(meta.outcomes[0].side_specs[0].name, "Yes");
5593        assert_eq!(meta.outcomes[0].side_specs[1].name, "No");
5594    }
5595
5596    #[rstest]
5597    #[tokio::test]
5598    async fn test_request_instrument_defs_errors_when_non_usdc_collateral_unresolved() {
5599        let addr = start_unresolved_collateral_server().await;
5600        let mut client =
5601            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5602        client.set_base_info_url(format!("http://{addr}/info"));
5603
5604        let err = client.request_instrument_defs().await.unwrap_err();
5605
5606        assert_eq!(
5607            err.to_string(),
5608            "decode error: failed to resolve perp collateral currency for dex 0: \
5609             Spot metadata required to resolve perp collateral token 360",
5610        );
5611    }
5612
5613    #[rstest]
5614    fn test_with_credentials_preserves_explicit_account_address() {
5615        let account_address = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
5616        let client = HyperliquidHttpClient::with_credentials(
5617            Some(TEST_PRIVATE_KEY.to_string()),
5618            None,
5619            Some(account_address),
5620            HyperliquidEnvironment::Mainnet,
5621            60,
5622            None,
5623        )
5624        .unwrap();
5625
5626        assert_eq!(client.get_account_address().unwrap(), account_address);
5627    }
5628
5629    #[rstest]
5630    fn test_from_resolved_credentials_preserves_account_address_without_private_key() {
5631        let account_address = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
5632        let client = HyperliquidHttpClient::from_resolved_credentials(
5633            None,
5634            None,
5635            Some(account_address.to_string()),
5636            HyperliquidEnvironment::Mainnet,
5637            60,
5638            None,
5639        )
5640        .unwrap();
5641
5642        assert_eq!(client.get_account_address().unwrap(), account_address);
5643    }
5644
5645    #[rstest]
5646    fn test_with_credentials_rejects_invalid_account_address() {
5647        let e = HyperliquidHttpClient::with_credentials(
5648            Some(TEST_PRIVATE_KEY.to_string()),
5649            None,
5650            Some("0xinvalid"),
5651            HyperliquidEnvironment::Mainnet,
5652            60,
5653            Some("invalid proxy URL".to_string()),
5654        )
5655        .unwrap_err();
5656
5657        assert_eq!(
5658            e.to_string(),
5659            "bad request: Account address must be 20 bytes of valid hex"
5660        );
5661    }
5662
5663    #[rstest]
5664    fn test_set_account_address_normalizes_and_preserves_override_on_error() {
5665        let mut client =
5666            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5667        client
5668            .set_account_address(Some(
5669                " \t0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045 ".to_string(),
5670            ))
5671            .unwrap();
5672        let e = client
5673            .set_account_address(Some("0xinvalid".to_string()))
5674            .unwrap_err();
5675
5676        assert_eq!(
5677            e.to_string(),
5678            "bad request: Account address must be 20 bytes of valid hex"
5679        );
5680        assert_eq!(
5681            client.get_account_address().unwrap(),
5682            "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"
5683        );
5684    }
5685
5686    #[rstest]
5687    #[case(None)]
5688    #[case(Some("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"))]
5689    fn test_set_account_address_clears_override(#[case] vault_address: Option<&str>) {
5690        let mut client = HyperliquidHttpClient::from_resolved_credentials(
5691            Some(TEST_PRIVATE_KEY.to_string()),
5692            vault_address,
5693            Some("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()),
5694            HyperliquidEnvironment::Mainnet,
5695            60,
5696            None,
5697        )
5698        .unwrap();
5699
5700        let expected_address = match vault_address {
5701            Some(vault) => vault.to_string(),
5702            None => client.get_user_address().unwrap(),
5703        };
5704
5705        client.set_account_address(None).unwrap();
5706
5707        assert_eq!(client.account_address, None);
5708        assert_eq!(client.get_account_address().unwrap(), expected_address);
5709    }
5710
5711    #[rstest]
5712    fn test_cache_instrument_by_raw_symbol() {
5713        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5714
5715        // Create a test instrument with base currency "vntls:vCURSOR"
5716        let base_code = "vntls:vCURSOR";
5717        let quote_code = "USDC";
5718
5719        // Register the custom currency
5720        {
5721            let mut currency_map = CURRENCY_MAP.lock();
5722            if !currency_map.contains_key(base_code) {
5723                currency_map.insert(
5724                    base_code.to_string(),
5725                    Currency::new(base_code, 8, 0, base_code, CurrencyType::Crypto),
5726                );
5727            }
5728        }
5729
5730        let base_currency = Currency::new(base_code, 8, 0, base_code, CurrencyType::Crypto);
5731        let quote_currency = Currency::new(quote_code, 6, 0, quote_code, CurrencyType::Crypto);
5732
5733        // Nautilus symbol is "vntls:vCURSOR-USDC-SPOT"
5734        let symbol = Symbol::new("vntls:vCURSOR-USDC-SPOT");
5735        let venue = *HYPERLIQUID_VENUE;
5736        let instrument_id = InstrumentId::new(symbol, venue);
5737
5738        // raw_symbol is set to the base currency "vntls:vCURSOR" (see parse.rs)
5739        let raw_symbol = Symbol::new(base_code);
5740
5741        let clock = get_atomic_clock_realtime();
5742        let ts = clock.get_time_ns();
5743
5744        let instrument = InstrumentAny::CurrencyPair(
5745            CurrencyPair::builder()
5746                .instrument_id(instrument_id)
5747                .raw_symbol(raw_symbol)
5748                .base_currency(base_currency)
5749                .quote_currency(quote_currency)
5750                .price_precision(8)
5751                .size_precision(8)
5752                .price_increment(Price::from("0.00000001"))
5753                .size_increment(Quantity::from("0.00000001"))
5754                .ts_event(ts)
5755                .ts_init(ts)
5756                .build()
5757                .unwrap(),
5758        );
5759
5760        // Cache the instrument
5761        client.cache_instrument(&instrument);
5762
5763        // Verify it can be looked up by full symbol
5764        let instruments = client.instruments.load();
5765        let by_full_symbol = instruments.get(&Ustr::from("vntls:vCURSOR-USDC-SPOT"));
5766        assert!(
5767            by_full_symbol.is_some(),
5768            "Instrument should be accessible by full symbol"
5769        );
5770        assert_eq!(by_full_symbol.unwrap().id(), instrument.id());
5771
5772        // Verify it can be looked up by raw_symbol (coin) - backward compatibility
5773        let by_raw_symbol = instruments.get(&Ustr::from("vntls:vCURSOR"));
5774        assert!(
5775            by_raw_symbol.is_some(),
5776            "Instrument should be accessible by raw_symbol (Hyperliquid coin identifier)"
5777        );
5778        assert_eq!(by_raw_symbol.unwrap().id(), instrument.id());
5779        drop(instruments);
5780
5781        // Verify it can be looked up by composite key (coin, product_type)
5782        let instruments_by_coin = client.instruments_by_coin.load();
5783        let by_coin =
5784            instruments_by_coin.get(&(Ustr::from("vntls:vCURSOR"), HyperliquidProductType::Spot));
5785        assert!(
5786            by_coin.is_some(),
5787            "Instrument should be accessible by coin and product type"
5788        );
5789        assert_eq!(by_coin.unwrap().id(), instrument.id());
5790        drop(instruments_by_coin);
5791
5792        // Verify get_or_create_instrument works with product type
5793        let retrieved_with_type = client.get_or_create_instrument(
5794            &Ustr::from("vntls:vCURSOR"),
5795            Some(HyperliquidProductType::Spot),
5796        );
5797        assert!(retrieved_with_type.is_some());
5798        assert_eq!(retrieved_with_type.unwrap().id(), instrument.id());
5799
5800        // Verify get_or_create_instrument works without product type (fallback)
5801        let retrieved_without_type =
5802            client.get_or_create_instrument(&Ustr::from("vntls:vCURSOR"), None);
5803        assert!(retrieved_without_type.is_some());
5804        assert_eq!(retrieved_without_type.unwrap().id(), instrument.id());
5805    }
5806
5807    #[rstest]
5808    fn test_get_or_create_instrument_outcome_fallback_no_product_type() {
5809        // HTTP fill payloads for HIP-4 outcomes arrive with `coin = "#E"` and
5810        // no product-type context, so the no-product fallback in
5811        // `get_or_create_instrument` must check the Outcome bucket. Without
5812        // this, venue Settlement and userOutcome fills are silently dropped
5813        // from request_fill_reports / request_order_status_reports.
5814        use nautilus_core::time::get_atomic_clock_realtime;
5815        use nautilus_model::{
5816            enums::AssetClass,
5817            identifiers::{InstrumentId, Symbol},
5818            instruments::{BinaryOption, InstrumentAny},
5819            types::{Currency, Price, Quantity},
5820        };
5821
5822        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5823        let coin = "#500";
5824        let token = "+500";
5825
5826        let usdh = Currency::new("USDH", 8, 0, "Hyperliquid USD", CurrencyType::Crypto);
5827        let symbol = Symbol::new(token);
5828        let raw_symbol = Symbol::new(coin);
5829        let venue = *HYPERLIQUID_VENUE;
5830        let instrument_id = InstrumentId::new(symbol, venue);
5831
5832        let clock = get_atomic_clock_realtime();
5833        let ts = clock.get_time_ns();
5834
5835        let binary = InstrumentAny::BinaryOption(
5836            BinaryOption::builder()
5837                .instrument_id(instrument_id)
5838                .raw_symbol(raw_symbol)
5839                .asset_class(AssetClass::Alternative)
5840                .currency(usdh)
5841                .activation_ns(Default::default())
5842                .expiration_ns(Default::default())
5843                .price_precision(4)
5844                .size_precision(2)
5845                .price_increment(Price::from("0.0001"))
5846                .size_increment(Quantity::from("0.01"))
5847                .ts_event(ts)
5848                .ts_init(ts)
5849                .build()
5850                .unwrap(),
5851        );
5852
5853        client.cache_instrument(&binary);
5854
5855        let with_type = client
5856            .get_or_create_instrument(&Ustr::from(coin), Some(HyperliquidProductType::Outcome));
5857        assert!(with_type.is_some());
5858        let with_type = with_type.unwrap();
5859        assert_eq!(with_type.id(), instrument_id);
5860        assert_eq!(with_type.quote_currency(), usdh);
5861
5862        let no_type = client.get_or_create_instrument(&Ustr::from(coin), None);
5863        assert!(
5864            no_type.is_some(),
5865            "Outcome coin must resolve through the no-product fallback",
5866        );
5867        let no_type = no_type.unwrap();
5868        assert_eq!(no_type.id(), instrument_id);
5869        assert_eq!(no_type.quote_currency(), usdh);
5870
5871        let missing = client.get_or_create_instrument(&Ustr::from("#9999"), None);
5872        assert!(missing.is_none());
5873    }
5874
5875    #[rstest]
5876    #[case::coin_form("#200", None, "20-YES-OUTCOME", "#200", 100_000_200)]
5877    #[case::token_form(
5878        "+201",
5879        Some(HyperliquidProductType::Outcome),
5880        "20-NO-OUTCOME",
5881        "#201",
5882        100_000_201
5883    )]
5884    fn test_get_or_create_instrument_resolves_unlisted_outcome(
5885        #[case] coin: &str,
5886        #[case] product_type: Option<HyperliquidProductType>,
5887        #[case] symbol: &str,
5888        #[case] raw_symbol: &str,
5889        #[case] asset_index: u32,
5890    ) {
5891        // Settled outcomes drop out of `outcomeMeta`, so fills carry `#E` coins
5892        // and spot balances carry `+E` tokens for markets never loaded
5893        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5894
5895        let instrument = client
5896            .get_or_create_instrument(&Ustr::from(coin), product_type)
5897            .expect("unlisted outcome coin must resolve from its encoding");
5898
5899        assert_eq!(
5900            instrument.id(),
5901            InstrumentId::new(Symbol::new(symbol), *HYPERLIQUID_VENUE)
5902        );
5903        assert_eq!(instrument.raw_symbol(), Symbol::new(raw_symbol));
5904        assert_eq!(instrument.price_precision(), 5);
5905        assert_eq!(instrument.size_precision(), 0);
5906        assert_eq!(instrument.quote_currency(), Currency::USDC());
5907        assert_eq!(instrument.settlement_currency(), Currency::USDC());
5908        assert_eq!(client.get_asset_index(symbol), Some(asset_index));
5909    }
5910
5911    #[rstest]
5912    fn test_cache_instrument_base_alias_first_write_wins_for_spot() {
5913        // Two spot pairs share the base token "HYPE": the canonical pair is
5914        // cached first; a subsequent non-canonical pair must not overwrite the
5915        // base-token alias so lookups by "HYPE" keep resolving to the canonical
5916        // instrument.
5917        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
5918
5919        let hype = Currency::new("HYPE", 8, 0, "HYPE", CurrencyType::Crypto);
5920        let usdc = Currency::new("USDC", 6, 0, "USDC", CurrencyType::Crypto);
5921        let clock = get_atomic_clock_realtime();
5922        let ts = clock.get_time_ns();
5923
5924        let canonical = InstrumentAny::CurrencyPair(
5925            CurrencyPair::builder()
5926                .instrument_id(InstrumentId::new(
5927                    Symbol::new("HYPE-USDC-SPOT"),
5928                    *HYPERLIQUID_VENUE,
5929                ))
5930                .raw_symbol(Symbol::new("@107"))
5931                .base_currency(hype)
5932                .quote_currency(usdc)
5933                .price_precision(5)
5934                .size_precision(2)
5935                .price_increment(Price::from("0.00001"))
5936                .size_increment(Quantity::from("0.01"))
5937                .ts_event(ts)
5938                .ts_init(ts)
5939                .build()
5940                .unwrap(),
5941        );
5942
5943        let non_canonical = InstrumentAny::CurrencyPair(
5944            CurrencyPair::builder()
5945                .instrument_id(InstrumentId::new(
5946                    Symbol::new("HYPE-USDC-SPOT"),
5947                    *HYPERLIQUID_VENUE,
5948                ))
5949                .raw_symbol(Symbol::new("@999"))
5950                .base_currency(hype)
5951                .quote_currency(usdc)
5952                .price_precision(5)
5953                .size_precision(2)
5954                .price_increment(Price::from("0.00001"))
5955                .size_increment(Quantity::from("0.01"))
5956                .ts_event(ts)
5957                .ts_init(ts)
5958                .build()
5959                .unwrap(),
5960        );
5961
5962        client.merge_instruments(&[canonical.clone(), non_canonical.clone()]);
5963
5964        let instruments_by_coin = client.instruments_by_coin.load();
5965        let by_base = instruments_by_coin
5966            .get(&(Ustr::from("HYPE"), HyperliquidProductType::Spot))
5967            .expect("base alias must resolve");
5968        assert_eq!(
5969            by_base.raw_symbol().inner().as_str(),
5970            "@107",
5971            "base alias must point to the canonical pair, not the one cached later",
5972        );
5973        drop(instruments_by_coin);
5974
5975        let InstrumentAny::CurrencyPair(mut refreshed) = canonical else {
5976            unreachable!();
5977        };
5978
5979        refreshed.price_precision = 4;
5980        refreshed.price_increment = Price::from("0.0001");
5981        refreshed.size_precision = 3;
5982        refreshed.size_increment = Quantity::from("0.001");
5983        let refreshed = InstrumentAny::CurrencyPair(refreshed);
5984        client.merge_instruments(&[refreshed.clone(), non_canonical]);
5985
5986        let resolved = client
5987            .get_or_create_instrument(&Ustr::from("HYPE"), Some(HyperliquidProductType::Spot))
5988            .unwrap();
5989        assert_eq!(
5990            serde_json::to_value(&resolved).unwrap(),
5991            serde_json::to_value(&refreshed).unwrap(),
5992        );
5993    }
5994
5995    #[rstest]
5996    fn test_cache_instrument_perp_aliases_sanitized_base() {
5997        // HIP-3 perp with wildcard-bearing venue name: `instrument_id.symbol`
5998        // is sanitized but order paths derive a coin key by splitting that
5999        // sanitized symbol on `-`. The cache must alias on the sanitized base
6000        // so those lookups resolve to the same instrument cached under
6001        // `raw_symbol` (the venue-official name).
6002        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
6003
6004        let base_currency = Currency::new(
6005            "dex:STREAMABCD****",
6006            8,
6007            0,
6008            "dex:STREAMABCD****",
6009            CurrencyType::Crypto,
6010        );
6011        let usd = Currency::new("USD", 8, 0, "USD", CurrencyType::Crypto);
6012        let usdc = Currency::new("USDC", 6, 0, "USDC", CurrencyType::Crypto);
6013        let clock = get_atomic_clock_realtime();
6014        let ts = clock.get_time_ns();
6015
6016        let hip3 = InstrumentAny::CryptoPerpetual(
6017            CryptoPerpetual::builder()
6018                .instrument_id(InstrumentId::new(
6019                    Symbol::new("dex:STREAMABCDxxxx-USD-PERP"),
6020                    *HYPERLIQUID_VENUE,
6021                ))
6022                .raw_symbol(Symbol::new("dex:STREAMABCD****"))
6023                .base_currency(base_currency)
6024                .quote_currency(usd)
6025                .settlement_currency(usdc)
6026                .is_inverse(false)
6027                .price_precision(6)
6028                .size_precision(3)
6029                .price_increment(Price::from("0.000001"))
6030                .size_increment(Quantity::from("0.001"))
6031                .ts_event(ts)
6032                .ts_init(ts)
6033                .build()
6034                .unwrap(),
6035        );
6036
6037        client.cache_instrument(&hip3);
6038
6039        let instruments_by_coin = client.instruments_by_coin.load();
6040        let by_raw = instruments_by_coin
6041            .get(&(
6042                Ustr::from("dex:STREAMABCD****"),
6043                HyperliquidProductType::Perp,
6044            ))
6045            .expect("venue coin lookup must resolve");
6046        assert_eq!(by_raw.id(), hip3.id());
6047
6048        let by_sanitized = instruments_by_coin
6049            .get(&(
6050                Ustr::from("dex:STREAMABCDxxxx"),
6051                HyperliquidProductType::Perp,
6052            ))
6053            .expect("sanitized base lookup must resolve");
6054        assert_eq!(by_sanitized.id(), hip3.id());
6055        drop(instruments_by_coin);
6056
6057        // Confirm the order-submission lookup path resolves through the alias.
6058        let resolved = client
6059            .get_or_create_instrument(
6060                &Ustr::from("dex:STREAMABCDxxxx"),
6061                Some(HyperliquidProductType::Perp),
6062            )
6063            .expect("get_or_create_instrument must resolve sanitized base for HIP-3");
6064        assert_eq!(resolved.id(), hip3.id());
6065
6066        let InstrumentAny::CryptoPerpetual(mut refreshed) = hip3 else {
6067            unreachable!();
6068        };
6069
6070        refreshed.price_precision = 4;
6071        refreshed.price_increment = Price::from("0.0001");
6072        refreshed.size_precision = 2;
6073        refreshed.size_increment = Quantity::from("0.01");
6074        let refreshed = InstrumentAny::CryptoPerpetual(refreshed);
6075        client.cache_instrument(&refreshed);
6076
6077        let resolved = client
6078            .get_or_create_instrument(
6079                &Ustr::from("dex:STREAMABCDxxxx"),
6080                Some(HyperliquidProductType::Perp),
6081            )
6082            .unwrap();
6083        assert_eq!(
6084            serde_json::to_value(&resolved).unwrap(),
6085            serde_json::to_value(&refreshed).unwrap(),
6086        );
6087    }
6088
6089    #[tokio::test]
6090    #[ignore = "connects to Hyperliquid mainnet public instrument metadata"]
6091    async fn test_live_mainnet_instrument_refresh_updates_aliases() {
6092        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
6093        let original = client.request_instruments().await.unwrap();
6094        assert!(!original.is_empty());
6095
6096        for instrument in original {
6097            client.cache_instrument(&instrument);
6098        }
6099
6100        let refreshed = client.request_instruments().await.unwrap();
6101        let mut spot_aliases = 0;
6102        let mut perp_aliases = 0;
6103
6104        for instrument in &refreshed {
6105            client.cache_instrument(instrument);
6106            let symbol = instrument.symbol();
6107            let product = HyperliquidProductType::from_symbol(symbol.as_str()).unwrap();
6108            let alias = super::cache_alias_for_symbol(symbol.as_str()).unwrap();
6109            let resolved = client
6110                .get_or_create_instrument(&Ustr::from(alias.as_str()), Some(product))
6111                .unwrap();
6112
6113            if resolved.raw_symbol() != instrument.raw_symbol() {
6114                continue;
6115            }
6116
6117            assert_eq!(
6118                serde_json::to_value(&resolved).unwrap(),
6119                serde_json::to_value(instrument).unwrap(),
6120            );
6121            assert_eq!(
6122                client.get_price_precision(symbol.as_str()),
6123                Some(instrument.price_precision()),
6124            );
6125
6126            if alias != instrument.raw_symbol().as_str() {
6127                match product {
6128                    HyperliquidProductType::Spot => spot_aliases += 1,
6129                    HyperliquidProductType::Perp => perp_aliases += 1,
6130                    HyperliquidProductType::Outcome => {}
6131                }
6132            }
6133        }
6134
6135        assert!(spot_aliases > 0);
6136        println!(
6137            "Validated {} refreshed definitions, {spot_aliases} spot aliases, and {perp_aliases} perp aliases",
6138            refreshed.len()
6139        );
6140    }
6141
6142    fn perp_with_asset_index(symbol: &str, asset_index: Option<u32>) -> InstrumentAny {
6143        let base_currency = Currency::new("NEW", 8, 0, "NEW", CurrencyType::Crypto);
6144        let usd = Currency::new("USD", 8, 0, "USD", CurrencyType::Crypto);
6145        let usdc = Currency::new("USDC", 6, 0, "USDC", CurrencyType::Crypto);
6146        let ts = get_atomic_clock_realtime().get_time_ns();
6147
6148        let info = asset_index.map(|asset_index| {
6149            Params::new([(ASSET_INDEX_INFO_KEY.to_string(), asset_index.into())].into())
6150        });
6151
6152        InstrumentAny::CryptoPerpetual(
6153            CryptoPerpetual::builder()
6154                .instrument_id(InstrumentId::new(Symbol::new(symbol), *HYPERLIQUID_VENUE))
6155                .raw_symbol(Symbol::new("NEW"))
6156                .base_currency(base_currency)
6157                .quote_currency(usd)
6158                .settlement_currency(usdc)
6159                .is_inverse(false)
6160                .price_precision(6)
6161                .size_precision(3)
6162                .price_increment(Price::from("0.000001"))
6163                .size_increment(Quantity::from("0.001"))
6164                .maybe_info(info)
6165                .ts_event(ts)
6166                .ts_init(ts)
6167                .build()
6168                .unwrap(),
6169        )
6170    }
6171
6172    #[rstest]
6173    fn test_cache_instrument_registers_asset_index_from_info() {
6174        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
6175
6176        client.cache_instrument(&perp_with_asset_index("NEW-USD-PERP", Some(42)));
6177
6178        assert_eq!(client.get_asset_index("NEW-USD-PERP"), Some(42));
6179    }
6180
6181    #[rstest]
6182    fn test_cache_instrument_without_asset_index_info_retains_existing_index() {
6183        // Guessing an index would route orders to the wrong asset, so an
6184        // instrument missing the info key must leave the map untouched.
6185        let client = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
6186
6187        client.cache_instrument(&perp_with_asset_index("NEW-USD-PERP", Some(42)));
6188        let asset_indices = client.asset_indices.load();
6189        client.cache_instrument(&perp_with_asset_index("NEW-USD-PERP", None));
6190        client.cache_instrument(&perp_with_asset_index("OTHER-USD-PERP", None));
6191
6192        assert_eq!(client.get_asset_index("NEW-USD-PERP"), Some(42));
6193        assert_eq!(client.get_asset_index("OTHER-USD-PERP"), None);
6194        assert!(Arc::ptr_eq(&asset_indices, &client.asset_indices.load()));
6195    }
6196
6197    fn btc_history_client() -> HyperliquidHttpClient {
6198        let mut client =
6199            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 60, None).unwrap();
6200        client.set_account_id(AccountId::from("HYPERLIQUID-001"));
6201
6202        let base = Currency::new("BTC", 8, 0, "BTC", CurrencyType::Crypto);
6203        let usd = Currency::new("USD", 8, 0, "USD", CurrencyType::Crypto);
6204        let usdc = Currency::new("USDC", 6, 0, "USDC", CurrencyType::Crypto);
6205        let ts = get_atomic_clock_realtime().get_time_ns();
6206        let perp = InstrumentAny::CryptoPerpetual(
6207            CryptoPerpetual::builder()
6208                .instrument_id(InstrumentId::new(
6209                    Symbol::new("BTC-USD-PERP"),
6210                    *HYPERLIQUID_VENUE,
6211                ))
6212                .raw_symbol(Symbol::new("BTC"))
6213                .base_currency(base)
6214                .quote_currency(usd)
6215                .settlement_currency(usdc)
6216                .is_inverse(false)
6217                .price_precision(1)
6218                .size_precision(5)
6219                .price_increment(Price::from("0.1"))
6220                .size_increment(Quantity::from("0.00001"))
6221                .ts_event(ts)
6222                .ts_init(ts)
6223                .build()
6224                .unwrap(),
6225        );
6226        client.cache_instrument(&perp);
6227        client
6228    }
6229
6230    fn history_rows(rows: Value) -> Vec<HyperliquidOrderStatusEntry> {
6231        serde_json::from_value(rows).unwrap()
6232    }
6233
6234    // Builds an order from the report the way reconciliation does for an external order
6235    fn assert_initializes_order(report: &OrderStatusReport) -> OrderAny {
6236        let initialized = OrderInitialized::new_checked(
6237            TraderId::from("TESTER-001"),
6238            StrategyId::from("EXTERNAL"),
6239            report.instrument_id,
6240            ClientOrderId::from(report.venue_order_id.as_str()),
6241            report.order_side.expect("report has an order side"),
6242            report.order_type,
6243            report.quantity,
6244            report.time_in_force,
6245            report.post_only,
6246            report.reduce_only,
6247            false,
6248            true,
6249            UUID4::new(),
6250            UnixNanos::default(),
6251            UnixNanos::default(),
6252            report.price,
6253            report.activation_price,
6254            report.trigger_price,
6255            report.trigger_type,
6256            report.limit_offset,
6257            report.trailing_offset,
6258            report.trailing_offset_type,
6259            report.expire_time,
6260            report.display_qty,
6261            None,
6262            None,
6263            report.contingency_type,
6264            report.order_list_id,
6265            report.linked_order_ids.clone(),
6266            report.parent_order_id,
6267            None,
6268            None,
6269            None,
6270            None,
6271        )
6272        .expect("report must initialize an order");
6273        OrderAny::from_events(vec![OrderEventAny::Initialized(initialized)])
6274            .expect("order must replay from its initialization")
6275    }
6276
6277    // `historicalOrders` rows for a position stop that triggered and filled: once filled, the
6278    // venue zeroes `triggerPx` and clears `isTrigger`, so only the earlier rows carry the trigger
6279    fn triggered_stop_rows() -> Value {
6280        let trigger_row = |status: &str, ts: u64| {
6281            json!({
6282                "order": {
6283                    "coin": "BTC", "side": "A", "limitPx": "58800.0", "sz": "0.0",
6284                    "oid": 900000001_u64, "timestamp": 1700000000000_u64,
6285                    "triggerCondition": "Price below 59500", "isTrigger": true,
6286                    "triggerPx": "59500.0", "children": [], "isPositionTpsl": true,
6287                    "reduceOnly": true, "orderType": "Stop Market", "origSz": "0.0", "tif": null,
6288                    "cloid": "0x00000000000000000000000000000a01"
6289                },
6290                "status": status,
6291                "statusTimestamp": ts
6292            })
6293        };
6294        json!([
6295            filled_stop_row(),
6296            trigger_row("triggered", 1700000600000),
6297            trigger_row("open", 1700000000000),
6298        ])
6299    }
6300
6301    fn filled_stop_row() -> Value {
6302        json!({
6303            "order": {
6304                "coin": "BTC", "side": "A", "limitPx": "58200.0", "sz": "0.0",
6305                "oid": 900000001_u64, "timestamp": 1700000600000_u64,
6306                "triggerCondition": "Triggered", "isTrigger": false, "triggerPx": "0.0",
6307                "children": [], "isPositionTpsl": true, "reduceOnly": true,
6308                "orderType": "Stop Market", "origSz": "0.02", "tif": "Gtc",
6309                "cloid": "0x00000000000000000000000000000a01"
6310            },
6311            "status": "filled",
6312            "statusTimestamp": 1700000600000_u64
6313        })
6314    }
6315
6316    #[rstest]
6317    fn test_historical_reports_triggered_stop_keeps_trigger_from_earlier_rows() {
6318        let client = btc_history_client();
6319
6320        let sweep = client
6321            .historical_order_status_reports_from_response(
6322                history_rows(triggered_stop_rows()),
6323                None,
6324            )
6325            .unwrap();
6326
6327        assert!(sweep.complete);
6328        assert_eq!(sweep.reports.len(), 1);
6329        let report = &sweep.reports[0];
6330        assert_eq!(report.venue_order_id, VenueOrderId::new("900000001"));
6331        assert_eq!(report.order_type, OrderType::StopMarket);
6332        assert_eq!(report.order_status, OrderStatus::Filled);
6333        assert_eq!(report.filled_qty, Quantity::from("0.02"));
6334        assert_eq!(report.trigger_price, Some(Price::from("59500.0")));
6335        assert_eq!(report.trigger_type, Some(TriggerType::Default));
6336        assert_initializes_order(report);
6337    }
6338
6339    #[rstest]
6340    fn test_historical_reports_triggered_stop_limit_keeps_trigger_and_price() {
6341        let client = btc_history_client();
6342        let mut rows = triggered_stop_rows();
6343        for row in rows.as_array_mut().unwrap() {
6344            row["order"]["orderType"] = json!("Stop Limit");
6345        }
6346
6347        let sweep = client
6348            .historical_order_status_reports_from_response(history_rows(rows), None)
6349            .unwrap();
6350
6351        assert_eq!(sweep.reports.len(), 1);
6352        let report = &sweep.reports[0];
6353        assert_eq!(report.order_type, OrderType::StopLimit);
6354        // The filled row carries no price; the merge takes it from the earlier rows
6355        assert_eq!(report.price, Some(Price::from("58800.0")));
6356        assert_eq!(report.trigger_price, Some(Price::from("59500.0")));
6357        assert_eq!(report.trigger_type, Some(TriggerType::Default));
6358        assert_initializes_order(report);
6359    }
6360
6361    #[rstest]
6362    #[case("Stop Market", "filled", OrderType::Market)]
6363    #[case("Take Profit Market", "filled", OrderType::Market)]
6364    #[case("Stop Limit", "filled", OrderType::Market)]
6365    #[case("Take Profit Limit", "filled", OrderType::Market)]
6366    #[case("Stop Market", "canceled", OrderType::Market)]
6367    #[case("Take Profit Market", "canceled", OrderType::Market)]
6368    #[case("Stop Limit", "canceled", OrderType::Limit)]
6369    #[case("Take Profit Limit", "canceled", OrderType::Limit)]
6370    fn test_historical_reports_closed_trigger_without_trigger_rows_is_untriggered(
6371        #[case] label: &str,
6372        #[case] status: &str,
6373        #[case] expected: OrderType,
6374    ) {
6375        // Only the zeroed final row survives (older rows aged out of the history window). A
6376        // filled row carries no price, so only a canceled limit-style row can stay a limit order.
6377        let client = btc_history_client();
6378        let mut row = filled_stop_row();
6379        row["order"]["orderType"] = json!(label);
6380        row["status"] = json!(status);
6381        // A canceled order's `sz` holds its unfilled size
6382        let expected_filled = if status == "canceled" {
6383            row["order"]["sz"] = json!("0.02");
6384            "0"
6385        } else {
6386            "0.02"
6387        };
6388
6389        let sweep = client
6390            .historical_order_status_reports_from_response(history_rows(json!([row])), None)
6391            .unwrap();
6392
6393        assert_eq!(sweep.reports.len(), 1);
6394        let report = &sweep.reports[0];
6395        assert_eq!(report.order_type, expected);
6396        assert_eq!(report.filled_qty, Quantity::from(expected_filled));
6397        assert!(report.trigger_price.is_none());
6398        assert!(report.trigger_type.is_none());
6399        assert_eq!(report.price.is_some(), expected == OrderType::Limit);
6400        assert!(report.reduce_only);
6401        assert_initializes_order(report);
6402    }
6403
6404    #[rstest]
6405    fn test_historical_reports_triggered_stop_filled_with_remainder() {
6406        // Both fixes on one row: a triggered stop's zeroed final row that also left a remainder
6407        let client = btc_history_client();
6408        let mut row = filled_stop_row();
6409        row["order"]["sz"] = json!("0.0008");
6410
6411        let sweep = client
6412            .historical_order_status_reports_from_response(history_rows(json!([row])), None)
6413            .unwrap();
6414
6415        assert_eq!(sweep.reports.len(), 1);
6416        let report = &sweep.reports[0];
6417        assert_eq!(report.order_status, OrderStatus::Canceled);
6418        assert_eq!(report.order_type, OrderType::Market);
6419        assert_eq!(report.filled_qty, Quantity::from("0.0192"));
6420        assert!(report.price.is_none());
6421        assert_initializes_order(report);
6422    }
6423
6424    #[rstest]
6425    fn test_historical_reports_open_trigger_without_trigger_price_keeps_order_type() {
6426        // An order that is still working keeps its trigger type even when its row lacks a
6427        // trigger price
6428        let client = btc_history_client();
6429        let mut row = filled_stop_row();
6430        row["status"] = json!("triggered");
6431
6432        let sweep = client
6433            .historical_order_status_reports_from_response(history_rows(json!([row])), None)
6434            .unwrap();
6435
6436        assert_eq!(sweep.reports.len(), 1);
6437        assert_eq!(sweep.reports[0].order_type, OrderType::StopMarket);
6438    }
6439
6440    // An IOC order the venue marks `filled` although 0.0005 of 0.015 went unfilled: `sz`
6441    // carries the canceled remainder
6442    #[rstest]
6443    fn test_historical_reports_partially_filled_ioc_is_canceled() {
6444        let client = btc_history_client();
6445        let row = |status: &str, sz: &str| {
6446            json!({
6447                "order": {
6448                    "coin": "BTC", "side": "A", "limitPx": "60100.0", "sz": sz,
6449                    "oid": 900000002_u64, "timestamp": 1700001000000_u64,
6450                    "triggerCondition": "N/A", "isTrigger": false, "triggerPx": "0.0",
6451                    "children": [], "isPositionTpsl": false, "reduceOnly": false,
6452                    "orderType": "Limit", "origSz": "0.015", "tif": "Ioc",
6453                    "cloid": "0x00000000000000000000000000000a02"
6454                },
6455                "status": status,
6456                "statusTimestamp": 1700001000000_u64
6457            })
6458        };
6459
6460        let sweep = client
6461            .historical_order_status_reports_from_response(
6462                history_rows(json!([row("filled", "0.0005"), row("open", "0.015")])),
6463                None,
6464            )
6465            .unwrap();
6466
6467        assert_eq!(sweep.reports.len(), 1);
6468        let report = &sweep.reports[0];
6469        assert_eq!(report.order_status, OrderStatus::Canceled);
6470        assert_eq!(report.order_type, OrderType::Limit);
6471        assert_eq!(report.quantity, Quantity::from("0.015"));
6472        assert_eq!(report.filled_qty, Quantity::from("0.0145"));
6473        // The filled row carries no price; the merge takes the limit price from the open row
6474        assert_eq!(report.price, Some(Price::from("60100.0")));
6475        assert_eq!(
6476            report.cancel_reason.as_deref(),
6477            Some("Unfilled remainder canceled")
6478        );
6479        assert_initializes_order(report);
6480    }
6481}