Skip to main content

nautilus_hyperliquid/http/
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
16use anyhow::Context;
17use indexmap::IndexMap;
18use jiff::Timestamp;
19use nautilus_core::{Params, UUID4, UnixNanos, datetime::unix_nanos_to_iso8601};
20use nautilus_model::{
21    data::TradeTick,
22    enums::{
23        AggressorSide, AssetClass, CurrencyType, LiquiditySide, OrderSide, OrderStatus, OrderType,
24        PositionSide, TimeInForce, TriggerType,
25    },
26    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, TradeId, VenueOrderId},
27    instruments::{BinaryOption, CryptoPerpetual, CurrencyPair, Instrument, InstrumentAny},
28    reports::{FillReport, OrderStatusReport, PositionStatusReport},
29    types::{Currency, Money, Price, Quantity},
30};
31use rust_decimal::Decimal;
32use serde::{Deserialize, Serialize};
33use serde_json::{Value, json};
34use ustr::Ustr;
35
36use super::models::{
37    AssetPosition, HyperliquidFill, HyperliquidRecentTrade, OutcomeMarket, OutcomeMeta,
38    OutcomeQuestion, PerpMeta, SpotBalance, SpotMeta,
39};
40use crate::{
41    common::{
42        consts::{ASSET_INDEX_INFO_KEY, HYPERLIQUID_VENUE},
43        converters::hyperliquid_time_in_force_to_nautilus,
44        enums::{
45            HyperliquidFillDirection, HyperliquidOrderStatus as HyperliquidOrderStatusEnum,
46            HyperliquidSide, HyperliquidTimeInForce,
47        },
48        parse::{
49            format_outcome_nautilus_symbol, is_conditional_order_data, make_fill_trade_id,
50            millis_to_nanos, parse_trigger_order_type, parse_trigger_order_type_label,
51        },
52        types::HyperliquidAssetId,
53    },
54    data_types::HyperliquidPublicTrade,
55    websocket::messages::{WsBasicOrderData, WsOrderData},
56};
57
58/// Market type enumeration for normalized instrument definitions.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
60pub enum HyperliquidMarketType {
61    /// Perpetual futures contract.
62    Perp,
63    /// Spot trading pair.
64    Spot,
65    /// HIP-4 binary outcome side token.
66    Outcome,
67}
68
69/// Outcome-specific metadata carried on [`HyperliquidInstrumentDef`] for HIP-4
70/// binary outcome side tokens.
71///
72/// The venue's `outcomeMeta` payload is partial today (no precision or
73/// expiry fields), so unknown values are left as defaults until real venue
74/// payloads are available.
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76pub struct HyperliquidOutcomeMetadata {
77    /// HIP-4 outcome index (`outcome` field from `outcomeMeta`).
78    pub outcome_index: u32,
79    /// Side digit (`0` or `1`).
80    pub outcome_side: u8,
81    /// Outcome market name (for example, "BTC daily").
82    pub market_name: Ustr,
83    /// Side specification name. Set from the venue's `sideSpecs` entry when
84    /// present, otherwise falls back to the canonical HIP-4 labels (`"Yes"`
85    /// for side `0`, `"No"` for side `1`).
86    pub side_name: Option<Ustr>,
87    /// Venue-supplied description.
88    pub description: Option<Ustr>,
89    /// Activation timestamp; `0` when the venue payload does not expose it.
90    pub activation_ns: UnixNanos,
91    /// Expiration timestamp; `0` when the venue payload does not expose it.
92    pub expiration_ns: UnixNanos,
93    /// Structured metadata surfaced as `BinaryOption.info`; see the Hyperliquid
94    /// integration guide for the field layout.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub info: Option<Params>,
97}
98
99/// Normalized instrument definition produced by this parser.
100///
101/// This deliberately avoids any tight coupling to Nautilus domain types.
102/// The InstrumentProvider can later convert this into Nautilus `Instrument`s.
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
104pub struct HyperliquidInstrumentDef {
105    /// Human-readable symbol (e.g., "BTC-USD-PERP", "PURR-USDC-SPOT").
106    pub symbol: Ustr,
107    /// Raw symbol used in Hyperliquid WebSocket subscriptions/messages.
108    /// For perps: base currency (e.g., "BTC").
109    /// For spot: `@{pair_index}` format (e.g., "@107" for HYPE-USDC).
110    /// For outcomes: `#<encoding>` spot-coin form (e.g., "#10").
111    pub raw_symbol: Ustr,
112    /// Base currency/asset (e.g., "BTC", "PURR").
113    pub base: Ustr,
114    /// Quote currency (e.g., the dex collateral token such as "USDC" for perps, "USDC" for spot).
115    pub quote: Ustr,
116    /// Settlement currency for perps. `None` for spot and outcome instruments.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub settlement: Option<Ustr>,
119    /// Market type (perpetual, spot, or outcome).
120    pub market_type: HyperliquidMarketType,
121    /// Asset index used for order submission.
122    /// For perps: index in meta.universe (0, 1, 2, ...).
123    /// For spot: 10000 + index in spotMeta.universe.
124    /// For outcomes: `100_000_000 + 10 * outcome + side`.
125    pub asset_index: u32,
126    /// Number of decimal places for price precision.
127    pub price_decimals: u32,
128    /// Number of decimal places for size precision.
129    pub size_decimals: u32,
130    /// Price tick size as decimal.
131    pub tick_size: Decimal,
132    /// Size lot increment as decimal.
133    pub lot_size: Decimal,
134    /// Maximum leverage (for perps).
135    pub max_leverage: Option<u32>,
136    /// Whether requires isolated margin only.
137    pub only_isolated: bool,
138    /// Whether this is a HIP-3 builder-deployed perpetual.
139    pub is_hip3: bool,
140    /// Whether the instrument is active/tradeable.
141    pub active: bool,
142    /// Outcome-specific metadata when [`market_type`](Self::market_type) is
143    /// [`HyperliquidMarketType::Outcome`].
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub outcome: Option<HyperliquidOutcomeMetadata>,
146    /// Raw upstream data for debugging.
147    pub raw_data: String,
148}
149
150// Replace wildcard bytes (`*`, `?`) in a venue-supplied symbol component with
151// `x` so the value is safe to embed in a Nautilus `InstrumentId`. HIP-3
152// perpetual names from Hyperliquid (e.g. `dex:STREAMABCD****-USD-PERP`)
153// collide with msgbus pattern syntax; the venue-official name is preserved on
154// `raw_symbol` for HTTP/WS wire calls, and orders use the numeric
155// `asset_index` so they do not see the substitution.
156#[must_use]
157fn sanitize_symbol(value: &str) -> std::borrow::Cow<'_, str> {
158    if value.bytes().any(|b| b == b'*' || b == b'?') {
159        let mut out = String::with_capacity(value.len());
160        for ch in value.chars() {
161            out.push(if ch == '*' || ch == '?' { 'x' } else { ch });
162        }
163        std::borrow::Cow::Owned(out)
164    } else {
165        std::borrow::Cow::Borrowed(value)
166    }
167}
168
169/// Parse perpetual instrument definitions from Hyperliquid `meta` response.
170///
171/// Hyperliquid perps follow specific rules:
172/// - Quote and settlement are the dex's collateral token, so notional, PnL and fees are in the
173///   currency the account holds (USDC on the standard dex). The venue labels prices as USD.
174/// - Price decimals = max(0, 6 - sz_decimals) per venue docs
175/// - Active = !is_delisted
176///
177/// `asset_index_base` controls the starting offset for asset IDs:
178/// - Standard perps (dex 0): base = 0
179/// - HIP-3 dexes: base = 100_000 + dex_index * 10_000
180///
181/// Delisted instruments are included but marked as inactive to support
182/// parsing historical data for instruments that may still have trading history.
183pub fn parse_perp_instruments(
184    meta: &PerpMeta,
185    asset_index_base: u32,
186) -> Result<Vec<HyperliquidInstrumentDef>, String> {
187    Ok(parse_perp_instruments_with_collateral(
188        meta,
189        asset_index_base,
190        DEFAULT_PERP_COLLATERAL_CURRENCY,
191    ))
192}
193
194pub(crate) fn parse_perp_instruments_with_collateral(
195    meta: &PerpMeta,
196    asset_index_base: u32,
197    collateral_currency: &str,
198) -> Vec<HyperliquidInstrumentDef> {
199    const PERP_MAX_DECIMALS: i32 = 6;
200
201    let mut defs = Vec::new();
202
203    for (index, asset) in meta.universe.iter().enumerate() {
204        let is_delisted = asset.is_delisted.unwrap_or(false);
205
206        let price_decimals = (PERP_MAX_DECIMALS - asset.sz_decimals as i32).max(0) as u32;
207        let tick_size = pow10_neg(price_decimals);
208        let lot_size = pow10_neg(asset.sz_decimals);
209
210        let symbol = format!("{}-USD-PERP", sanitize_symbol(&asset.name));
211
212        let raw_symbol: Ustr = asset.name.as_str().into();
213
214        let def = HyperliquidInstrumentDef {
215            symbol: symbol.into(),
216            raw_symbol,
217            base: asset.name.clone().into(),
218            quote: collateral_currency.into(),
219            settlement: Some(collateral_currency.into()),
220            market_type: HyperliquidMarketType::Perp,
221            asset_index: asset_index_base + index as u32,
222            price_decimals,
223            size_decimals: asset.sz_decimals,
224            tick_size,
225            lot_size,
226            max_leverage: asset.max_leverage,
227            only_isolated: asset.only_isolated.unwrap_or(false),
228            is_hip3: asset_index_base > 0,
229            active: !is_delisted,
230            outcome: None,
231            raw_data: serde_json::to_string(asset).unwrap_or_default(),
232        };
233
234        defs.push(def);
235    }
236
237    defs
238}
239
240const DEFAULT_PERP_COLLATERAL_TOKEN: u32 = 0;
241const DEFAULT_PERP_COLLATERAL_CURRENCY: &str = "USDC";
242
243pub(crate) fn resolve_perp_collateral_currency(
244    meta: &PerpMeta,
245    spot_meta: Option<&SpotMeta>,
246) -> Result<Ustr, String> {
247    let Some(collateral_token) = meta.collateral_token else {
248        return Ok(DEFAULT_PERP_COLLATERAL_CURRENCY.into());
249    };
250
251    if collateral_token == DEFAULT_PERP_COLLATERAL_TOKEN {
252        return Ok(DEFAULT_PERP_COLLATERAL_CURRENCY.into());
253    }
254
255    let spot_meta = spot_meta.ok_or_else(|| {
256        format!("Spot metadata required to resolve perp collateral token {collateral_token}")
257    })?;
258    let token = spot_meta
259        .tokens
260        .iter()
261        .find(|token| token.index == collateral_token)
262        .ok_or_else(|| {
263            format!("Perp collateral token index {collateral_token} not found in spot metadata")
264        })?;
265
266    Ok(token.name.as_str().into())
267}
268
269/// Parse spot instrument definitions from Hyperliquid `spotMeta` response.
270///
271/// Hyperliquid spot follows these rules:
272/// - Price decimals = max(0, 8 - base_sz_decimals) per venue docs
273/// - Size decimals from base token
274/// - All pairs in the universe are active, including non-canonical pairs
275pub fn parse_spot_instruments(meta: &SpotMeta) -> Result<Vec<HyperliquidInstrumentDef>, String> {
276    const SPOT_MAX_DECIMALS: i32 = 8; // Hyperliquid spot price decimal limit
277    const SPOT_INDEX_OFFSET: u32 = 10000; // Spot assets use 10000 + index
278
279    let mut defs = Vec::new();
280
281    // Build index -> token lookup
282    let mut tokens_by_index = ahash::AHashMap::new();
283    for token in &meta.tokens {
284        tokens_by_index.insert(token.index, token);
285    }
286
287    // Cache canonical pairs first because base-token aliases are first-write-wins
288    let mut pairs = meta.universe.iter().collect::<Vec<_>>();
289    pairs.sort_by(|a, b| {
290        b.is_canonical
291            .cmp(&a.is_canonical)
292            .then(a.index.cmp(&b.index))
293    });
294
295    for pair in pairs {
296        let base_token = tokens_by_index
297            .get(&pair.tokens[0])
298            .ok_or_else(|| format!("Base token index {} not found", pair.tokens[0]))?;
299        let quote_token = tokens_by_index
300            .get(&pair.tokens[1])
301            .ok_or_else(|| format!("Quote token index {} not found", pair.tokens[1]))?;
302
303        let price_decimals = (SPOT_MAX_DECIMALS - base_token.sz_decimals as i32).max(0) as u32;
304        let tick_size = pow10_neg(price_decimals);
305        let lot_size = pow10_neg(base_token.sz_decimals);
306
307        let symbol = format!(
308            "{}-{}-SPOT",
309            sanitize_symbol(&base_token.name),
310            sanitize_symbol(&quote_token.name),
311        );
312
313        // Hyperliquid spot raw_symbol formats (per API docs):
314        // - PURR uses slash format from pair.name (e.g., "PURR/USDC")
315        // - All others use "@{pair_index}" format (e.g., "@107" for HYPE)
316        let raw_symbol: Ustr = if base_token.name == "PURR" {
317            pair.name.as_str().into()
318        } else {
319            format!("@{}", pair.index).into()
320        };
321
322        let def = HyperliquidInstrumentDef {
323            symbol: symbol.into(),
324            raw_symbol,
325            base: base_token.name.clone().into(),
326            quote: quote_token.name.clone().into(),
327            settlement: None,
328            market_type: HyperliquidMarketType::Spot,
329            asset_index: SPOT_INDEX_OFFSET + pair.index,
330            price_decimals,
331            size_decimals: base_token.sz_decimals,
332            tick_size,
333            lot_size,
334            max_leverage: None,
335            only_isolated: false,
336            is_hip3: false,
337            active: true,
338            outcome: None,
339            raw_data: serde_json::to_string(pair).unwrap_or_default(),
340        };
341
342        defs.push(def);
343    }
344
345    Ok(defs)
346}
347
348// Precision for HIP-4 outcome side tokens, which `outcomeMeta` does not expose.
349// Venue order books and fills price outcomes in steps of `0.00001` (5 decimals)
350// and size them in whole tokens.
351pub const OUTCOME_PRICE_DECIMALS: u32 = 5;
352pub const OUTCOME_SIZE_DECIMALS: u32 = 0;
353
354pub(crate) const DEFAULT_OUTCOME_QUOTE_CURRENCY: &str = "USDC";
355
356/// Parse outcome instrument definitions from Hyperliquid `outcomeMeta` response.
357///
358/// Each [`OutcomeMarket`] yields two definitions, one per side (`0` and `1`),
359/// modeled as binary outcome side tokens. The Nautilus internal symbol uses
360/// the form `{outcome_index}-{YES|NO}-OUTCOME` (symmetric with `-PERP` /
361/// `-SPOT`), and the wire `raw_symbol` uses the spot-coin form
362/// (`#<encoding>`) which is what `l2Book`, `trades`, and `bbo` subscriptions
363/// accept.
364///
365/// Expiry is read from the market's own description when it carries
366/// `class:priceBinary`; for outcomes that point at a parent question (`other`
367/// or `index:N`), the expiry is inherited from that question's description.
368///
369/// `side_name` is taken from the venue's `sideSpecs` entry when present,
370/// otherwise it falls back to the canonical HIP-4 labels (`"Yes"` / `"No"`).
371/// Quote and settlement currency use `quoteToken`, falling back to USDC
372/// when the field is absent.
373pub fn parse_outcome_instruments(
374    meta: &OutcomeMeta,
375) -> Result<Vec<HyperliquidInstrumentDef>, String> {
376    let mut defs = Vec::with_capacity(meta.outcomes.len() * 2);
377
378    for market in &meta.outcomes {
379        for side in 0u8..=1u8 {
380            defs.push(build_outcome_def(market, side, meta)?);
381        }
382    }
383
384    Ok(defs)
385}
386
387pub(crate) fn parse_unlisted_outcome_instrument(
388    asset_id: HyperliquidAssetId,
389) -> Result<HyperliquidInstrumentDef, String> {
390    let (Some(outcome), Some(side)) = (asset_id.outcome_index(), asset_id.outcome_side()) else {
391        return Err(format!("Asset {asset_id} is not a HIP-4 outcome"));
392    };
393
394    // Only the encoding survives settlement, so market metadata stays empty
395    let market = OutcomeMarket {
396        outcome,
397        name: String::new(),
398        description: String::new(),
399        quote_token: None,
400        side_specs: Vec::new(),
401    };
402
403    let meta = OutcomeMeta {
404        outcomes: Vec::new(),
405        questions: Vec::new(),
406    };
407
408    build_outcome_def(&market, side, &meta)
409}
410
411fn build_outcome_def(
412    market: &OutcomeMarket,
413    side: u8,
414    meta: &OutcomeMeta,
415) -> Result<HyperliquidInstrumentDef, String> {
416    let outcome_index = market.outcome;
417    let asset_id = HyperliquidAssetId::outcome(outcome_index, side);
418    let encoding = asset_id.outcome_encoding().ok_or_else(|| {
419        format!("Invalid outcome encoding for outcome={outcome_index} side={side}")
420    })?;
421
422    let token = format!("+{encoding}");
423    let coin = format!("#{encoding}");
424    let symbol = format_outcome_nautilus_symbol(outcome_index, side);
425
426    let side_name = market
427        .side_specs
428        .get(usize::from(side))
429        .map(|spec| Ustr::from(spec.name.as_str()))
430        .or_else(|| Some(Ustr::from(default_side_label(side))));
431
432    let description = if market.description.is_empty() {
433        None
434    } else {
435        Some(Ustr::from(market.description.as_str()))
436    };
437
438    let parent_question = meta.parent_question(outcome_index);
439    let expiration_ns = resolve_outcome_expiration_ns(market, meta);
440
441    let info = build_outcome_info(
442        market,
443        side,
444        encoding,
445        asset_id.to_raw(),
446        side_name.as_ref().map(Ustr::as_str),
447        parent_question,
448    );
449
450    let outcome_metadata = HyperliquidOutcomeMetadata {
451        outcome_index,
452        outcome_side: side,
453        market_name: Ustr::from(market.name.as_str()),
454        side_name,
455        description,
456        activation_ns: UnixNanos::default(),
457        expiration_ns,
458        info: Some(info),
459    };
460
461    Ok(HyperliquidInstrumentDef {
462        symbol: Ustr::from(symbol.as_str()),
463        raw_symbol: Ustr::from(coin.as_str()),
464        base: Ustr::from(token.as_str()),
465        quote: market
466            .quote_token
467            .as_deref()
468            .unwrap_or(DEFAULT_OUTCOME_QUOTE_CURRENCY)
469            .into(),
470        settlement: None,
471        market_type: HyperliquidMarketType::Outcome,
472        asset_index: asset_id.to_raw(),
473        price_decimals: OUTCOME_PRICE_DECIMALS,
474        size_decimals: OUTCOME_SIZE_DECIMALS,
475        tick_size: pow10_neg(OUTCOME_PRICE_DECIMALS),
476        lot_size: pow10_neg(OUTCOME_SIZE_DECIMALS),
477        max_leverage: None,
478        only_isolated: false,
479        is_hip3: false,
480        active: true,
481        outcome: Some(outcome_metadata),
482        raw_data: serde_json::to_string(market).unwrap_or_default(),
483    })
484}
485
486// Side `0` is Yes, `1` is No; matches the HIP-4 encoding convention.
487fn default_side_label(side: u8) -> &'static str {
488    if side == 0 { "Yes" } else { "No" }
489}
490
491// Splits a `key:value|key:value|...` description into snake_case keyed entries
492// keyed on the venue's camelCase keys lowered to snake_case. Empty descriptions
493// produce an empty iterator.
494fn parse_description_fields(description: &str) -> impl Iterator<Item = (String, String)> + '_ {
495    description
496        .split('|')
497        .filter_map(|piece| piece.split_once(':'))
498        .map(|(key, value)| (camel_to_snake(key.trim()), value.trim().to_string()))
499}
500
501fn camel_to_snake(s: &str) -> String {
502    let mut out = String::with_capacity(s.len() + 4);
503    for (i, ch) in s.char_indices() {
504        if ch.is_ascii_uppercase() {
505            if i > 0 {
506                out.push('_');
507            }
508            out.push(ch.to_ascii_lowercase());
509        } else {
510            out.push(ch);
511        }
512    }
513    out
514}
515
516fn build_outcome_info(
517    market: &OutcomeMarket,
518    side: u8,
519    encoding: u32,
520    asset_id_raw: u32,
521    side_name: Option<&str>,
522    parent_question: Option<&OutcomeQuestion>,
523) -> Params {
524    let mut info = IndexMap::from([
525        ("outcome_index".into(), json!(market.outcome)),
526        ("outcome_side".into(), json!(side)),
527    ]);
528
529    if let Some(name) = side_name {
530        info.insert("side_name".into(), Value::String(name.to_string()));
531    }
532    info.insert("encoding".into(), json!(encoding));
533    info.insert("asset_id".into(), json!(asset_id_raw));
534    info.insert("market_name".into(), Value::String(market.name.clone()));
535
536    // Direct binary outcomes (`class:priceBinary|...`) carry the full metadata
537    // on the market description. Named-outcome descriptions are sentinels
538    // (`index:N` / `other`) that just point at the parent question.
539    for (key, value) in parse_description_fields(&market.description) {
540        match key.as_str() {
541            "index" => {
542                if let Ok(named) = value.parse::<u32>() {
543                    info.insert("named_index".into(), json!(named));
544                }
545            }
546            "other" => {
547                info.insert("is_fallback".into(), json!(true));
548            }
549            _ => {
550                info.insert(key, Value::String(value));
551            }
552        }
553    }
554
555    // The market description for named outcomes is literally the keyless
556    // sentinel `other`; capture it explicitly so consumers don't need to
557    // inspect the raw description.
558    if market.description.trim() == "other" {
559        info.insert("is_fallback".into(), json!(true));
560    }
561
562    if let Some(question) = parent_question {
563        info.insert("question".into(), json!(question.question));
564        info.insert("question_name".into(), Value::String(question.name.clone()));
565        for (key, value) in parse_description_fields(&question.description) {
566            let prefixed = format!("question_{key}");
567            info.insert(prefixed, Value::String(value));
568        }
569    }
570
571    Params::new(info)
572}
573
574fn pow10_neg(decimals: u32) -> Decimal {
575    if decimals == 0 {
576        return Decimal::ONE;
577    }
578
579    // Build 1 / 10^decimals using integer arithmetic
580    Decimal::from_i128_with_scale(1, decimals)
581}
582
583// Direct binary outcomes carry `expiry:` in their own description. Named
584// outcomes (`index:N`) and the `other` fallback inherit expiry from the
585// parent question. Returns zero when no expiry can be located.
586fn resolve_outcome_expiration_ns(market: &OutcomeMarket, meta: &OutcomeMeta) -> UnixNanos {
587    if let Some(ns) = parse_expiry_from_description(&market.description) {
588        return ns;
589    }
590
591    meta.parent_question(market.outcome)
592        .and_then(|q| parse_expiry_from_description(&q.description))
593        .unwrap_or_default()
594}
595
596fn parse_expiry_from_description(description: &str) -> Option<UnixNanos> {
597    description
598        .split('|')
599        .filter_map(|piece| piece.split_once(':'))
600        .find_map(|(key, value)| (key == "expiry").then_some(value))
601        .and_then(parse_outcome_expiry_ns)
602}
603
604// Parses a Hyperliquid outcome expiry stamp `YYYYMMDD-HHMM` (UTC) to UnixNanos.
605fn parse_outcome_expiry_ns(s: &str) -> Option<UnixNanos> {
606    let (date_part, time_part) = s.split_once('-')?;
607    if date_part.len() != 8 || time_part.len() != 4 {
608        return None;
609    }
610
611    let year: i32 = date_part[0..4].parse().ok()?;
612    let month: u32 = date_part[4..6].parse().ok()?;
613    let day: u32 = date_part[6..8].parse().ok()?;
614    let hour: u32 = time_part[0..2].parse().ok()?;
615    let minute: u32 = time_part[2..4].parse().ok()?;
616
617    let datetime = format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:00Z")
618        .parse::<Timestamp>()
619        .ok()?;
620    u64::try_from(datetime.as_nanosecond())
621        .ok()
622        .map(UnixNanos::from)
623}
624
625/// Settlement state for a single HIP-4 outcome side token.
626#[derive(Debug, Clone, Copy, PartialEq, Eq)]
627pub struct OutcomeSettlement {
628    /// Outcome index from `outcomeMeta`.
629    pub outcome_index: u32,
630    /// Side token (`0` or `1`).
631    pub outcome_side: u8,
632    /// Final settlement value: `1` for the winning side, `0` for losing sides.
633    pub final_value: u8,
634}
635
636/// Derives per-side settlement values from an `outcomeMeta` snapshot.
637///
638/// Returns one [`OutcomeSettlement`] for every side of every outcome whose
639/// resolution can be inferred from the snapshot:
640///
641/// - For each question with non-empty `settled_named_outcomes`, every named
642///   outcome and the fallback are emitted: the winning named outcomes get
643///   `Yes -> 1, No -> 0`, every other named outcome and the fallback get
644///   `Yes -> 0, No -> 1`.
645/// - Standalone outcomes (not referenced by any question) are skipped because
646///   the venue does not expose their resolution in `outcomeMeta`. They will
647///   need a separate signal (status flag, fill, or position-state event).
648///
649/// Outcomes referenced by a question that has not yet settled are also
650/// skipped. This lets a caller poll `outcomeMeta` and emit settlement events
651/// when entries first appear in the result.
652#[must_use]
653pub fn derive_outcome_settlements(meta: &OutcomeMeta) -> Vec<OutcomeSettlement> {
654    let mut settlements = Vec::new();
655
656    for question in &meta.questions {
657        if question.settled_named_outcomes.is_empty() {
658            continue;
659        }
660
661        let losing_sides_won = |outcome_index: u32| -> [OutcomeSettlement; 2] {
662            // Named outcome did not win; Yes side -> 0, No side -> 1.
663            [
664                OutcomeSettlement {
665                    outcome_index,
666                    outcome_side: 0,
667                    final_value: 0,
668                },
669                OutcomeSettlement {
670                    outcome_index,
671                    outcome_side: 1,
672                    final_value: 1,
673                },
674            ]
675        };
676
677        let winning_sides = |outcome_index: u32| -> [OutcomeSettlement; 2] {
678            // Named outcome won; Yes side -> 1, No side -> 0.
679            [
680                OutcomeSettlement {
681                    outcome_index,
682                    outcome_side: 0,
683                    final_value: 1,
684                },
685                OutcomeSettlement {
686                    outcome_index,
687                    outcome_side: 1,
688                    final_value: 0,
689                },
690            ]
691        };
692
693        for outcome_index in &question.named_outcomes {
694            if question.settled_named_outcomes.contains(outcome_index) {
695                settlements.extend(winning_sides(*outcome_index));
696            } else {
697                settlements.extend(losing_sides_won(*outcome_index));
698            }
699        }
700
701        // The fallback is the "no named outcome resolved" branch; it loses
702        // whenever any named outcome won.
703        if let Some(fallback) = question.fallback_outcome {
704            settlements.extend(losing_sides_won(fallback));
705        }
706    }
707
708    settlements
709}
710
711pub fn get_currency(code: &str) -> Currency {
712    Currency::try_from_str(code).unwrap_or_else(|| {
713        let currency = Currency::new(code, 8, 0, code, CurrencyType::Crypto);
714        if let Err(e) = Currency::register(currency, false) {
715            log::error!("Failed to register currency '{code}': {e}");
716        }
717        currency
718    })
719}
720
721/// Returns USDH, registering it at 8-decimal precision on first call.
722///
723/// Used when venue metadata selects USDH as the collateral currency.
724pub fn get_usdh_currency() -> Currency {
725    Currency::try_from_str("USDH").unwrap_or_else(|| {
726        let currency = Currency::new("USDH", 8, 0, "Hyperliquid USD", CurrencyType::Crypto);
727        if let Err(e) = Currency::register(currency, false) {
728            log::error!("Failed to register USDH currency: {e}");
729        }
730        currency
731    })
732}
733
734/// Resolves the commission currency for a fill given the venue's `feeToken` field.
735///
736/// HIP-4 outcome fills can echo the side token (e.g. `+50`) as `feeToken` when
737/// the fee is zero. The side token is not a Nautilus currency and emitting it as
738/// the commission currency would leak into `OrderFilled` events and persistence;
739/// for outcome side tokens the instrument's quote currency is always used, even
740/// when another adapter path (such as spot-balance parsing) has registered the
741/// side token in the global registry. Non-zero side-token fees error: the venue
742/// does not denominate fees in side tokens. Other unknown tokens fall back to
743/// the instrument's quote currency only when the fee is zero.
744///
745/// # Errors
746///
747/// Returns an error if an outcome side token carries a non-zero fee, or when `fee_token` cannot be
748/// resolved and `fee_amount` is non-zero.
749pub fn resolve_fee_currency(
750    fee_token: &str,
751    fee_amount: Decimal,
752    instrument: &dyn Instrument,
753) -> anyhow::Result<Currency> {
754    if is_outcome_side_token(fee_token) {
755        if !fee_amount.is_zero() {
756            anyhow::bail!(
757                "Outcome side token '{fee_token}' carried a non-zero fee {fee_amount}; \
758                 venue does not denominate fees in side tokens",
759            );
760        }
761        return Ok(instrument.quote_currency());
762    }
763
764    if let Some(currency) = Currency::try_from_str(fee_token) {
765        return Ok(currency);
766    }
767
768    if fee_amount.is_zero() {
769        let fallback = instrument.quote_currency();
770        log::debug!(
771            "Unregistered fee token '{fee_token}' on zero-fee fill for {}; using {fallback} as fallback",
772            instrument.id(),
773        );
774        return Ok(fallback);
775    }
776
777    anyhow::bail!("Unknown fee token '{fee_token}' with non-zero fee {fee_amount}")
778}
779
780fn is_outcome_side_token(symbol: &str) -> bool {
781    let Some(rest) = symbol.strip_prefix('+') else {
782        return false;
783    };
784    !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())
785}
786
787// Hyperliquid documents a venue-wide minimum order notional: $10 for perps,
788// and 10 quote_token for spot.
789// https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/error-responses
790const HYPERLIQUID_MIN_ORDER_NOTIONAL: Decimal = Decimal::TEN;
791
792/// Returns `info` with the venue asset index added under [`ASSET_INDEX_INFO_KEY`].
793///
794/// Hyperliquid signs orders with the numeric asset index rather than the symbol,
795/// and `InstrumentAny` is the only instrument shape published on the message bus.
796/// Carrying the index here lets the execution client register a market discovered
797/// after its own bootstrap without refetching venue metadata.
798fn info_with_asset_index(info: Option<IndexMap<String, Value>>, asset_index: u32) -> Params {
799    let mut info = info.unwrap_or_default();
800    info.insert(ASSET_INDEX_INFO_KEY.to_string(), json!(asset_index));
801    Params::new(info)
802}
803
804/// Converts a single Hyperliquid instrument definition into a Nautilus `InstrumentAny`.
805///
806/// Returns `None` if the conversion fails (e.g., unsupported market type).
807///
808/// # Panics
809///
810/// Panics if the constructed instrument fails validation.
811#[must_use]
812pub fn create_instrument_from_def(
813    def: &HyperliquidInstrumentDef,
814    ts_init: UnixNanos,
815) -> Option<InstrumentAny> {
816    let symbol = Symbol::new(def.symbol);
817    let venue = *HYPERLIQUID_VENUE;
818    let instrument_id = InstrumentId::new(symbol, venue);
819
820    // Use the raw_symbol from the definition which is format-specific:
821    // - Perps: base currency (e.g., "BTC")
822    // - Spot PURR: slash format (e.g., "PURR/USDC")
823    // - Spot others: @{index} format (e.g., "@107")
824    let raw_symbol = Symbol::new(def.raw_symbol);
825    let price_increment = Price::from(def.tick_size.to_string());
826    let size_increment = Quantity::from(def.lot_size.to_string());
827
828    match def.market_type {
829        HyperliquidMarketType::Spot => {
830            let base_currency = get_currency(&def.base);
831            let quote_currency = get_currency(&def.quote);
832            let min_notional = Some(min_order_notional(quote_currency)?);
833            let info = serde_json::from_str::<IndexMap<String, Value>>(&def.raw_data).ok();
834            let info = info_with_asset_index(info, def.asset_index);
835
836            Some(InstrumentAny::CurrencyPair(
837                CurrencyPair::builder()
838                    .instrument_id(instrument_id)
839                    .raw_symbol(raw_symbol)
840                    .base_currency(base_currency)
841                    .quote_currency(quote_currency)
842                    .price_precision(def.price_decimals as u8)
843                    .size_precision(def.size_decimals as u8)
844                    .price_increment(price_increment)
845                    .size_increment(size_increment)
846                    .maybe_min_notional(min_notional)
847                    .info(info)
848                    // Identical to ts_init for now
849                    .ts_event(ts_init)
850                    .ts_init(ts_init)
851                    .build()
852                    .unwrap(),
853            ))
854        }
855        HyperliquidMarketType::Perp => {
856            let base_currency = get_currency(&def.base);
857            let settlement_code = def
858                .settlement
859                .as_ref()
860                .map_or(DEFAULT_PERP_COLLATERAL_CURRENCY, Ustr::as_str);
861            let settlement_currency = if settlement_code == "USDH" {
862                get_usdh_currency()
863            } else {
864                get_currency(settlement_code)
865            };
866            // After the settlement, so a USDH quote finds USDH registered under its own name
867            let quote_currency = get_currency(&def.quote);
868            let min_notional = Some(min_order_notional(quote_currency)?);
869
870            Some(InstrumentAny::CryptoPerpetual(
871                CryptoPerpetual::builder()
872                    .instrument_id(instrument_id)
873                    .raw_symbol(raw_symbol)
874                    .base_currency(base_currency)
875                    .quote_currency(quote_currency)
876                    .settlement_currency(settlement_currency)
877                    .is_inverse(false)
878                    .price_precision(def.price_decimals as u8)
879                    .size_precision(def.size_decimals as u8)
880                    .price_increment(price_increment)
881                    .size_increment(size_increment)
882                    .maybe_min_notional(min_notional)
883                    .info(info_with_asset_index(None, def.asset_index))
884                    // Identical to ts_init for now
885                    .ts_event(ts_init)
886                    .ts_init(ts_init)
887                    .build()
888                    .unwrap(),
889            ))
890        }
891        HyperliquidMarketType::Outcome => {
892            let outcome = def.outcome.as_ref()?;
893            let currency = get_outcome_currency(&def.quote);
894            let info = outcome.info.as_deref().cloned();
895            let info = info_with_asset_index(info, def.asset_index);
896
897            Some(InstrumentAny::BinaryOption(
898                BinaryOption::builder()
899                    .instrument_id(instrument_id)
900                    .raw_symbol(raw_symbol)
901                    .asset_class(AssetClass::Alternative)
902                    .currency(currency)
903                    .activation_ns(outcome.activation_ns)
904                    .expiration_ns(outcome.expiration_ns)
905                    .price_precision(def.price_decimals as u8)
906                    .size_precision(def.size_decimals as u8)
907                    .price_increment(price_increment)
908                    .size_increment(size_increment)
909                    .maybe_outcome(outcome.side_name)
910                    .maybe_description(outcome.description)
911                    .info(info)
912                    .ts_event(ts_init)
913                    .ts_init(ts_init)
914                    .build()
915                    .unwrap(),
916            ))
917        }
918    }
919}
920
921fn min_order_notional(currency: Currency) -> Option<Money> {
922    Money::from_decimal(HYPERLIQUID_MIN_ORDER_NOTIONAL, currency).ok()
923}
924
925pub(crate) fn get_outcome_currency(code: &str) -> Currency {
926    if code == "USDH" {
927        get_usdh_currency()
928    } else {
929        get_currency(code)
930    }
931}
932
933/// Convert a collection of Hyperliquid instrument definitions into Nautilus instruments,
934/// discarding any definitions that fail to convert.
935#[must_use]
936pub fn instruments_from_defs(
937    defs: &[HyperliquidInstrumentDef],
938    ts_init: UnixNanos,
939) -> Vec<InstrumentAny> {
940    defs.iter()
941        .filter_map(|def| create_instrument_from_def(def, ts_init))
942        .collect()
943}
944
945/// Convert owned definitions into Nautilus instruments, consuming the input vector.
946#[must_use]
947pub fn instruments_from_defs_owned(
948    defs: Vec<HyperliquidInstrumentDef>,
949    ts_init: UnixNanos,
950) -> Vec<InstrumentAny> {
951    defs.into_iter()
952        .filter_map(|def| create_instrument_from_def(&def, ts_init))
953        .collect()
954}
955
956fn parse_fill_side(side: &HyperliquidSide) -> OrderSide {
957    match side {
958        HyperliquidSide::Buy => OrderSide::Buy,
959        HyperliquidSide::Sell => OrderSide::Sell,
960    }
961}
962
963/// Parse WebSocket order data to OrderStatusReport.
964///
965/// # Errors
966///
967/// Returns an error if required fields are missing or invalid.
968pub fn parse_order_status_report_from_ws(
969    order_data: &WsOrderData,
970    instrument: &dyn Instrument,
971    account_id: AccountId,
972    ts_init: UnixNanos,
973) -> anyhow::Result<OrderStatusReport> {
974    parse_order_status_report_from_basic(
975        &order_data.order,
976        &order_data.status,
977        instrument,
978        account_id,
979        ts_init,
980    )
981}
982
983/// Parse basic order data to OrderStatusReport.
984///
985/// # Errors
986///
987/// Returns an error if required fields are missing or invalid.
988pub fn parse_order_status_report_from_basic(
989    order: &WsBasicOrderData,
990    status: &HyperliquidOrderStatusEnum,
991    instrument: &dyn Instrument,
992    account_id: AccountId,
993    ts_init: UnixNanos,
994) -> anyhow::Result<OrderStatusReport> {
995    let instrument_id = instrument.id();
996    let venue_order_id = VenueOrderId::new(order.oid.to_string());
997    let order_side = OrderSide::from(order.side);
998
999    // REST rows (`frontendOpenOrders`) carry trigger semantics in the `orderType` label
1000    // instead of the WebSocket `tpsl` / `isMarket` fields
1001    let (tpsl, is_market) = match (order.tpsl, order.order_type.as_deref()) {
1002        (Some(tpsl), _) => (Some(tpsl), order.is_market),
1003        (None, Some(label)) => match parse_trigger_order_type_label(label) {
1004            Some((tpsl, is_market)) => (Some(tpsl), Some(is_market)),
1005            None => (None, order.is_market),
1006        },
1007        (None, None) => (None, order.is_market),
1008    };
1009
1010    let is_conditional = is_conditional_order_data(order.trigger_px, tpsl.as_ref());
1011    let order_type = if is_conditional {
1012        match (is_market, tpsl.as_ref()) {
1013            (Some(is_market), Some(tpsl)) => parse_trigger_order_type(is_market, tpsl),
1014            (None, Some(tpsl)) => parse_trigger_order_type(false, tpsl),
1015            _ => OrderType::Limit,
1016        }
1017    } else {
1018        OrderType::Limit
1019    };
1020
1021    let time_in_force = order
1022        .tif
1023        .map_or(TimeInForce::Gtc, hyperliquid_time_in_force_to_nautilus);
1024    let price_precision = instrument.price_precision();
1025    let size_precision = instrument.size_precision();
1026
1027    let orig_sz = order.orig_sz;
1028    let current_sz = order.sz;
1029
1030    let quantity = Quantity::from_decimal_dp(orig_sz.abs(), size_precision)
1031        .map_err(|e| anyhow::anyhow!("Failed to create quantity from orig_sz: {e}"))?;
1032    let filled_sz = orig_sz.abs() - current_sz.abs();
1033    let filled_qty = Quantity::from_decimal_dp(filled_sz, size_precision)
1034        .map_err(|e| anyhow::anyhow!("Failed to create quantity from filled_sz: {e}"))?;
1035
1036    // The venue marks an order `filled` once it stops executing, with `sz` holding any remainder
1037    // it canceled (seen on IOC orders). A filled report would leave that remainder open.
1038    let venue_status = OrderStatus::from(*status);
1039    let remainder_canceled = venue_status == OrderStatus::Filled && filled_qty < quantity;
1040    let order_status = if remainder_canceled {
1041        OrderStatus::Canceled
1042    } else {
1043        venue_status
1044    };
1045
1046    let ts_accepted = UnixNanos::from(order.timestamp * 1_000_000);
1047    let ts_last = ts_accepted;
1048    let report_id = UUID4::new();
1049
1050    let mut report = OrderStatusReport::new(
1051        account_id,
1052        instrument_id,
1053        None, // client_order_id - will be set if present
1054        venue_order_id,
1055        order_side.into(),
1056        order_type,
1057        time_in_force,
1058        order_status,
1059        quantity,
1060        filled_qty,
1061        ts_accepted,
1062        ts_last,
1063        ts_init,
1064        Some(report_id),
1065    );
1066
1067    // Add client order ID if present
1068    if let Some(cloid) = &order.cloid {
1069        let client_order_id =
1070            ClientOrderId::new_checked(cloid.as_str()).context("invalid order client order ID")?;
1071        report = report.with_client_order_id(client_order_id);
1072    }
1073
1074    if matches!(order.tif, Some(HyperliquidTimeInForce::Alo)) {
1075        report = report.with_post_only(true);
1076    }
1077
1078    if let Some(reduce_only) = order.reduce_only {
1079        report = report.with_reduce_only(reduce_only);
1080    }
1081
1082    if let Some(reason) = status.rejection_reason() {
1083        report = report.with_cancel_reason(reason.to_string());
1084    } else if remainder_canceled {
1085        report = report.with_cancel_reason("Unfilled remainder canceled".to_string());
1086    }
1087
1088    // Only set price for orders the venue did not report as filled. For filled orders, the
1089    // limit price is not the execution price, and setting it would cause bogus inferred fills
1090    // to be created during reconciliation. Real fills arrive via the userEvents WebSocket channel.
1091    if !matches!(
1092        venue_status,
1093        OrderStatus::Filled | OrderStatus::PartiallyFilled
1094    ) {
1095        let price = Price::from_decimal_dp(order.limit_px, price_precision)
1096            .map_err(|e| anyhow::anyhow!("Failed to create price from limit_px: {e}"))?;
1097        report = report.with_price(price);
1098    }
1099
1100    if is_conditional && let Some(trigger_px) = order.trigger_px {
1101        let trigger_price = Price::from_decimal_dp(trigger_px, price_precision)
1102            .map_err(|e| anyhow::anyhow!("Failed to create trigger price: {e}"))?;
1103        report = report
1104            .with_trigger_price(trigger_price)
1105            .with_trigger_type(TriggerType::Default);
1106    }
1107
1108    Ok(report)
1109}
1110
1111/// Parses a `recentTrades` info entry into a [`TradeTick`].
1112///
1113/// Mirrors the field mapping of the WebSocket trade parser
1114/// [`parse_ws_trade_tick`](crate::websocket::parse::parse_ws_trade_tick): both the
1115/// `trades` channel and the `recentTrades` endpoint carry the same
1116/// `px`/`sz`/`side`/`time`/`tid` fields. For this historical snapshot `ts_init` is
1117/// set to the trade's `ts_event` (venue time), matching the other request
1118/// converters so the data engine's window trimming keeps bounded requests.
1119///
1120/// # Errors
1121///
1122/// Returns an error if the price, size, trade identifier, or timestamp is invalid.
1123pub fn parse_recent_trade(
1124    trade: &HyperliquidRecentTrade,
1125    instrument: &InstrumentAny,
1126) -> anyhow::Result<TradeTick> {
1127    let price = Price::from_decimal_dp(trade.px, instrument.price_precision())
1128        .with_context(|| format!("Failed to create price from '{}'", trade.px))?;
1129
1130    let size = Quantity::from_decimal_dp(trade.sz.abs(), instrument.size_precision())
1131        .with_context(|| format!("Failed to create size from '{}'", trade.sz))?;
1132
1133    let aggressor = AggressorSide::from(trade.side);
1134    let trade_id = TradeId::new_checked(trade.tid.to_string())
1135        .context("invalid trade identifier in Hyperliquid recent trade")?;
1136    let ts_event = millis_to_nanos(trade.time)?;
1137
1138    TradeTick::new_checked(
1139        instrument.id(),
1140        price,
1141        size,
1142        aggressor,
1143        trade_id,
1144        ts_event,
1145        ts_event,
1146    )
1147    .context("failed to construct TradeTick from Hyperliquid recent trade")
1148}
1149
1150/// Parses a `recentTrades` info entry into a complete public Hyperliquid trade.
1151pub fn parse_recent_public_trade(
1152    trade: &HyperliquidRecentTrade,
1153    instrument: &InstrumentAny,
1154) -> anyhow::Result<HyperliquidPublicTrade> {
1155    let price = Price::from_decimal_dp(trade.px, instrument.price_precision())
1156        .with_context(|| format!("Failed to create price from '{}'", trade.px))?;
1157    let size = Quantity::from_decimal_dp(trade.sz.abs(), instrument.size_precision())
1158        .with_context(|| format!("Failed to create size from '{}'", trade.sz))?;
1159    let ts_event = millis_to_nanos(trade.time)?;
1160
1161    Ok(HyperliquidPublicTrade::new(
1162        instrument.id(),
1163        price,
1164        size,
1165        AggressorSide::from(trade.side),
1166        trade.tid.to_string(),
1167        trade.users[0].clone(),
1168        trade.users[1].clone(),
1169        trade.hash.clone(),
1170        ts_event,
1171        ts_event,
1172    ))
1173}
1174
1175/// Constrains a recent public-trade snapshot to a requested time window.
1176///
1177/// The `recentTrades` endpoint only provides bounded recent coverage, so a
1178/// request whose end precedes the snapshot floor cannot be fulfilled.
1179pub fn filter_recent_public_trades(
1180    trades: Vec<HyperliquidPublicTrade>,
1181    start: Option<UnixNanos>,
1182    end: Option<UnixNanos>,
1183    limit: Option<usize>,
1184    instrument_id: InstrumentId,
1185) -> Vec<HyperliquidPublicTrade> {
1186    let Some(floor) = trades.first().map(|trade| trade.ts_event) else {
1187        return Vec::new();
1188    };
1189
1190    if let Some(end) = end
1191        && end < floor
1192    {
1193        log::warn!(
1194            "Recent public trades for {instrument_id} are entirely older than the requested window; \
1195             snapshot only covers back to {}",
1196            unix_nanos_to_iso8601(floor),
1197        );
1198        return Vec::new();
1199    }
1200
1201    if let Some(start) = start
1202        && start < floor
1203    {
1204        log::warn!(
1205            "Recent public trades for {instrument_id} only cover back to {}; \
1206             the requested start is earlier and cannot be served",
1207            unix_nanos_to_iso8601(floor),
1208        );
1209    }
1210
1211    let mut filtered: Vec<HyperliquidPublicTrade> = trades
1212        .into_iter()
1213        .filter(|trade| start.is_none_or(|value| trade.ts_event >= value))
1214        .filter(|trade| end.is_none_or(|value| trade.ts_event <= value))
1215        .collect();
1216
1217    if let Some(limit) = limit
1218        && filtered.len() > limit
1219    {
1220        // Preserve ascending event-time order while retaining the newest data.
1221        filtered.drain(0..filtered.len() - limit);
1222    }
1223
1224    filtered
1225}
1226
1227/// Parse Hyperliquid fill to FillReport.
1228///
1229/// Preserves the raw venue CLOID as the client order ID when present.
1230///
1231/// # Errors
1232///
1233/// Returns an error if required fields are missing or invalid.
1234pub fn parse_fill_report(
1235    fill: &HyperliquidFill,
1236    instrument: &dyn Instrument,
1237    account_id: AccountId,
1238    ts_init: UnixNanos,
1239) -> anyhow::Result<FillReport> {
1240    let instrument_id = instrument.id();
1241    let venue_order_id = VenueOrderId::new(fill.oid.to_string());
1242
1243    if matches!(fill.dir, HyperliquidFillDirection::AutoDeleveraging) {
1244        log::warn!(
1245            "Auto-deleveraging fill: {instrument_id} oid={} px={} sz={}",
1246            fill.oid,
1247            fill.px,
1248            fill.sz,
1249        );
1250    }
1251
1252    let trade_id = make_fill_trade_id(
1253        &fill.hash,
1254        fill.oid,
1255        fill.px,
1256        fill.sz,
1257        fill.time,
1258        fill.start_position,
1259    );
1260    let order_side = parse_fill_side(&fill.side);
1261
1262    let price_precision = instrument.price_precision();
1263    let size_precision = instrument.size_precision();
1264
1265    let last_px = Price::from_decimal_dp(fill.px, price_precision)
1266        .map_err(|e| anyhow::anyhow!("Failed to create price from fill px: {e}"))?;
1267    let last_qty = Quantity::from_decimal_dp(fill.sz.abs(), size_precision)
1268        .map_err(|e| anyhow::anyhow!("Failed to create quantity from fill sz: {e}"))?;
1269
1270    let fee_amount = fill.fee;
1271
1272    let fee_currency = resolve_fee_currency(fill.fee_token.as_str(), fee_amount, instrument)?;
1273    let commission = Money::from_decimal(fee_amount, fee_currency)
1274        .map_err(|e| anyhow::anyhow!("Failed to create commission from fee: {e}"))?;
1275
1276    // Determine liquidity side based on 'crossed' flag
1277    let liquidity_side = if fill.crossed {
1278        LiquiditySide::Taker
1279    } else {
1280        LiquiditySide::Maker
1281    };
1282
1283    let ts_event = UnixNanos::from(fill.time * 1_000_000);
1284    let report_id = UUID4::new();
1285    let client_order_id = fill
1286        .cloid
1287        .as_deref()
1288        .map(ClientOrderId::new_checked)
1289        .transpose()
1290        .context("invalid fill client order ID")?;
1291
1292    let report = FillReport::new(
1293        account_id,
1294        instrument_id,
1295        venue_order_id,
1296        trade_id,
1297        order_side,
1298        last_qty,
1299        last_px,
1300        commission,
1301        liquidity_side,
1302        client_order_id,
1303        None, // venue_position_id
1304        ts_event,
1305        ts_init,
1306        Some(report_id),
1307    );
1308
1309    Ok(report)
1310}
1311
1312/// Parse position data from clearinghouse state to PositionStatusReport.
1313///
1314/// # Errors
1315///
1316/// Returns an error if required fields are missing or invalid.
1317pub fn parse_position_status_report(
1318    position_data: &serde_json::Value,
1319    instrument: &dyn Instrument,
1320    account_id: AccountId,
1321    ts_init: UnixNanos,
1322) -> anyhow::Result<PositionStatusReport> {
1323    // Deserialize the position data
1324    let asset_position: AssetPosition = serde_json::from_value(position_data.clone())
1325        .context("failed to deserialize AssetPosition")?;
1326
1327    let position = &asset_position.position;
1328    let instrument_id = instrument.id();
1329
1330    // Determine position side based on size (szi)
1331    let (position_side, quantity_value) = if position.szi.is_zero() {
1332        (PositionSide::Flat, Decimal::ZERO)
1333    } else if position.szi.is_sign_positive() {
1334        (PositionSide::Long, position.szi)
1335    } else {
1336        (PositionSide::Short, position.szi.abs())
1337    };
1338
1339    let quantity = Quantity::from_decimal_dp(quantity_value, instrument.size_precision())
1340        .context("failed to create quantity from decimal")?;
1341    let report_id = UUID4::new();
1342    let ts_last = ts_init;
1343    let avg_px_open = position.entry_px;
1344
1345    // Hyperliquid uses netting (one position per instrument), not hedging
1346    Ok(PositionStatusReport::new(
1347        account_id,
1348        instrument_id,
1349        position_side,
1350        quantity,
1351        ts_last,
1352        ts_init,
1353        Some(report_id),
1354        None, // No venue_position_id for netting positions
1355        avg_px_open,
1356    )
1357    .with_avg_px_open_precision(instrument.price_precision()))
1358}
1359
1360/// Parse a spot token balance into a [`PositionStatusReport`] against the spot instrument.
1361///
1362/// Spot holdings are always Long (Hyperliquid spot has no short exposure). The average
1363/// entry price is derived from `entry_ntl / total` when both are non-zero; otherwise it
1364/// is omitted.
1365///
1366/// # Errors
1367///
1368/// Returns an error if the quantity cannot be constructed at the instrument's precision.
1369pub fn parse_spot_position_status_report(
1370    balance: &SpotBalance,
1371    instrument: &dyn Instrument,
1372    account_id: AccountId,
1373    ts_init: UnixNanos,
1374) -> anyhow::Result<PositionStatusReport> {
1375    let (position_side, quantity_value) = if balance.total.is_zero() {
1376        (PositionSide::Flat, Decimal::ZERO)
1377    } else {
1378        (PositionSide::Long, balance.total)
1379    };
1380
1381    let quantity = Quantity::from_decimal_dp(quantity_value, instrument.size_precision())
1382        .context("failed to create spot quantity from decimal")?;
1383
1384    Ok(PositionStatusReport::new(
1385        account_id,
1386        instrument.id(),
1387        position_side,
1388        quantity,
1389        ts_init,
1390        ts_init,
1391        Some(UUID4::new()),
1392        None,
1393        balance.avg_entry_px(),
1394    ))
1395}
1396
1397#[cfg(test)]
1398mod tests {
1399    use nautilus_execution::reconciliation::position_prices_match;
1400    use rstest::rstest;
1401    use rust_decimal_macros::dec;
1402
1403    use super::{
1404        super::models::{
1405            HyperliquidL2Book, OutcomeMarket, OutcomeMeta, OutcomeQuestion, OutcomeSideSpec,
1406            PerpAsset, SpotPair, SpotToken,
1407        },
1408        *,
1409    };
1410
1411    #[rstest]
1412    fn test_parse_fill_side() {
1413        assert_eq!(parse_fill_side(&HyperliquidSide::Buy), OrderSide::Buy,);
1414        assert_eq!(parse_fill_side(&HyperliquidSide::Sell), OrderSide::Sell,);
1415    }
1416
1417    #[rstest]
1418    #[case::meme("MEME", PositionSide::Long, "43917117", dec!(0.000471), 6, false)]
1419    #[case::bigtime("BIGTIME", PositionSide::Short, "6059690", dec!(0.006712), 6, false)]
1420    #[case::btc("BTC", PositionSide::Long, "0.09354", dec!(78152.9), 1, true)]
1421    #[case::eth("ETH", PositionSide::Long, "2.4242", dec!(2288.79), 2, true)]
1422    #[case::atom("ATOM", PositionSide::Long, "11055.03", dec!(1.4666), 4, true)]
1423    fn test_parse_position_status_report_precision(
1424        #[case] coin: &str,
1425        #[case] position_side: PositionSide,
1426        #[case] qty: &str,
1427        #[case] avg_px_open: Decimal,
1428        #[case] expected_precision: u8,
1429        #[case] matches_without_precision: bool,
1430    ) {
1431        let meta: PerpMeta = load_test_data("http_meta_position_precision.json");
1432        let defs = parse_perp_instruments(&meta, 0).unwrap();
1433        let def = defs
1434            .iter()
1435            .find(|def| def.raw_symbol.as_str() == coin)
1436            .unwrap();
1437        let instrument = create_instrument_from_def(def, UnixNanos::default()).unwrap();
1438        let positions: Vec<Value> = load_test_data("http_positions_precision.json");
1439        let position_data = positions
1440            .iter()
1441            .find(|row| row["position"]["coin"] == coin)
1442            .unwrap();
1443        let position: AssetPosition = serde_json::from_value(position_data.clone()).unwrap();
1444        let position = position.position;
1445
1446        let sign = if position.szi.is_sign_positive() {
1447            Decimal::ONE
1448        } else {
1449            -Decimal::ONE
1450        };
1451
1452        let cached_avg_px =
1453            (position.position_value - position.unrealized_pnl * sign) / position.szi.abs();
1454        let account_id = AccountId::from("HYPERLIQUID-001");
1455        let ts_init = UnixNanos::from(1_700_000_003_000_000_000);
1456
1457        let report =
1458            parse_position_status_report(position_data, &instrument, account_id, ts_init).unwrap();
1459        let expected = PositionStatusReport::new(
1460            account_id,
1461            instrument.id(),
1462            position_side,
1463            Quantity::from(qty),
1464            ts_init,
1465            ts_init,
1466            Some(report.report_id),
1467            None,
1468            Some(avg_px_open),
1469        )
1470        .with_avg_px_open_precision(expected_precision);
1471        let beyond_allowance = avg_px_open
1472            + avg_px_open * dec!(0.0001)
1473            + Decimal::new(2, u32::from(expected_precision));
1474
1475        assert_eq!(report, expected);
1476        assert_eq!(
1477            position_prices_match(cached_avg_px, avg_px_open, None, None),
1478            matches_without_precision,
1479        );
1480        assert!(position_prices_match(
1481            cached_avg_px,
1482            avg_px_open,
1483            None,
1484            report.avg_px_open_precision,
1485        ));
1486        assert!(!position_prices_match(
1487            beyond_allowance,
1488            avg_px_open,
1489            None,
1490            report.avg_px_open_precision,
1491        ));
1492    }
1493
1494    #[rstest]
1495    #[case::with_cloid(Some("0x0123456789abcdef0123456789abcdef"))]
1496    #[case::without_cloid(None)]
1497    fn test_parse_fill_report_client_order_id(#[case] cloid: Option<&str>) {
1498        let meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1499        let defs = parse_perp_instruments(&meta, 0).unwrap();
1500        let instrument = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
1501        let mut fills: Vec<HyperliquidFill> = load_test_data("http_query_order_fills.json");
1502        fills[0].cloid = cloid.map(String::from);
1503        let account_id = AccountId::from("HYPERLIQUID-REST");
1504        let ts_init = UnixNanos::from(1_700_000_003_000_000_000);
1505
1506        let report = parse_fill_report(&fills[0], &instrument, account_id, ts_init).unwrap();
1507
1508        assert_eq!(report.client_order_id, cloid.map(ClientOrderId::new));
1509        assert_eq!(report.account_id, account_id);
1510        assert_eq!(report.instrument_id, instrument.id());
1511        assert_eq!(report.venue_order_id, VenueOrderId::from("900029"));
1512        assert_eq!(
1513            report.trade_id,
1514            make_fill_trade_id(
1515                "0xquery-fill-a",
1516                900029,
1517                dec!(90000),
1518                dec!(0.0004),
1519                1_700_000_001_000,
1520                dec!(0)
1521            )
1522        );
1523        assert_eq!(report.order_side, OrderSide::Buy);
1524        assert_eq!(report.last_qty.as_decimal(), dec!(0.0004));
1525        assert_eq!(report.last_px.as_decimal(), dec!(90000));
1526        assert_eq!(report.commission, Money::from("0.010 USDC"));
1527        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
1528        assert_eq!(report.venue_position_id, None);
1529        assert_eq!(report.ts_event, UnixNanos::from(1_700_000_001_000_000_000));
1530        assert_eq!(report.ts_init, ts_init);
1531    }
1532
1533    #[rstest]
1534    #[case::empty("")]
1535    #[case::whitespace("   ")]
1536    #[case::non_ascii("0x\u{e9}")]
1537    fn test_parse_fill_report_rejects_invalid_client_order_id(#[case] cloid: &str) {
1538        let instrument = create_btc_perp_instrument();
1539        let mut fills: Vec<HyperliquidFill> = load_test_data("http_query_order_fills.json");
1540        fills[0].cloid = Some(cloid.to_string());
1541
1542        let result = parse_fill_report(
1543            &fills[0],
1544            &instrument,
1545            AccountId::from("HYPERLIQUID-REST"),
1546            UnixNanos::default(),
1547        );
1548
1549        assert_eq!(
1550            result.unwrap_err().to_string(),
1551            "invalid fill client order ID"
1552        );
1553    }
1554
1555    #[rstest]
1556    fn test_pow10_neg() {
1557        assert_eq!(pow10_neg(0), dec!(1));
1558        assert_eq!(pow10_neg(1), dec!(0.1));
1559        assert_eq!(pow10_neg(5), dec!(0.00001));
1560    }
1561
1562    #[rstest]
1563    fn test_parse_perp_instruments() {
1564        let meta = PerpMeta {
1565            universe: vec![
1566                PerpAsset {
1567                    name: "BTC".to_string(),
1568                    sz_decimals: 5,
1569                    max_leverage: Some(50),
1570                    ..Default::default()
1571                },
1572                PerpAsset {
1573                    name: "DELIST".to_string(),
1574                    sz_decimals: 3,
1575                    max_leverage: Some(10),
1576                    only_isolated: Some(true),
1577                    is_delisted: Some(true),
1578                    ..Default::default()
1579                },
1580            ],
1581            margin_tables: vec![],
1582            collateral_token: None,
1583        };
1584
1585        let defs = parse_perp_instruments(&meta, 0).unwrap();
1586
1587        // Should have both BTC and DELIST (delisted instruments are included for historical data)
1588        assert_eq!(defs.len(), 2);
1589
1590        let btc = &defs[0];
1591        assert_eq!(btc.symbol, "BTC-USD-PERP");
1592        assert_eq!(btc.base, "BTC");
1593        assert_eq!(btc.quote, "USDC");
1594        assert_eq!(btc.settlement.as_ref().unwrap(), "USDC");
1595        assert_eq!(btc.market_type, HyperliquidMarketType::Perp);
1596        assert_eq!(btc.price_decimals, 1); // 6 - 5 = 1
1597        assert_eq!(btc.size_decimals, 5);
1598        assert_eq!(btc.tick_size, dec!(0.1));
1599        assert_eq!(btc.lot_size, dec!(0.00001));
1600        assert_eq!(btc.max_leverage, Some(50));
1601        assert!(!btc.only_isolated);
1602        assert!(btc.active);
1603
1604        let delist = &defs[1];
1605        assert_eq!(delist.symbol, "DELIST-USD-PERP");
1606        assert_eq!(delist.base, "DELIST");
1607        assert!(!delist.active); // Delisted instruments are marked as inactive
1608    }
1609
1610    use crate::common::testing::load_test_data;
1611
1612    #[rstest]
1613    fn test_parse_perp_instruments_from_real_data() {
1614        let meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1615
1616        let defs = parse_perp_instruments(&meta, 0).unwrap();
1617
1618        // Should have 3 instruments (BTC, ETH, ATOM)
1619        assert_eq!(defs.len(), 3);
1620
1621        // Validate BTC
1622        let btc = &defs[0];
1623        assert_eq!(btc.symbol, "BTC-USD-PERP");
1624        assert_eq!(btc.base, "BTC");
1625        assert_eq!(btc.quote, "USDC");
1626        assert_eq!(btc.settlement.as_ref().unwrap(), "USDC");
1627        assert_eq!(btc.market_type, HyperliquidMarketType::Perp);
1628        assert_eq!(btc.size_decimals, 5);
1629        assert_eq!(btc.max_leverage, Some(40));
1630        assert!(btc.active);
1631
1632        // Validate ETH
1633        let eth = &defs[1];
1634        assert_eq!(eth.symbol, "ETH-USD-PERP");
1635        assert_eq!(eth.base, "ETH");
1636        assert_eq!(eth.size_decimals, 4);
1637        assert_eq!(eth.max_leverage, Some(25));
1638
1639        // Validate ATOM
1640        let atom = &defs[2];
1641        assert_eq!(atom.symbol, "ATOM-USD-PERP");
1642        assert_eq!(atom.base, "ATOM");
1643        assert_eq!(atom.size_decimals, 2);
1644        assert_eq!(atom.max_leverage, Some(5));
1645    }
1646
1647    #[rstest]
1648    fn test_parse_recent_trade() {
1649        let meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1650        let defs = parse_perp_instruments(&meta, 0).unwrap();
1651        let instrument = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
1652
1653        let trade = HyperliquidRecentTrade {
1654            coin: Ustr::from("BTC"),
1655            side: HyperliquidSide::Sell,
1656            px: dec!(50000.0),
1657            sz: dec!(0.5),
1658            hash: "0xhash".to_string(),
1659            time: 1_769_916_000_000,
1660            tid: 987_654_321,
1661            users: ["0xbuyer".to_string(), "0xseller".to_string()],
1662        };
1663
1664        let tick = parse_recent_trade(&trade, &instrument).unwrap();
1665
1666        assert_eq!(tick.instrument_id, instrument.id());
1667        assert_eq!(tick.price.as_decimal(), dec!(50000));
1668        assert_eq!(tick.size.as_decimal(), dec!(0.5));
1669        assert_eq!(tick.aggressor_side, AggressorSide::Sell);
1670        assert_eq!(tick.trade_id.to_string(), "987654321");
1671        assert_eq!(
1672            tick.ts_event,
1673            UnixNanos::from(1_769_916_000_000 * 1_000_000)
1674        );
1675        // Historical trades carry ts_init == ts_event so the engine's window
1676        // trimming (by ts_init) keeps bounded requests.
1677        assert_eq!(tick.ts_init, tick.ts_event);
1678    }
1679
1680    #[rstest]
1681    fn test_recent_trade_rejects_invalid_price() {
1682        // Price is now a Decimal field, so an invalid value is rejected at
1683        // deserialization rather than by parse_recent_trade.
1684        let json = r#"{"coin":"BTC","side":"B","px":"not-a-number","sz":"0.5","time":1769916000000,"tid":1}"#;
1685        assert!(serde_json::from_str::<HyperliquidRecentTrade>(json).is_err());
1686    }
1687
1688    #[rstest]
1689    fn test_create_instrument_from_def_perp_sets_min_notional() {
1690        let meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1691        let defs = parse_perp_instruments(&meta, 0).unwrap();
1692
1693        let instrument = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
1694
1695        match instrument {
1696            InstrumentAny::CryptoPerpetual(perp) => {
1697                let min_notional = perp.min_notional.unwrap();
1698                assert_eq!(min_notional.currency, Currency::USDC());
1699                assert_eq!(min_notional.as_decimal(), dec!(10));
1700                assert_eq!(perp.settlement_currency.code, "USDC");
1701            }
1702            other => panic!("Expected CryptoPerpetual, was {other:?}"),
1703        }
1704    }
1705
1706    #[rstest]
1707    fn test_perp_money_flows_in_the_collateral_currency() {
1708        // Notional, PnL and fees come out in cost_currency (= quote), which must match the
1709        // collateral the account holds, as the venue reports prices in USD but settles in USDC
1710        let meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1711        let defs = parse_perp_instruments(&meta, 0).unwrap();
1712
1713        let InstrumentAny::CryptoPerpetual(perp) =
1714            create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap()
1715        else {
1716            panic!("Expected CryptoPerpetual");
1717        };
1718        let notional =
1719            perp.calculate_notional_value(Quantity::from("2"), Price::from("30000.0"), None);
1720
1721        assert_eq!(perp.id.symbol.as_str(), "BTC-USD-PERP");
1722        assert!(!perp.is_quanto());
1723        assert_eq!(perp.quote_currency, Currency::USDC());
1724        assert_eq!(perp.cost_currency(), Currency::USDC());
1725        assert_eq!(
1726            notional,
1727            Money::from_decimal(dec!(60000), Currency::USDC()).unwrap()
1728        );
1729    }
1730
1731    #[rstest]
1732    fn test_create_instrument_from_def_carries_asset_index_on_info() {
1733        // The execution client resolves a market listed after its own bootstrap
1734        // from the instrument published on the message bus, so every market type
1735        // must carry its signing asset index on `info`.
1736        let perp_meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1737        let outcome_meta = OutcomeMeta {
1738            outcomes: vec![OutcomeMarket {
1739                outcome: 2,
1740                name: "Recurring BTC".to_string(),
1741                description: "Daily settlement".to_string(),
1742                quote_token: Some("USDC".to_string()),
1743                side_specs: vec![
1744                    OutcomeSideSpec {
1745                        name: "Yes".to_string(),
1746                    },
1747                    OutcomeSideSpec {
1748                        name: "No".to_string(),
1749                    },
1750                ],
1751            }],
1752            questions: vec![],
1753        };
1754
1755        let mut defs = parse_perp_instruments(&perp_meta, 0).unwrap();
1756        defs.extend(parse_perp_instruments(&perp_meta, 110_000).unwrap());
1757        defs.extend(parse_outcome_instruments(&outcome_meta).unwrap());
1758
1759        assert!(defs.iter().any(|def| def.is_hip3));
1760
1761        for def in &defs {
1762            let instrument = create_instrument_from_def(def, UnixNanos::default()).unwrap();
1763            let info = instrument
1764                .info()
1765                .unwrap_or_else(|| panic!("info missing for {}", def.symbol));
1766
1767            assert_eq!(
1768                info.get_u64(ASSET_INDEX_INFO_KEY),
1769                Some(u64::from(def.asset_index)),
1770                "asset index mismatch for {}",
1771                def.symbol,
1772            );
1773        }
1774    }
1775
1776    #[rstest]
1777    fn test_parse_perp_instruments_with_non_usdc_collateral() {
1778        let all_metas: Vec<PerpMeta> =
1779            load_test_data("http_all_perp_metas_non_usdc_collateral.json");
1780        let spot_meta: SpotMeta = load_test_data("http_spot_meta_non_usdc_collateral.json");
1781
1782        // Dex, asset index base, collateral token, its name, and the market's symbol
1783        let cases = [
1784            (1, 110_000, 360, "USDH", "km:US500-USD-PERP"),
1785            (2, 140_000, 235, "USDE", "hyna:BTC-USD-PERP"),
1786        ];
1787
1788        for (dex, base, token, code, symbol) in cases {
1789            assert_eq!(all_metas[dex].collateral_token, Some(token));
1790
1791            let collateral_currency =
1792                resolve_perp_collateral_currency(&all_metas[dex], Some(&spot_meta)).unwrap();
1793            let defs = parse_perp_instruments_with_collateral(
1794                &all_metas[dex],
1795                base,
1796                collateral_currency.as_str(),
1797            );
1798
1799            assert_eq!(collateral_currency, code);
1800            assert_eq!(defs.len(), 1);
1801            assert_eq!(defs[0].symbol, symbol);
1802            assert_eq!(defs[0].quote, code);
1803            assert_eq!(defs[0].settlement.as_ref().unwrap(), code);
1804
1805            let instrument = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
1806            match instrument {
1807                InstrumentAny::CryptoPerpetual(perp) => {
1808                    assert_eq!(perp.quote_currency, perp.settlement_currency);
1809                    assert_eq!(perp.settlement_currency.code, code);
1810                    assert_eq!(perp.cost_currency().code, code);
1811                    assert!(!perp.is_quanto());
1812                }
1813                other => panic!("Expected CryptoPerpetual, was {other:?}"),
1814            }
1815        }
1816
1817        // USDH is registered with its own name, for both quote and settlement
1818        let defs = parse_perp_instruments_with_collateral(&all_metas[1], 110_000, "USDH");
1819        let InstrumentAny::CryptoPerpetual(perp) =
1820            create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap()
1821        else {
1822            panic!("Expected CryptoPerpetual");
1823        };
1824        assert_eq!(perp.quote_currency.name, "Hyperliquid USD");
1825        assert_eq!(perp.settlement_currency.name, "Hyperliquid USD");
1826    }
1827
1828    #[rstest]
1829    fn test_create_instrument_from_def_perp_defaults_missing_settlement_to_usdc() {
1830        let meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1831        let mut defs = parse_perp_instruments(&meta, 0).unwrap();
1832        defs[0].settlement = None;
1833
1834        let instrument = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
1835
1836        match instrument {
1837            InstrumentAny::CryptoPerpetual(perp) => {
1838                assert_eq!(perp.quote_currency.code, "USDC");
1839                assert_eq!(perp.settlement_currency.code, "USDC");
1840            }
1841            other => panic!("Expected CryptoPerpetual, was {other:?}"),
1842        }
1843    }
1844
1845    #[rstest]
1846    fn test_resolve_perp_collateral_currency_defaults_to_usdc() {
1847        let legacy_meta: PerpMeta = load_test_data("http_meta_perp_sample.json");
1848        let all_metas: Vec<PerpMeta> =
1849            load_test_data("http_all_perp_metas_non_usdc_collateral.json");
1850
1851        let legacy_settlement = resolve_perp_collateral_currency(&legacy_meta, None).unwrap();
1852        let token_zero_settlement = resolve_perp_collateral_currency(&all_metas[0], None).unwrap();
1853
1854        assert_eq!(legacy_settlement, "USDC");
1855        assert_eq!(token_zero_settlement, "USDC");
1856    }
1857
1858    #[rstest]
1859    fn test_resolve_perp_collateral_currency_requires_spot_meta_for_non_usdc() {
1860        let all_metas: Vec<PerpMeta> =
1861            load_test_data("http_all_perp_metas_non_usdc_collateral.json");
1862
1863        let err = resolve_perp_collateral_currency(&all_metas[1], None).unwrap_err();
1864
1865        assert_eq!(
1866            err,
1867            "Spot metadata required to resolve perp collateral token 360",
1868        );
1869    }
1870
1871    #[rstest]
1872    fn test_resolve_perp_collateral_currency_errors_on_missing_token_index() {
1873        let all_metas: Vec<PerpMeta> =
1874            load_test_data("http_all_perp_metas_non_usdc_collateral.json");
1875        let spot_meta = SpotMeta {
1876            tokens: Vec::new(),
1877            universe: Vec::new(),
1878        };
1879
1880        let err = resolve_perp_collateral_currency(&all_metas[1], Some(&spot_meta)).unwrap_err();
1881
1882        assert_eq!(
1883            err,
1884            "Perp collateral token index 360 not found in spot metadata",
1885        );
1886    }
1887
1888    #[rstest]
1889    fn test_deserialize_l2_book_from_real_data() {
1890        let book: HyperliquidL2Book = load_test_data("http_l2_book_btc.json");
1891
1892        // Validate basic structure
1893        assert_eq!(book.coin, "BTC");
1894        assert_eq!(book.levels.len(), 2); // [bids, asks]
1895        assert_eq!(book.levels[0].len(), 5); // 5 bid levels
1896        assert_eq!(book.levels[1].len(), 5); // 5 ask levels
1897
1898        // Verify bids and asks are properly ordered
1899        let bids = &book.levels[0];
1900        let asks = &book.levels[1];
1901
1902        // Bids should be descending (highest first)
1903        for i in 1..bids.len() {
1904            let prev_price = bids[i - 1].px;
1905            let curr_price = bids[i].px;
1906            assert!(prev_price >= curr_price, "Bids should be descending");
1907        }
1908
1909        // Asks should be ascending (lowest first)
1910        for i in 1..asks.len() {
1911            let prev_price = asks[i - 1].px;
1912            let curr_price = asks[i].px;
1913            assert!(prev_price <= curr_price, "Asks should be ascending");
1914        }
1915    }
1916
1917    #[rstest]
1918    fn test_parse_spot_instruments() {
1919        let tokens = vec![
1920            SpotToken {
1921                name: "USDC".to_string(),
1922                sz_decimals: 6,
1923                wei_decimals: 6,
1924                index: 0,
1925                token_id: "0x1".to_string(),
1926                is_canonical: true,
1927                evm_contract: None,
1928                full_name: None,
1929                deployer_trading_fee_share: None,
1930            },
1931            SpotToken {
1932                name: "PURR".to_string(),
1933                sz_decimals: 0,
1934                wei_decimals: 5,
1935                index: 1,
1936                token_id: "0x2".to_string(),
1937                is_canonical: true,
1938                evm_contract: None,
1939                full_name: None,
1940                deployer_trading_fee_share: None,
1941            },
1942        ];
1943
1944        let pairs = vec![
1945            SpotPair {
1946                name: "PURR/USDC".to_string(),
1947                tokens: [1, 0], // PURR base, USDC quote
1948                index: 0,
1949                is_canonical: true,
1950            },
1951            SpotPair {
1952                name: "ALIAS".to_string(),
1953                tokens: [1, 0],
1954                index: 1,
1955                is_canonical: false,
1956            },
1957        ];
1958
1959        let meta = SpotMeta {
1960            tokens,
1961            universe: pairs,
1962        };
1963
1964        let defs = parse_spot_instruments(&meta).unwrap();
1965
1966        assert_eq!(defs.len(), 2);
1967
1968        let purr_usdc = &defs[0];
1969        assert_eq!(purr_usdc.symbol, "PURR-USDC-SPOT");
1970        assert_eq!(purr_usdc.base, "PURR");
1971        assert_eq!(purr_usdc.quote, "USDC");
1972        assert_eq!(purr_usdc.market_type, HyperliquidMarketType::Spot);
1973        assert_eq!(purr_usdc.price_decimals, 8); // 8 - 0 = 8 (PURR sz_decimals = 0)
1974        assert_eq!(purr_usdc.size_decimals, 0);
1975        assert_eq!(purr_usdc.tick_size, dec!(0.00000001));
1976        assert_eq!(purr_usdc.lot_size, dec!(1));
1977        assert_eq!(purr_usdc.max_leverage, None);
1978        assert!(!purr_usdc.only_isolated);
1979        assert!(purr_usdc.active);
1980
1981        let alias = &defs[1];
1982        assert_eq!(alias.symbol, "PURR-USDC-SPOT");
1983        assert_eq!(alias.base, "PURR");
1984        assert!(alias.active);
1985
1986        let instrument = create_instrument_from_def(purr_usdc, UnixNanos::default()).unwrap();
1987
1988        match instrument {
1989            InstrumentAny::CurrencyPair(pair) => {
1990                let min_notional = pair.min_notional.unwrap();
1991                let info = pair.info.unwrap();
1992                assert_eq!(min_notional.currency, Currency::USDC());
1993                assert_eq!(min_notional.as_decimal(), dec!(10));
1994                assert_eq!(info.len(), 5);
1995                assert_eq!(info.get_str("name"), Some("PURR/USDC"));
1996                assert_eq!(info.get("tokens"), Some(&json!([1, 0])));
1997                assert_eq!(info.get_u64("index"), Some(0));
1998                assert_eq!(info.get_bool("isCanonical"), Some(true));
1999                assert_eq!(
2000                    info.get_u64(ASSET_INDEX_INFO_KEY),
2001                    Some(u64::from(purr_usdc.asset_index)),
2002                );
2003            }
2004            other => panic!("Expected CurrencyPair, was {other:?}"),
2005        }
2006
2007        let instrument = create_instrument_from_def(alias, UnixNanos::default()).unwrap();
2008
2009        match instrument {
2010            InstrumentAny::CurrencyPair(pair) => {
2011                let info = pair.info.unwrap();
2012                assert_eq!(info.len(), 5);
2013                assert_eq!(info.get_str("name"), Some("ALIAS"));
2014                assert_eq!(info.get("tokens"), Some(&json!([1, 0])));
2015                assert_eq!(info.get_u64("index"), Some(1));
2016                assert_eq!(info.get_bool("isCanonical"), Some(false));
2017                assert_eq!(
2018                    info.get_u64(ASSET_INDEX_INFO_KEY),
2019                    Some(u64::from(alias.asset_index)),
2020                );
2021            }
2022            other => panic!("Expected CurrencyPair, was {other:?}"),
2023        }
2024    }
2025
2026    #[rstest]
2027    fn test_parse_spot_instruments_sorts_canonical_before_non_canonical() {
2028        // Non-canonical pair uses a lower pair index than the canonical one;
2029        // the sort must still put canonical first so the base-token alias in
2030        // cache_instrument resolves to the canonical instrument.
2031        let tokens = vec![
2032            SpotToken {
2033                name: "USDC".to_string(),
2034                sz_decimals: 6,
2035                wei_decimals: 6,
2036                index: 0,
2037                token_id: "0x1".to_string(),
2038                is_canonical: true,
2039                evm_contract: None,
2040                full_name: None,
2041                deployer_trading_fee_share: None,
2042            },
2043            SpotToken {
2044                name: "HYPE".to_string(),
2045                sz_decimals: 2,
2046                wei_decimals: 8,
2047                index: 150,
2048                token_id: "0x2".to_string(),
2049                is_canonical: true,
2050                evm_contract: None,
2051                full_name: None,
2052                deployer_trading_fee_share: None,
2053            },
2054        ];
2055
2056        let pairs = vec![
2057            SpotPair {
2058                name: "HYPE_OLD".to_string(),
2059                tokens: [150, 0],
2060                index: 3,
2061                is_canonical: false,
2062            },
2063            SpotPair {
2064                name: "HYPE".to_string(),
2065                tokens: [150, 0],
2066                index: 107,
2067                is_canonical: true,
2068            },
2069        ];
2070
2071        let defs = parse_spot_instruments(&SpotMeta {
2072            tokens,
2073            universe: pairs,
2074        })
2075        .unwrap();
2076
2077        assert_eq!(defs.len(), 2);
2078        assert!(defs[0].active);
2079        assert_eq!(defs[0].raw_symbol, "@107");
2080        assert_eq!(defs[0].asset_index, 10000 + 107);
2081        assert!(defs[1].active);
2082        assert_eq!(defs[1].raw_symbol, "@3");
2083        assert_eq!(defs[1].asset_index, 10000 + 3);
2084    }
2085
2086    #[rstest]
2087    fn test_price_decimals_clamping() {
2088        let meta = PerpMeta {
2089            universe: vec![PerpAsset {
2090                name: "HIGHPREC".to_string(),
2091                sz_decimals: 10, // 6 - 10 = -4, should clamp to 0
2092                max_leverage: Some(1),
2093                ..Default::default()
2094            }],
2095            margin_tables: vec![],
2096            collateral_token: None,
2097        };
2098
2099        let defs = parse_perp_instruments(&meta, 0).unwrap();
2100        assert_eq!(defs[0].price_decimals, 0);
2101        assert_eq!(defs[0].tick_size, dec!(1));
2102    }
2103
2104    #[rstest]
2105    fn test_parse_perp_instruments_hip3_dex() {
2106        // HIP-3 dex at index 1: asset_index_base = 100_000 + 1 * 10_000 = 110_000
2107        let meta = PerpMeta {
2108            universe: vec![
2109                PerpAsset {
2110                    name: "xyz:TSLA".to_string(),
2111                    sz_decimals: 3,
2112                    max_leverage: Some(10),
2113                    only_isolated: None,
2114                    is_delisted: None,
2115                    growth_mode: Some("enabled".to_string()),
2116                    margin_mode: Some("strictIsolated".to_string()),
2117                },
2118                PerpAsset {
2119                    name: "xyz:NVDA".to_string(),
2120                    sz_decimals: 3,
2121                    max_leverage: Some(20),
2122                    only_isolated: None,
2123                    is_delisted: None,
2124                    growth_mode: None,
2125                    margin_mode: None,
2126                },
2127            ],
2128            margin_tables: vec![],
2129            collateral_token: None,
2130        };
2131
2132        let defs = parse_perp_instruments(&meta, 110_000).unwrap();
2133        assert_eq!(defs.len(), 2);
2134
2135        // HIP-3 asset: colon in symbol, offset asset index
2136        assert_eq!(defs[0].symbol, "xyz:TSLA-USD-PERP");
2137        assert!(defs[0].symbol.contains(':'));
2138        assert_eq!(defs[0].base, "xyz:TSLA");
2139        assert_eq!(defs[0].asset_index, 110_000);
2140        assert!(defs[0].active);
2141
2142        assert_eq!(defs[1].symbol, "xyz:NVDA-USD-PERP");
2143        assert_eq!(defs[1].asset_index, 110_001);
2144    }
2145
2146    #[rstest]
2147    #[case("BTC", "BTC")]
2148    #[case("kPEPE", "kPEPE")]
2149    #[case("xyz:TSLA", "xyz:TSLA")]
2150    #[case("dex:STREAMABCD****", "dex:STREAMABCDxxxx")]
2151    #[case("ABC?", "ABCx")]
2152    #[case("a*b?c", "axbxc")]
2153    fn test_sanitize_symbol(#[case] input: &str, #[case] expected: &str) {
2154        assert_eq!(sanitize_symbol(input), expected);
2155    }
2156
2157    #[rstest]
2158    fn test_parse_spot_instruments_sanitizes_wildcard_token_names() {
2159        // Hypothetical spot token whose venue name contains `?`. Sanitization
2160        // must apply to the constructed `symbol` while leaving `raw_symbol`
2161        // and `base` carrying the venue-official name for wire I/O.
2162        let tokens = vec![
2163            SpotToken {
2164                name: "USDC".to_string(),
2165                sz_decimals: 6,
2166                wei_decimals: 6,
2167                index: 0,
2168                token_id: "0x1".to_string(),
2169                is_canonical: true,
2170                evm_contract: None,
2171                full_name: None,
2172                deployer_trading_fee_share: None,
2173            },
2174            SpotToken {
2175                name: "ABC?".to_string(),
2176                sz_decimals: 4,
2177                wei_decimals: 4,
2178                index: 1,
2179                token_id: "0x2".to_string(),
2180                is_canonical: true,
2181                evm_contract: None,
2182                full_name: None,
2183                deployer_trading_fee_share: None,
2184            },
2185        ];
2186
2187        let pairs = vec![SpotPair {
2188            name: "ABC?/USDC".to_string(),
2189            tokens: [1, 0],
2190            index: 50,
2191            is_canonical: true,
2192        }];
2193
2194        let meta = SpotMeta {
2195            tokens,
2196            universe: pairs,
2197        };
2198
2199        let defs = parse_spot_instruments(&meta).unwrap();
2200        assert_eq!(defs.len(), 1);
2201        assert_eq!(defs[0].symbol, "ABCx-USDC-SPOT");
2202        assert_eq!(defs[0].base, "ABC?");
2203        assert_eq!(defs[0].quote, "USDC");
2204    }
2205
2206    #[rstest]
2207    fn test_parse_perp_instruments_sanitizes_hip3_wildcards() {
2208        let meta = PerpMeta {
2209            universe: vec![PerpAsset {
2210                name: "dex:STREAMABCD****".to_string(),
2211                sz_decimals: 3,
2212                max_leverage: Some(10),
2213                only_isolated: None,
2214                is_delisted: None,
2215                growth_mode: None,
2216                margin_mode: None,
2217            }],
2218            margin_tables: vec![],
2219            collateral_token: None,
2220        };
2221
2222        let defs = parse_perp_instruments(&meta, 110_000).unwrap();
2223        assert_eq!(defs.len(), 1);
2224        assert_eq!(defs[0].symbol, "dex:STREAMABCDxxxx-USD-PERP");
2225        assert_eq!(defs[0].raw_symbol, "dex:STREAMABCD****");
2226        assert_eq!(defs[0].base, "dex:STREAMABCD****");
2227    }
2228
2229    #[rstest]
2230    fn test_parse_outcome_quote_tokens_from_metadata() {
2231        let meta: OutcomeMeta = load_test_data("http_outcome_meta.json");
2232        assert_eq!(meta.outcomes[0].quote_token.as_deref(), Some("USDC"));
2233        assert_eq!(meta.outcomes[1].quote_token.as_deref(), Some("USDH"));
2234        assert_eq!(meta.outcomes[2].quote_token, None);
2235
2236        let defs = parse_outcome_instruments(&meta).unwrap();
2237        assert_eq!(defs.len(), 6);
2238
2239        for (index, currency) in [Currency::USDC(), get_usdh_currency(), Currency::USDC()]
2240            .into_iter()
2241            .enumerate()
2242        {
2243            for side in 0..=1 {
2244                let def = &defs[2 * index + side];
2245                let instrument = create_instrument_from_def(def, UnixNanos::default()).unwrap();
2246                assert_eq!(def.quote, currency.code);
2247                assert_eq!(instrument.quote_currency(), currency);
2248                assert_eq!(instrument.settlement_currency(), currency);
2249                assert_eq!(
2250                    instrument.id().symbol.as_str(),
2251                    format!(
2252                        "{}-{}-OUTCOME",
2253                        index + 1,
2254                        if side == 0 { "YES" } else { "NO" }
2255                    )
2256                );
2257            }
2258        }
2259    }
2260
2261    #[rstest]
2262    fn test_parse_outcome_instruments_emits_both_sides() {
2263        let meta = OutcomeMeta {
2264            outcomes: vec![OutcomeMarket {
2265                outcome: 1,
2266                name: "BTC daily".to_string(),
2267                description: "BTC settles above strike at 06:00 UTC".to_string(),
2268                quote_token: Some("USDC".to_string()),
2269                side_specs: vec![
2270                    OutcomeSideSpec {
2271                        name: "Yes".to_string(),
2272                    },
2273                    OutcomeSideSpec {
2274                        name: "No".to_string(),
2275                    },
2276                ],
2277            }],
2278            questions: vec![],
2279        };
2280
2281        let defs = parse_outcome_instruments(&meta).unwrap();
2282        assert_eq!(defs.len(), 2);
2283
2284        let yes = &defs[0];
2285        assert_eq!(yes.symbol, "1-YES-OUTCOME");
2286        assert_eq!(yes.raw_symbol, "#10");
2287        assert_eq!(yes.market_type, HyperliquidMarketType::Outcome);
2288        assert_eq!(yes.asset_index, 100_000_010);
2289        assert_eq!(yes.price_decimals, OUTCOME_PRICE_DECIMALS);
2290        assert_eq!(yes.size_decimals, OUTCOME_SIZE_DECIMALS);
2291        assert_eq!(yes.tick_size, dec!(0.00001));
2292        assert_eq!(yes.lot_size, dec!(1));
2293        assert_eq!(yes.quote, "USDC");
2294        assert!(yes.active);
2295
2296        let yes_meta = yes.outcome.as_ref().unwrap();
2297        assert_eq!(yes_meta.outcome_index, 1);
2298        assert_eq!(yes_meta.outcome_side, 0);
2299        assert_eq!(yes_meta.market_name, "BTC daily");
2300        assert_eq!(yes_meta.side_name.unwrap(), "Yes");
2301        assert_eq!(
2302            yes_meta.description.unwrap(),
2303            "BTC settles above strike at 06:00 UTC"
2304        );
2305
2306        let no = &defs[1];
2307        assert_eq!(no.symbol, "1-NO-OUTCOME");
2308        assert_eq!(no.raw_symbol, "#11");
2309        assert_eq!(no.asset_index, 100_000_011);
2310        let no_meta = no.outcome.as_ref().unwrap();
2311        assert_eq!(no_meta.outcome_side, 1);
2312        assert_eq!(no_meta.side_name.unwrap(), "No");
2313    }
2314
2315    #[rstest]
2316    fn test_parse_outcome_instruments_handles_missing_side_specs() {
2317        let meta = OutcomeMeta {
2318            outcomes: vec![OutcomeMarket {
2319                outcome: 5,
2320                name: "Recurring".to_string(),
2321                description: String::new(),
2322                quote_token: Some("USDC".to_string()),
2323                side_specs: vec![],
2324            }],
2325            questions: vec![],
2326        };
2327
2328        let defs = parse_outcome_instruments(&meta).unwrap();
2329        assert_eq!(defs.len(), 2);
2330
2331        // Even when the venue omits `sideSpecs`, the parser falls back to the
2332        // canonical HIP-4 labels ("Yes" / "No") so downstream `BinaryOption`
2333        // instruments always carry a meaningful side label.
2334        assert_eq!(defs[0].outcome.as_ref().unwrap().side_name.unwrap(), "Yes");
2335        assert_eq!(defs[1].outcome.as_ref().unwrap().side_name.unwrap(), "No");
2336
2337        for def in &defs {
2338            assert!(def.outcome.as_ref().unwrap().description.is_none());
2339        }
2340
2341        assert_eq!(defs[0].asset_index, 100_000_050);
2342        assert_eq!(defs[1].asset_index, 100_000_051);
2343    }
2344
2345    #[rstest]
2346    #[case::yes(0, "20-YES-OUTCOME", "#200", "+200", 100_000_200, "Yes")]
2347    #[case::no(1, "20-NO-OUTCOME", "#201", "+201", 100_000_201, "No")]
2348    fn test_parse_unlisted_outcome_instrument(
2349        #[case] side: u8,
2350        #[case] symbol: &str,
2351        #[case] raw_symbol: &str,
2352        #[case] base: &str,
2353        #[case] asset_index: u32,
2354        #[case] side_name: &str,
2355    ) {
2356        let listed_meta = OutcomeMeta {
2357            outcomes: vec![OutcomeMarket {
2358                outcome: 20,
2359                name: "Recurring".to_string(),
2360                description: "class:priceBinary|underlying:BTC|expiry:20260511-0600".to_string(),
2361                quote_token: Some("USDC".to_string()),
2362                side_specs: vec![],
2363            }],
2364            questions: vec![],
2365        };
2366
2367        let listed = parse_outcome_instruments(&listed_meta).unwrap();
2368
2369        let def = parse_unlisted_outcome_instrument(HyperliquidAssetId::outcome(20, side)).unwrap();
2370
2371        let listed = &listed[usize::from(side)];
2372        let outcome = def.outcome.as_ref().unwrap();
2373        assert_eq!(def.symbol, symbol);
2374        assert_eq!(def.raw_symbol, raw_symbol);
2375        assert_eq!(def.base, base);
2376        assert_eq!(def.quote, "USDC");
2377        let instrument = create_instrument_from_def(&def, UnixNanos::default()).unwrap();
2378        assert_eq!(instrument.quote_currency(), Currency::USDC());
2379        assert_eq!(instrument.settlement_currency(), Currency::USDC());
2380        assert_eq!(def.market_type, HyperliquidMarketType::Outcome);
2381        assert_eq!(def.asset_index, asset_index);
2382        assert_eq!(def.price_decimals, OUTCOME_PRICE_DECIMALS);
2383        assert_eq!(def.size_decimals, OUTCOME_SIZE_DECIMALS);
2384        assert_eq!(def.tick_size, dec!(0.00001));
2385        assert_eq!(def.lot_size, dec!(1));
2386        assert!(def.active);
2387        assert_eq!(outcome.outcome_index, 20);
2388        assert_eq!(outcome.outcome_side, side);
2389        assert_eq!(outcome.market_name, "");
2390        assert_eq!(outcome.side_name.unwrap(), side_name);
2391        assert_eq!(outcome.description, None);
2392        assert_eq!(outcome.expiration_ns, UnixNanos::default());
2393        assert_eq!(
2394            (def.symbol, def.raw_symbol, def.asset_index),
2395            (listed.symbol, listed.raw_symbol, listed.asset_index),
2396            "an unlisted side must map to the same instrument as its listed form",
2397        );
2398    }
2399
2400    #[rstest]
2401    fn test_parse_unlisted_outcome_instrument_rejects_non_outcome_asset() {
2402        let result = parse_unlisted_outcome_instrument(HyperliquidAssetId::spot(107));
2403
2404        assert_eq!(
2405            result.unwrap_err(),
2406            "Asset 10107 is not a HIP-4 outcome".to_string()
2407        );
2408    }
2409
2410    #[rstest]
2411    fn test_get_usdh_currency_registers_with_explicit_precision() {
2412        let currency = get_usdh_currency();
2413        assert_eq!(currency.code, "USDH");
2414        assert_eq!(currency.precision, 8);
2415        assert_eq!(currency.currency_type, CurrencyType::Crypto);
2416
2417        // Repeated calls return the same registered currency
2418        let again = get_usdh_currency();
2419        assert_eq!(again, currency);
2420        assert!(Currency::try_from_str("USDH").is_some());
2421    }
2422
2423    #[rstest]
2424    fn test_create_instrument_from_def_outcome_emits_binary_option() {
2425        let meta = OutcomeMeta {
2426            outcomes: vec![OutcomeMarket {
2427                outcome: 2,
2428                name: "Recurring BTC".to_string(),
2429                description: "Daily settlement".to_string(),
2430                quote_token: Some("USDC".to_string()),
2431                side_specs: vec![
2432                    OutcomeSideSpec {
2433                        name: "Yes".to_string(),
2434                    },
2435                    OutcomeSideSpec {
2436                        name: "No".to_string(),
2437                    },
2438                ],
2439            }],
2440            questions: vec![],
2441        };
2442
2443        let defs = parse_outcome_instruments(&meta).unwrap();
2444        let instrument = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
2445
2446        match instrument {
2447            InstrumentAny::BinaryOption(bo) => {
2448                assert_eq!(bo.id.symbol.as_str(), "2-YES-OUTCOME");
2449                assert_eq!(bo.raw_symbol.as_str(), "#20");
2450                assert_eq!(bo.asset_class, AssetClass::Alternative);
2451                assert_eq!(bo.currency.code, "USDC");
2452                assert_eq!(bo.price_precision, OUTCOME_PRICE_DECIMALS as u8);
2453                assert_eq!(bo.size_precision, OUTCOME_SIZE_DECIMALS as u8);
2454                assert_eq!(bo.outcome.unwrap(), "Yes");
2455                assert_eq!(bo.description.unwrap(), "Daily settlement");
2456
2457                let info = bo.info.expect("info should be populated for outcomes");
2458                assert_eq!(info.get_u64("outcome_index"), Some(2));
2459                assert_eq!(info.get_u64("outcome_side"), Some(0));
2460                assert_eq!(info.get_u64("encoding"), Some(20));
2461                assert_eq!(info.get_u64("asset_id"), Some(100_000_020));
2462                assert_eq!(info.get_str("side_name"), Some("Yes"));
2463                assert_eq!(info.get_str("market_name"), Some("Recurring BTC"));
2464            }
2465            other => panic!("Expected BinaryOption, was {other:?}"),
2466        }
2467    }
2468
2469    #[rstest]
2470    fn test_create_instrument_from_def_outcome_info_carries_parsed_description() {
2471        let meta = OutcomeMeta {
2472            outcomes: vec![OutcomeMarket {
2473                outcome: 5,
2474                name: "Recurring BTC".to_string(),
2475                description:
2476                    "class:priceBinary|underlying:BTC|expiry:20260508-0600|targetPrice:81041|period:1d"
2477                        .to_string(),
2478                quote_token: Some("USDC".to_string()),
2479                side_specs: vec![
2480                    OutcomeSideSpec {
2481                        name: "Yes".to_string(),
2482                    },
2483                    OutcomeSideSpec {
2484                        name: "No".to_string(),
2485                    },
2486                ],
2487            }],
2488            questions: vec![],
2489        };
2490
2491        let defs = parse_outcome_instruments(&meta).unwrap();
2492        let yes = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
2493
2494        match yes {
2495            InstrumentAny::BinaryOption(bo) => {
2496                let info = bo.info.expect("info should be populated for outcomes");
2497                assert_eq!(info.get_str("class"), Some("priceBinary"));
2498                assert_eq!(info.get_str("underlying"), Some("BTC"));
2499                assert_eq!(info.get_str("expiry"), Some("20260508-0600"));
2500                assert_eq!(info.get_str("target_price"), Some("81041"));
2501                assert_eq!(info.get_str("period"), Some("1d"));
2502                assert!(info.get("question").is_none());
2503            }
2504            other => panic!("Expected BinaryOption, was {other:?}"),
2505        }
2506    }
2507
2508    #[rstest]
2509    fn test_create_instrument_from_def_outcome_info_merges_parent_question() {
2510        let meta = OutcomeMeta {
2511            outcomes: vec![
2512                OutcomeMarket {
2513                    outcome: 6,
2514                    name: "Recurring Fallback".to_string(),
2515                    description: "other".to_string(),
2516                    quote_token: Some("USDC".to_string()),
2517                    side_specs: vec![],
2518                },
2519                OutcomeMarket {
2520                    outcome: 7,
2521                    name: "Recurring Named Outcome".to_string(),
2522                    description: "index:0".to_string(),
2523                    quote_token: Some("USDC".to_string()),
2524                    side_specs: vec![],
2525                },
2526            ],
2527            questions: vec![OutcomeQuestion {
2528                question: 0,
2529                name: "Recurring".to_string(),
2530                description:
2531                    "class:priceBucket|underlying:BTC|expiry:20260508-0600|priceThresholds:79303,82540|period:1d"
2532                        .to_string(),
2533                fallback_outcome: Some(6),
2534                named_outcomes: vec![7, 8, 9],
2535                settled_named_outcomes: vec![],
2536            }],
2537        };
2538
2539        let defs = parse_outcome_instruments(&meta).unwrap();
2540
2541        // Named outcome 7, Yes side (defs[2]).
2542        let named = create_instrument_from_def(&defs[2], UnixNanos::default()).unwrap();
2543        match named {
2544            InstrumentAny::BinaryOption(bo) => {
2545                assert_eq!(bo.id.symbol.as_str(), "7-YES-OUTCOME");
2546                let info = bo.info.expect("info should be populated for outcomes");
2547                assert_eq!(info.get_u64("named_index"), Some(0));
2548                assert_eq!(info.get_u64("question"), Some(0));
2549                assert_eq!(info.get_str("question_name"), Some("Recurring"));
2550                assert_eq!(info.get_str("question_class"), Some("priceBucket"));
2551                assert_eq!(info.get_str("question_underlying"), Some("BTC"));
2552                assert_eq!(
2553                    info.get_str("question_price_thresholds"),
2554                    Some("79303,82540"),
2555                );
2556                assert_eq!(info.get_str("question_expiry"), Some("20260508-0600"));
2557            }
2558            other => panic!("Expected BinaryOption, was {other:?}"),
2559        }
2560
2561        // Fallback outcome 6, Yes side (defs[0]).
2562        let fallback = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
2563        match fallback {
2564            InstrumentAny::BinaryOption(bo) => {
2565                assert_eq!(bo.id.symbol.as_str(), "6-YES-OUTCOME");
2566                let info = bo.info.expect("info should be populated for outcomes");
2567                assert_eq!(info.get_bool("is_fallback"), Some(true));
2568                assert_eq!(info.get_u64("question"), Some(0));
2569                assert_eq!(info.get_str("question_class"), Some("priceBucket"));
2570            }
2571            other => panic!("Expected BinaryOption, was {other:?}"),
2572        }
2573    }
2574
2575    #[rstest]
2576    #[case::usdc_side_token("USDC", "+420", Decimal::ZERO)]
2577    #[case::usdh_side_token("USDH", "+420", Decimal::ZERO)]
2578    #[case::usdc_fee("USDC", "USDC", dec!(0.0345))]
2579    fn test_parse_fill_report_outcome_round_trip(
2580        #[case] quote_token: &str,
2581        #[case] fee_token: &str,
2582        #[case] fee: Decimal,
2583    ) {
2584        let meta = OutcomeMeta {
2585            outcomes: vec![OutcomeMarket {
2586                outcome: 42,
2587                name: "BTC daily".to_string(),
2588                description: "BTC settles above strike at 06:00 UTC".to_string(),
2589                quote_token: Some(quote_token.to_string()),
2590                side_specs: vec![
2591                    OutcomeSideSpec {
2592                        name: "Yes".to_string(),
2593                    },
2594                    OutcomeSideSpec {
2595                        name: "No".to_string(),
2596                    },
2597                ],
2598            }],
2599            questions: vec![],
2600        };
2601
2602        let defs = parse_outcome_instruments(&meta).unwrap();
2603        let yes = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
2604        assert_eq!(yes.id().symbol.as_str(), "42-YES-OUTCOME");
2605
2606        let fill = HyperliquidFill {
2607            coin: Ustr::from("#420"),
2608            px: dec!(0.5500),
2609            sz: dec!(1000.00),
2610            side: HyperliquidSide::Buy,
2611            time: 1_704_470_400_000,
2612            start_position: dec!(0.00),
2613            dir: HyperliquidFillDirection::OpenLong,
2614            closed_pnl: dec!(0.0),
2615            hash: "0xfeed".to_string(),
2616            oid: 99_001,
2617            crossed: true,
2618            fee,
2619            tid: 77_001,
2620            fee_token: Ustr::from(fee_token),
2621            builder_fee: Some(dec!(0.0001)),
2622            cloid: None,
2623        };
2624
2625        let account_id = AccountId::from("HYPERLIQUID-001");
2626        let report = parse_fill_report(&fill, &yes, account_id, UnixNanos::default()).unwrap();
2627
2628        // Zero-fee outcome fills resolve commission to the instrument's quote
2629        // currency rather than the side token, so downstream OrderFilled
2630        // events and persistence carry a registered currency.
2631        assert_eq!(
2632            report.commission,
2633            Money::from_decimal(fee, yes.quote_currency()).unwrap()
2634        );
2635        assert_eq!(report.order_side, OrderSide::Buy);
2636        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
2637        assert_eq!(report.last_qty.as_decimal(), dec!(1000));
2638        assert_eq!(report.last_px.as_decimal(), dec!(0.55));
2639    }
2640
2641    #[rstest]
2642    fn test_parse_fill_report_outcome_keeps_venue_price() {
2643        // Venue outcome prices use five decimals, which must not be rounded away
2644        let meta = OutcomeMeta {
2645            outcomes: vec![OutcomeMarket {
2646                outcome: 1473,
2647                name: "Recurring".to_string(),
2648                description: String::new(),
2649                quote_token: Some("USDC".to_string()),
2650                side_specs: vec![],
2651            }],
2652            questions: vec![],
2653        };
2654
2655        let defs = parse_outcome_instruments(&meta).unwrap();
2656        let yes = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
2657
2658        let fill = HyperliquidFill {
2659            coin: Ustr::from("#14730"),
2660            px: dec!(0.61271),
2661            sz: dec!(112.0),
2662            side: HyperliquidSide::Sell,
2663            time: 1_791_262_678_530,
2664            start_position: dec!(112.0),
2665            dir: HyperliquidFillDirection::Sell,
2666            closed_pnl: dec!(-0.0056),
2667            hash: "0xbeef".to_string(),
2668            oid: 99_002,
2669            crossed: true,
2670            fee: dec!(0.09223001),
2671            tid: 77_002,
2672            fee_token: Ustr::from("USDC"),
2673            builder_fee: None,
2674            cloid: None,
2675        };
2676
2677        let account_id = AccountId::from("HYPERLIQUID-001");
2678        let report = parse_fill_report(&fill, &yes, account_id, UnixNanos::default()).unwrap();
2679
2680        assert_eq!(report.last_px, Price::from("0.61271"));
2681        assert_eq!(report.last_qty, Quantity::from("112"));
2682        assert_eq!(report.last_qty.precision, 0);
2683    }
2684
2685    #[rstest]
2686    fn test_deserialize_user_fills_with_dust_conversion() {
2687        // #4325 regression: a userFills batch must decode whole, not fail on one
2688        // unmodeled direction. Fixture is real mainnet wire data.
2689        let fills: Vec<HyperliquidFill> = load_test_data("http_user_fills_dust_conversion.json");
2690
2691        let dirs: Vec<HyperliquidFillDirection> = fills.iter().map(|f| f.dir).collect();
2692
2693        assert_eq!(
2694            dirs,
2695            vec![
2696                HyperliquidFillDirection::OpenLong,
2697                HyperliquidFillDirection::CloseShort,
2698                HyperliquidFillDirection::Buy,
2699                HyperliquidFillDirection::SpotDustConversion,
2700                HyperliquidFillDirection::NetChildVaults,
2701            ],
2702        );
2703    }
2704
2705    #[rstest]
2706    fn test_resolve_fee_currency_outcome_token_returns_quote_even_when_registered() {
2707        let meta = OutcomeMeta {
2708            outcomes: vec![OutcomeMarket {
2709                outcome: 88,
2710                name: "Edge".to_string(),
2711                description: String::new(),
2712                quote_token: Some("USDC".to_string()),
2713                side_specs: vec![],
2714            }],
2715            questions: vec![],
2716        };
2717        let defs = parse_outcome_instruments(&meta).unwrap();
2718        let yes = create_instrument_from_def(&defs[0], UnixNanos::default()).unwrap();
2719
2720        // Simulate another adapter path (e.g. spot balance parsing) having already
2721        // registered the side token in the global currency registry.
2722        let _ = get_currency("+880");
2723        assert!(Currency::try_from_str("+880").is_some());
2724
2725        let currency = resolve_fee_currency("+880", Decimal::ZERO, &yes)
2726            .expect("zero-fee outcome side token must resolve to quote currency");
2727        assert_eq!(currency.code, "USDC");
2728
2729        let err = resolve_fee_currency("+880", dec!(0.01), &yes).unwrap_err();
2730        let err_msg = err.to_string();
2731        assert!(err_msg.contains("Outcome side token '+880'"));
2732        assert!(err_msg.contains("non-zero fee"));
2733    }
2734
2735    #[rstest]
2736    #[case("+50", true)]
2737    #[case("+0", true)]
2738    #[case("+880", true)]
2739    #[case("", false)]
2740    #[case("+", false)]
2741    #[case("+abc", false)]
2742    #[case("+50a", false)]
2743    #[case("#50", false)]
2744    #[case("USDC", false)]
2745    #[case("-50", false)]
2746    fn test_is_outcome_side_token(#[case] input: &str, #[case] expected: bool) {
2747        assert_eq!(is_outcome_side_token(input), expected);
2748    }
2749
2750    #[rstest]
2751    fn test_resolve_fee_currency_falls_back_to_quote_when_unregistered_and_zero_fee() {
2752        let meta = OutcomeMeta {
2753            outcomes: vec![OutcomeMarket {
2754                outcome: 77,
2755                name: "Edge".to_string(),
2756                description: String::new(),
2757                quote_token: Some("USDC".to_string()),
2758                side_specs: vec![],
2759            }],
2760            questions: vec![],
2761        };
2762
2763        let defs = parse_outcome_instruments(&meta).unwrap();
2764        let no = create_instrument_from_def(&defs[1], UnixNanos::default()).unwrap();
2765
2766        // Use a token that the venue would not normally emit; resolve_fee_currency must still
2767        // return the instrument's quote currency on a zero-fee fill.
2768        let currency = resolve_fee_currency("+UNREGISTERED-TOKEN", Decimal::ZERO, &no)
2769            .expect("zero-fee fallback should succeed");
2770        assert_eq!(currency.code, "USDC");
2771
2772        let err = resolve_fee_currency("+UNREGISTERED-TOKEN", dec!(0.01), &no).unwrap_err();
2773        assert!(err.to_string().contains("non-zero fee"));
2774    }
2775
2776    #[rstest]
2777    fn test_parse_outcome_expiry_ns_round_trip() {
2778        // 2026-05-08 06:00:00 UTC == 1778652000 seconds since epoch
2779        let ns = parse_outcome_expiry_ns("20260508-0600").unwrap();
2780        assert_eq!(ns.as_u64(), 1_778_220_000_000_000_000);
2781    }
2782
2783    #[rstest]
2784    #[case("")]
2785    #[case("20260508")]
2786    #[case("20260508-")]
2787    #[case("20260508-0600 ")]
2788    #[case("2026-05-08-06-00")]
2789    #[case("20261308-0600")]
2790    fn test_parse_outcome_expiry_ns_rejects_bad_input(#[case] input: &str) {
2791        assert!(parse_outcome_expiry_ns(input).is_none());
2792    }
2793
2794    #[rstest]
2795    fn test_parse_outcome_instruments_pulls_expiry_from_price_binary() {
2796        let meta = OutcomeMeta {
2797            outcomes: vec![OutcomeMarket {
2798                outcome: 5,
2799                name: "Recurring".to_string(),
2800                description:
2801                    "class:priceBinary|underlying:BTC|expiry:20260508-0600|targetPrice:81041|period:1d"
2802                        .to_string(),
2803                quote_token: Some("USDC".to_string()),
2804                side_specs: vec![
2805                    OutcomeSideSpec {
2806                        name: "Yes".to_string(),
2807                    },
2808                    OutcomeSideSpec {
2809                        name: "No".to_string(),
2810                    },
2811                ],
2812            }],
2813            questions: vec![],
2814        };
2815
2816        let defs = parse_outcome_instruments(&meta).unwrap();
2817        let yes_meta = defs[0].outcome.as_ref().unwrap();
2818        assert_eq!(yes_meta.expiration_ns.as_u64(), 1_778_220_000_000_000_000);
2819    }
2820
2821    #[rstest]
2822    fn test_parse_outcome_instruments_inherits_expiry_from_parent_question() {
2823        // outcome=7 has `index:0` description and is referenced by question 0's
2824        // `named_outcomes`. outcome=6 has `other` description and is the
2825        // `fallback_outcome`. Both should pick up the question's expiry.
2826        let meta = OutcomeMeta {
2827            outcomes: vec![
2828                OutcomeMarket {
2829                    outcome: 6,
2830                    name: "Recurring Fallback".to_string(),
2831                    description: "other".to_string(),
2832                    quote_token: Some("USDC".to_string()),
2833                    side_specs: vec![],
2834                },
2835                OutcomeMarket {
2836                    outcome: 7,
2837                    name: "Recurring Named Outcome".to_string(),
2838                    description: "index:0".to_string(),
2839                    quote_token: Some("USDC".to_string()),
2840                    side_specs: vec![],
2841                },
2842            ],
2843            questions: vec![OutcomeQuestion {
2844                question: 0,
2845                name: "Recurring".to_string(),
2846                description:
2847                    "class:priceBucket|underlying:BTC|expiry:20260508-0600|priceThresholds:79303,82540|period:1d"
2848                        .to_string(),
2849                fallback_outcome: Some(6),
2850                named_outcomes: vec![7, 8, 9],
2851                settled_named_outcomes: vec![],
2852            }],
2853        };
2854
2855        let defs = parse_outcome_instruments(&meta).unwrap();
2856        let expected_ns: u64 = 1_778_220_000_000_000_000;
2857
2858        for def in &defs {
2859            let outcome = def.outcome.as_ref().unwrap();
2860            assert_eq!(
2861                outcome.expiration_ns.as_u64(),
2862                expected_ns,
2863                "outcome {} side {} should inherit expiry",
2864                outcome.outcome_index,
2865                outcome.outcome_side,
2866            );
2867        }
2868    }
2869
2870    #[rstest]
2871    fn test_derive_outcome_settlements_returns_empty_when_no_questions() {
2872        let meta = OutcomeMeta {
2873            outcomes: vec![],
2874            questions: vec![],
2875        };
2876        assert!(derive_outcome_settlements(&meta).is_empty());
2877    }
2878
2879    #[rstest]
2880    fn test_derive_outcome_settlements_returns_empty_when_no_questions_settled() {
2881        let meta = OutcomeMeta {
2882            outcomes: vec![],
2883            questions: vec![OutcomeQuestion {
2884                question: 0,
2885                name: "Recurring".to_string(),
2886                description: "class:priceBucket|expiry:20260508-0600".to_string(),
2887                fallback_outcome: Some(6),
2888                named_outcomes: vec![7, 8, 9],
2889                settled_named_outcomes: vec![],
2890            }],
2891        };
2892
2893        assert!(derive_outcome_settlements(&meta).is_empty());
2894    }
2895
2896    #[rstest]
2897    fn test_derive_outcome_settlements_marks_winners_losers_and_fallback() {
2898        let meta = OutcomeMeta {
2899            outcomes: vec![],
2900            questions: vec![OutcomeQuestion {
2901                question: 0,
2902                name: "Recurring".to_string(),
2903                description: "class:priceBucket|expiry:20260508-0600".to_string(),
2904                fallback_outcome: Some(6),
2905                named_outcomes: vec![7, 8, 9],
2906                settled_named_outcomes: vec![8],
2907            }],
2908        };
2909
2910        let settlements = derive_outcome_settlements(&meta);
2911        let lookup: ahash::AHashMap<(u32, u8), u8> = settlements
2912            .into_iter()
2913            .map(|s| ((s.outcome_index, s.outcome_side), s.final_value))
2914            .collect();
2915
2916        // Winning named outcome 8: Yes -> 1, No -> 0
2917        assert_eq!(lookup[&(8, 0)], 1);
2918        assert_eq!(lookup[&(8, 1)], 0);
2919
2920        // Losing named outcomes 7, 9 and fallback 6: Yes -> 0, No -> 1
2921        for losing in [7, 9, 6] {
2922            assert_eq!(lookup[&(losing, 0)], 0, "outcome {losing} Yes side");
2923            assert_eq!(lookup[&(losing, 1)], 1, "outcome {losing} No side");
2924        }
2925
2926        assert_eq!(lookup.len(), 8);
2927    }
2928
2929    #[rstest]
2930    fn test_parse_outcome_meta_question_settlement_round_trip() {
2931        let json = r#"{
2932            "outcomes": [{"outcome": 5, "name": "Recurring", "description": "class:priceBinary|expiry:20260508-0600", "sideSpecs": []}],
2933            "questions": [{
2934                "question": 0,
2935                "name": "Recurring",
2936                "description": "class:priceBucket|expiry:20260508-0600",
2937                "fallbackOutcome": 6,
2938                "namedOutcomes": [7, 8, 9],
2939                "settledNamedOutcomes": [8]
2940            }]
2941        }"#;
2942
2943        let meta: OutcomeMeta = serde_json::from_str(json).unwrap();
2944        assert_eq!(meta.questions.len(), 1);
2945        let q = &meta.questions[0];
2946        assert_eq!(q.fallback_outcome, Some(6));
2947        assert_eq!(q.named_outcomes, vec![7, 8, 9]);
2948        assert_eq!(q.settled_named_outcomes, vec![8]);
2949
2950        assert!(meta.parent_question(7).is_some());
2951        assert!(meta.parent_question(6).is_some());
2952        assert!(meta.parent_question(99).is_none());
2953    }
2954
2955    fn frontend_open_order_row(order_type: &str, is_trigger: bool, trigger_px: &str) -> Value {
2956        // Shape of a `frontendOpenOrders` row: no `tpsl` / `isMarket`, the trigger kind is
2957        // only carried by the `orderType` label
2958        json!({
2959            "coin": "BTC",
2960            "side": "A",
2961            "limitPx": "49000.0",
2962            "sz": "0.01",
2963            "oid": 42,
2964            "timestamp": 1_754_000_000_000u64,
2965            "triggerCondition": if is_trigger { "Price below 50000" } else { "N/A" },
2966            "isTrigger": is_trigger,
2967            "triggerPx": trigger_px,
2968            "children": [],
2969            "isPositionTpsl": false,
2970            "reduceOnly": true,
2971            "orderType": order_type,
2972            "origSz": "0.01",
2973            "tif": if is_trigger { Value::Null } else { json!("Gtc") },
2974            "cloid": null
2975        })
2976    }
2977
2978    fn create_btc_perp_instrument() -> InstrumentAny {
2979        let instrument_id = InstrumentId::new(Symbol::new("BTC-PERP"), *HYPERLIQUID_VENUE);
2980
2981        InstrumentAny::CryptoPerpetual(
2982            CryptoPerpetual::builder()
2983                .instrument_id(instrument_id)
2984                .raw_symbol(Symbol::new("BTC-PERP"))
2985                .base_currency(Currency::from("BTC"))
2986                .quote_currency(Currency::from("USDC"))
2987                .settlement_currency(Currency::from("USDC"))
2988                .is_inverse(false)
2989                .price_precision(1)
2990                .size_precision(5)
2991                .price_increment(Price::from("0.1"))
2992                .size_increment(Quantity::from("0.00001"))
2993                .ts_event(UnixNanos::default())
2994                .ts_init(UnixNanos::default())
2995                .build()
2996                .unwrap(),
2997        )
2998    }
2999
3000    #[rstest]
3001    #[case("Stop Market", OrderType::StopMarket)]
3002    #[case("Stop Limit", OrderType::StopLimit)]
3003    #[case("Take Profit Market", OrderType::MarketIfTouched)]
3004    #[case("Take Profit Limit", OrderType::LimitIfTouched)]
3005    fn test_parse_order_status_report_from_frontend_open_order_trigger_label(
3006        #[case] label: &str,
3007        #[case] expected: OrderType,
3008    ) {
3009        let instrument = create_btc_perp_instrument();
3010        let order: WsBasicOrderData =
3011            serde_json::from_value(frontend_open_order_row(label, true, "50000.0")).unwrap();
3012
3013        let report = parse_order_status_report_from_basic(
3014            &order,
3015            &HyperliquidOrderStatusEnum::Open,
3016            &instrument,
3017            AccountId::new("HYPERLIQUID-001"),
3018            UnixNanos::default(),
3019        )
3020        .unwrap();
3021
3022        assert_eq!(report.order_type, expected);
3023        assert_eq!(report.trigger_price, Some(Price::from("50000.0")));
3024        assert_eq!(report.trigger_type, Some(TriggerType::Default));
3025        assert_eq!(report.price, Some(Price::from("49000.0")));
3026        assert!(report.reduce_only);
3027    }
3028
3029    #[rstest]
3030    fn test_parse_order_status_report_from_frontend_open_order_plain_limit() {
3031        let instrument = create_btc_perp_instrument();
3032        let order: WsBasicOrderData =
3033            serde_json::from_value(frontend_open_order_row("Limit", false, "0.0")).unwrap();
3034
3035        let report = parse_order_status_report_from_basic(
3036            &order,
3037            &HyperliquidOrderStatusEnum::Open,
3038            &instrument,
3039            AccountId::new("HYPERLIQUID-001"),
3040            UnixNanos::default(),
3041        )
3042        .unwrap();
3043
3044        assert_eq!(report.order_type, OrderType::Limit);
3045        assert!(report.trigger_price.is_none());
3046        assert!(report.trigger_type.is_none());
3047    }
3048
3049    #[rstest]
3050    #[case::empty("")]
3051    #[case::whitespace("   ")]
3052    #[case::non_ascii("0x\u{e9}")]
3053    fn test_parse_order_status_report_rejects_invalid_client_order_id(#[case] cloid: &str) {
3054        let instrument = create_btc_perp_instrument();
3055        let mut order: WsBasicOrderData =
3056            serde_json::from_value(frontend_open_order_row("Limit", false, "0.0")).unwrap();
3057        order.cloid = Some(cloid.to_string());
3058
3059        let result = parse_order_status_report_from_basic(
3060            &order,
3061            &HyperliquidOrderStatusEnum::Open,
3062            &instrument,
3063            AccountId::from("HYPERLIQUID-REST"),
3064            UnixNanos::default(),
3065        );
3066
3067        assert_eq!(
3068            result.unwrap_err().to_string(),
3069            "invalid order client order ID"
3070        );
3071    }
3072
3073    #[rstest]
3074    #[case("Ioc", "0.0005", OrderStatus::Canceled, "0.0145")]
3075    #[case("Gtc", "0.0005", OrderStatus::Canceled, "0.0145")]
3076    #[case("Ioc", "0.0", OrderStatus::Filled, "0.015")]
3077    #[case("Ioc", "0.000001", OrderStatus::Filled, "0.015")] // Below size precision
3078    fn test_parse_order_status_report_from_basic_filled_with_remainder(
3079        #[case] tif: &str,
3080        #[case] sz: &str,
3081        #[case] expected_status: OrderStatus,
3082        #[case] expected_filled: &str,
3083    ) {
3084        // The venue marks an IOC order `filled` even when its remainder was canceled; `sz`
3085        // carries that unfilled remainder
3086        let instrument = create_btc_perp_instrument();
3087        let mut row = frontend_open_order_row("Limit", false, "0.0");
3088        row["origSz"] = json!("0.015");
3089        row["sz"] = json!(sz);
3090        row["tif"] = json!(tif);
3091        let order: WsBasicOrderData = serde_json::from_value(row).unwrap();
3092
3093        let report = parse_order_status_report_from_basic(
3094            &order,
3095            &HyperliquidOrderStatusEnum::Filled,
3096            &instrument,
3097            AccountId::new("HYPERLIQUID-001"),
3098            UnixNanos::default(),
3099        )
3100        .unwrap();
3101
3102        assert_eq!(report.order_status, expected_status);
3103        assert_eq!(report.quantity, Quantity::from("0.015"));
3104        assert_eq!(report.filled_qty, Quantity::from(expected_filled));
3105        assert!(report.price.is_none(), "venue-filled rows carry no price");
3106        assert_eq!(
3107            report.cancel_reason.is_some(),
3108            expected_status == OrderStatus::Canceled
3109        );
3110    }
3111}