Skip to main content

nautilus_hyperliquid/common/
parse.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//! Parsing utilities that convert Hyperliquid payloads into Nautilus domain models.
17//!
18//! # Conditional Order Support
19//!
20//! This module implements conditional order support for Hyperliquid.
21//!
22//! ## Supported Order Types
23//!
24//! ### Standard Orders
25//! - **Market**: Implemented as IOC (Immediate-or-Cancel) limit orders.
26//! - **Limit**: Standard limit orders with GTC/IOC/ALO time-in-force.
27//!
28//! ### Conditional/Trigger Orders
29//! - **StopMarket**: Protective stop that triggers at specified price and executes at market.
30//! - **StopLimit**: Protective stop that triggers at specified price and executes at limit.
31//! - **MarketIfTouched**: Profit-taking/entry order that triggers and executes at market.
32//! - **LimitIfTouched**: Profit-taking/entry order that triggers and executes at limit.
33//!
34//! ## Order Semantics
35//!
36//! ### Stop Orders (StopMarket/StopLimit)
37//! - Used for protective stops and risk management.
38//! - Mapped to Hyperliquid's trigger orders with `tpsl: Sl`.
39//! - Trigger when price reaches the stop level.
40//! - Execute immediately (market) or at limit price.
41//!
42//! ### If Touched Orders (MarketIfTouched/LimitIfTouched)
43//! - Used for profit-taking or entry orders.
44//! - Mapped to Hyperliquid's trigger orders with `tpsl: Tp`.
45//! - Trigger when price reaches the target level.
46//! - Execute immediately (market) or at limit price.
47//!
48//! ## Trigger Price Logic
49//!
50//! The `tpsl` field (Take Profit / Stop Loss) is determined by:
51//! 1. **Order Type**: Stop orders → SL, If Touched orders → TP
52//! 2. **Price Relationship** (if available):
53//!    - For BUY orders: trigger above market → SL, below → TP
54//!    - For SELL orders: trigger below market → SL, above → TP
55//!
56//! ## Trigger Type Support
57//!
58//! Hyperliquid uses **mark price** for all trigger evaluations (TP/SL orders).
59
60use anyhow::Context;
61pub use nautilus_core::serialization::{
62    deserialize_decimal_from_str, deserialize_optional_decimal_from_str,
63    deserialize_vec_decimal_from_str, serialize_decimal_as_str, serialize_optional_decimal_as_str,
64    serialize_vec_decimal_as_str,
65};
66use nautilus_core::{UnixNanos, datetime::NANOSECONDS_IN_MILLISECOND};
67use nautilus_model::{
68    data::{bar::BarType, quote::QuoteTick},
69    enums::{
70        AggregationSource, BarAggregation, ContingencyType, OrderSide, OrderStatus, OrderType,
71        TimeInForce,
72    },
73    identifiers::{ClientOrderId, TradeId},
74    orders::{Order, any::OrderAny},
75    types::{AccountBalance, Currency, MarginBalance, Money},
76};
77use rust_decimal::Decimal;
78
79use crate::{
80    common::{
81        enums::{
82            HyperliquidAccountAbstraction,
83            HyperliquidBarInterval::{self, *},
84            HyperliquidOrderStatus, HyperliquidTpSl,
85        },
86        types::HyperliquidAssetId,
87    },
88    http::models::{
89        ClearinghouseState, Cloid, HyperliquidExchangeCancelByCloidRequest,
90        HyperliquidExchangeCancelStatus, HyperliquidExchangeGrouping,
91        HyperliquidExchangeLimitParams, HyperliquidExchangeModifyStatus,
92        HyperliquidExchangeOrderKind, HyperliquidExchangeOrderStatus,
93        HyperliquidExchangePlaceOrderRequest, HyperliquidExchangeResponse,
94        HyperliquidExchangeResponseData, HyperliquidExchangeTif, HyperliquidExchangeTpSl,
95        HyperliquidExchangeTriggerParams, RESPONSE_STATUS_OK, SpotClearinghouseState,
96    },
97    websocket::messages::TrailingOffsetType,
98};
99
100/// Creates a deterministic [`TradeId`] from fill fields common to both WS and HTTP responses.
101///
102/// Uses FNV-1a hash of `(hash, oid, px, sz, time, start_position)` to produce a unique
103/// identifier consistent across both data sources for the same physical fill.
104/// Includes `start_position` (running position before each fill) to disambiguate
105/// multiple partial fills within the same transaction at the same price/size.
106/// Format: `{fnv_hex}-{oid_hex}` (exactly 33 chars, within 36-char limit).
107pub fn make_fill_trade_id(
108    hash: &str,
109    oid: u64,
110    px: Decimal,
111    sz: Decimal,
112    time: u64,
113    start_position: Decimal,
114) -> TradeId {
115    // FNV-1a with fixed seed for deterministic output
116    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
117    for &b in hash.as_bytes() {
118        h ^= b as u64;
119        h = h.wrapping_mul(0x0100_0000_01b3);
120    }
121
122    for b in oid.to_le_bytes() {
123        h ^= b as u64;
124        h = h.wrapping_mul(0x0100_0000_01b3);
125    }
126
127    for &b in px.to_string().as_bytes() {
128        h ^= b as u64;
129        h = h.wrapping_mul(0x0100_0000_01b3);
130    }
131
132    for &b in sz.to_string().as_bytes() {
133        h ^= b as u64;
134        h = h.wrapping_mul(0x0100_0000_01b3);
135    }
136
137    for b in time.to_le_bytes() {
138        h ^= b as u64;
139        h = h.wrapping_mul(0x0100_0000_01b3);
140    }
141
142    for &b in start_position.to_string().as_bytes() {
143        h ^= b as u64;
144        h = h.wrapping_mul(0x0100_0000_01b3);
145    }
146    TradeId::new(format!("{h:016x}-{oid:016x}"))
147}
148
149/// Round price down to the nearest valid tick size.
150#[inline]
151pub fn round_down_to_tick(price: Decimal, tick_size: Decimal) -> Decimal {
152    if tick_size.is_zero() {
153        return price;
154    }
155    (price / tick_size).floor() * tick_size
156}
157
158/// Round quantity down to the nearest valid step size.
159#[inline]
160pub fn round_down_to_step(qty: Decimal, step_size: Decimal) -> Decimal {
161    if step_size.is_zero() {
162        return qty;
163    }
164    (qty / step_size).floor() * step_size
165}
166
167/// Ensure the notional value meets minimum requirements.
168#[inline]
169pub fn ensure_min_notional(
170    price: Decimal,
171    qty: Decimal,
172    min_notional: Decimal,
173) -> Result<(), String> {
174    let notional = price * qty;
175    if notional < min_notional {
176        Err(format!(
177            "Notional value {notional} is less than minimum required {min_notional}"
178        ))
179    } else {
180        Ok(())
181    }
182}
183
184/// Round a decimal to at most N significant figures.
185/// Hyperliquid requires prices to have at most 5 significant figures.
186pub fn round_to_sig_figs(value: Decimal, sig_figs: u32) -> Decimal {
187    if value.is_zero() {
188        return Decimal::ZERO;
189    }
190
191    // log10(|value|) = log10(|mantissa|) - scale; `ilog10` skips the float path
192    let mantissa = value.mantissa().unsigned_abs();
193    let magnitude = mantissa.ilog10() as i32 - value.scale() as i32;
194
195    let shift = sig_figs as i32 - 1 - magnitude;
196    let factor = Decimal::from(10_i64.pow(shift.unsigned_abs()));
197
198    if shift >= 0 {
199        (value * factor).round() / factor
200    } else {
201        (value / factor).round() * factor
202    }
203}
204
205/// Normalize price to the specified number of decimal places.
206pub fn normalize_price(price: Decimal, decimals: u8) -> Decimal {
207    // First round to 5 significant figures (Hyperliquid requirement)
208    let sig_fig_price = round_to_sig_figs(price, 5);
209    // Then truncate to max decimal places
210    let scale = Decimal::from(10_u64.pow(decimals as u32));
211    (sig_fig_price * scale).floor() / scale
212}
213
214/// Normalize quantity to the specified number of decimal places.
215pub fn normalize_quantity(qty: Decimal, decimals: u8) -> Decimal {
216    let scale = Decimal::from(10_u64.pow(decimals as u32));
217    (qty * scale).floor() / scale
218}
219
220/// Validates venue canonical wire form for a price submitted with price
221/// normalization disabled: at most `price_decimals` fractional digits. The
222/// venue parses prices into its canonical form before verifying the action
223/// signature, so a price with excess decimals fails signature verification
224/// and surfaces as a misleading "wallet does not exist" error instead of an
225/// order validation error.
226fn ensure_canonical_wire_price(
227    label: &str,
228    price: Decimal,
229    price_decimals: u8,
230) -> anyhow::Result<()> {
231    anyhow::ensure!(
232        price.scale() <= u32::from(price_decimals),
233        "{label} {price} exceeds the instrument maximum of {price_decimals} decimal places; \
234         enable normalize_prices or adjust the price"
235    );
236    Ok(())
237}
238
239/// Normalizes a price to the venue wire form, or validates the canonical
240/// form when normalization is disabled. Validation is skipped when the
241/// instrument decimal cap is unknown (`None`): the prior raw passthrough is
242/// preserved rather than validating against a placeholder. See
243/// [`ensure_canonical_wire_price`].
244pub(crate) fn normalize_or_validate_wire_price(
245    raw: Decimal,
246    label: &str,
247    price_decimals: Option<u8>,
248    should_normalize_prices: bool,
249) -> anyhow::Result<Decimal> {
250    if should_normalize_prices {
251        Ok(normalize_price(raw, price_decimals.unwrap_or(2)).normalize())
252    } else {
253        let value = raw.normalize();
254        if let Some(decimals) = price_decimals {
255            ensure_canonical_wire_price(label, value, decimals)?;
256        }
257        Ok(value)
258    }
259}
260
261/// Complete normalization for an order including price, quantity, and notional validation
262pub fn normalize_order(
263    price: Decimal,
264    qty: Decimal,
265    tick_size: Decimal,
266    step_size: Decimal,
267    min_notional: Decimal,
268    price_decimals: u8,
269    size_decimals: u8,
270) -> Result<(Decimal, Decimal), String> {
271    // Normalize to decimal places first
272    let normalized_price = normalize_price(price, price_decimals);
273    let normalized_qty = normalize_quantity(qty, size_decimals);
274
275    // Round down to tick/step sizes
276    let final_price = round_down_to_tick(normalized_price, tick_size);
277    let final_qty = round_down_to_step(normalized_qty, step_size);
278
279    // Validate minimum notional
280    ensure_min_notional(final_price, final_qty, min_notional)?;
281
282    Ok((final_price, final_qty))
283}
284
285/// Converts millisecond timestamp to [`UnixNanos`].
286#[inline]
287pub fn millis_to_nanos(millis: u64) -> anyhow::Result<UnixNanos> {
288    millis
289        .checked_mul(NANOSECONDS_IN_MILLISECOND)
290        .map(UnixNanos::from)
291        .with_context(|| format!("milliseconds {millis} is out of range for `u64` nanoseconds"))
292}
293
294/// Parses an outcome (HIP-4) spot coin or token symbol into an asset ID.
295///
296/// Hyperliquid represents outcome spot coins as `#<encoding>` and outcome
297/// token names as `+<encoding>`, where `encoding = 10 * outcome + side`.
298///
299/// # Errors
300///
301/// Returns an error if the symbol is not an outcome symbol, the encoding is
302/// not numeric, overflows the asset id range, or carries an invalid side digit.
303pub fn parse_outcome_symbol(symbol: &str) -> anyhow::Result<HyperliquidAssetId> {
304    let encoding = parse_outcome_symbol_encoding(symbol)?;
305    HyperliquidAssetId::from_outcome_encoding(encoding).with_context(|| {
306        format!(
307            "Invalid Hyperliquid outcome symbol '{symbol}': encoding must fit u32 and end with side digit 0 or 1"
308        )
309    })
310}
311
312fn parse_outcome_symbol_encoding(symbol: &str) -> anyhow::Result<u32> {
313    let encoding = symbol
314        .strip_prefix('#')
315        .or_else(|| symbol.strip_prefix('+'))
316        .with_context(|| {
317            format!(
318                "Invalid Hyperliquid outcome symbol '{symbol}': expected #<encoding> or +<encoding>"
319            )
320        })?;
321
322    if encoding.is_empty() {
323        anyhow::bail!("Invalid Hyperliquid outcome symbol '{symbol}': encoding must not be empty");
324    }
325
326    if !encoding.bytes().all(|b| b.is_ascii_digit()) {
327        anyhow::bail!("Invalid Hyperliquid outcome symbol '{symbol}': encoding must be numeric");
328    }
329
330    encoding
331        .parse::<u32>()
332        .with_context(|| format!("Invalid Hyperliquid outcome symbol '{symbol}'"))
333}
334
335/// Suffix shared by every Nautilus outcome symbol, mirroring `-PERP` / `-SPOT`.
336pub const OUTCOME_SYMBOL_SUFFIX: &str = "-OUTCOME";
337/// Yes-side label on Nautilus outcome symbols.
338pub const OUTCOME_SIDE_YES: &str = "YES";
339/// No-side label on Nautilus outcome symbols.
340pub const OUTCOME_SIDE_NO: &str = "NO";
341
342/// Parses a Nautilus outcome instrument symbol of the form
343/// `{outcome_index}-{YES|NO}-OUTCOME` into `(outcome_index, side)` where side
344/// is `0` for Yes and `1` for No.
345///
346/// Returns `None` if the symbol does not match the expected shape or if the
347/// `(outcome_index, side)` pair would not encode into a valid HIP-4
348/// `HyperliquidAssetId` (i.e. `100_000_000 + 10 * outcome_index + side`
349/// would overflow `u32`). The legacy `#E` / `+E` wire parser already rejects
350/// out-of-range encodings; this keeps the two paths in parity so downstream
351/// arithmetic on the returned pair cannot overflow.
352#[must_use]
353pub fn parse_outcome_nautilus_symbol(symbol: &str) -> Option<(u32, u8)> {
354    let rest = symbol.strip_suffix(OUTCOME_SYMBOL_SUFFIX)?;
355    let (index_str, side_str) = rest.rsplit_once('-')?;
356    let outcome_index = index_str.parse::<u32>().ok()?;
357    let side = match side_str {
358        OUTCOME_SIDE_YES => 0,
359        OUTCOME_SIDE_NO => 1,
360        _ => return None,
361    };
362    let encoding = outcome_index
363        .checked_mul(10)?
364        .checked_add(u32::from(side))?;
365    HyperliquidAssetId::from_outcome_encoding(encoding)?;
366    Some((outcome_index, side))
367}
368
369/// Formats an `(outcome_index, side)` pair into the Nautilus outcome symbol
370/// form `{outcome_index}-{YES|NO}-OUTCOME`.
371#[must_use]
372pub fn format_outcome_nautilus_symbol(outcome_index: u32, side: u8) -> String {
373    let side_label = match side {
374        0 => OUTCOME_SIDE_YES,
375        _ => OUTCOME_SIDE_NO,
376    };
377    format!("{outcome_index}-{side_label}{OUTCOME_SYMBOL_SUFFIX}")
378}
379
380/// Returns the `+<encoding>` token form for the side token referenced by a
381/// Nautilus outcome symbol, or `None` if the symbol is not an outcome.
382#[must_use]
383pub fn outcome_token_from_nautilus_symbol(symbol: &str) -> Option<String> {
384    let (outcome_index, side) = parse_outcome_nautilus_symbol(symbol)?;
385    let encoding = 10 * outcome_index + u32::from(side);
386    Some(format!("+{encoding}"))
387}
388
389/// Returns the secondary cache-alias key for a Nautilus instrument symbol.
390///
391/// For outcome symbols, this is the `+<encoding>` token form (matching the
392/// `coin` field on `spotClearinghouseState` balances). For perp / spot
393/// symbols it is the leading segment before the first `-` (the base asset
394/// or sanitized base for HIP-3 perps). Returns `None` for an empty symbol.
395///
396/// Used by `cache_instrument`, order-response report builders, and the bar
397/// lookup so all three derive the same alias and stay in sync as the symbol
398/// shape evolves.
399#[must_use]
400pub fn cache_alias_for_symbol(symbol: &str) -> Option<String> {
401    if let Some(token) = outcome_token_from_nautilus_symbol(symbol) {
402        return Some(token);
403    }
404
405    let leading = symbol.split('-').next()?;
406    if leading.is_empty() {
407        None
408    } else {
409        Some(leading.to_string())
410    }
411}
412
413/// Converts a Nautilus `TimeInForce` to Hyperliquid TIF.
414///
415/// # Errors
416///
417/// Returns an error if the time in force is not supported.
418pub fn time_in_force_to_hyperliquid_tif(
419    tif: TimeInForce,
420    is_post_only: bool,
421) -> anyhow::Result<HyperliquidExchangeTif> {
422    match (tif, is_post_only) {
423        (_, true) => Ok(HyperliquidExchangeTif::Alo), // Always use ALO for post-only orders
424        (TimeInForce::Gtc, false) => Ok(HyperliquidExchangeTif::Gtc),
425        (TimeInForce::Ioc, false) => Ok(HyperliquidExchangeTif::Ioc),
426        (TimeInForce::Fok, false) => {
427            anyhow::bail!("FOK time in force is not supported by Hyperliquid")
428        }
429        _ => anyhow::bail!("Unsupported time in force for Hyperliquid: {tif:?}"),
430    }
431}
432
433fn determine_tpsl_type(
434    order_type: OrderType,
435    order_side: OrderSide,
436    trigger_price: Decimal,
437    current_price: Option<Decimal>,
438) -> HyperliquidExchangeTpSl {
439    match order_type {
440        // Stop orders are protective - always SL
441        OrderType::StopMarket | OrderType::StopLimit => HyperliquidExchangeTpSl::Sl,
442
443        // If Touched orders are profit-taking or entry orders - always TP
444        OrderType::MarketIfTouched | OrderType::LimitIfTouched => HyperliquidExchangeTpSl::Tp,
445
446        // For other trigger types, try to infer from price relationship if available
447        _ => {
448            if let Some(current) = current_price {
449                match order_side {
450                    OrderSide::Buy => {
451                        // Buy order: trigger above market = stop loss, below = take profit
452                        if trigger_price > current {
453                            HyperliquidExchangeTpSl::Sl
454                        } else {
455                            HyperliquidExchangeTpSl::Tp
456                        }
457                    }
458                    OrderSide::Sell => {
459                        // Sell order: trigger below market = stop loss, above = take profit
460                        if trigger_price < current {
461                            HyperliquidExchangeTpSl::Sl
462                        } else {
463                            HyperliquidExchangeTpSl::Tp
464                        }
465                    }
466                }
467            } else {
468                // No market price available, default to SL for safety
469                HyperliquidExchangeTpSl::Sl
470            }
471        }
472    }
473}
474
475/// Converts a Nautilus `BarType` to a Hyperliquid bar interval.
476///
477/// # Errors
478///
479/// Returns an error if the bar type uses an unsupported aggregation or step value.
480pub fn bar_type_to_interval(bar_type: &BarType) -> anyhow::Result<HyperliquidBarInterval> {
481    let spec = bar_type.spec();
482    let step = spec.step.get();
483
484    anyhow::ensure!(
485        bar_type.aggregation_source() == AggregationSource::External,
486        "Only EXTERNAL aggregation is supported"
487    );
488
489    let interval = match spec.aggregation {
490        BarAggregation::Minute => match step {
491            1 => OneMinute,
492            3 => ThreeMinutes,
493            5 => FiveMinutes,
494            15 => FifteenMinutes,
495            30 => ThirtyMinutes,
496            _ => anyhow::bail!("Unsupported minute step: {step}"),
497        },
498        BarAggregation::Hour => match step {
499            1 => OneHour,
500            2 => TwoHours,
501            4 => FourHours,
502            8 => EightHours,
503            12 => TwelveHours,
504            _ => anyhow::bail!("Unsupported hour step: {step}"),
505        },
506        BarAggregation::Day => match step {
507            1 => OneDay,
508            3 => ThreeDays,
509            _ => anyhow::bail!("Unsupported day step: {step}"),
510        },
511        BarAggregation::Week if step == 1 => OneWeek,
512        BarAggregation::Month if step == 1 => OneMonth,
513        a => anyhow::bail!("Hyperliquid does not support {a:?} aggregation"),
514    };
515
516    Ok(interval)
517}
518
519/// Converts a Nautilus order to Hyperliquid request using a pre-resolved asset index.
520///
521/// This variant is used when the caller has already resolved the asset index
522/// from the instrument cache (e.g., for SPOT instruments where the index
523/// cannot be derived from the symbol alone). `slippage_bps` controls the
524/// buffer applied when deriving a limit from a stop trigger price.
525pub fn order_to_hyperliquid_request_with_asset(
526    order: &OrderAny,
527    asset: u32,
528    price_decimals: u8,
529    should_normalize_prices: bool,
530    slippage_bps: u32,
531) -> anyhow::Result<HyperliquidExchangePlaceOrderRequest> {
532    order_to_hyperliquid_request_with_asset_and_cloid(
533        order,
534        asset,
535        price_decimals,
536        should_normalize_prices,
537        slippage_bps,
538        Some(Cloid::from_client_order_id(order.client_order_id())),
539    )
540}
541
542/// Converts a Nautilus order to Hyperliquid request with an explicit CLOID.
543pub fn order_to_hyperliquid_request_with_asset_and_cloid(
544    order: &OrderAny,
545    asset: u32,
546    price_decimals: u8,
547    should_normalize_prices: bool,
548    slippage_bps: u32,
549    cloid: Option<Cloid>,
550) -> anyhow::Result<HyperliquidExchangePlaceOrderRequest> {
551    order_to_hyperliquid_request_with_optional_decimals(
552        order,
553        asset,
554        Some(price_decimals),
555        should_normalize_prices,
556        slippage_bps,
557        cloid,
558    )
559}
560
561/// Converts a Nautilus order to Hyperliquid request when the instrument
562/// decimal cap may be unknown. A `None` cap disables local wire-price
563/// validation and falls back to the default two-decimal normalization.
564pub(crate) fn order_to_hyperliquid_request_with_optional_decimals(
565    order: &OrderAny,
566    asset: u32,
567    price_decimals: Option<u8>,
568    should_normalize_prices: bool,
569    slippage_bps: u32,
570    cloid: Option<Cloid>,
571) -> anyhow::Result<HyperliquidExchangePlaceOrderRequest> {
572    let is_buy = matches!(order.order_side(), OrderSide::Buy);
573    let reduce_only = order.is_reduce_only();
574    let order_side = order.order_side();
575    let order_type = order.order_type();
576
577    let normalize_or_validate = |raw: Decimal, label: &str| {
578        normalize_or_validate_wire_price(raw, label, price_decimals, should_normalize_prices)
579    };
580
581    // Normalize decimals to strip trailing zeros, matching the server's
582    // canonical form used for EIP-712 signing hash verification.
583    let price_decimal = if let Some(price) = order.price() {
584        normalize_or_validate(price.as_decimal(), "Price")?
585    } else if matches!(order_type, OrderType::Market) {
586        Decimal::ZERO
587    } else if matches!(
588        order_type,
589        OrderType::StopMarket | OrderType::MarketIfTouched
590    ) {
591        match order.trigger_price() {
592            Some(tp) => {
593                let base = tp.as_decimal().normalize();
594                let derived = derive_limit_from_trigger(base, is_buy, slippage_bps);
595                let sig_rounded = round_to_sig_figs(derived, 5);
596                clamp_price_to_precision(sig_rounded, price_decimals.unwrap_or(2), is_buy)
597                    .normalize()
598            }
599            None => Decimal::ZERO,
600        }
601    } else {
602        anyhow::bail!("Limit orders require a price")
603    };
604
605    let size_decimal = order.quantity().as_decimal().normalize();
606
607    // Determine order kind based on order type
608    let kind = match order_type {
609        OrderType::Market => HyperliquidExchangeOrderKind::Limit {
610            limit: HyperliquidExchangeLimitParams {
611                tif: HyperliquidExchangeTif::Ioc,
612            },
613        },
614        OrderType::Limit => {
615            let tif =
616                time_in_force_to_hyperliquid_tif(order.time_in_force(), order.is_post_only())?;
617            HyperliquidExchangeOrderKind::Limit {
618                limit: HyperliquidExchangeLimitParams { tif },
619            }
620        }
621        OrderType::StopMarket => {
622            if let Some(trigger_price) = order.trigger_price() {
623                let trigger_price_decimal =
624                    normalize_or_validate(trigger_price.as_decimal(), "Trigger price")?;
625                let tpsl = determine_tpsl_type(order_type, order_side, trigger_price_decimal, None);
626                HyperliquidExchangeOrderKind::Trigger {
627                    trigger: HyperliquidExchangeTriggerParams {
628                        is_market: true,
629                        trigger_px: trigger_price_decimal,
630                        tpsl,
631                    },
632                }
633            } else {
634                anyhow::bail!("Stop market orders require a trigger price")
635            }
636        }
637        OrderType::StopLimit => {
638            if let Some(trigger_price) = order.trigger_price() {
639                let trigger_price_decimal =
640                    normalize_or_validate(trigger_price.as_decimal(), "Trigger price")?;
641                let tpsl = determine_tpsl_type(order_type, order_side, trigger_price_decimal, None);
642                HyperliquidExchangeOrderKind::Trigger {
643                    trigger: HyperliquidExchangeTriggerParams {
644                        is_market: false,
645                        trigger_px: trigger_price_decimal,
646                        tpsl,
647                    },
648                }
649            } else {
650                anyhow::bail!("Stop limit orders require a trigger price")
651            }
652        }
653        OrderType::MarketIfTouched => {
654            if let Some(trigger_price) = order.trigger_price() {
655                let trigger_price_decimal =
656                    normalize_or_validate(trigger_price.as_decimal(), "Trigger price")?;
657                HyperliquidExchangeOrderKind::Trigger {
658                    trigger: HyperliquidExchangeTriggerParams {
659                        is_market: true,
660                        trigger_px: trigger_price_decimal,
661                        tpsl: HyperliquidExchangeTpSl::Tp,
662                    },
663                }
664            } else {
665                anyhow::bail!("Market-if-touched orders require a trigger price")
666            }
667        }
668        OrderType::LimitIfTouched => {
669            if let Some(trigger_price) = order.trigger_price() {
670                let trigger_price_decimal =
671                    normalize_or_validate(trigger_price.as_decimal(), "Trigger price")?;
672                HyperliquidExchangeOrderKind::Trigger {
673                    trigger: HyperliquidExchangeTriggerParams {
674                        is_market: false,
675                        trigger_px: trigger_price_decimal,
676                        tpsl: HyperliquidExchangeTpSl::Tp,
677                    },
678                }
679            } else {
680                anyhow::bail!("Limit-if-touched orders require a trigger price")
681            }
682        }
683        _ => anyhow::bail!("Unsupported order type for Hyperliquid: {order_type:?}"),
684    };
685
686    Ok(HyperliquidExchangePlaceOrderRequest {
687        asset,
688        is_buy,
689        price: price_decimal,
690        size: size_decimal,
691        reduce_only,
692        kind,
693        cloid,
694    })
695}
696
697/// Default slippage buffer in basis points for MARKET orders.
698pub const DEFAULT_MARKET_SLIPPAGE_BPS: u32 = 50;
699
700/// Derives a market order limit price from a quote with a configurable
701/// slippage buffer in basis points, rounded to 5 significant figures and
702/// clamped to the instrument's price precision.
703pub fn derive_market_order_price(
704    quote: &QuoteTick,
705    is_buy: bool,
706    price_decimals: u8,
707    slippage_bps: u32,
708) -> Decimal {
709    let base = if is_buy {
710        quote.ask_price.as_decimal()
711    } else {
712        quote.bid_price.as_decimal()
713    };
714    let derived = derive_limit_from_trigger(base, is_buy, slippage_bps);
715    let sig_rounded = round_to_sig_figs(derived, 5);
716    clamp_price_to_precision(sig_rounded, price_decimals, is_buy).normalize()
717}
718
719/// Derives a limit price from a trigger price with a configurable
720/// slippage buffer in basis points, widening the limit so BUY satisfies
721/// `limit_px >= trigger_px` and SELL satisfies `limit_px <= trigger_px`.
722pub fn derive_limit_from_trigger(
723    trigger_price: Decimal,
724    is_buy: bool,
725    slippage_bps: u32,
726) -> Decimal {
727    // bps -> Decimal: e.g. 50 bps -> 0.005
728    let slippage = Decimal::new(slippage_bps as i64, 4);
729    let price = if is_buy {
730        trigger_price * (Decimal::ONE + slippage)
731    } else {
732        trigger_price * (Decimal::ONE - slippage)
733    };
734
735    // Strip trailing zeros for EIP-712 signing hash verification
736    price.normalize()
737}
738
739/// Clamp a price to the instrument's decimal precision,
740/// rounding in the direction that preserves the slippage buffer.
741pub fn clamp_price_to_precision(price: Decimal, decimals: u8, is_buy: bool) -> Decimal {
742    let scale = Decimal::from(10_u64.pow(decimals as u32));
743
744    if is_buy {
745        (price * scale).ceil() / scale
746    } else {
747        (price * scale).floor() / scale
748    }
749}
750
751/// Converts a client order ID to a Hyperliquid cancel request using a pre-resolved asset index.
752pub fn client_order_id_to_cancel_request_with_asset(
753    client_order_id: &str,
754    asset: u32,
755) -> HyperliquidExchangeCancelByCloidRequest {
756    let cloid = Cloid::from_client_order_id(ClientOrderId::from(client_order_id));
757    HyperliquidExchangeCancelByCloidRequest { asset, cloid }
758}
759
760/// Extracts per-item error from a successful Hyperliquid exchange response.
761///
762/// When the top-level status is "ok", individual items in the `statuses`
763/// array may still contain errors. Returns the first error found, or
764/// `None` if all items succeeded or the response cannot be parsed.
765pub fn extract_inner_error(response: &HyperliquidExchangeResponse) -> Option<String> {
766    let HyperliquidExchangeResponse::Status { response, .. } = response else {
767        return None;
768    };
769    let data: HyperliquidExchangeResponseData = serde_json::from_value(response.clone()).ok()?;
770    match data {
771        HyperliquidExchangeResponseData::Order { data } => {
772            for status in &data.statuses {
773                if let HyperliquidExchangeOrderStatus::Error { error } = status {
774                    return Some(error.clone());
775                }
776            }
777            None
778        }
779        HyperliquidExchangeResponseData::Cancel { data } => {
780            for status in &data.statuses {
781                if let HyperliquidExchangeCancelStatus::Error { error } = status {
782                    return Some(error.clone());
783                }
784            }
785            None
786        }
787        HyperliquidExchangeResponseData::Modify { data } => {
788            for status in &data.statuses {
789                if let HyperliquidExchangeModifyStatus::Error { error } = status {
790                    return Some(error.clone());
791                }
792            }
793            None
794        }
795        _ => None,
796    }
797}
798
799/// Extracts per-item errors from a successful batch response.
800///
801/// Returns a `Vec` with one `Option<String>` per item in the `statuses`
802/// array: `Some(error)` for failed items, `None` for successful ones.
803/// Returns an empty vec if the response cannot be parsed.
804pub fn extract_inner_errors(response: &HyperliquidExchangeResponse) -> Vec<Option<String>> {
805    let HyperliquidExchangeResponse::Status { response, .. } = response else {
806        return Vec::new();
807    };
808    let Ok(data) = serde_json::from_value::<HyperliquidExchangeResponseData>(response.clone())
809    else {
810        return Vec::new();
811    };
812
813    match data {
814        HyperliquidExchangeResponseData::Order { data } => data
815            .statuses
816            .into_iter()
817            .map(|s| match s {
818                HyperliquidExchangeOrderStatus::Error { error } => Some(error),
819                _ => None,
820            })
821            .collect(),
822        HyperliquidExchangeResponseData::Cancel { data } => data
823            .statuses
824            .into_iter()
825            .map(|s| match s {
826                HyperliquidExchangeCancelStatus::Error { error } => Some(error),
827                HyperliquidExchangeCancelStatus::Success(_) => None,
828            })
829            .collect(),
830        HyperliquidExchangeResponseData::Modify { data } => data
831            .statuses
832            .into_iter()
833            .map(|s| match s {
834                HyperliquidExchangeModifyStatus::Error { error } => Some(error),
835                HyperliquidExchangeModifyStatus::Success(_) => None,
836            })
837            .collect(),
838        _ => Vec::new(),
839    }
840}
841
842/// Extracts error message from a Hyperliquid exchange response.
843pub fn extract_error_message(response: &HyperliquidExchangeResponse) -> String {
844    match response {
845        HyperliquidExchangeResponse::Status { status, response } => {
846            if status == RESPONSE_STATUS_OK {
847                "Operation successful".to_string()
848            } else {
849                // Try to extract error message from response data
850                if let Some(error_msg) = response
851                    .as_str()
852                    .or_else(|| response.get("error").and_then(|v| v.as_str()))
853                    .or_else(|| {
854                        (response.get("type").and_then(|v| v.as_str()) == Some("error"))
855                            .then(|| response.get("data").and_then(|v| v.as_str()))
856                            .flatten()
857                    })
858                {
859                    error_msg.to_string()
860                } else {
861                    format!("Request failed with status: {status}")
862                }
863            }
864        }
865        HyperliquidExchangeResponse::Error { error } => error.clone(),
866    }
867}
868
869/// Determines if an order is a conditional/trigger order based on order data.
870///
871/// # Returns
872///
873/// `true` if the order is a conditional order, `false` otherwise.
874pub fn is_conditional_order_data(
875    trigger_px: Option<Decimal>,
876    tpsl: Option<&HyperliquidTpSl>,
877) -> bool {
878    trigger_px.is_some() && tpsl.is_some()
879}
880
881/// Parses trigger order type from Hyperliquid order data.
882///
883/// # Returns
884///
885/// The corresponding Nautilus `OrderType`.
886pub fn parse_trigger_order_type(is_market: bool, tpsl: &HyperliquidTpSl) -> OrderType {
887    match (is_market, tpsl) {
888        (true, HyperliquidTpSl::Sl) => OrderType::StopMarket,
889        (false, HyperliquidTpSl::Sl) => OrderType::StopLimit,
890        (true, HyperliquidTpSl::Tp) => OrderType::MarketIfTouched,
891        (false, HyperliquidTpSl::Tp) => OrderType::LimitIfTouched,
892    }
893}
894
895/// Parses trigger semantics from a REST `orderType` label.
896///
897/// REST order rows (`frontendOpenOrders`, `historicalOrders`) describe conditional orders with
898/// labels such as `"Stop Market"` or `"Take Profit Limit"`, rather than the `tpsl` and
899/// `isMarket` fields carried by WebSocket order updates.
900///
901/// # Returns
902///
903/// The trigger kind and whether the order executes as market once triggered, or `None` when
904/// the label does not describe a trigger order (for example `"Limit"` or `"Market"`).
905#[must_use]
906pub fn parse_trigger_order_type_label(label: &str) -> Option<(HyperliquidTpSl, bool)> {
907    let tpsl = if label.starts_with("Take Profit") {
908        HyperliquidTpSl::Tp
909    } else if label.starts_with("Stop") {
910        HyperliquidTpSl::Sl
911    } else {
912        return None;
913    };
914    Some((tpsl, label.ends_with("Market")))
915}
916
917/// Extracts order status from WebSocket order data.
918///
919/// # Returns
920///
921/// A tuple of (OrderStatus, optional trigger status string).
922pub fn parse_order_status_with_trigger(
923    status: HyperliquidOrderStatus,
924    trigger_activated: Option<bool>,
925) -> (OrderStatus, Option<String>) {
926    let base_status = OrderStatus::from(status);
927
928    // For conditional orders, add trigger status information
929    if let Some(activated) = trigger_activated {
930        let trigger_status = if activated {
931            Some("activated".to_string())
932        } else {
933            Some("pending".to_string())
934        };
935        (base_status, trigger_status)
936    } else {
937        (base_status, None)
938    }
939}
940
941/// Converts WebSocket trailing stop data to description string.
942pub fn format_trailing_stop_info(
943    offset: &str,
944    offset_type: TrailingOffsetType,
945    callback_price: Option<&str>,
946) -> String {
947    let offset_desc = offset_type.format_offset(offset);
948
949    if let Some(callback) = callback_price {
950        format!("Trailing stop: {offset_desc} offset, callback at {callback}")
951    } else {
952        format!("Trailing stop: {offset_desc} offset")
953    }
954}
955
956/// Validates conditional order parameters from WebSocket data.
957///
958/// # Returns
959///
960/// `Ok(())` if parameters are valid, `Err` with description otherwise.
961pub fn validate_conditional_order_params(
962    trigger_px: Option<&str>,
963    tpsl: Option<&HyperliquidTpSl>,
964    is_market: Option<bool>,
965) -> anyhow::Result<()> {
966    if trigger_px.is_none() {
967        anyhow::bail!("Conditional order missing trigger price");
968    }
969
970    if tpsl.is_none() {
971        anyhow::bail!("Conditional order missing tpsl indicator");
972    }
973
974    // No need to validate tpsl value - the enum type guarantees it's either Tp or Sl
975
976    if is_market.is_none() {
977        anyhow::bail!("Conditional order missing is_market flag");
978    }
979
980    Ok(())
981}
982
983/// Parses trigger price from string to Decimal.
984///
985/// # Returns
986///
987/// Parsed Decimal value or error.
988pub fn parse_trigger_price(trigger_px: &str) -> anyhow::Result<Decimal> {
989    Decimal::from_str_exact(trigger_px)
990        .with_context(|| format!("Failed to parse trigger price: {trigger_px}"))
991}
992
993/// Parses Hyperliquid clearinghouse state into Nautilus account balances and margins.
994///
995/// Uses the same field selection as the HTTP account-state path
996/// (`cross_margin_summary.total_raw_usd` for total, top-level `state.withdrawable`
997/// for free) so the execution adapter and the HTTP client emit consistent balances
998/// for the same clearinghouse snapshot.
999///
1000/// # Errors
1001///
1002/// Returns an error if the data cannot be parsed.
1003pub fn parse_account_balances_and_margins(
1004    state: &ClearinghouseState,
1005) -> anyhow::Result<(Vec<AccountBalance>, Vec<MarginBalance>)> {
1006    let mut balances = Vec::new();
1007    let mut margins = Vec::new();
1008
1009    let currency = Currency::USDC();
1010
1011    let cross_margin_summary = match &state.cross_margin_summary {
1012        Some(summary) => summary,
1013        None => return Ok((balances, margins)),
1014    };
1015
1016    let mut total_value = cross_margin_summary.total_raw_usd;
1017    let free_value = state.withdrawable.unwrap_or(total_value).max(Decimal::ZERO);
1018
1019    // Withdrawable may include spot balances that sit outside a positive margin
1020    // account value; raise total so those funds are not silently clamped away.
1021    if total_value >= Decimal::ZERO && free_value > total_value {
1022        total_value = free_value;
1023    }
1024
1025    balances.push(AccountBalance::from_total_and_free(
1026        total_value,
1027        free_value,
1028        currency,
1029    )?);
1030
1031    let margin_used = cross_margin_summary.total_margin_used;
1032
1033    if margin_used > Decimal::ZERO {
1034        // Hyperliquid perps use a single-collateral (USDC) cross-margin model, so the
1035        // reserved margin is emitted as an account-wide entry keyed by USDC.
1036        let initial_margin = Money::from_decimal(margin_used, currency)?;
1037        let maintenance_margin = Money::from_decimal(margin_used, currency)?;
1038        margins.push(MarginBalance::new(initial_margin, maintenance_margin, None));
1039    }
1040
1041    Ok((balances, margins))
1042}
1043
1044/// Merges perp clearinghouse balances with spot balances into a unified set.
1045///
1046/// Unified and portfolio margin accounts report every balance and hold in the spot
1047/// clearinghouse state, so balances come from spot alone and the spot USDC `hold` becomes the
1048/// account-wide margin entry. That hold covers margin on every USDC-collateralized perp dex plus
1049/// USDC reserved by resting spot orders; margin on dexes collateralized in another token shows
1050/// up as that token's locked balance. The perp summary describes only the default dex in these
1051/// modes: its `totalRawUsd` goes negative while longs are open and its `withdrawable` is per-dex.
1052///
1053/// Otherwise the perp parser already reflects combined USDC when its cross-margin summary
1054/// carries collateral or margin state, so this parser appends only non-USDC spot
1055/// tokens in that case. If the perp state has no margin summary, or the summary
1056/// is present but zeroed, spot USDC is used verbatim.
1057///
1058/// Account updates keep any currency an update omits, so spot tokens the venue lists at zero are
1059/// reported at zero, clearing a previous balance, and USDC is always reported, at zero when there
1060/// is no USDC balance. On accounts without spot collateral this needs a perp summary; with none,
1061/// no zeroed entries are reported and the previous balances are kept.
1062///
1063/// # Errors
1064///
1065/// Returns an error if any balance conversion fails.
1066pub fn parse_combined_account_balances_and_margins(
1067    perp_state: &ClearinghouseState,
1068    spot_state: &SpotClearinghouseState,
1069    abstraction: HyperliquidAccountAbstraction,
1070) -> anyhow::Result<(Vec<AccountBalance>, Vec<MarginBalance>)> {
1071    if abstraction.uses_spot_collateral() {
1072        let mut balances = parse_spot_account_balances(spot_state)?;
1073        push_zeroed_balances(&mut balances, spot_state);
1074
1075        let mut margins = Vec::new();
1076
1077        if let Some(usdc) = spot_state
1078            .balances
1079            .iter()
1080            .find(|balance| balance.coin.as_str() == "USDC")
1081            && usdc.hold > Decimal::ZERO
1082        {
1083            let margin_used = Money::from_decimal(usdc.hold, Currency::USDC())?;
1084            margins.push(MarginBalance::new(margin_used, margin_used, None));
1085        }
1086
1087        return Ok((balances, margins));
1088    }
1089
1090    let (mut balances, margins) = parse_account_balances_and_margins(perp_state)?;
1091
1092    let perp_reflects_usdc = perp_state
1093        .cross_margin_summary
1094        .as_ref()
1095        .is_some_and(|summary| {
1096            summary.total_raw_usd != Decimal::ZERO
1097                || summary.total_margin_used > Decimal::ZERO
1098                || perp_state.withdrawable.unwrap_or(Decimal::ZERO) > Decimal::ZERO
1099        });
1100
1101    if perp_state.cross_margin_summary.is_some() && !perp_reflects_usdc {
1102        balances.retain(|balance| balance.currency.code != "USDC");
1103    }
1104
1105    let spot_balances = parse_spot_account_balances(spot_state)?;
1106
1107    for balance in spot_balances {
1108        let is_usdc = balance.currency.code == "USDC";
1109        if perp_reflects_usdc && is_usdc {
1110            continue;
1111        }
1112        balances.push(balance);
1113    }
1114
1115    // Without a perp summary the response is not a full account reading, so report no zeroed
1116    // entries and keep the previous balances and margins rather than clear them
1117    if perp_state.cross_margin_summary.is_some() {
1118        push_zeroed_balances(&mut balances, spot_state);
1119    }
1120
1121    Ok((balances, margins))
1122}
1123
1124// Account updates keep any currency an update omits, so a balance that reached zero must still be
1125// reported to clear the previous one: spot tokens the venue lists at zero, and USDC whenever the
1126// update would otherwise carry none. The venue keeps every token an
1127// account has held as a zero row, so these entries recur on every update; a token dropped from
1128// the spot state entirely still keeps its last balance
1129fn push_zeroed_balances(balances: &mut Vec<AccountBalance>, spot_state: &SpotClearinghouseState) {
1130    let zeroed_spot = spot_state
1131        .balances
1132        .iter()
1133        .filter(|balance| balance.total.is_zero())
1134        .map(|balance| crate::http::parse::get_currency(balance.coin.as_str()));
1135
1136    for currency in zeroed_spot.chain(std::iter::once(Currency::USDC())) {
1137        if !balances.iter().any(|balance| balance.currency == currency) {
1138            let zero = Money::zero(currency);
1139            balances.push(AccountBalance::new(zero, zero, zero));
1140        }
1141    }
1142}
1143
1144/// Parses Hyperliquid spot clearinghouse state into Nautilus account balances.
1145///
1146/// Emits one [`AccountBalance`] per non-zero spot token, deriving free from
1147/// `total - hold`. Tokens unknown to the global currency registry are registered
1148/// on the fly with 8-decimal precision (matches Hyperliquid's `sz_decimals` cap).
1149///
1150/// # Errors
1151///
1152/// Returns an error if any balance cannot be converted to a Nautilus `Money`.
1153pub fn parse_spot_account_balances(
1154    state: &SpotClearinghouseState,
1155) -> anyhow::Result<Vec<AccountBalance>> {
1156    let mut balances = Vec::with_capacity(state.balances.len());
1157
1158    for balance in &state.balances {
1159        if balance.total.is_zero() {
1160            continue;
1161        }
1162
1163        let currency = crate::http::parse::get_currency(balance.coin.as_str());
1164
1165        // Let `from_total_and_locked` do the clamping and derivation at currency
1166        // precision so the `total == locked + free` invariant holds without
1167        // bespoke rounding here.
1168        balances.push(AccountBalance::from_total_and_locked(
1169            balance.total,
1170            balance.hold,
1171            currency,
1172        )?);
1173    }
1174
1175    Ok(balances)
1176}
1177
1178/// Determine the Hyperliquid grouping strategy for an order list.
1179///
1180/// Contingency type, reduce-only flags, structural shape, and parent/child
1181/// linkage must all agree to avoid misclassifying generic contingent lists
1182/// as Hyperliquid TP/SL groups.
1183///
1184/// - `NormalTpsl` (OTOCO bracket): entry order is OTO and not reduce-only,
1185///   all child orders are OCO or OUO, reduce-only, and reference the entry as parent.
1186/// - `PositionTpsl` (linked exit pair): every order is OCO or OUO, reduce-only,
1187///   and linked to the same sibling set.
1188/// - `Na`: everything else (independent batch).
1189pub(crate) fn determine_order_list_grouping(orders: &[OrderAny]) -> HyperliquidExchangeGrouping {
1190    if orders.len() >= 2 {
1191        let entry = &orders[0];
1192        let children = &orders[1..];
1193        let entry_id = entry.client_order_id();
1194        let entry_is_oto =
1195            entry.contingency_type() == Some(ContingencyType::Oto) && !entry.is_reduce_only();
1196        let children_are_linked = children.iter().all(|o| {
1197            matches!(
1198                o.contingency_type(),
1199                Some(ContingencyType::Oco | ContingencyType::Ouo)
1200            ) && o.is_reduce_only()
1201                && o.parent_order_id() == Some(entry_id)
1202        });
1203
1204        if entry_is_oto && children_are_linked {
1205            return HyperliquidExchangeGrouping::NormalTpsl;
1206        }
1207    }
1208
1209    let all_oco_linked = orders.len() >= 2
1210        && orders.iter().all(|o| {
1211            matches!(
1212                o.contingency_type(),
1213                Some(ContingencyType::Oco | ContingencyType::Ouo)
1214            ) && o.is_reduce_only()
1215        })
1216        && orders.iter().all(|o| {
1217            o.linked_order_ids().is_some_and(|ids| {
1218                ids.iter()
1219                    .all(|id| orders.iter().any(|other| other.client_order_id() == *id))
1220            })
1221        });
1222
1223    if all_oco_linked {
1224        HyperliquidExchangeGrouping::PositionTpsl
1225    } else {
1226        HyperliquidExchangeGrouping::Na
1227    }
1228}
1229
1230pub(crate) fn is_false_or_none(value: &Option<bool>) -> bool {
1231    // Hyperliquid rejects cancel actions hashed with an explicit false fast flag
1232    *value != Some(true)
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237    use std::str::FromStr;
1238
1239    use nautilus_model::{
1240        enums::{OrderSide, TimeInForce, TriggerType},
1241        identifiers::{ClientOrderId, InstrumentId, StrategyId, TraderId},
1242        orders::{LimitOrder, OrderAny, StopMarketOrder},
1243        types::{Price, Quantity},
1244    };
1245    use rstest::rstest;
1246    use rust_decimal::Decimal;
1247    use rust_decimal_macros::dec;
1248    use serde::{Deserialize, Serialize};
1249
1250    use super::*;
1251
1252    #[rstest]
1253    fn test_make_fill_trade_id_is_stable() {
1254        // Pins the deterministic FNV output so the Decimal `Display` hashing
1255        // stays stable for reconciliation dedup across the String->Decimal change.
1256        let id = make_fill_trade_id(
1257            "0xabc123",
1258            12345,
1259            dec!(50000.0),
1260            dec!(0.1),
1261            1704470400000,
1262            dec!(0.0),
1263        );
1264        assert_eq!(id.to_string(), "a846ae6f557868e9-0000000000003039");
1265    }
1266
1267    #[derive(Serialize, Deserialize)]
1268    struct TestStruct {
1269        #[serde(
1270            serialize_with = "serialize_decimal_as_str",
1271            deserialize_with = "deserialize_decimal_from_str"
1272        )]
1273        value: Decimal,
1274        #[serde(
1275            serialize_with = "serialize_optional_decimal_as_str",
1276            deserialize_with = "deserialize_optional_decimal_from_str"
1277        )]
1278        optional_value: Option<Decimal>,
1279    }
1280
1281    #[rstest]
1282    #[case("#10", 100_000_010, 1, 0)]
1283    #[case("+10", 100_000_010, 1, 0)]
1284    #[case("#31", 100_000_031, 3, 1)]
1285    #[case("+31", 100_000_031, 3, 1)]
1286    fn test_parse_outcome_symbol(
1287        #[case] symbol: &str,
1288        #[case] raw_asset_id: u32,
1289        #[case] outcome: u32,
1290        #[case] side: u8,
1291    ) {
1292        let asset_id = parse_outcome_symbol(symbol).unwrap();
1293        assert_eq!(asset_id.to_raw(), raw_asset_id);
1294        assert_eq!(asset_id.outcome_index(), Some(outcome));
1295        assert_eq!(asset_id.outcome_side(), Some(side));
1296    }
1297
1298    #[rstest]
1299    #[case("25-YES-OUTCOME", 25, 0)]
1300    #[case("25-NO-OUTCOME", 25, 1)]
1301    #[case("0-YES-OUTCOME", 0, 0)]
1302    #[case("999-NO-OUTCOME", 999, 1)]
1303    fn test_parse_outcome_nautilus_symbol(
1304        #[case] symbol: &str,
1305        #[case] outcome_index: u32,
1306        #[case] side: u8,
1307    ) {
1308        let parsed = parse_outcome_nautilus_symbol(symbol).unwrap();
1309        assert_eq!(parsed, (outcome_index, side));
1310    }
1311
1312    #[rstest]
1313    #[case("25-OUTCOME")]
1314    #[case("25-MAYBE-OUTCOME")]
1315    #[case("25-yes-OUTCOME")]
1316    #[case("-YES-OUTCOME")]
1317    #[case("YES-25-OUTCOME")]
1318    #[case("25-YES-outcome")]
1319    #[case("25-YES")]
1320    fn test_parse_outcome_nautilus_symbol_rejects_invalid(#[case] symbol: &str) {
1321        assert!(parse_outcome_nautilus_symbol(symbol).is_none());
1322    }
1323
1324    #[rstest]
1325    // outcome_index * 10 overflows u32.
1326    #[case("999999999-YES-OUTCOME")]
1327    // outcome_index * 10 fits but 100_000_000 + encoding overflows u32.
1328    #[case("429496729-YES-OUTCOME")]
1329    // u32::MAX itself; rejected on the multiply.
1330    #[case("4294967295-NO-OUTCOME")]
1331    fn test_parse_outcome_nautilus_symbol_rejects_overflow(#[case] symbol: &str) {
1332        assert!(parse_outcome_nautilus_symbol(symbol).is_none());
1333    }
1334
1335    #[rstest]
1336    #[case(25, 0, "25-YES-OUTCOME")]
1337    #[case(25, 1, "25-NO-OUTCOME")]
1338    #[case(0, 0, "0-YES-OUTCOME")]
1339    fn test_format_outcome_nautilus_symbol(
1340        #[case] outcome_index: u32,
1341        #[case] side: u8,
1342        #[case] expected: &str,
1343    ) {
1344        assert_eq!(
1345            format_outcome_nautilus_symbol(outcome_index, side),
1346            expected,
1347        );
1348    }
1349
1350    #[rstest]
1351    #[case("25-YES-OUTCOME", Some("+250".to_string()))]
1352    #[case("25-NO-OUTCOME", Some("+251".to_string()))]
1353    #[case("0-YES-OUTCOME", Some("+0".to_string()))]
1354    #[case("BTC-USD-PERP", None)]
1355    #[case("+250", None)]
1356    fn test_outcome_token_from_nautilus_symbol(
1357        #[case] symbol: &str,
1358        #[case] expected: Option<String>,
1359    ) {
1360        assert_eq!(outcome_token_from_nautilus_symbol(symbol), expected);
1361    }
1362
1363    #[rstest]
1364    #[case("25-YES-OUTCOME", Some("+250".to_string()))]
1365    #[case("25-NO-OUTCOME", Some("+251".to_string()))]
1366    #[case("BTC-USD-PERP", Some("BTC".to_string()))]
1367    #[case("PURR-USDC-SPOT", Some("PURR".to_string()))]
1368    #[case("dex:STREAMABCDxxxx-USD-PERP", Some("dex:STREAMABCDxxxx".to_string()))]
1369    #[case("+250", Some("+250".to_string()))]
1370    #[case("#250", Some("#250".to_string()))]
1371    #[case("", None)]
1372    fn test_cache_alias_for_symbol(#[case] symbol: &str, #[case] expected: Option<String>) {
1373        assert_eq!(cache_alias_for_symbol(symbol), expected);
1374    }
1375
1376    #[rstest]
1377    #[case("10", "expected #<encoding> or +<encoding>")]
1378    #[case("#", "encoding must not be empty")]
1379    #[case("#1a", "encoding must be numeric")]
1380    #[case("#12", "side digit 0 or 1")]
1381    #[case("#4294967295", "fit u32")]
1382    fn test_parse_outcome_symbol_rejects_invalid_values(
1383        #[case] symbol: &str,
1384        #[case] expected_error: &str,
1385    ) {
1386        let err = parse_outcome_symbol(symbol).unwrap_err();
1387        assert!(
1388            err.to_string().contains(expected_error),
1389            "expected error to contain '{expected_error}', received '{err}'",
1390        );
1391    }
1392
1393    #[rstest]
1394    fn test_decimal_serialization_roundtrip() {
1395        let original = TestStruct {
1396            value: Decimal::from_str("123.456789012345678901234567890").unwrap(),
1397            optional_value: Some(Decimal::from_str("0.000000001").unwrap()),
1398        };
1399
1400        let json = serde_json::to_string(&original).unwrap();
1401        println!("Serialized: {json}");
1402
1403        // Check that it's serialized as strings (rust_decimal may normalize precision)
1404        assert!(json.contains("\"123.45678901234567890123456789\""));
1405        assert!(json.contains("\"0.000000001\""));
1406
1407        let deserialized: TestStruct = serde_json::from_str(&json).unwrap();
1408        assert_eq!(original.value, deserialized.value);
1409        assert_eq!(original.optional_value, deserialized.optional_value);
1410    }
1411
1412    #[rstest]
1413    fn test_decimal_precision_preservation() {
1414        let test_cases = [
1415            "0",
1416            "1",
1417            "0.1",
1418            "0.01",
1419            "0.001",
1420            "123.456789012345678901234567890",
1421            "999999999999999999.999999999999999999",
1422        ];
1423
1424        for case in test_cases {
1425            let decimal = Decimal::from_str(case).unwrap();
1426            let test_struct = TestStruct {
1427                value: decimal,
1428                optional_value: Some(decimal),
1429            };
1430
1431            let json = serde_json::to_string(&test_struct).unwrap();
1432            let parsed: TestStruct = serde_json::from_str(&json).unwrap();
1433
1434            assert_eq!(decimal, parsed.value, "Failed for case: {case}");
1435            assert_eq!(
1436                Some(decimal),
1437                parsed.optional_value,
1438                "Failed for case: {case}"
1439            );
1440        }
1441    }
1442
1443    #[rstest]
1444    fn test_optional_none_handling() {
1445        let test_struct = TestStruct {
1446            value: Decimal::from_str("42.0").unwrap(),
1447            optional_value: None,
1448        };
1449
1450        let json = serde_json::to_string(&test_struct).unwrap();
1451        assert!(json.contains("null"));
1452
1453        let parsed: TestStruct = serde_json::from_str(&json).unwrap();
1454        assert_eq!(test_struct.value, parsed.value);
1455        assert_eq!(None, parsed.optional_value);
1456    }
1457
1458    #[rstest]
1459    fn test_round_down_to_tick() {
1460        assert_eq!(round_down_to_tick(dec!(100.07), dec!(0.05)), dec!(100.05));
1461        assert_eq!(round_down_to_tick(dec!(100.03), dec!(0.05)), dec!(100.00));
1462        assert_eq!(round_down_to_tick(dec!(100.05), dec!(0.05)), dec!(100.05));
1463
1464        // Edge case: zero tick size
1465        assert_eq!(round_down_to_tick(dec!(100.07), dec!(0)), dec!(100.07));
1466    }
1467
1468    #[rstest]
1469    fn test_round_down_to_step() {
1470        assert_eq!(
1471            round_down_to_step(dec!(0.12349), dec!(0.0001)),
1472            dec!(0.1234)
1473        );
1474        assert_eq!(round_down_to_step(dec!(1.5555), dec!(0.1)), dec!(1.5));
1475        assert_eq!(round_down_to_step(dec!(1.0001), dec!(0.0001)), dec!(1.0001));
1476
1477        // Edge case: zero step size
1478        assert_eq!(round_down_to_step(dec!(0.12349), dec!(0)), dec!(0.12349));
1479    }
1480
1481    #[rstest]
1482    fn test_min_notional_validation() {
1483        // Should pass
1484        assert!(ensure_min_notional(dec!(100), dec!(0.1), dec!(10)).is_ok());
1485        assert!(ensure_min_notional(dec!(100), dec!(0.11), dec!(10)).is_ok());
1486
1487        // Should fail
1488        assert!(ensure_min_notional(dec!(100), dec!(0.05), dec!(10)).is_err());
1489        assert!(ensure_min_notional(dec!(1), dec!(5), dec!(10)).is_err());
1490
1491        // Edge case: exactly at minimum
1492        assert!(ensure_min_notional(dec!(100), dec!(0.1), dec!(10)).is_ok());
1493    }
1494
1495    #[rstest]
1496    fn test_round_to_sig_figs() {
1497        // BTC price ~$104,567 needs to round to 5 sig figs
1498        assert_eq!(round_to_sig_figs(dec!(104567.3), 5), dec!(104570));
1499        assert_eq!(round_to_sig_figs(dec!(104522.5), 5), dec!(104520));
1500        assert_eq!(round_to_sig_figs(dec!(99999.9), 5), dec!(100000));
1501
1502        // Smaller prices should keep decimals
1503        assert_eq!(round_to_sig_figs(dec!(1234.5), 5), dec!(1234.5));
1504        assert_eq!(round_to_sig_figs(dec!(0.12345), 5), dec!(0.12345));
1505        assert_eq!(round_to_sig_figs(dec!(0.123456), 5), dec!(0.12346));
1506
1507        // Sub-1 values with leading zeros must preserve 5 sig figs
1508        assert_eq!(round_to_sig_figs(dec!(0.000123456), 5), dec!(0.00012346));
1509        assert_eq!(round_to_sig_figs(dec!(0.000999999), 5), dec!(0.0010000)); // 6 sig figs -> 5
1510
1511        // Zero case
1512        assert_eq!(round_to_sig_figs(dec!(0), 5), dec!(0));
1513
1514        assert_eq!(round_to_sig_figs(dec!(-104567.3), 5), dec!(-104570));
1515        assert_eq!(round_to_sig_figs(dec!(-1234.5), 5), dec!(-1234.5));
1516        assert_eq!(round_to_sig_figs(dec!(-0.000123456), 5), dec!(-0.00012346));
1517        assert_eq!(round_to_sig_figs(dec!(-0.123456), 5), dec!(-0.12346));
1518    }
1519
1520    #[rstest]
1521    fn test_normalize_price() {
1522        // Now includes 5 sig fig rounding first
1523        assert_eq!(normalize_price(dec!(100.12345), 2), dec!(100.12));
1524        assert_eq!(normalize_price(dec!(100.19999), 2), dec!(100.2)); // Rounded to 5 sig figs first
1525        assert_eq!(normalize_price(dec!(100.999), 0), dec!(101)); // 100.999 -> 101.00 (5 sig) -> 101
1526        assert_eq!(normalize_price(dec!(100.12345), 4), dec!(100.12)); // 5 sig figs = 100.12
1527
1528        // BTC-like prices get rounded to 5 sig figs
1529        assert_eq!(normalize_price(dec!(104567.3), 1), dec!(104570));
1530    }
1531
1532    #[rstest]
1533    fn test_normalize_quantity() {
1534        assert_eq!(normalize_quantity(dec!(1.12345), 3), dec!(1.123));
1535        assert_eq!(normalize_quantity(dec!(1.99999), 3), dec!(1.999));
1536        assert_eq!(normalize_quantity(dec!(1.999), 0), dec!(1));
1537        assert_eq!(normalize_quantity(dec!(1.12345), 5), dec!(1.12345));
1538    }
1539
1540    #[rstest]
1541    fn test_normalize_order_complete() {
1542        let result = normalize_order(
1543            dec!(100.12345), // price
1544            dec!(0.123456),  // qty
1545            dec!(0.01),      // tick_size
1546            dec!(0.0001),    // step_size
1547            dec!(10),        // min_notional
1548            2,               // price_decimals
1549            4,               // size_decimals
1550        );
1551
1552        assert!(result.is_ok());
1553        let (price, qty) = result.unwrap();
1554        assert_eq!(price, dec!(100.12)); // normalized and rounded down
1555        assert_eq!(qty, dec!(0.1234)); // normalized and rounded down
1556    }
1557
1558    #[rstest]
1559    fn test_normalize_order_min_notional_fail() {
1560        let result = normalize_order(
1561            dec!(100.12345), // price
1562            dec!(0.05),      // qty (too small for min notional)
1563            dec!(0.01),      // tick_size
1564            dec!(0.0001),    // step_size
1565            dec!(10),        // min_notional
1566            2,               // price_decimals
1567            4,               // size_decimals
1568        );
1569
1570        assert!(result.is_err());
1571        assert!(result.unwrap_err().contains("Notional value"));
1572    }
1573
1574    #[rstest]
1575    fn test_edge_cases() {
1576        // Test with very small numbers
1577        assert_eq!(
1578            round_down_to_tick(dec!(0.000001), dec!(0.000001)),
1579            dec!(0.000001)
1580        );
1581
1582        // Test with large numbers
1583        assert_eq!(round_down_to_tick(dec!(999999.99), dec!(1.0)), dec!(999999));
1584
1585        // Test rounding edge case
1586        assert_eq!(
1587            round_down_to_tick(dec!(100.009999), dec!(0.01)),
1588            dec!(100.00)
1589        );
1590    }
1591
1592    #[rstest]
1593    fn test_is_conditional_order_data() {
1594        // Test with trigger price and tpsl (conditional)
1595        assert!(is_conditional_order_data(
1596            Some(dec!(50000.0)),
1597            Some(&HyperliquidTpSl::Sl)
1598        ));
1599
1600        // Test with only trigger price (not conditional - needs both)
1601        assert!(!is_conditional_order_data(Some(dec!(50000.0)), None));
1602
1603        // Test with only tpsl (not conditional - needs both)
1604        assert!(!is_conditional_order_data(None, Some(&HyperliquidTpSl::Tp)));
1605
1606        // Test with no conditional fields
1607        assert!(!is_conditional_order_data(None, None));
1608    }
1609
1610    #[rstest]
1611    fn test_parse_trigger_order_type() {
1612        // Stop Market
1613        assert_eq!(
1614            parse_trigger_order_type(true, &HyperliquidTpSl::Sl),
1615            OrderType::StopMarket
1616        );
1617
1618        // Stop Limit
1619        assert_eq!(
1620            parse_trigger_order_type(false, &HyperliquidTpSl::Sl),
1621            OrderType::StopLimit
1622        );
1623
1624        // Take Profit Market
1625        assert_eq!(
1626            parse_trigger_order_type(true, &HyperliquidTpSl::Tp),
1627            OrderType::MarketIfTouched
1628        );
1629
1630        // Take Profit Limit
1631        assert_eq!(
1632            parse_trigger_order_type(false, &HyperliquidTpSl::Tp),
1633            OrderType::LimitIfTouched
1634        );
1635    }
1636
1637    #[rstest]
1638    #[case("Stop Market", Some((HyperliquidTpSl::Sl, true)))]
1639    #[case("Stop Limit", Some((HyperliquidTpSl::Sl, false)))]
1640    #[case("Take Profit Market", Some((HyperliquidTpSl::Tp, true)))]
1641    #[case("Take Profit Limit", Some((HyperliquidTpSl::Tp, false)))]
1642    #[case("Limit", None)]
1643    #[case("Market", None)]
1644    #[case("", None)]
1645    fn test_parse_trigger_order_type_label(
1646        #[case] label: &str,
1647        #[case] expected: Option<(HyperliquidTpSl, bool)>,
1648    ) {
1649        assert_eq!(parse_trigger_order_type_label(label), expected);
1650    }
1651
1652    #[rstest]
1653    fn test_parse_order_status_with_trigger() {
1654        // Test with open status and activated trigger
1655        let (status, trigger_status) =
1656            parse_order_status_with_trigger(HyperliquidOrderStatus::Open, Some(true));
1657        assert_eq!(status, OrderStatus::Accepted);
1658        assert_eq!(trigger_status, Some("activated".to_string()));
1659
1660        // Test with open status and not activated
1661        let (status, trigger_status) =
1662            parse_order_status_with_trigger(HyperliquidOrderStatus::Open, Some(false));
1663        assert_eq!(status, OrderStatus::Accepted);
1664        assert_eq!(trigger_status, Some("pending".to_string()));
1665
1666        // Test without trigger info
1667        let (status, trigger_status) =
1668            parse_order_status_with_trigger(HyperliquidOrderStatus::Open, None);
1669        assert_eq!(status, OrderStatus::Accepted);
1670        assert_eq!(trigger_status, None);
1671    }
1672
1673    #[rstest]
1674    fn test_format_trailing_stop_info() {
1675        // Price offset
1676        let info = format_trailing_stop_info("100.0", TrailingOffsetType::Price, Some("50000.0"));
1677        assert!(info.contains("100.0"));
1678        assert!(info.contains("callback at 50000.0"));
1679
1680        // Percentage offset
1681        let info = format_trailing_stop_info("5.0", TrailingOffsetType::Percentage, None);
1682        assert!(info.contains("5.0%"));
1683        assert!(info.contains("Trailing stop"));
1684
1685        // Basis points offset
1686        let info =
1687            format_trailing_stop_info("250", TrailingOffsetType::BasisPoints, Some("49000.0"));
1688        assert!(info.contains("250 bps"));
1689        assert!(info.contains("49000.0"));
1690    }
1691
1692    #[rstest]
1693    fn test_parse_trigger_price() {
1694        // Valid price
1695        let result = parse_trigger_price("50000.0");
1696        assert!(result.is_ok());
1697        assert_eq!(result.unwrap(), dec!(50000.0));
1698
1699        // Valid integer price
1700        let result = parse_trigger_price("49000");
1701        assert!(result.is_ok());
1702        assert_eq!(result.unwrap(), dec!(49000));
1703
1704        // Invalid price
1705        let result = parse_trigger_price("invalid");
1706        assert!(result.is_err());
1707
1708        // Empty string
1709        let result = parse_trigger_price("");
1710        assert!(result.is_err());
1711    }
1712
1713    #[rstest]
1714    #[case(dec!(0), true, dec!(0))] // Zero
1715    #[case(dec!(0), false, dec!(0))] // Zero
1716    #[case(dec!(0.001), true, dec!(0.001005))] // Small price BUY
1717    #[case(dec!(0.001), false, dec!(0.000995))] // Small price SELL
1718    #[case(dec!(100), true, dec!(100.5))] // Round price BUY
1719    #[case(dec!(100), false, dec!(99.5))] // Round price SELL
1720    #[case(dec!(2470), true, dec!(2482.35))] // ETH-like BUY
1721    #[case(dec!(2470), false, dec!(2457.65))] // ETH-like SELL
1722    #[case(dec!(104567.3), true, dec!(105090.1365))] // BTC-like BUY
1723    #[case(dec!(104567.3), false, dec!(104044.4635))] // BTC-like SELL
1724    fn test_derive_limit_from_trigger(
1725        #[case] trigger_price: Decimal,
1726        #[case] is_buy: bool,
1727        #[case] expected: Decimal,
1728    ) {
1729        let result = derive_limit_from_trigger(trigger_price, is_buy, DEFAULT_MARKET_SLIPPAGE_BPS);
1730        assert_eq!(result, expected);
1731
1732        // Verify invariant: BUY limit >= trigger, SELL limit <= trigger
1733        if is_buy {
1734            assert!(result >= trigger_price);
1735        } else {
1736            assert!(result <= trigger_price);
1737        }
1738    }
1739
1740    #[rstest]
1741    // BUY rounds up (ceil)
1742    #[case(dec!(2457.65), 2, true, dec!(2457.65))] // Already at precision
1743    #[case(dec!(2457.65), 1, true, dec!(2457.7))] // Ceil to 1dp
1744    #[case(dec!(2457.65), 0, true, dec!(2458))] // Ceil to integer
1745    // SELL rounds down (floor)
1746    #[case(dec!(2457.65), 2, false, dec!(2457.65))] // Already at precision
1747    #[case(dec!(2457.65), 1, false, dec!(2457.6))] // Floor to 1dp
1748    #[case(dec!(2457.65), 0, false, dec!(2457))] // Floor to integer
1749    // High precision (no-op)
1750    #[case(dec!(0.4975), 4, true, dec!(0.4975))]
1751    #[case(dec!(0.4975), 4, false, dec!(0.4975))]
1752    // Precision forces clamping on small values
1753    #[case(dec!(0.4975), 2, true, dec!(0.50))]
1754    #[case(dec!(0.4975), 2, false, dec!(0.49))]
1755    fn test_clamp_price_to_precision(
1756        #[case] price: Decimal,
1757        #[case] decimals: u8,
1758        #[case] is_buy: bool,
1759        #[case] expected: Decimal,
1760    ) {
1761        assert_eq!(clamp_price_to_precision(price, decimals, is_buy), expected);
1762    }
1763
1764    fn stop_market_order(side: OrderSide, trigger_price: &str) -> OrderAny {
1765        OrderAny::StopMarket(StopMarketOrder::new(
1766            TraderId::from("TESTER-001"),
1767            StrategyId::from("S-001"),
1768            InstrumentId::from("ETH-USD-PERP.HYPERLIQUID"),
1769            ClientOrderId::from("O-001"),
1770            side,
1771            Quantity::from(1),
1772            Price::from(trigger_price),
1773            TriggerType::LastPrice,
1774            TimeInForce::Gtc,
1775            None,
1776            false,
1777            false,
1778            None,
1779            None,
1780            None,
1781            None,
1782            None,
1783            None,
1784            None,
1785            None,
1786            None,
1787            None,
1788            None,
1789            Default::default(),
1790            Default::default(),
1791        ))
1792    }
1793
1794    #[rstest]
1795    // ETH-like (precision=2): clamping is a no-op
1796    #[case(OrderSide::Sell, "2470.00", 2)]
1797    #[case(OrderSide::Buy, "2470.00", 2)]
1798    // BTC-like (precision=1): clamping is a no-op
1799    #[case(OrderSide::Sell, "104567.3", 1)]
1800    #[case(OrderSide::Buy, "104567.3", 1)]
1801    // Low-price token (precision=4): clamping is a no-op
1802    #[case(OrderSide::Sell, "0.50", 4)]
1803    #[case(OrderSide::Buy, "0.50", 4)]
1804    // Clamping materially changes: ETH trigger at precision=1
1805    // SELL: 2470 * 0.995 = 2457.65 → sig5 = 2457.6 → floor(1dp) = 2457.6
1806    // BUY:  2470 * 1.005 = 2482.35 → sig5 = 2482.4 → ceil(1dp) = 2482.4
1807    #[case(OrderSide::Sell, "2470.00", 1)]
1808    #[case(OrderSide::Buy, "2470.00", 1)]
1809    // Clamping materially changes: precision=0 forces integer
1810    // SELL: 2470 * 0.995 = 2457.65 → sig5 = 2457.6 → floor(0dp) = 2457
1811    // BUY:  2470 * 1.005 = 2482.35 → sig5 = 2482.4 → ceil(0dp) = 2483
1812    #[case(OrderSide::Sell, "2470.00", 0)]
1813    #[case(OrderSide::Buy, "2470.00", 0)]
1814    fn test_order_to_request_stop_market_derives_limit_from_trigger(
1815        #[case] side: OrderSide,
1816        #[case] trigger_str: &str,
1817        #[case] price_decimals: u8,
1818    ) {
1819        let order = stop_market_order(side, trigger_str);
1820        let request = order_to_hyperliquid_request_with_asset(
1821            &order,
1822            0,
1823            price_decimals,
1824            true,
1825            DEFAULT_MARKET_SLIPPAGE_BPS,
1826        )
1827        .unwrap();
1828        let trigger = Decimal::from_str(trigger_str).unwrap();
1829        let is_buy = matches!(side, OrderSide::Buy);
1830
1831        // Price must satisfy Hyperliquid's directional constraint
1832        if is_buy {
1833            assert!(
1834                request.price >= trigger,
1835                "BUY limit {} must be >= trigger {trigger}",
1836                request.price,
1837            );
1838            assert!(request.is_buy);
1839        } else {
1840            assert!(
1841                request.price <= trigger,
1842                "SELL limit {} must be <= trigger {trigger}",
1843                request.price,
1844            );
1845            assert!(!request.is_buy);
1846        }
1847
1848        // Price must equal the full pipeline: derive -> sig figs -> clamp -> normalize
1849        let derived = derive_limit_from_trigger(trigger, is_buy, DEFAULT_MARKET_SLIPPAGE_BPS);
1850        let sig_rounded = round_to_sig_figs(derived, 5);
1851        let expected = clamp_price_to_precision(sig_rounded, price_decimals, is_buy).normalize();
1852        assert_eq!(request.price, expected);
1853
1854        // Decimal places must not exceed instrument precision
1855        let price_str = request.price.to_string();
1856        let actual_decimals = price_str
1857            .find('.')
1858            .map_or(0, |dot| price_str.len() - dot - 1);
1859        assert!(
1860            actual_decimals <= price_decimals as usize,
1861            "Price {price_str} has {actual_decimals} decimals, max allowed {price_decimals}",
1862        );
1863
1864        // Decimal trailing zeros must be stripped (canonical form)
1865        if price_str.contains('.') {
1866            assert!(
1867                !price_str.ends_with('0'),
1868                "Price {price_str} has decimal trailing zeros",
1869            );
1870        }
1871
1872        let expected_trigger = normalize_price(trigger, price_decimals).normalize();
1873        assert_eq!(
1874            request.kind,
1875            HyperliquidExchangeOrderKind::Trigger {
1876                trigger: HyperliquidExchangeTriggerParams {
1877                    is_market: true,
1878                    trigger_px: expected_trigger,
1879                    tpsl: HyperliquidExchangeTpSl::Sl,
1880                },
1881            },
1882        );
1883    }
1884
1885    fn ok_response(inner: serde_json::Value) -> HyperliquidExchangeResponse {
1886        HyperliquidExchangeResponse::Status {
1887            status: "ok".to_string(),
1888            response: inner,
1889        }
1890    }
1891
1892    #[rstest]
1893    fn test_extract_inner_error_order_with_error() {
1894        let response = ok_response(serde_json::json!({
1895            "type": "order",
1896            "data": {"statuses": [{"error": "Order has invalid price."}]}
1897        }));
1898        assert_eq!(
1899            extract_inner_error(&response),
1900            Some("Order has invalid price.".to_string()),
1901        );
1902    }
1903
1904    #[rstest]
1905    fn test_extract_inner_error_order_resting() {
1906        let response = ok_response(serde_json::json!({
1907            "type": "order",
1908            "data": {"statuses": [{"resting": {"oid": 12345}}]}
1909        }));
1910        assert_eq!(extract_inner_error(&response), None);
1911    }
1912
1913    #[rstest]
1914    fn test_extract_inner_error_order_filled() {
1915        let response = ok_response(serde_json::json!({
1916            "type": "order",
1917            "data": {"statuses": [{"filled": {"totalSz": "0.01", "avgPx": "2470.0", "oid": 99}}]}
1918        }));
1919        assert_eq!(extract_inner_error(&response), None);
1920    }
1921
1922    #[rstest]
1923    fn test_extract_inner_error_cancel_error() {
1924        let response = ok_response(serde_json::json!({
1925            "type": "cancel",
1926            "data": {"statuses": [{"error": "Order not found"}]}
1927        }));
1928        assert_eq!(
1929            extract_inner_error(&response),
1930            Some("Order not found".to_string()),
1931        );
1932    }
1933
1934    #[rstest]
1935    fn test_extract_inner_error_cancel_success() {
1936        let response = ok_response(serde_json::json!({
1937            "type": "cancel",
1938            "data": {"statuses": ["success"]}
1939        }));
1940        assert_eq!(extract_inner_error(&response), None);
1941    }
1942
1943    #[rstest]
1944    fn test_extract_inner_error_modify_error() {
1945        let response = ok_response(serde_json::json!({
1946            "type": "modify",
1947            "data": {"statuses": [{"error": "Invalid modify"}]}
1948        }));
1949        assert_eq!(
1950            extract_inner_error(&response),
1951            Some("Invalid modify".to_string()),
1952        );
1953    }
1954
1955    #[rstest]
1956    fn test_extract_inner_error_modify_success() {
1957        let response = ok_response(serde_json::json!({
1958            "type": "modify",
1959            "data": {"statuses": ["success"]}
1960        }));
1961        assert_eq!(extract_inner_error(&response), None);
1962    }
1963
1964    #[rstest]
1965    fn test_extract_inner_error_non_status_response() {
1966        let response = HyperliquidExchangeResponse::Error {
1967            error: "top-level error".to_string(),
1968        };
1969        assert_eq!(extract_inner_error(&response), None);
1970    }
1971
1972    #[rstest]
1973    fn test_extract_inner_error_unparsable_response() {
1974        let response = ok_response(serde_json::json!({"unknown": "data"}));
1975        assert_eq!(extract_inner_error(&response), None);
1976    }
1977
1978    #[rstest]
1979    fn test_extract_inner_error_returns_first_error_in_batch() {
1980        let response = ok_response(serde_json::json!({
1981            "type": "order",
1982            "data": {"statuses": [
1983                {"resting": {"oid": 1}},
1984                {"error": "Second failed"},
1985                {"error": "Third failed"},
1986            ]}
1987        }));
1988        assert_eq!(
1989            extract_inner_error(&response),
1990            Some("Second failed".to_string()),
1991        );
1992    }
1993
1994    #[rstest]
1995    fn test_extract_inner_errors_mixed_batch() {
1996        let response = ok_response(serde_json::json!({
1997            "type": "order",
1998            "data": {"statuses": [
1999                {"resting": {"oid": 1}},
2000                {"error": "Failed order"},
2001                {"filled": {"totalSz": "0.01", "avgPx": "100.0", "oid": 2}},
2002            ]}
2003        }));
2004        let errors = extract_inner_errors(&response);
2005        assert_eq!(errors.len(), 3);
2006        assert_eq!(errors[0], None);
2007        assert_eq!(errors[1], Some("Failed order".to_string()));
2008        assert_eq!(errors[2], None);
2009    }
2010
2011    #[rstest]
2012    fn test_extract_inner_errors_all_success() {
2013        let response = ok_response(serde_json::json!({
2014            "type": "order",
2015            "data": {"statuses": [
2016                {"resting": {"oid": 1}},
2017                {"resting": {"oid": 2}},
2018            ]}
2019        }));
2020        let errors = extract_inner_errors(&response);
2021        assert_eq!(errors.len(), 2);
2022        assert!(errors.iter().all(|e| e.is_none()));
2023    }
2024
2025    #[rstest]
2026    fn test_extract_inner_errors_cancel_success() {
2027        let response = ok_response(serde_json::json!({
2028            "type": "cancel",
2029            "data": {"statuses": ["success"]}
2030        }));
2031        let errors = extract_inner_errors(&response);
2032        assert_eq!(errors.len(), 1);
2033        assert!(errors[0].is_none());
2034    }
2035
2036    #[rstest]
2037    fn test_extract_inner_errors_cancel_mixed() {
2038        let response = ok_response(serde_json::json!({
2039            "type": "cancel",
2040            "data": {"statuses": [
2041                "success",
2042                {"error": "Order was never placed, already canceled, or filled."},
2043                "success",
2044            ]}
2045        }));
2046        let errors = extract_inner_errors(&response);
2047        assert_eq!(errors.len(), 3);
2048        assert_eq!(errors[0], None);
2049        assert_eq!(
2050            errors[1],
2051            Some("Order was never placed, already canceled, or filled.".to_string())
2052        );
2053        assert_eq!(errors[2], None);
2054    }
2055
2056    #[rstest]
2057    fn test_extract_inner_errors_modify_mixed() {
2058        let response = ok_response(serde_json::json!({
2059            "type": "modify",
2060            "data": {"statuses": [
2061                "success",
2062                {"error": "Order does not exist"},
2063            ]}
2064        }));
2065        let errors = extract_inner_errors(&response);
2066        assert_eq!(errors.len(), 2);
2067        assert_eq!(errors[0], None);
2068        assert_eq!(errors[1], Some("Order does not exist".to_string()));
2069    }
2070
2071    #[rstest]
2072    fn test_extract_inner_errors_unparsable() {
2073        let response = ok_response(serde_json::json!({"foo": "bar"}));
2074        let errors = extract_inner_errors(&response);
2075        assert!(errors.is_empty());
2076    }
2077
2078    fn count_sig_figs(s: &str) -> usize {
2079        let s = s.trim_start_matches('-');
2080        if s.contains('.') {
2081            // Decimal: all digits excluding leading zeros are significant
2082            let digits: String = s.replace('.', "");
2083            digits.trim_start_matches('0').len()
2084        } else {
2085            // Integer: trailing zeros are place-holders, not significant
2086            let s = s.trim_start_matches('0');
2087            s.trim_end_matches('0').len()
2088        }
2089    }
2090
2091    fn make_quote(bid: &str, ask: &str) -> QuoteTick {
2092        QuoteTick::new(
2093            InstrumentId::from("ETH-USD-PERP.HYPERLIQUID"),
2094            Price::from(bid),
2095            Price::from(ask),
2096            Quantity::from("1"),
2097            Quantity::from("1"),
2098            Default::default(),
2099            Default::default(),
2100        )
2101    }
2102
2103    #[rstest]
2104    // BUY uses ask, SELL uses bid
2105    // Pipeline: base → +/-0.5% slippage → round 5 sig figs → clamp → normalize
2106    //
2107    // ETH-like (precision=2)
2108    // BUY: ask=2470 → 2470*1.005=2482.35 → sig5=2482.4 → clamp(2,ceil)=2482.40 → 2482.4
2109    #[case("2460.00", "2470.00", true, 2, "2482.4")]
2110    // SELL: bid=2460 → 2460*0.995=2447.70 → sig5=2447.7 → clamp(2,floor)=2447.70 → 2447.7
2111    #[case("2460.00", "2470.00", false, 2, "2447.7")]
2112    //
2113    // BTC-like (precision=1)
2114    // BUY: ask=104567.3 → 104567.3*1.005=105090.1365 → sig5=105090 → clamp(1,ceil)=105090 → 105090
2115    #[case("104500.0", "104567.3", true, 1, "105090")]
2116    // SELL: bid=104500.0 → 104500*0.995=103977.5 → sig5=103980 → clamp(1,floor)=103980 → 103980
2117    #[case("104500.0", "104567.3", false, 1, "103980")]
2118    //
2119    // Low-price token (precision=4)
2120    // BUY: ask=0.5000 → 0.5*1.005=0.5025 → sig5=0.50250 → clamp(4,ceil)=0.5025 → 0.5025
2121    #[case("0.4900", "0.5000", true, 4, "0.5025")]
2122    // SELL: bid=0.49 → 0.49*0.995=0.48755 → sig5=0.48755 → clamp(4,floor)=0.4875 → 0.4875
2123    #[case("0.4900", "0.5000", false, 4, "0.4875")]
2124    //
2125    // High-price low-precision (precision=0)
2126    // BUY: ask=50000 → 50000*1.005=50250 → sig5=50250 → clamp(0,ceil)=50250 → 50250
2127    #[case("49900", "50000", true, 0, "50250")]
2128    // SELL: bid=49900 → 49900*0.995=49650.5 → sig5=49650 → clamp(0,floor)=49650 → 49650
2129    #[case("49900", "50000", false, 0, "49650")]
2130    //
2131    // Very small price (precision=6)
2132    // BUY: ask=0.001234 → 0.001234*1.005=0.0012402 → sig5=0.0012402 → clamp(6,ceil)=0.001241
2133    #[case("0.001200", "0.001234", true, 6, "0.001241")]
2134    // SELL: bid=0.0012 → 0.0012*0.995=0.001194 → sig5=0.001194 → clamp(6,floor)=0.001194
2135    #[case("0.001200", "0.001234", false, 6, "0.001194")]
2136    fn test_derive_market_order_price(
2137        #[case] bid: &str,
2138        #[case] ask: &str,
2139        #[case] is_buy: bool,
2140        #[case] price_decimals: u8,
2141        #[case] expected: &str,
2142    ) {
2143        let quote = make_quote(bid, ask);
2144        let result =
2145            derive_market_order_price(&quote, is_buy, price_decimals, DEFAULT_MARKET_SLIPPAGE_BPS);
2146        let expected_dec = Decimal::from_str(expected).unwrap();
2147        assert_eq!(result, expected_dec);
2148
2149        // Verify the result matches the full pipeline manually
2150        let base = if is_buy {
2151            quote.ask_price.as_decimal()
2152        } else {
2153            quote.bid_price.as_decimal()
2154        };
2155        let derived = derive_limit_from_trigger(base, is_buy, DEFAULT_MARKET_SLIPPAGE_BPS);
2156        let sig_rounded = round_to_sig_figs(derived, 5);
2157        let pipeline = clamp_price_to_precision(sig_rounded, price_decimals, is_buy).normalize();
2158        assert_eq!(result, pipeline);
2159
2160        // Must not have trailing zeros after decimal point
2161        let s = result.to_string();
2162        if s.contains('.') {
2163            assert!(!s.ends_with('0'), "Price {s} has trailing zeros");
2164        }
2165
2166        // Sig figs must not exceed 5
2167        let sig_count = count_sig_figs(&s);
2168        assert!(sig_count <= 5, "Price {s} has {sig_count} sig figs, max 5",);
2169
2170        // Decimal places must not exceed instrument precision
2171        let actual_decimals = s.find('.').map_or(0, |dot| s.len() - dot - 1);
2172        assert!(
2173            actual_decimals <= price_decimals as usize,
2174            "Price {s} has {actual_decimals} decimals, max {price_decimals}",
2175        );
2176    }
2177
2178    #[rstest]
2179    #[case(50, dec!(1000), true, dec!(1005))] // default 0.5% BUY
2180    #[case(50, dec!(1000), false, dec!(995))] // default 0.5% SELL
2181    #[case(0, dec!(1000), true, dec!(1000))] // 0 bps: no adjustment
2182    #[case(100, dec!(1000), true, dec!(1010))] // 1% BUY
2183    #[case(100, dec!(1000), false, dec!(990))] // 1% SELL
2184    #[case(800, dec!(1000), true, dec!(1080))] // 8% (Hyperliquid SDK default) BUY
2185    #[case(800, dec!(1000), false, dec!(920))] // 8% SELL
2186    fn test_derive_limit_from_trigger_respects_bps(
2187        #[case] slippage_bps: u32,
2188        #[case] trigger: Decimal,
2189        #[case] is_buy: bool,
2190        #[case] expected: Decimal,
2191    ) {
2192        let result = derive_limit_from_trigger(trigger, is_buy, slippage_bps);
2193        assert_eq!(result, expected);
2194    }
2195
2196    #[rstest]
2197    fn test_derive_market_order_price_respects_slippage_override() {
2198        let quote = make_quote("100.00", "100.10");
2199        let tight = derive_market_order_price(&quote, true, 2, 50);
2200        let wide = derive_market_order_price(&quote, true, 2, 800);
2201        assert_eq!(tight, dec!(100.6));
2202        assert_eq!(wide, dec!(108.11));
2203        assert!(wide > tight);
2204    }
2205
2206    // Locks in the field-selection invariant; diverging from it would silently
2207    // disagree with the HTTP parser whenever `account_value != total_raw_usd`
2208    // or the nested and top-level `withdrawable` values differ.
2209    #[rstest]
2210    fn test_parse_account_balances_uses_total_raw_usd_and_top_level_withdrawable() {
2211        let json = r#"{
2212            "assetPositions": [],
2213            "crossMarginSummary": {
2214                "accountValue": "150",
2215                "totalNtlPos": "0",
2216                "totalRawUsd": "100",
2217                "totalMarginUsed": "20",
2218                "withdrawable": "120"
2219            },
2220            "withdrawable": "80",
2221            "time": 1700000000000
2222        }"#;
2223
2224        let state: ClearinghouseState = serde_json::from_str(json).unwrap();
2225        let (balances, margins) = parse_account_balances_and_margins(&state).unwrap();
2226
2227        assert_eq!(balances.len(), 1);
2228        let balance = &balances[0];
2229        // Total comes from total_raw_usd (100), not account_value (150); free comes
2230        // from top-level state.withdrawable (80), not the nested summary.withdrawable (120).
2231        assert_eq!(balance.total.as_decimal(), dec!(100));
2232        assert_eq!(balance.free.as_decimal(), dec!(80));
2233        assert_eq!(balance.locked.as_decimal(), dec!(20));
2234
2235        assert_eq!(margins.len(), 1);
2236        assert_eq!(margins[0].initial.as_decimal(), dec!(20));
2237    }
2238
2239    #[rstest]
2240    fn test_parse_account_balances_preserves_negative_total_raw_usd() {
2241        let json =
2242            include_str!("../../test_data/http_clearinghouse_state_negative_total_raw_usd.json");
2243
2244        let state: ClearinghouseState = serde_json::from_str(json).unwrap();
2245        let (balances, margins) = parse_account_balances_and_margins(&state).unwrap();
2246
2247        assert_eq!(balances.len(), 1);
2248        let balance = &balances[0];
2249        assert_eq!(balance.total.as_decimal(), dec!(-22358.938225));
2250        assert_eq!(balance.free.as_decimal(), dec!(772.232111));
2251        assert_eq!(balance.locked.as_decimal(), dec!(-23131.170336));
2252
2253        assert_eq!(margins.len(), 1);
2254        assert_eq!(margins[0].initial.as_decimal(), dec!(963.798764));
2255    }
2256
2257    #[rstest]
2258    fn test_parse_account_balances_bumps_positive_total_when_withdrawable_exceeds() {
2259        let json = r#"{
2260            "assetPositions": [],
2261            "crossMarginSummary": {
2262                "accountValue": "100",
2263                "totalNtlPos": "0",
2264                "totalRawUsd": "100",
2265                "totalMarginUsed": "0",
2266                "withdrawable": "100"
2267            },
2268            "withdrawable": "150",
2269            "time": 1700000000000
2270        }"#;
2271
2272        let state: ClearinghouseState = serde_json::from_str(json).unwrap();
2273        let (balances, _) = parse_account_balances_and_margins(&state).unwrap();
2274
2275        assert_eq!(balances.len(), 1);
2276        let balance = &balances[0];
2277        assert_eq!(balance.total.as_decimal(), dec!(150));
2278        assert_eq!(balance.free.as_decimal(), dec!(150));
2279        assert_eq!(balance.locked.as_decimal(), dec!(0));
2280    }
2281
2282    #[rstest]
2283    fn test_parse_account_balances_returns_empty_when_no_cross_margin_summary() {
2284        let json = r#"{
2285            "assetPositions": [],
2286            "withdrawable": "100",
2287            "time": 1700000000000
2288        }"#;
2289
2290        let state: ClearinghouseState = serde_json::from_str(json).unwrap();
2291        let (balances, margins) = parse_account_balances_and_margins(&state).unwrap();
2292        assert!(balances.is_empty());
2293        assert!(margins.is_empty());
2294    }
2295
2296    #[rstest]
2297    fn test_parse_spot_account_balances_emits_one_per_token() {
2298        let json = r#"{
2299            "balances": [
2300                {"coin": "USDC", "token": 0, "total": "100.25", "hold": "10", "entryNtl": "0"},
2301                {"coin": "PURR", "token": 1, "total": "50", "hold": "0", "entryNtl": "25"},
2302                {"coin": "DUST", "token": 2, "total": "0", "hold": "0", "entryNtl": "0"}
2303            ]
2304        }"#;
2305
2306        let state: SpotClearinghouseState = serde_json::from_str(json).unwrap();
2307        let balances = parse_spot_account_balances(&state).unwrap();
2308
2309        assert_eq!(balances.len(), 2);
2310
2311        let usdc = &balances[0];
2312        assert_eq!(usdc.currency.code, "USDC");
2313        assert_eq!(usdc.total.as_decimal(), dec!(100.25));
2314        assert_eq!(usdc.free.as_decimal(), dec!(90.25));
2315        assert_eq!(usdc.locked.as_decimal(), dec!(10));
2316
2317        let purr = &balances[1];
2318        assert_eq!(purr.currency.code, "PURR");
2319        assert_eq!(purr.total.as_decimal(), dec!(50));
2320        assert_eq!(purr.free.as_decimal(), dec!(50));
2321    }
2322
2323    #[rstest]
2324    fn test_parse_spot_account_balances_clamps_hold_to_total() {
2325        let json = r#"{
2326            "balances": [
2327                {"coin": "HYPE", "token": 5, "total": "5", "hold": "10", "entryNtl": "0"}
2328            ]
2329        }"#;
2330
2331        let state: SpotClearinghouseState = serde_json::from_str(json).unwrap();
2332        let balances = parse_spot_account_balances(&state).unwrap();
2333
2334        assert_eq!(balances.len(), 1);
2335        let hype = &balances[0];
2336        assert_eq!(hype.total.as_decimal(), dec!(5));
2337        assert_eq!(hype.free.as_decimal(), dec!(0));
2338        assert_eq!(hype.locked.as_decimal(), dec!(5));
2339    }
2340
2341    #[rstest]
2342    fn test_parse_spot_account_balances_empty() {
2343        let state = SpotClearinghouseState::default();
2344        let balances = parse_spot_account_balances(&state).unwrap();
2345        assert!(balances.is_empty());
2346    }
2347
2348    #[rstest]
2349    fn test_parse_combined_deduplicates_usdc_when_perp_summary_present() {
2350        let perp_json = r#"{
2351            "assetPositions": [],
2352            "crossMarginSummary": {
2353                "accountValue": "500",
2354                "totalNtlPos": "0",
2355                "totalRawUsd": "500",
2356                "totalMarginUsed": "0",
2357                "withdrawable": "500"
2358            },
2359            "withdrawable": "500"
2360        }"#;
2361        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2362
2363        let spot_json = r#"{
2364            "balances": [
2365                {"coin": "USDC", "token": 0, "total": "123", "hold": "0", "entryNtl": "0"},
2366                {"coin": "PURR", "token": 1, "total": "10", "hold": "0", "entryNtl": "5"}
2367            ]
2368        }"#;
2369        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2370
2371        let (balances, margins) = parse_combined_account_balances_and_margins(
2372            &perp_state,
2373            &spot_state,
2374            HyperliquidAccountAbstraction::Disabled,
2375        )
2376        .unwrap();
2377
2378        assert!(margins.is_empty());
2379        assert_eq!(balances.len(), 2);
2380        assert_eq!(balances[0].currency.code, "USDC");
2381        assert_eq!(balances[0].total.as_decimal(), dec!(500));
2382        assert_eq!(balances[1].currency.code, "PURR");
2383        assert_eq!(balances[1].total.as_decimal(), dec!(10));
2384    }
2385
2386    #[rstest]
2387    fn test_parse_combined_surfaces_spot_usdc_when_perp_summary_zeroed_unified() {
2388        let perp_json = r#"{
2389            "assetPositions": [],
2390            "crossMarginSummary": {
2391                "accountValue": "0",
2392                "totalNtlPos": "0",
2393                "totalRawUsd": "0",
2394                "totalMarginUsed": "0",
2395                "withdrawable": "0"
2396            },
2397            "withdrawable": "0"
2398        }"#;
2399        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2400
2401        let spot_json = r#"{
2402            "balances": [
2403                {"coin": "USDC", "token": 0, "total": "75", "hold": "5", "entryNtl": "0"},
2404                {"coin": "PURR", "token": 1, "total": "10", "hold": "0", "entryNtl": "5"}
2405            ]
2406        }"#;
2407        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2408
2409        let (balances, margins) = parse_combined_account_balances_and_margins(
2410            &perp_state,
2411            &spot_state,
2412            HyperliquidAccountAbstraction::Disabled,
2413        )
2414        .unwrap();
2415
2416        assert!(margins.is_empty());
2417        assert_eq!(balances.len(), 2);
2418        assert_eq!(balances[0].currency.code, "USDC");
2419        assert_eq!(balances[0].total.as_decimal(), dec!(75));
2420        assert_eq!(balances[0].free.as_decimal(), dec!(70));
2421        assert_eq!(balances[1].currency.code, "PURR");
2422        assert_eq!(balances[1].total.as_decimal(), dec!(10));
2423    }
2424
2425    #[rstest]
2426    fn test_parse_combined_deduplicates_usdc_when_perp_total_raw_usd_non_zero() {
2427        let perp_json = r#"{
2428            "assetPositions": [],
2429            "crossMarginSummary": {
2430                "accountValue": "50",
2431                "totalNtlPos": "0",
2432                "totalRawUsd": "50",
2433                "totalMarginUsed": "0",
2434                "withdrawable": "0"
2435            },
2436            "withdrawable": "0"
2437        }"#;
2438        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2439
2440        let spot_json = r#"{
2441            "balances": [
2442                {"coin": "USDC", "token": 0, "total": "75", "hold": "0", "entryNtl": "0"},
2443                {"coin": "PURR", "token": 1, "total": "10", "hold": "0", "entryNtl": "5"}
2444            ]
2445        }"#;
2446        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2447
2448        let (balances, margins) = parse_combined_account_balances_and_margins(
2449            &perp_state,
2450            &spot_state,
2451            HyperliquidAccountAbstraction::Disabled,
2452        )
2453        .unwrap();
2454
2455        assert!(margins.is_empty());
2456        assert_eq!(balances.len(), 2);
2457        assert_eq!(balances[0].currency.code, "USDC");
2458        assert_eq!(balances[0].total.as_decimal(), dec!(50));
2459        assert_eq!(balances[1].currency.code, "PURR");
2460        assert_eq!(balances[1].total.as_decimal(), dec!(10));
2461    }
2462
2463    #[rstest]
2464    fn test_parse_combined_deduplicates_usdc_when_perp_total_raw_usd_negative() {
2465        let perp_json = r#"{
2466            "assetPositions": [],
2467            "crossMarginSummary": {
2468                "accountValue": "-50",
2469                "totalNtlPos": "0",
2470                "totalRawUsd": "-50",
2471                "totalMarginUsed": "0",
2472                "withdrawable": "0"
2473            },
2474            "withdrawable": "0"
2475        }"#;
2476        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2477
2478        let spot_json = r#"{
2479            "balances": [
2480                {"coin": "USDC", "token": 0, "total": "75", "hold": "0", "entryNtl": "0"},
2481                {"coin": "PURR", "token": 1, "total": "10", "hold": "0", "entryNtl": "5"}
2482            ]
2483        }"#;
2484        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2485
2486        let (balances, margins) = parse_combined_account_balances_and_margins(
2487            &perp_state,
2488            &spot_state,
2489            HyperliquidAccountAbstraction::Disabled,
2490        )
2491        .unwrap();
2492
2493        assert!(margins.is_empty());
2494        assert_eq!(balances.len(), 2);
2495        assert_eq!(balances[0].currency.code, "USDC");
2496        assert_eq!(balances[0].total.as_decimal(), dec!(-50));
2497        assert_eq!(balances[1].currency.code, "PURR");
2498        assert_eq!(balances[1].total.as_decimal(), dec!(10));
2499    }
2500
2501    #[rstest]
2502    fn test_parse_combined_deduplicates_usdc_when_perp_margin_used_non_zero() {
2503        let perp_json = r#"{
2504            "assetPositions": [],
2505            "crossMarginSummary": {
2506                "accountValue": "0",
2507                "totalNtlPos": "0",
2508                "totalRawUsd": "0",
2509                "totalMarginUsed": "25",
2510                "withdrawable": "0"
2511            },
2512            "withdrawable": "0"
2513        }"#;
2514        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2515
2516        let spot_json = r#"{
2517            "balances": [
2518                {"coin": "USDC", "token": 0, "total": "75", "hold": "0", "entryNtl": "0"},
2519                {"coin": "PURR", "token": 1, "total": "10", "hold": "0", "entryNtl": "5"}
2520            ]
2521        }"#;
2522        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2523
2524        let (balances, margins) = parse_combined_account_balances_and_margins(
2525            &perp_state,
2526            &spot_state,
2527            HyperliquidAccountAbstraction::Disabled,
2528        )
2529        .unwrap();
2530
2531        assert_eq!(margins.len(), 1);
2532        assert_eq!(balances.len(), 2);
2533        assert_eq!(balances[0].currency.code, "USDC");
2534        assert_eq!(balances[0].total.as_decimal(), dec!(0));
2535        assert_eq!(balances[1].currency.code, "PURR");
2536        assert_eq!(balances[1].total.as_decimal(), dec!(10));
2537    }
2538
2539    #[rstest]
2540    fn test_parse_combined_deduplicates_usdc_when_perp_withdrawable_non_zero() {
2541        let perp_json = r#"{
2542            "assetPositions": [],
2543            "crossMarginSummary": {
2544                "accountValue": "0",
2545                "totalNtlPos": "0",
2546                "totalRawUsd": "0",
2547                "totalMarginUsed": "0",
2548                "withdrawable": "50"
2549            },
2550            "withdrawable": "50"
2551        }"#;
2552        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2553
2554        let spot_json = r#"{
2555            "balances": [
2556                {"coin": "USDC", "token": 0, "total": "75", "hold": "0", "entryNtl": "0"},
2557                {"coin": "PURR", "token": 1, "total": "10", "hold": "0", "entryNtl": "5"}
2558            ]
2559        }"#;
2560        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2561
2562        let (balances, margins) = parse_combined_account_balances_and_margins(
2563            &perp_state,
2564            &spot_state,
2565            HyperliquidAccountAbstraction::Disabled,
2566        )
2567        .unwrap();
2568
2569        assert!(margins.is_empty());
2570        assert_eq!(balances.len(), 2);
2571        assert_eq!(balances[0].currency.code, "USDC");
2572        assert_eq!(balances[0].total.as_decimal(), dec!(50));
2573        assert_eq!(balances[0].free.as_decimal(), dec!(50));
2574        assert_eq!(balances[1].currency.code, "PURR");
2575        assert_eq!(balances[1].total.as_decimal(), dec!(10));
2576    }
2577
2578    #[rstest]
2579    fn test_parse_combined_uses_spot_usdc_when_perp_summary_missing() {
2580        let perp_json = r#"{"assetPositions": []}"#;
2581        let perp_state: ClearinghouseState = serde_json::from_str(perp_json).unwrap();
2582
2583        let spot_json = r#"{
2584            "balances": [
2585                {"coin": "USDC", "token": 0, "total": "50", "hold": "0", "entryNtl": "0"}
2586            ]
2587        }"#;
2588        let spot_state: SpotClearinghouseState = serde_json::from_str(spot_json).unwrap();
2589
2590        let (balances, _) = parse_combined_account_balances_and_margins(
2591            &perp_state,
2592            &spot_state,
2593            HyperliquidAccountAbstraction::Disabled,
2594        )
2595        .unwrap();
2596
2597        assert_eq!(balances.len(), 1);
2598        assert_eq!(balances[0].currency.code, "USDC");
2599        assert_eq!(balances[0].total.as_decimal(), dec!(50));
2600    }
2601
2602    // Unified account holding longs on the default dex and on a HIP-3 dex: the perp summary
2603    // carries a negative `totalRawUsd` (`accountValue - totalNtlPos`) and a per-dex
2604    // `withdrawable`, while spot USDC holds the collateral and `hold` is the margin used across
2605    // every dex (180 default + 240 on a HIP-3 dex).
2606    #[rstest]
2607    fn test_parse_combined_unified_account_with_open_positions_uses_spot_usdc() {
2608        let perp_state: ClearinghouseState = serde_json::from_str(include_str!(
2609            "../../test_data/http_clearinghouse_state_unified_open_positions.json"
2610        ))
2611        .unwrap();
2612
2613        let spot_state: SpotClearinghouseState = serde_json::from_str(include_str!(
2614            "../../test_data/http_spot_clearinghouse_state_unified_open_positions.json"
2615        ))
2616        .unwrap();
2617
2618        let (balances, margins) = parse_combined_account_balances_and_margins(
2619            &perp_state,
2620            &spot_state,
2621            HyperliquidAccountAbstraction::UnifiedAccount,
2622        )
2623        .unwrap();
2624
2625        assert_eq!(balances.len(), 2);
2626        assert_eq!(balances[0].currency.code, "USDC");
2627        assert_eq!(balances[0].total.as_decimal(), dec!(512.25));
2628        assert_eq!(balances[0].free.as_decimal(), dec!(92.25));
2629        assert_eq!(balances[0].locked.as_decimal(), dec!(420.0));
2630        assert_eq!(balances[1].currency.code, "PURR");
2631        assert_eq!(margins.len(), 1);
2632        assert_eq!(margins[0].initial.as_decimal(), dec!(420.0));
2633        assert_eq!(margins[0].maintenance.as_decimal(), dec!(420.0));
2634    }
2635
2636    #[rstest]
2637    fn test_parse_combined_unified_account_flat_has_no_margin() {
2638        let perp_state: ClearinghouseState = serde_json::from_str(include_str!(
2639            "../../test_data/http_clearinghouse_state_unified_flat.json"
2640        ))
2641        .unwrap();
2642        let spot_state: SpotClearinghouseState = serde_json::from_str(include_str!(
2643            "../../test_data/http_spot_clearinghouse_state_unified_flat.json"
2644        ))
2645        .unwrap();
2646
2647        let (balances, margins) = parse_combined_account_balances_and_margins(
2648            &perp_state,
2649            &spot_state,
2650            HyperliquidAccountAbstraction::UnifiedAccount,
2651        )
2652        .unwrap();
2653
2654        assert_eq!(balances.len(), 1);
2655        assert_eq!(balances[0].total.as_decimal(), dec!(100));
2656        assert_eq!(balances[0].free.as_decimal(), dec!(100));
2657        assert!(margins.is_empty());
2658    }
2659
2660    #[rstest]
2661    fn test_parse_combined_unified_account_without_usdc_ignores_perp_summary() {
2662        let perp_state: ClearinghouseState = serde_json::from_str(include_str!(
2663            "../../test_data/http_clearinghouse_state_unified_without_usdc.json"
2664        ))
2665        .unwrap();
2666        let spot_state: SpotClearinghouseState = serde_json::from_str(include_str!(
2667            "../../test_data/http_spot_clearinghouse_state_unified_without_usdc.json"
2668        ))
2669        .unwrap();
2670
2671        let (balances, margins) = parse_combined_account_balances_and_margins(
2672            &perp_state,
2673            &spot_state,
2674            HyperliquidAccountAbstraction::UnifiedAccount,
2675        )
2676        .unwrap();
2677
2678        assert_eq!(balances.len(), 2);
2679        assert_eq!(balances[0].currency.code, "PURR");
2680        // USDC is reported as zero from spot rather than taken from the perp summary
2681        assert_eq!(balances[1].currency.code, "USDC");
2682        assert!(balances[1].total.is_zero());
2683        assert!(balances[1].free.is_zero());
2684        assert!(margins.is_empty());
2685    }
2686
2687    // Portfolio margin borrows against other collateral, so spot USDC can go negative.
2688    #[rstest]
2689    fn test_parse_combined_portfolio_margin_uses_spot_including_negative_usdc() {
2690        let perp_state: ClearinghouseState = serde_json::from_str(include_str!(
2691            "../../test_data/http_clearinghouse_state_portfolio_margin_negative_usdc.json"
2692        ))
2693        .unwrap();
2694        let spot_state: SpotClearinghouseState = serde_json::from_str(include_str!(
2695            "../../test_data/http_spot_clearinghouse_state_portfolio_margin_negative_usdc.json"
2696        ))
2697        .unwrap();
2698
2699        let (balances, margins) = parse_combined_account_balances_and_margins(
2700            &perp_state,
2701            &spot_state,
2702            HyperliquidAccountAbstraction::PortfolioMargin,
2703        )
2704        .unwrap();
2705
2706        assert_eq!(balances.len(), 2);
2707        assert_eq!(balances[0].currency.code, "USDC");
2708        assert_eq!(balances[0].total.as_decimal(), dec!(-25));
2709        assert_eq!(balances[1].currency.code, "HYPE");
2710        assert_eq!(margins.len(), 1);
2711        assert_eq!(margins[0].initial.as_decimal(), dec!(50));
2712    }
2713
2714    fn limit_order(price: &str) -> OrderAny {
2715        OrderAny::Limit(LimitOrder::new(
2716            TraderId::from("TESTER-001"),
2717            StrategyId::from("S-001"),
2718            InstrumentId::from("BTC-USD-PERP.HYPERLIQUID"),
2719            ClientOrderId::from("O-1"),
2720            OrderSide::Buy,
2721            Quantity::from(1),
2722            Price::from(price),
2723            TimeInForce::Gtc,
2724            None,
2725            false,
2726            false,
2727            false,
2728            None,
2729            None,
2730            None,
2731            None,
2732            None,
2733            None,
2734            None,
2735            None,
2736            None,
2737            None,
2738            None,
2739            Default::default(),
2740            Default::default(),
2741        ))
2742    }
2743
2744    #[rstest]
2745    // Venue-accepted forms pass: at the cap, integer, zero, trailing zeros
2746    #[case("78764.5", 1)]
2747    #[case("102393", 1)]
2748    #[case("0", 0)]
2749    #[case("0.11525", 5)]
2750    #[case("0.10", 1)]
2751    fn test_ensure_canonical_wire_price_accepts(#[case] price: &str, #[case] decimals: u8) {
2752        let value = Decimal::from_str(price).unwrap().normalize();
2753        ensure_canonical_wire_price("Price", value, decimals).unwrap();
2754    }
2755
2756    #[rstest]
2757    // Six significant figures with one decimal inside the cap: the venue
2758    // accepts these at signing (live-probed), so no false rejection.
2759    #[case("78764.5", 1)]
2760    #[case("102393", 1)]
2761    fn test_order_to_request_raw_price_accepts_canonical_boundary(
2762        #[case] price: &str,
2763        #[case] decimals: u8,
2764    ) {
2765        let request =
2766            order_to_hyperliquid_request_with_asset(&limit_order(price), 0, decimals, false, 50)
2767                .unwrap();
2768        assert_eq!(request.price, Decimal::from_str(price).unwrap());
2769    }
2770
2771    #[rstest]
2772    #[case("limit")]
2773    #[case("trigger")]
2774    fn test_order_conversion_matches_normalized_decimal_fixture(
2775        #[case] case_name: &str,
2776        #[values(false, true)] normalize_prices: bool,
2777    ) {
2778        let fixture: serde_json::Value =
2779            serde_json::from_str(include_str!("../../test_data/order_decimal_signing.json"))
2780                .unwrap();
2781        let case = fixture["cases"]
2782            .as_array()
2783            .unwrap()
2784            .iter()
2785            .find(|case| case["name"] == case_name)
2786            .unwrap();
2787        let input = &case["input"]["orders"][0];
2788        let order = if case_name == "limit" {
2789            limit_order(input["p"].as_str().unwrap())
2790        } else {
2791            stop_market_order(
2792                OrderSide::Buy,
2793                input["t"]["trigger"]["triggerPx"].as_str().unwrap(),
2794            )
2795        };
2796
2797        let converted = order_to_hyperliquid_request_with_asset_and_cloid(
2798            &order,
2799            0,
2800            0,
2801            normalize_prices,
2802            50,
2803            None,
2804        )
2805        .unwrap();
2806        let direct: HyperliquidExchangePlaceOrderRequest =
2807            serde_json::from_value(input.clone()).unwrap();
2808
2809        assert_eq!(
2810            serde_json::to_value(&converted).unwrap(),
2811            case["action"]["orders"][0]
2812        );
2813        assert_eq!(
2814            serde_json::to_value(&direct).unwrap(),
2815            serde_json::to_value(&converted).unwrap()
2816        );
2817        assert_eq!(
2818            rmp_serde::to_vec_named(&direct).unwrap(),
2819            rmp_serde::to_vec_named(&converted).unwrap()
2820        );
2821    }
2822
2823    #[rstest]
2824    fn test_order_to_request_raw_price_rejects_excess_decimals() {
2825        let err = order_to_hyperliquid_request_with_asset(&limit_order("0.62201"), 0, 4, false, 50)
2826            .unwrap_err();
2827        let msg = err.to_string();
2828        assert!(msg.contains("Price 0.62201"), "unexpected message: {msg}");
2829        assert!(
2830            msg.contains("4 decimal places"),
2831            "unexpected message: {msg}"
2832        );
2833    }
2834
2835    #[rstest]
2836    fn test_order_to_request_normalize_still_accepts_excess_decimals() {
2837        let request =
2838            order_to_hyperliquid_request_with_asset(&limit_order("0.62201"), 0, 4, true, 50)
2839                .unwrap();
2840        assert_eq!(request.price, dec!(0.622));
2841    }
2842
2843    #[rstest]
2844    fn test_order_to_request_raw_trigger_price_rejects_excess_decimals() {
2845        let order = stop_market_order(OrderSide::Sell, "0.62201");
2846        let err = order_to_hyperliquid_request_with_asset(&order, 0, 4, false, 50).unwrap_err();
2847        let msg = err.to_string();
2848        assert!(
2849            msg.contains("Trigger price 0.62201"),
2850            "unexpected message: {msg}"
2851        );
2852        assert!(
2853            msg.contains("4 decimal places"),
2854            "unexpected message: {msg}"
2855        );
2856    }
2857
2858    #[rstest]
2859    // Unknown instrument cap: validation is skipped and the prior raw
2860    // passthrough is preserved rather than validating against a placeholder.
2861    #[case(false)]
2862    // Unknown cap with normalization enabled: falls back to two decimals
2863    #[case(true)]
2864    fn test_order_to_request_optional_decimals_unknown_cap(#[case] normalize: bool) {
2865        let request = order_to_hyperliquid_request_with_optional_decimals(
2866            &limit_order("0.123456"),
2867            0,
2868            None,
2869            normalize,
2870            50,
2871            None,
2872        )
2873        .unwrap();
2874        let expected = if normalize {
2875            dec!(0.12)
2876        } else {
2877            dec!(0.123456)
2878        };
2879        assert_eq!(request.price, expected);
2880    }
2881
2882    #[rstest]
2883    #[case(1_762_819_200_001, 1_762_819_200_001_000_000)]
2884    #[case(18_446_744_073_709, 18_446_744_073_709_000_000)]
2885    fn test_millis_to_nanos_is_exact(#[case] millis: u64, #[case] expected: u64) {
2886        assert_eq!(millis_to_nanos(millis).unwrap(), UnixNanos::from(expected));
2887    }
2888
2889    #[rstest]
2890    fn test_millis_to_nanos_overflow_errors() {
2891        let err = millis_to_nanos(18_446_744_073_710).unwrap_err();
2892        assert_eq!(
2893            err.to_string(),
2894            "milliseconds 18446744073710 is out of range for `u64` nanoseconds"
2895        );
2896    }
2897}