Skip to main content

nautilus_architect_ax/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
16//! Parsing functions to convert Ax HTTP responses to Nautilus domain types.
17
18use std::collections::HashMap;
19
20use anyhow::Context;
21use indexmap::IndexMap;
22use jiff::tz::Offset;
23use nautilus_core::{Params, UUID4, datetime::datetime_to_unix_nanos, nanos::UnixNanos};
24use nautilus_model::{
25    data::{Bar, BarSpecification, BarType, FundingRateUpdate, TradeTick},
26    enums::{
27        AccountType, AggregationSource, AggressorSide, AssetClass, AvgPxReconciliation,
28        BarAggregation, CurrencyType, LiquiditySide, OrderSide, OrderStatus, OrderType,
29        PositionSide, PriceType, TimeInForce,
30    },
31    events::AccountState,
32    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, TradeId, VenueOrderId},
33    instruments::{FuturesContract, Instrument, PerpetualContract, any::InstrumentAny},
34    reports::{FillReport, OrderStatusReport, PositionStatusReport},
35    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
36};
37use rust_decimal::Decimal;
38use serde_json::json;
39use ustr::Ustr;
40
41use super::models::{
42    AxBalancesResponse, AxCandle, AxFill, AxFundingRate, AxInstrument, AxOpenOrder, AxOrderDetail,
43    AxOrderRejectReason, AxPosition, AxRestTrade, AxRiskSnapshot,
44};
45use crate::common::{
46    consts::{AX_FILL_ORDER_PREFIX, AX_VENUE},
47    enums::{AxCandleWidth, AxOrderSide, AxOrderStatus, AxTimeInForce},
48    parse::{
49        ax_timestamp_ns_to_unix_nanos, ax_timestamp_s_to_unix_nanos,
50        ax_timestamp_stn_to_unix_nanos, cid_to_client_order_id, create_architect_trade_id,
51    },
52};
53
54fn decimal_to_price(value: Decimal, field_name: &str) -> anyhow::Result<Price> {
55    Price::from_decimal(value)
56        .with_context(|| format!("Failed to convert {field_name} Decimal to Price"))
57}
58
59fn decimal_to_quantity(value: Decimal, field_name: &str) -> anyhow::Result<Quantity> {
60    Quantity::from_decimal(value)
61        .with_context(|| format!("Failed to convert {field_name} Decimal to Quantity"))
62}
63
64fn decimal_to_price_dp(value: Decimal, precision: u8, field: &str) -> anyhow::Result<Price> {
65    Price::from_decimal_dp(value, precision).with_context(|| {
66        format!("Failed to construct Price for {field} with precision {precision}")
67    })
68}
69
70fn get_currency(code: &str) -> Currency {
71    Currency::try_from_str(code).unwrap_or_else(|| {
72        // Create new currency with precision 0 (whole units for equity perps)
73        let currency = Currency::new(code, 0, 0, code, CurrencyType::Crypto);
74        if let Err(e) = Currency::register(currency, false) {
75            log::warn!("Failed to register currency '{code}': {e}");
76        }
77        currency
78    })
79}
80
81/// Converts an Ax candle width to a Nautilus bar specification.
82#[must_use]
83pub fn candle_width_to_bar_spec(width: AxCandleWidth) -> BarSpecification {
84    match width {
85        AxCandleWidth::Seconds1 => {
86            BarSpecification::new(1, BarAggregation::Second, PriceType::Last)
87        }
88        AxCandleWidth::Seconds5 => {
89            BarSpecification::new(5, BarAggregation::Second, PriceType::Last)
90        }
91        AxCandleWidth::Minutes1 => {
92            BarSpecification::new(1, BarAggregation::Minute, PriceType::Last)
93        }
94        AxCandleWidth::Minutes5 => {
95            BarSpecification::new(5, BarAggregation::Minute, PriceType::Last)
96        }
97        AxCandleWidth::Minutes15 => {
98            BarSpecification::new(15, BarAggregation::Minute, PriceType::Last)
99        }
100        AxCandleWidth::Hours1 => BarSpecification::new(1, BarAggregation::Hour, PriceType::Last),
101        AxCandleWidth::Days1 => BarSpecification::new(1, BarAggregation::Day, PriceType::Last),
102    }
103}
104
105/// Parses an Ax candle into a Nautilus Bar.
106///
107/// # Errors
108///
109/// Returns an error if any OHLCV field cannot be parsed.
110pub fn parse_bar(
111    candle: &AxCandle,
112    instrument: &InstrumentAny,
113    ts_init: UnixNanos,
114) -> anyhow::Result<Bar> {
115    let price_precision = instrument.price_precision();
116    let size_precision = instrument.size_precision();
117
118    let open = decimal_to_price_dp(candle.open, price_precision, "candle.open")?;
119    let high = decimal_to_price_dp(candle.high, price_precision, "candle.high")?;
120    let low = decimal_to_price_dp(candle.low, price_precision, "candle.low")?;
121    let close = decimal_to_price_dp(candle.close, price_precision, "candle.close")?;
122
123    // Ax provides volume as i64 contracts
124    let volume = Quantity::from_decimal_dp(Decimal::from(candle.volume), size_precision)?;
125
126    let ts_event = ax_timestamp_s_to_unix_nanos(candle.ts)?;
127
128    let bar_spec = candle_width_to_bar_spec(candle.width);
129    let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::External);
130
131    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
132        .context("Failed to construct Bar from Ax candle")
133}
134
135/// Parses an Ax funding rate into a Nautilus [`FundingRateUpdate`].
136///
137/// # Errors
138///
139/// Returns an error if the timestamp is invalid.
140pub fn parse_funding_rate(
141    ax_rate: &AxFundingRate,
142    instrument_id: InstrumentId,
143    ts_init: UnixNanos,
144) -> anyhow::Result<FundingRateUpdate> {
145    Ok(FundingRateUpdate::new(
146        instrument_id,
147        ax_rate.funding_rate,
148        None,
149        None, // AX doesn't provide next funding time
150        ax_timestamp_ns_to_unix_nanos(ax_rate.timestamp_ns)?,
151        ts_init,
152    ))
153}
154
155/// Parses an Ax instrument into a Nautilus perpetual or dated futures contract.
156///
157/// # Errors
158///
159/// Returns an error if any required field cannot be parsed or is invalid.
160pub fn parse_instrument(
161    definition: &AxInstrument,
162    ts_event: UnixNanos,
163    ts_init: UnixNanos,
164) -> anyhow::Result<InstrumentAny> {
165    let raw_symbol_str = definition.symbol.as_str();
166    let raw_symbol = Symbol::new(raw_symbol_str);
167    let instrument_id = InstrumentId::new(raw_symbol, *AX_VENUE);
168
169    let symbol_prefix = raw_symbol_str
170        .split('-')
171        .next()
172        .context("Failed to extract symbol prefix")?;
173
174    let underlying = match definition.product {
175        Some(product) => {
176            let trimmed = product.trim();
177            anyhow::ensure!(
178                !trimmed.is_empty() && trimmed == product,
179                "AX instrument product must be non-empty without surrounding whitespace, was '{product}'"
180            );
181            product
182        }
183        None => Ustr::from(symbol_prefix),
184    };
185
186    // Derive base code by stripping quote currency suffix if present
187    // e.g. JPYUSD-PERP → base=JPY, BTC-PERP → base=BTC
188    let quote_code = definition.quote_currency.as_str();
189    let base_code = if symbol_prefix.ends_with(quote_code) && symbol_prefix.len() > quote_code.len()
190    {
191        &symbol_prefix[..symbol_prefix.len() - quote_code.len()]
192    } else {
193        symbol_prefix
194    };
195
196    let asset_class = AssetClass::from(definition.category);
197
198    // Only resolve base currency for FX/crypto where the base code is a currency
199    let base_currency = match asset_class {
200        AssetClass::FX | AssetClass::Cryptocurrency => Some(get_currency(base_code)),
201        _ => None,
202    };
203
204    let quote_currency = get_currency(quote_code);
205    let settlement_currency = get_currency(definition.funding_settlement_currency.as_str());
206
207    let price_increment = decimal_to_price(definition.tick_size, "tick_size")?;
208    anyhow::ensure!(
209        definition.minimum_order_size > Decimal::ZERO
210            && definition.minimum_order_size.fract().is_zero(),
211        "AX minimum_order_size must be a positive whole number, was {}",
212        definition.minimum_order_size
213    );
214    let size_increment = decimal_to_quantity(Decimal::ONE, "size_increment")?;
215    let lot_size = Some(size_increment);
216    let min_quantity = Some(decimal_to_quantity(
217        definition.minimum_order_size.normalize(),
218        "minimum_order_size",
219    )?);
220
221    let (margin_init, margin_maint) = parse_margin_rates(
222        definition.initial_margin_pct,
223        definition.maintenance_margin_pct,
224    )?;
225
226    let mut info = IndexMap::new();
227    if let Some(ref desc) = definition.description {
228        info.insert("description".to_string(), json!(desc));
229    }
230
231    if let Some(product) = definition.product {
232        info.insert("product".to_string(), json!(product.as_str()));
233    }
234
235    info.insert(
236        "initial_margin_pct".to_string(),
237        json!(definition.initial_margin_pct.to_string()),
238    );
239    info.insert(
240        "maintenance_margin_pct".to_string(),
241        json!(definition.maintenance_margin_pct.to_string()),
242    );
243    info.insert(
244        "quantity_increment_source".to_string(),
245        json!("integer_contract_wire_quantity"),
246    );
247
248    if let Some(ref s) = definition.contract_size {
249        info.insert("contract_size".to_string(), json!(s));
250    }
251
252    if let Some(ref s) = definition.contract_mark_price {
253        info.insert("contract_mark_price".to_string(), json!(s));
254    }
255
256    if let Some(ref s) = definition.price_quotation {
257        info.insert("price_quotation".to_string(), json!(s));
258    }
259
260    if let Some(ref s) = definition.underlying_benchmark_price {
261        info.insert("underlying_benchmark_price".to_string(), json!(s));
262    }
263
264    if let Some(ref s) = definition.price_bands {
265        info.insert("price_bands".to_string(), json!(s));
266    }
267
268    if let Some(v) = definition.funding_rate_cap_upper_pct {
269        info.insert(
270            "funding_rate_cap_upper_pct".to_string(),
271            json!(v.to_string()),
272        );
273    }
274
275    if let Some(v) = definition.funding_rate_cap_lower_pct {
276        info.insert(
277            "funding_rate_cap_lower_pct".to_string(),
278            json!(v.to_string()),
279        );
280    }
281
282    if let Some(v) = definition.price_band_upper_deviation_pct {
283        info.insert(
284            "price_band_upper_deviation_pct".to_string(),
285            json!(v.to_string()),
286        );
287    }
288
289    if let Some(v) = definition.price_band_lower_deviation_pct {
290        info.insert(
291            "price_band_lower_deviation_pct".to_string(),
292            json!(v.to_string()),
293        );
294    }
295
296    if let Some(expiration) = definition.expiration {
297        anyhow::ensure!(
298            definition.quote_currency == definition.funding_settlement_currency,
299            "AX dated contract {} has different quote and settlement currencies: {} and {}",
300            definition.symbol,
301            definition.quote_currency,
302            definition.funding_settlement_currency
303        );
304        let expiration_ns = datetime_to_unix_nanos(Some(expiration))
305            .context("Failed to convert AX contract expiration to Unix nanoseconds")?;
306        let multiplier = decimal_to_quantity(definition.multiplier, "multiplier")?;
307        info.insert(
308            "expiration".to_string(),
309            json!(expiration.display_with_offset(Offset::UTC).to_string()),
310        );
311        info.insert(
312            "activation_source".to_string(),
313            json!("unavailable_from_ax"),
314        );
315
316        let instrument = FuturesContract::builder()
317            .instrument_id(instrument_id)
318            .raw_symbol(raw_symbol)
319            .asset_class(asset_class)
320            .underlying(underlying)
321            .activation_ns(UnixNanos::default())
322            .expiration_ns(expiration_ns)
323            .currency(quote_currency)
324            .price_precision(price_increment.precision)
325            .price_increment(price_increment)
326            .multiplier(multiplier)
327            .lot_size(size_increment)
328            .maybe_min_quantity(min_quantity)
329            .margin_init(margin_init)
330            .margin_maint(margin_maint)
331            .info(Params::new(info))
332            .ts_event(ts_event)
333            .ts_init(ts_init)
334            .build()
335            .context("Failed to construct AX dated futures contract")?;
336
337        return Ok(InstrumentAny::FuturesContract(instrument));
338    }
339
340    let instrument = PerpetualContract::builder()
341        .instrument_id(instrument_id)
342        .raw_symbol(raw_symbol)
343        .underlying(underlying)
344        .asset_class(asset_class)
345        .maybe_base_currency(base_currency)
346        .quote_currency(quote_currency)
347        .settlement_currency(settlement_currency)
348        .is_inverse(false)
349        .multiplier(decimal_to_quantity(definition.multiplier, "multiplier")?)
350        .price_precision(price_increment.precision)
351        .size_precision(size_increment.precision)
352        .price_increment(price_increment)
353        .size_increment(size_increment)
354        .maybe_lot_size(lot_size)
355        .maybe_min_quantity(min_quantity)
356        .margin_init(margin_init)
357        .margin_maint(margin_maint)
358        .info(Params::new(info))
359        .ts_event(ts_event)
360        .ts_init(ts_init)
361        .build()
362        .context("failed to construct AX perpetual contract")?;
363
364    Ok(InstrumentAny::PerpetualContract(instrument))
365}
366
367fn parse_margin_rates(
368    initial_margin_pct: Decimal,
369    maintenance_margin_pct: Decimal,
370) -> anyhow::Result<(Decimal, Decimal)> {
371    anyhow::ensure!(
372        initial_margin_pct > Decimal::ZERO,
373        "AX initial_margin_pct must be positive, was {initial_margin_pct}"
374    );
375    anyhow::ensure!(
376        maintenance_margin_pct > Decimal::ZERO,
377        "AX maintenance_margin_pct must be positive, was {maintenance_margin_pct}"
378    );
379    anyhow::ensure!(
380        maintenance_margin_pct <= initial_margin_pct,
381        "AX maintenance_margin_pct {maintenance_margin_pct} exceeds initial_margin_pct {initial_margin_pct}"
382    );
383
384    Ok((
385        margin_percent_to_rate(initial_margin_pct, "initial_margin_pct")?,
386        margin_percent_to_rate(maintenance_margin_pct, "maintenance_margin_pct")?,
387    ))
388}
389
390fn margin_percent_to_rate(value: Decimal, field: &str) -> anyhow::Result<Decimal> {
391    let normalized = value.normalize();
392    let scale = normalized.scale();
393    anyhow::ensure!(
394        scale <= 26,
395        "AX {field} scale must not exceed 26 for exact percent conversion, was {scale}"
396    );
397    Decimal::try_from_i128_with_scale(normalized.mantissa(), scale + 2)
398        .with_context(|| format!("Failed to convert AX {field} percentage to a rate"))
399}
400
401/// Parses an Ax balances response into a Nautilus [`AccountState`].
402///
403/// Ax provides a simple balance structure with symbol and amount. When a
404/// [`AxRiskSnapshot`] is supplied, its USD margin requirements populate the
405/// USD balance's locked funds and the account's margin balances; without one,
406/// locked stays zero for every currency.
407///
408/// # Errors
409///
410/// Returns an error if balance amount parsing fails.
411pub fn parse_account_state(
412    response: &AxBalancesResponse,
413    risk: Option<&AxRiskSnapshot>,
414    account_id: AccountId,
415    ts_event: UnixNanos,
416    ts_init: UnixNanos,
417) -> anyhow::Result<AccountState> {
418    // Pass the raw USD requirement through; from_total_and_locked clamps a disagreement
419    let usd_locked = risk.map_or(Decimal::ZERO, |risk| risk.initial_margin_required_total);
420
421    let mut balances = Vec::with_capacity(response.balances.len());
422
423    for balance in &response.balances {
424        let symbol_str = balance.symbol.trim();
425        if symbol_str.is_empty() {
426            log::debug!("Skipping balance with empty symbol");
427            continue;
428        }
429
430        let currency = get_currency(symbol_str);
431
432        let locked = if currency == Currency::USD() {
433            usd_locked
434        } else {
435            Decimal::ZERO
436        };
437
438        let balance = AccountBalance::from_total_and_locked(balance.amount, locked, currency)
439            .with_context(|| format!("Failed to convert balance for {symbol_str}"))?;
440        balances.push(balance);
441    }
442
443    if balances.is_empty() {
444        let zero_currency = Currency::USD();
445        let zero_money = Money::zero(zero_currency);
446        balances.push(AccountBalance::new(zero_money, zero_money, zero_money));
447    }
448
449    let margins = risk
450        .map(|risk| {
451            vec![MarginBalance::new(
452                Money::from_decimal(risk.initial_margin_required_total, Currency::USD())
453                    .unwrap_or_else(|_| Money::zero(Currency::USD())),
454                Money::from_decimal(risk.maintenance_margin_required, Currency::USD())
455                    .unwrap_or_else(|_| Money::zero(Currency::USD())),
456                None,
457            )]
458        })
459        .unwrap_or_default();
460
461    Ok(AccountState::new(
462        account_id,
463        AccountType::Margin,
464        balances,
465        margins,
466        true,
467        UUID4::new(),
468        ts_event,
469        ts_init,
470        None,
471    ))
472}
473
474/// Parses an Ax open order into a Nautilus [`OrderStatusReport`].
475///
476/// The `cid_resolver` parameter is an optional function that resolves a `cid` (u64)
477/// to a `ClientOrderId`. This is needed because orders submitted via WebSocket use
478/// a hashed `cid` for correlation rather than storing the full `ClientOrderId` in the tag.
479///
480/// # Errors
481///
482/// Returns an error if:
483/// - Price or quantity fields cannot be parsed.
484/// - Timestamp conversion fails.
485pub fn parse_order_status_report<F>(
486    order: &AxOpenOrder,
487    account_id: AccountId,
488    instrument: &InstrumentAny,
489    ts_init: UnixNanos,
490    cid_resolver: Option<&F>,
491) -> anyhow::Result<OrderStatusReport>
492where
493    F: Fn(u64) -> Option<ClientOrderId>,
494{
495    parse_order_status_report_fields(
496        &OrderStatusReportFields::from(order),
497        account_id,
498        instrument,
499        ts_init,
500        cid_resolver,
501    )
502}
503
504/// Parses an Ax historical order into a Nautilus [`OrderStatusReport`].
505///
506/// The `cid_resolver` parameter is an optional function that resolves a `cid` (u64)
507/// to a `ClientOrderId`. This is needed because orders submitted via WebSocket use
508/// a hashed `cid` for correlation rather than storing the full `ClientOrderId` in the tag.
509///
510/// # Errors
511///
512/// Returns an error if:
513/// - Price or quantity fields cannot be parsed.
514/// - Timestamp conversion fails.
515pub fn parse_order_detail_status_report<F>(
516    order: &AxOrderDetail,
517    account_id: AccountId,
518    instrument: &InstrumentAny,
519    ts_init: UnixNanos,
520    cid_resolver: Option<&F>,
521) -> anyhow::Result<OrderStatusReport>
522where
523    F: Fn(u64) -> Option<ClientOrderId>,
524{
525    parse_order_status_report_fields(
526        &OrderStatusReportFields::from(order),
527        account_id,
528        instrument,
529        ts_init,
530        cid_resolver,
531    )
532}
533
534pub(crate) fn update_order_report_timestamps(
535    reports: &mut [OrderStatusReport],
536    fills: &[FillReport],
537) {
538    let mut last_fill_timestamps = HashMap::new();
539    for fill in fills {
540        last_fill_timestamps
541            .entry((fill.account_id, fill.venue_order_id))
542            .and_modify(|ts: &mut UnixNanos| *ts = (*ts).max(fill.ts_event))
543            .or_insert(fill.ts_event);
544    }
545
546    for report in reports {
547        if !report.order_status.is_closed() {
548            continue;
549        }
550
551        if let Some(ts_last_fill) =
552            last_fill_timestamps.get(&(report.account_id, report.venue_order_id))
553        {
554            report.ts_last = report.ts_last.max(*ts_last_fill);
555        }
556    }
557}
558
559struct OrderStatusReportFields<'a> {
560    ts: i64,
561    tn: i64,
562    post_only: bool,
563    oid: &'a str,
564    price: Decimal,
565    quantity: u64,
566    filled_qty: u64,
567    status: AxOrderStatus,
568    side: AxOrderSide,
569    time_in_force: AxTimeInForce,
570    cid: Option<u64>,
571    reject_reason: Option<AxOrderRejectReason>,
572    text: Option<&'a str>,
573}
574
575impl<'a> From<&'a AxOpenOrder> for OrderStatusReportFields<'a> {
576    fn from(order: &'a AxOpenOrder) -> Self {
577        Self {
578            ts: order.ts,
579            tn: order.tn,
580            post_only: order.po,
581            oid: &order.oid,
582            price: order.p,
583            quantity: order.q,
584            filled_qty: order.xq,
585            status: order.o,
586            side: order.d,
587            time_in_force: order.tif,
588            cid: order.cid,
589            reject_reason: order.r,
590            text: order.txt.as_deref(),
591        }
592    }
593}
594
595impl<'a> From<&'a AxOrderDetail> for OrderStatusReportFields<'a> {
596    fn from(order: &'a AxOrderDetail) -> Self {
597        Self {
598            ts: order.ts,
599            tn: order.tn,
600            post_only: order.po,
601            oid: &order.oid,
602            price: order.p,
603            quantity: order.q,
604            filled_qty: order.xq,
605            status: order.o,
606            side: order.d,
607            time_in_force: order.tif,
608            cid: order.cid,
609            reject_reason: order.r,
610            text: order.txt.as_deref(),
611        }
612    }
613}
614
615fn parse_order_status_report_fields<F>(
616    order: &OrderStatusReportFields<'_>,
617    account_id: AccountId,
618    instrument: &InstrumentAny,
619    ts_init: UnixNanos,
620    cid_resolver: Option<&F>,
621) -> anyhow::Result<OrderStatusReport>
622where
623    F: Fn(u64) -> Option<ClientOrderId>,
624{
625    let instrument_id = instrument.id();
626    let venue_order_id = VenueOrderId::new(order.oid);
627    let order_side = OrderSide::from(order.side);
628    let time_in_force = TimeInForce::try_from(order.time_in_force)?;
629    let order_status = parse_order_status(order.status, time_in_force)?;
630
631    // The current AX wire shape maps to a Nautilus limit order.
632    let order_type = OrderType::Limit;
633
634    // Parse quantity (Ax uses i64 contracts)
635    let quantity =
636        Quantity::from_decimal_dp(Decimal::from(order.quantity), instrument.size_precision())?;
637    let filled_qty =
638        Quantity::from_decimal_dp(Decimal::from(order.filled_qty), instrument.size_precision())?;
639
640    // Parse price
641    let price = decimal_to_price_dp(order.price, instrument.price_precision(), "order.p")?;
642
643    // Ax timestamps are in Unix epoch seconds
644    let ts_event = ax_timestamp_stn_to_unix_nanos(order.ts, order.tn)?;
645
646    let mut report = OrderStatusReport::new(
647        account_id,
648        instrument_id,
649        None,
650        venue_order_id,
651        order_side.into(),
652        order_type,
653        time_in_force,
654        order_status,
655        quantity,
656        filled_qty,
657        ts_event,
658        ts_event,
659        ts_init,
660        Some(UUID4::new()),
661    );
662
663    if let Some(cid) = order.cid {
664        let client_order_id = cid_resolver
665            .and_then(|resolver| resolver(cid))
666            .unwrap_or_else(|| cid_to_client_order_id(cid));
667        report = report.with_client_order_id(client_order_id);
668    }
669
670    report = report.with_price(price).with_post_only(order.post_only);
671
672    // Keep reconciled terminal reasons identical to live WS events
673    if let Some(reason) = AxOrderRejectReason::reason_str(order.reject_reason, order.text) {
674        report = report.with_cancel_reason(reason);
675    }
676
677    // We don't set avg_px here since the order endpoint only provides the
678    // limit price, not actual fill prices. True average would need to be
679    // calculated from fill reports.
680
681    Ok(report)
682}
683
684pub(super) fn parse_order_status(
685    status: AxOrderStatus,
686    time_in_force: TimeInForce,
687) -> anyhow::Result<OrderStatus> {
688    if status == AxOrderStatus::Expired
689        && matches!(time_in_force, TimeInForce::Ioc | TimeInForce::Fok)
690    {
691        return Ok(OrderStatus::Canceled);
692    }
693
694    OrderStatus::try_from(status)
695}
696
697/// Parses an Ax fill into a Nautilus [`FillReport`].
698///
699/// AX may omit an order ID for block trades and final settlement fills. Those
700/// records receive a deterministic reconciliation ID derived from the trade ID.
701/// The special-fill classifications are optional for regular fills with an
702/// order ID.
703///
704/// # Errors
705///
706/// Returns an error if:
707/// - Price or quantity fields cannot be parsed.
708/// - Fee parsing fails.
709/// - Fill classification is inconsistent.
710/// - A fill is neither explicitly special nor linked to a valid order ID.
711pub fn parse_fill_report(
712    fill: &AxFill,
713    account_id: AccountId,
714    instrument: &InstrumentAny,
715    ts_init: UnixNanos,
716) -> anyhow::Result<FillReport> {
717    let instrument_id = instrument.id();
718
719    let trade_id = TradeId::new_checked(&fill.trade_id).context("Invalid trade_id in Ax fill")?;
720    let is_block_trade = fill.is_block_trade;
721    let is_final_settlement = fill.is_final_settlement;
722    anyhow::ensure!(
723        !(is_final_settlement == Some(true) && is_block_trade == Some(false)),
724        "AX final-settlement fill must also be classified as a block trade"
725    );
726
727    let is_special_fill = is_block_trade == Some(true) || is_final_settlement == Some(true);
728
729    let venue_order_id = if is_special_fill {
730        VenueOrderId::new_checked(format!("{AX_FILL_ORDER_PREFIX}{}", fill.trade_id))
731            .context("Invalid synthetic venue order ID for AX fill")?
732    } else {
733        let order_id = fill
734            .order_id
735            .as_deref()
736            .context("AX fill is missing order_id and explicit special-fill classification")?;
737        anyhow::ensure!(
738            !order_id.is_empty(),
739            "AX regular fill has an empty order_id"
740        );
741        VenueOrderId::new_checked(order_id).context("Invalid order_id in AX fill")?
742    };
743
744    // Use explicit side field from fill
745    let order_side = OrderSide::from(fill.side);
746
747    let last_px = decimal_to_price_dp(fill.price, instrument.price_precision(), "fill.price")?;
748    let last_qty =
749        Quantity::from_decimal_dp(Decimal::from(fill.quantity), instrument.size_precision())?;
750
751    let currency = Currency::USD();
752    let commission = Money::from_decimal(fill.fee, currency)
753        .context("Failed to convert fill.fee Decimal to Money")?;
754
755    let liquidity_side = if fill.is_taker {
756        LiquiditySide::Taker
757    } else {
758        LiquiditySide::Maker
759    };
760
761    let ts_event = match u64::try_from(fill.timestamp.as_nanosecond().unsigned_abs()) {
762        Ok(nanos) => UnixNanos::from(nanos),
763        Err(_) => {
764            log::warn!(
765                "Timestamp overflow for fill {} (timestamp={}), defaulting to 0",
766                fill.trade_id,
767                fill.timestamp
768            );
769            UnixNanos::from(0u64)
770        }
771    };
772
773    Ok(FillReport::new(
774        account_id,
775        instrument_id,
776        venue_order_id,
777        trade_id,
778        order_side,
779        last_qty,
780        last_px,
781        commission,
782        liquidity_side,
783        None,
784        None,
785        ts_event,
786        ts_init,
787        None,
788    ))
789}
790
791/// Parses an Ax position into a Nautilus [`PositionStatusReport`].
792///
793/// Reports the signed fill-ledger cost-basis average with
794/// [`AvgPxReconciliation::OpeningOnly`] semantics.
795///
796/// # Errors
797///
798/// Returns an error if:
799/// - Position quantity parsing fails.
800/// - Timestamp conversion fails.
801pub fn parse_position_status_report(
802    position: &AxPosition,
803    account_id: AccountId,
804    instrument: &InstrumentAny,
805    ts_init: UnixNanos,
806) -> anyhow::Result<PositionStatusReport> {
807    let instrument_id = instrument.id();
808
809    // Determine position side and quantity from signed_quantity sign
810    let (position_side, quantity) = if position.signed_quantity > 0 {
811        (
812            PositionSide::Long,
813            Quantity::from_decimal_dp(
814                Decimal::from(position.signed_quantity),
815                instrument.size_precision(),
816            )?,
817        )
818    } else if position.signed_quantity < 0 {
819        (
820            PositionSide::Short,
821            Quantity::from_decimal_dp(
822                Decimal::from(position.signed_quantity.unsigned_abs()),
823                instrument.size_precision(),
824            )?,
825        )
826    } else {
827        (
828            PositionSide::Flat,
829            Quantity::zero(instrument.size_precision()),
830        )
831    };
832
833    let avg_px_open = if position.signed_quantity != 0 {
834        let qty_dec = Decimal::from(position.signed_quantity);
835        Some(
836            position
837                .signed_cost_basis
838                .unwrap_or(position.signed_notional)
839                / qty_dec,
840        )
841    } else {
842        None
843    };
844
845    let ts_last = match u64::try_from(position.timestamp.as_nanosecond().unsigned_abs()) {
846        Ok(nanos) => UnixNanos::from(nanos),
847        Err(_) => {
848            log::warn!(
849                "Timestamp overflow for position {} (timestamp={}), defaulting to 0",
850                position.symbol,
851                position.timestamp
852            );
853            UnixNanos::from(0u64)
854        }
855    };
856
857    Ok(PositionStatusReport::new(
858        account_id,
859        instrument_id,
860        position_side,
861        quantity,
862        ts_last,
863        ts_init,
864        None,
865        None,
866        avg_px_open,
867    )
868    .with_avg_px_open_reconciliation(AvgPxReconciliation::OpeningOnly))
869}
870
871/// Parses an Ax REST trade into a Nautilus [`TradeTick`].
872///
873/// # Errors
874///
875/// Returns an error if any field cannot be parsed.
876pub fn parse_trade_tick(
877    trade: &AxRestTrade,
878    instrument: &InstrumentAny,
879    ts_init: UnixNanos,
880) -> anyhow::Result<TradeTick> {
881    let price = decimal_to_price_dp(trade.p, instrument.price_precision(), "trade.p")?;
882    let size = Quantity::from_decimal_dp(Decimal::from(trade.q), instrument.size_precision())?;
883    let aggressor_side: AggressorSide = trade.d.into();
884
885    let ts_event = ax_timestamp_stn_to_unix_nanos(trade.ts, trade.tn)?;
886    let trade_id = create_architect_trade_id(ts_event, price, size, aggressor_side)?;
887
888    TradeTick::new_checked(
889        instrument.id(),
890        price,
891        size,
892        aggressor_side,
893        trade_id,
894        ts_event,
895        ts_init,
896    )
897    .context("Failed to construct TradeTick from Ax REST trade")
898}
899
900#[cfg(test)]
901mod tests {
902    use jiff::Timestamp;
903    use nautilus_core::nanos::UnixNanos;
904    use nautilus_model::enums::OrderStatus;
905    use rstest::rstest;
906    use rust_decimal_macros::dec;
907    use ustr::Ustr;
908
909    use super::*;
910    use crate::{
911        common::enums::{AxCategory, AxInstrumentState, AxOrderSide, AxOrderStatus, AxTimeInForce},
912        http::models::{
913            AxBalance, AxBalancesResponse, AxFundingRatesResponse, AxInstrumentsResponse,
914            AxOpenOrder, AxOrderDetail, AxOrderRejectReason,
915        },
916    };
917
918    fn create_eurusd_instrument() -> AxInstrument {
919        AxInstrument {
920            price_scale: None,
921            additional_product_specs: Default::default(),
922            delisted_at: None,
923            is_closing: false,
924            estimated_funding_supported: false,
925            funding_schedule_calendar_description: None,
926            funding_schedule_time_description: None,
927            funding_schedule: None,
928            trading_schedule: None,
929            symbol: Ustr::from("EURUSD-PERP"),
930            product: Some(Ustr::from("EURUSD")),
931            state: AxInstrumentState::Open,
932            multiplier: dec!(1),
933            minimum_order_size: dec!(100),
934            tick_size: dec!(0.0001),
935            quote_currency: Ustr::from("USD"),
936            funding_settlement_currency: Ustr::from("USD"),
937            category: AxCategory::Fx,
938            maintenance_margin_pct: dec!(4.0),
939            initial_margin_pct: dec!(8.0),
940            contract_mark_price: Some("Average price on AX at London 4pm".to_string()),
941            contract_size: Some("1 Euro per contract".to_string()),
942            description: Some("Euro / US Dollar FX Perpetual Future".to_string()),
943            expiration: None,
944            funding_calendar_schedule: None,
945            funding_frequency: None,
946            funding_rate_cap_lower_pct: Some(dec!(-1.0)),
947            funding_rate_cap_upper_pct: Some(dec!(1.0)),
948            price_band_lower_deviation_pct: Some(dec!(10)),
949            price_band_upper_deviation_pct: Some(dec!(10)),
950            price_bands: Some("+/- 10% from prior Contract Mark Price".to_string()),
951            price_quotation: Some("U.S. dollars per Euro".to_string()),
952            underlying_benchmark_price: Some("WMR London 4pm Closing Spot Rate".to_string()),
953        }
954    }
955
956    fn create_nvda_instrument() -> AxInstrument {
957        AxInstrument {
958            price_scale: None,
959            additional_product_specs: Default::default(),
960            delisted_at: None,
961            is_closing: false,
962            estimated_funding_supported: false,
963            funding_schedule_calendar_description: None,
964            funding_schedule_time_description: None,
965            funding_schedule: None,
966            trading_schedule: None,
967            symbol: Ustr::from("NVDA-PERP"),
968            product: Some(Ustr::from("NVDA")),
969            state: AxInstrumentState::Open,
970            multiplier: dec!(1),
971            minimum_order_size: dec!(1),
972            tick_size: dec!(0.01),
973            quote_currency: Ustr::from("USD"),
974            funding_settlement_currency: Ustr::from("USD"),
975            category: AxCategory::Equities,
976            maintenance_margin_pct: dec!(10),
977            initial_margin_pct: dec!(20),
978            contract_mark_price: Some(
979                "Average price on ArchitectX at 4pm New York Time".to_string(),
980            ),
981            contract_size: Some("1 share per contract".to_string()),
982            description: Some("NVIDIA Corp US Equity Perpetual Future".to_string()),
983            expiration: None,
984            funding_calendar_schedule: None,
985            funding_frequency: None,
986            funding_rate_cap_lower_pct: Some(dec!(-1)),
987            funding_rate_cap_upper_pct: Some(dec!(1)),
988            price_band_lower_deviation_pct: Some(dec!(10)),
989            price_band_upper_deviation_pct: Some(dec!(10)),
990            price_bands: Some("+/- 10% from prior Contract Mark Price".to_string()),
991            price_quotation: Some("U.S. dollars per share".to_string()),
992            underlying_benchmark_price: Some("Nasdaq Official Closing Price".to_string()),
993        }
994    }
995
996    fn create_xau_instrument() -> AxInstrument {
997        AxInstrument {
998            price_scale: None,
999            additional_product_specs: Default::default(),
1000            delisted_at: None,
1001            is_closing: false,
1002            estimated_funding_supported: false,
1003            funding_schedule_calendar_description: None,
1004            funding_schedule_time_description: None,
1005            funding_schedule: None,
1006            trading_schedule: None,
1007            symbol: Ustr::from("XAU-PERP"),
1008            product: Some(Ustr::from("XAU")),
1009            state: AxInstrumentState::Open,
1010            multiplier: dec!(1),
1011            minimum_order_size: dec!(1),
1012            tick_size: dec!(0.1),
1013            quote_currency: Ustr::from("USD"),
1014            funding_settlement_currency: Ustr::from("USD"),
1015            category: AxCategory::Metals,
1016            maintenance_margin_pct: dec!(5),
1017            initial_margin_pct: dec!(10),
1018            contract_mark_price: Some("Average price on ArchitectX at London 4pm".to_string()),
1019            contract_size: Some("1 ounce per contract".to_string()),
1020            description: Some("Gold Metals Perpetual Future".to_string()),
1021            expiration: None,
1022            funding_calendar_schedule: None,
1023            funding_frequency: None,
1024            funding_rate_cap_lower_pct: Some(dec!(-1)),
1025            funding_rate_cap_upper_pct: Some(dec!(1)),
1026            price_band_lower_deviation_pct: Some(dec!(10)),
1027            price_band_upper_deviation_pct: Some(dec!(10)),
1028            price_bands: Some("+/- 10% from prior Contract Mark Price".to_string()),
1029            price_quotation: Some("U.S. dollars per ounce".to_string()),
1030            underlying_benchmark_price: Some("XAU WMR Metals Daily Closing Rate".to_string()),
1031        }
1032    }
1033
1034    fn create_fill() -> AxFill {
1035        AxFill {
1036            trade_id: "T-01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string(),
1037            order_id: Some("O-01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string()),
1038            fee: dec!(0.10),
1039            is_taker: true,
1040            is_block_trade: Some(false),
1041            is_final_settlement: Some(false),
1042            price: dec!(1.0845),
1043            quantity: 100,
1044            side: AxOrderSide::Buy,
1045            symbol: Ustr::from("EURUSD-PERP"),
1046            timestamp: "2026-07-17T00:00:00Z".parse::<Timestamp>().unwrap(),
1047            account_id: Ustr::from("account-1"),
1048            realized_pnl: None,
1049        }
1050    }
1051
1052    #[rstest]
1053    fn test_get_currency_known() {
1054        let currency = get_currency("USD");
1055        assert_eq!(currency.code, Ustr::from("USD"));
1056        assert_eq!(currency.precision, 2);
1057    }
1058
1059    #[rstest]
1060    fn test_get_currency_unknown_creates_new() {
1061        let currency = get_currency("NVDA");
1062        assert_eq!(currency.code, Ustr::from("NVDA"));
1063        assert_eq!(currency.precision, 0);
1064    }
1065
1066    fn create_order_detail(
1067        status: AxOrderStatus,
1068        reject_reason: Option<AxOrderRejectReason>,
1069        text: Option<&str>,
1070    ) -> AxOrderDetail {
1071        AxOrderDetail {
1072            ts: 1_609_459_200,
1073            tn: 0,
1074            oid: "O-REJECTED".to_string(),
1075            aid: Some(Ustr::from("account-1")),
1076            u: Ustr::from("user"),
1077            s: Ustr::from("EURUSD-PERP"),
1078            p: dec!(1.0845),
1079            q: 100,
1080            xq: 0,
1081            rq: 100,
1082            o: status,
1083            d: AxOrderSide::Buy,
1084            tif: AxTimeInForce::Gtc,
1085            cid: Some(42),
1086            r: reject_reason,
1087            tag: None,
1088            txt: text.map(str::to_string),
1089            po: false,
1090            rb: None,
1091        }
1092    }
1093
1094    #[rstest]
1095    #[case::canceled(AxOrderStatus::Canceled, "matching", 1_704_067_200_508_000_123)]
1096    #[case::expired(AxOrderStatus::Expired, "matching", 1_704_067_200_508_000_123)]
1097    #[case::filled(AxOrderStatus::Filled, "matching", 1_704_067_200_508_000_123)]
1098    #[case::open(AxOrderStatus::PartiallyFilled, "matching", 1_704_067_200_500_000_000)]
1099    #[case::empty(AxOrderStatus::Canceled, "empty", 1_704_067_200_500_000_000)]
1100    #[case::older(AxOrderStatus::Canceled, "older", 1_704_067_200_500_000_000)]
1101    #[case::other_account(AxOrderStatus::Canceled, "other_account", 1_704_067_200_500_000_000)]
1102    #[case::later_report(AxOrderStatus::Canceled, "later_report", 1_704_067_200_600_000_000)]
1103    fn test_closed_order_report_uses_latest_fill_timestamp(
1104        #[case] status: AxOrderStatus,
1105        #[case] scenario: &str,
1106        #[case] expected_last: u64,
1107    ) {
1108        let orders: crate::http::models::AxOrdersResponse = serde_json::from_str(include_str!(
1109            "../../test_data/http_get_orders_partial_canceled.json"
1110        ))
1111        .unwrap();
1112        let fills: crate::http::models::AxFillsResponse = serde_json::from_str(include_str!(
1113            "../../test_data/http_get_fills_partial_canceled.json"
1114        ))
1115        .unwrap();
1116        let instrument = parse_instrument(
1117            &create_eurusd_instrument(),
1118            UnixNanos::default(),
1119            UnixNanos::default(),
1120        )
1121        .unwrap();
1122        let account_id = AccountId::from("AX-001");
1123        let ts_init = UnixNanos::from(1_704_067_201_000_000_000_u64);
1124        let mut order = orders.orders[0].clone();
1125        order.o = status;
1126        order.q = if status == AxOrderStatus::Filled {
1127            100
1128        } else {
1129            200
1130        };
1131
1132        order.rq = if status == AxOrderStatus::PartiallyFilled {
1133            100
1134        } else {
1135            0
1136        };
1137
1138        let mut reports = [parse_order_detail_status_report(
1139            &order,
1140            account_id,
1141            &instrument,
1142            ts_init,
1143            None::<&fn(u64) -> Option<ClientOrderId>>,
1144        )
1145        .unwrap()];
1146        let mut fills: Vec<_> = fills
1147            .fills
1148            .iter()
1149            .map(|fill| parse_fill_report(fill, account_id, &instrument, ts_init).unwrap())
1150            .collect();
1151
1152        match scenario {
1153            "empty" => fills.clear(),
1154            "older" => {
1155                for fill in &mut fills {
1156                    fill.ts_event = UnixNanos::from(1_704_067_200_400_000_000_u64);
1157                }
1158            }
1159            "other_account" => {
1160                for fill in &mut fills {
1161                    fill.account_id = AccountId::from("AX-OTHER");
1162                }
1163            }
1164            "later_report" => {
1165                reports[0].ts_last = UnixNanos::from(1_704_067_200_600_000_000_u64);
1166            }
1167            "matching" => {}
1168            _ => panic!("unexpected test scenario: {scenario}"),
1169        }
1170
1171        let mut expected = reports[0].clone();
1172        expected.ts_last = UnixNanos::from(expected_last);
1173
1174        update_order_report_timestamps(&mut reports, &fills);
1175
1176        let report = &reports[0];
1177        assert_eq!(*report, expected);
1178        assert_eq!(
1179            report.ts_accepted,
1180            UnixNanos::from(1_704_067_200_500_000_000_u64)
1181        );
1182        assert_eq!(report.ts_last, UnixNanos::from(expected_last));
1183        assert_eq!(report.ts_init, ts_init);
1184        assert_eq!(report.quantity.as_decimal(), Decimal::from(order.q));
1185        assert_eq!(report.filled_qty.as_decimal(), dec!(100));
1186        assert_eq!(
1187            report.venue_order_id,
1188            VenueOrderId::from("O-PARTIAL-CANCELED")
1189        );
1190    }
1191
1192    #[rstest]
1193    fn test_parse_order_detail_status_report_carries_reject_reason() {
1194        let instrument = parse_instrument(
1195            &create_eurusd_instrument(),
1196            UnixNanos::default(),
1197            UnixNanos::default(),
1198        )
1199        .unwrap();
1200        let order = create_order_detail(
1201            AxOrderStatus::Rejected,
1202            Some(AxOrderRejectReason::PriceOutOfBounds),
1203            None,
1204        );
1205
1206        let report = parse_order_detail_status_report(
1207            &order,
1208            AccountId::from("AX-001"),
1209            &instrument,
1210            UnixNanos::default(),
1211            None::<&fn(u64) -> Option<ClientOrderId>>,
1212        )
1213        .unwrap();
1214
1215        assert_eq!(report.order_status, OrderStatus::Rejected);
1216        assert_eq!(
1217            report.cancel_reason,
1218            Some("PRICE_OUT_OF_BOUNDS".to_string())
1219        );
1220    }
1221
1222    #[rstest]
1223    fn test_parse_order_detail_status_report_falls_back_to_text_reason() {
1224        let instrument = parse_instrument(
1225            &create_eurusd_instrument(),
1226            UnixNanos::default(),
1227            UnixNanos::default(),
1228        )
1229        .unwrap();
1230        let order = create_order_detail(
1231            AxOrderStatus::Rejected,
1232            Some(AxOrderRejectReason::Unknown),
1233            Some("risk blocked"),
1234        );
1235
1236        let report = parse_order_detail_status_report(
1237            &order,
1238            AccountId::from("AX-001"),
1239            &instrument,
1240            UnixNanos::default(),
1241            None::<&fn(u64) -> Option<ClientOrderId>>,
1242        )
1243        .unwrap();
1244
1245        assert_eq!(report.cancel_reason, Some("risk blocked".to_string()));
1246    }
1247
1248    #[rstest]
1249    fn test_parse_order_detail_status_report_without_reason_leaves_cancel_reason_unset() {
1250        let instrument = parse_instrument(
1251            &create_eurusd_instrument(),
1252            UnixNanos::default(),
1253            UnixNanos::default(),
1254        )
1255        .unwrap();
1256        let order = create_order_detail(AxOrderStatus::Filled, None, None);
1257
1258        let report = parse_order_detail_status_report(
1259            &order,
1260            AccountId::from("AX-001"),
1261            &instrument,
1262            UnixNanos::default(),
1263            None::<&fn(u64) -> Option<ClientOrderId>>,
1264        )
1265        .unwrap();
1266
1267        assert_eq!(report.cancel_reason, None);
1268    }
1269
1270    fn create_risk_snapshot() -> AxRiskSnapshot {
1271        AxRiskSnapshot {
1272            account_id: Ustr::from("account-1"),
1273            timestamp_ns: "2024-01-15T10:30:00Z".parse::<Timestamp>().unwrap(),
1274            balance_usd: dec!(100000.50),
1275            equity: dec!(102500.75),
1276            initial_margin_available: dec!(95500.75),
1277            initial_margin_required_for_open_orders: dec!(2000.00),
1278            initial_margin_required_for_positions: dec!(5000.00),
1279            initial_margin_required_total: dec!(7000.00),
1280            maintenance_margin_available: dec!(99000.75),
1281            maintenance_margin_required: dec!(3500.00),
1282            unrealized_pnl: dec!(2500.25),
1283            per_symbol: Default::default(),
1284        }
1285    }
1286
1287    fn create_balances_response() -> AxBalancesResponse {
1288        AxBalancesResponse {
1289            usd_borrow: None,
1290            balances: vec![
1291                AxBalance {
1292                    account_id: None,
1293                    symbol: Ustr::from("USD"),
1294                    amount: dec!(100000.50),
1295                },
1296                AxBalance {
1297                    account_id: None,
1298                    symbol: Ustr::from("BTC"),
1299                    amount: dec!(1.25),
1300                },
1301            ],
1302        }
1303    }
1304
1305    #[rstest]
1306    fn test_parse_account_state_applies_risk_snapshot_margins() {
1307        let risk = create_risk_snapshot();
1308        let state = parse_account_state(
1309            &create_balances_response(),
1310            Some(&risk),
1311            AccountId::from("AX-001"),
1312            UnixNanos::default(),
1313            UnixNanos::default(),
1314        )
1315        .unwrap();
1316
1317        let usd = state
1318            .balances
1319            .iter()
1320            .find(|b| b.total.currency == Currency::USD())
1321            .unwrap();
1322        assert_eq!(usd.locked.as_decimal(), dec!(7000.00));
1323        assert_eq!(usd.free.as_decimal(), dec!(93000.50));
1324
1325        let btc = state
1326            .balances
1327            .iter()
1328            .find(|b| b.total.currency.code.as_str() == "BTC")
1329            .unwrap();
1330        assert_eq!(btc.locked.as_decimal(), Decimal::ZERO);
1331        assert_eq!(btc.free.as_decimal(), dec!(1.25));
1332
1333        assert_eq!(state.margins.len(), 1);
1334        assert_eq!(state.margins[0].initial.as_decimal(), dec!(7000.00));
1335        assert_eq!(state.margins[0].maintenance.as_decimal(), dec!(3500.00));
1336        assert_eq!(state.margins[0].currency, Currency::USD());
1337    }
1338
1339    #[rstest]
1340    fn test_parse_account_state_without_risk_snapshot_locks_zero() {
1341        let state = parse_account_state(
1342            &create_balances_response(),
1343            None,
1344            AccountId::from("AX-001"),
1345            UnixNanos::default(),
1346            UnixNanos::default(),
1347        )
1348        .unwrap();
1349
1350        let usd = state
1351            .balances
1352            .iter()
1353            .find(|b| b.total.currency == Currency::USD())
1354            .unwrap();
1355        assert_eq!(usd.locked.as_decimal(), Decimal::ZERO);
1356        assert_eq!(usd.free.as_decimal(), dec!(100000.50));
1357        assert!(state.margins.is_empty());
1358    }
1359
1360    #[rstest]
1361    fn test_parse_account_state_clamps_locked_to_balance() {
1362        let mut risk = create_risk_snapshot();
1363        risk.initial_margin_required_total = dec!(500000.00);
1364        let state = parse_account_state(
1365            &create_balances_response(),
1366            Some(&risk),
1367            AccountId::from("AX-001"),
1368            UnixNanos::default(),
1369            UnixNanos::default(),
1370        )
1371        .unwrap();
1372
1373        let usd = state
1374            .balances
1375            .iter()
1376            .find(|b| b.total.currency == Currency::USD())
1377            .unwrap();
1378        assert_eq!(usd.locked.as_decimal(), dec!(100000.50));
1379        assert_eq!(usd.free.as_decimal(), Decimal::ZERO);
1380    }
1381
1382    #[rstest]
1383    fn test_parse_account_state_negative_balance_preserves_locked() {
1384        // A borrowed balance keeps the raw margin requirement and carries the shortfall in free
1385        let mut balances = create_balances_response();
1386        balances.balances[0].amount = dec!(-500.00);
1387
1388        let state = parse_account_state(
1389            &balances,
1390            Some(&create_risk_snapshot()),
1391            AccountId::from("AX-001"),
1392            UnixNanos::default(),
1393            UnixNanos::default(),
1394        )
1395        .unwrap();
1396
1397        let usd = state
1398            .balances
1399            .iter()
1400            .find(|b| b.total.currency == Currency::USD())
1401            .unwrap();
1402        assert_eq!(usd.total.as_decimal(), dec!(-500.00));
1403        assert_eq!(usd.locked.as_decimal(), dec!(7000.00));
1404        assert_eq!(usd.free.as_decimal(), dec!(-7500.00));
1405    }
1406
1407    #[rstest]
1408    fn test_parse_order_status_report_uses_cid_resolver() {
1409        let instrument = parse_instrument(
1410            &create_eurusd_instrument(),
1411            UnixNanos::default(),
1412            UnixNanos::default(),
1413        )
1414        .unwrap();
1415        let order = AxOpenOrder {
1416            aid: None,
1417            r: None,
1418            txt: None,
1419            tn: 0,
1420            ts: 1_609_459_200,
1421            d: AxOrderSide::Buy,
1422            o: AxOrderStatus::Accepted,
1423            oid: "O-NEW".to_string(),
1424            p: dec!(1.0845),
1425            q: 100,
1426            rq: 100,
1427            s: Ustr::from("EURUSD-PERP"),
1428            tif: AxTimeInForce::Gtc,
1429            u: Ustr::from("user"),
1430            xq: 0,
1431            cid: Some(42),
1432            tag: None,
1433            po: true,
1434            rb: None,
1435        };
1436        let expected_client_order_id = ClientOrderId::from("O-PERSISTED");
1437        let resolver = |cid| (cid == 42).then_some(expected_client_order_id);
1438
1439        let report = parse_order_status_report(
1440            &order,
1441            AccountId::from("AX-001"),
1442            &instrument,
1443            UnixNanos::default(),
1444            Some(&resolver),
1445        )
1446        .unwrap();
1447
1448        assert_eq!(report.client_order_id, Some(expected_client_order_id));
1449        assert_eq!(report.venue_order_id, VenueOrderId::from("O-NEW"));
1450    }
1451
1452    #[rstest]
1453    #[case(Some(false), Some(false))]
1454    #[case(None, Some(false))]
1455    #[case(Some(false), None)]
1456    #[case(None, None)]
1457    fn test_parse_fill_report_uses_real_order_id_for_regular_fill(
1458        #[case] is_block_trade: Option<bool>,
1459        #[case] is_final_settlement: Option<bool>,
1460    ) {
1461        let instrument = parse_instrument(
1462            &create_eurusd_instrument(),
1463            UnixNanos::default(),
1464            UnixNanos::default(),
1465        )
1466        .unwrap();
1467        let mut fill = create_fill();
1468        fill.is_block_trade = is_block_trade;
1469        fill.is_final_settlement = is_final_settlement;
1470
1471        let report = parse_fill_report(
1472            &fill,
1473            AccountId::from("AX-001"),
1474            &instrument,
1475            UnixNanos::default(),
1476        )
1477        .unwrap();
1478
1479        assert_eq!(
1480            report.venue_order_id.as_str(),
1481            "O-01ARZ3NDEKTSV4RRFFQ69G5FAV"
1482        );
1483    }
1484
1485    #[rstest]
1486    fn test_parse_fill_report_rounds_sub_cent_fee_to_usd_precision() {
1487        let instrument = parse_instrument(
1488            &create_eurusd_instrument(),
1489            UnixNanos::default(),
1490            UnixNanos::default(),
1491        )
1492        .unwrap();
1493        let mut fill = create_fill();
1494        fill.fee = dec!(0.012188);
1495
1496        let report = parse_fill_report(
1497            &fill,
1498            AccountId::from("AX-001"),
1499            &instrument,
1500            UnixNanos::default(),
1501        )
1502        .unwrap();
1503
1504        assert_eq!(report.commission, Money::from("0.01 USD"));
1505    }
1506
1507    #[rstest]
1508    fn test_parse_fill_report_rejects_unrepresentable_fee() {
1509        let instrument = parse_instrument(
1510            &create_eurusd_instrument(),
1511            UnixNanos::default(),
1512            UnixNanos::default(),
1513        )
1514        .unwrap();
1515        let mut fill = create_fill();
1516        fill.fee = dec!(9999999999999999999999999999);
1517
1518        let error = parse_fill_report(
1519            &fill,
1520            AccountId::from("AX-001"),
1521            &instrument,
1522            UnixNanos::default(),
1523        )
1524        .unwrap_err();
1525
1526        assert!(
1527            error
1528                .to_string()
1529                .contains("Failed to convert fill.fee Decimal to Money"),
1530            "expected fee conversion failure, was {error}"
1531        );
1532    }
1533
1534    #[rstest]
1535    #[case(None)]
1536    #[case(Some("O-01ARZ3NDEKTSV4RRFFQ69G5FAV"))]
1537    fn test_parse_fill_report_uses_stable_surrogate_for_block_fill(#[case] order_id: Option<&str>) {
1538        let instrument = parse_instrument(
1539            &create_eurusd_instrument(),
1540            UnixNanos::default(),
1541            UnixNanos::default(),
1542        )
1543        .unwrap();
1544        let mut fill = create_fill();
1545        fill.order_id = order_id.map(str::to_string);
1546        fill.is_block_trade = Some(true);
1547
1548        let report = parse_fill_report(
1549            &fill,
1550            AccountId::from("AX-001"),
1551            &instrument,
1552            UnixNanos::default(),
1553        )
1554        .unwrap();
1555
1556        assert_eq!(
1557            report.venue_order_id.as_str(),
1558            "AX-FILL-T-01ARZ3NDEKTSV4RRFFQ69G5FAV"
1559        );
1560    }
1561
1562    #[rstest]
1563    fn test_parse_fill_report_uses_stable_surrogate_for_final_settlement() {
1564        let instrument = parse_instrument(
1565            &create_eurusd_instrument(),
1566            UnixNanos::default(),
1567            UnixNanos::default(),
1568        )
1569        .unwrap();
1570        let mut fill = create_fill();
1571        fill.order_id = None;
1572        fill.is_block_trade = Some(true);
1573        fill.is_final_settlement = Some(true);
1574
1575        let report = parse_fill_report(
1576            &fill,
1577            AccountId::from("AX-001"),
1578            &instrument,
1579            UnixNanos::default(),
1580        )
1581        .unwrap();
1582
1583        assert_eq!(
1584            report.venue_order_id.as_str(),
1585            "AX-FILL-T-01ARZ3NDEKTSV4RRFFQ69G5FAV"
1586        );
1587    }
1588
1589    #[rstest]
1590    fn test_parse_fill_report_rejects_final_settlement_without_block_classification() {
1591        let instrument = parse_instrument(
1592            &create_eurusd_instrument(),
1593            UnixNanos::default(),
1594            UnixNanos::default(),
1595        )
1596        .unwrap();
1597        let mut fill = create_fill();
1598        fill.is_block_trade = Some(false);
1599        fill.is_final_settlement = Some(true);
1600
1601        let error = parse_fill_report(
1602            &fill,
1603            AccountId::from("AX-001"),
1604            &instrument,
1605            UnixNanos::default(),
1606        )
1607        .unwrap_err();
1608
1609        assert_eq!(
1610            error.to_string(),
1611            "AX final-settlement fill must also be classified as a block trade"
1612        );
1613    }
1614
1615    #[rstest]
1616    #[case::missing_classification(None, None)]
1617    #[case::regular_fill(Some(false), Some(false))]
1618    fn test_parse_fill_report_rejects_missing_order_id(
1619        #[case] is_block_trade: Option<bool>,
1620        #[case] is_final_settlement: Option<bool>,
1621    ) {
1622        let instrument = parse_instrument(
1623            &create_eurusd_instrument(),
1624            UnixNanos::default(),
1625            UnixNanos::default(),
1626        )
1627        .unwrap();
1628        let mut fill = create_fill();
1629        fill.order_id = None;
1630        fill.is_block_trade = is_block_trade;
1631        fill.is_final_settlement = is_final_settlement;
1632
1633        let error = parse_fill_report(
1634            &fill,
1635            AccountId::from("AX-001"),
1636            &instrument,
1637            UnixNanos::default(),
1638        )
1639        .unwrap_err();
1640
1641        assert_eq!(
1642            error.to_string(),
1643            "AX fill is missing order_id and explicit special-fill classification"
1644        );
1645    }
1646
1647    #[rstest]
1648    #[case("")]
1649    #[case(" ")]
1650    #[case("O-α")]
1651    fn test_parse_fill_report_rejects_invalid_regular_order_id(#[case] order_id: &str) {
1652        let instrument = parse_instrument(
1653            &create_eurusd_instrument(),
1654            UnixNanos::default(),
1655            UnixNanos::default(),
1656        )
1657        .unwrap();
1658        let mut fill = create_fill();
1659        fill.order_id = Some(order_id.to_string());
1660        fill.is_block_trade = None;
1661        fill.is_final_settlement = None;
1662
1663        let result = parse_fill_report(
1664            &fill,
1665            AccountId::from("AX-001"),
1666            &instrument,
1667            UnixNanos::default(),
1668        );
1669
1670        assert!(result.is_err());
1671    }
1672
1673    #[rstest]
1674    fn test_parse_fx_instrument() {
1675        let definition = create_eurusd_instrument();
1676        let ts_now = UnixNanos::default();
1677
1678        let result = parse_instrument(&definition, ts_now, ts_now);
1679        assert!(result.is_ok());
1680
1681        let instrument = result.unwrap();
1682        match instrument {
1683            InstrumentAny::PerpetualContract(perp) => {
1684                assert_eq!(perp.id.symbol.as_str(), "EURUSD-PERP");
1685                assert_eq!(perp.id.venue, *AX_VENUE);
1686                assert_eq!(perp.underlying, "EURUSD");
1687                assert_eq!(perp.asset_class, AssetClass::FX);
1688                assert_eq!(perp.base_currency.unwrap().code, "EUR");
1689                assert_eq!(perp.quote_currency.code, "USD");
1690                assert_eq!(perp.settlement_currency.code, "USD");
1691                assert_eq!(perp.price_precision, 4);
1692                assert_eq!(perp.size_increment.as_decimal(), Decimal::ONE);
1693                assert_eq!(perp.lot_size.as_decimal(), Decimal::ONE);
1694                assert_eq!(perp.min_quantity.unwrap().as_decimal(), dec!(100));
1695                assert_eq!(perp.margin_init, dec!(0.08));
1696                assert_eq!(perp.margin_maint, dec!(0.04));
1697                let info = perp.info.as_ref().unwrap();
1698                assert_eq!(info["initial_margin_pct"], json!("8.0"));
1699                assert_eq!(info["maintenance_margin_pct"], json!("4.0"));
1700                assert_eq!(
1701                    info["quantity_increment_source"],
1702                    json!("integer_contract_wire_quantity")
1703                );
1704                assert!(!perp.is_inverse);
1705            }
1706            _ => panic!("Expected PerpetualContract instrument"),
1707        }
1708    }
1709
1710    #[rstest]
1711    fn test_parse_equity_instrument() {
1712        let definition = create_nvda_instrument();
1713        let ts_now = UnixNanos::default();
1714
1715        let result = parse_instrument(&definition, ts_now, ts_now);
1716        assert!(result.is_ok());
1717
1718        let instrument = result.unwrap();
1719        match instrument {
1720            InstrumentAny::PerpetualContract(perp) => {
1721                assert_eq!(perp.id.symbol.as_str(), "NVDA-PERP");
1722                assert_eq!(perp.id.venue, *AX_VENUE);
1723                assert_eq!(perp.underlying, "NVDA");
1724                assert_eq!(perp.asset_class, AssetClass::Equity);
1725                assert_eq!(perp.quote_currency.code, "USD");
1726                assert_eq!(perp.settlement_currency.code, "USD");
1727                assert_eq!(perp.price_precision, 2);
1728                assert!(!perp.is_inverse);
1729            }
1730            _ => panic!("Expected PerpetualContract instrument"),
1731        }
1732    }
1733
1734    #[rstest]
1735    fn test_parse_metals_instrument() {
1736        let definition = create_xau_instrument();
1737        let ts_now = UnixNanos::default();
1738
1739        let result = parse_instrument(&definition, ts_now, ts_now);
1740        let instrument = result.unwrap();
1741        match instrument {
1742            InstrumentAny::PerpetualContract(perp) => {
1743                assert_eq!(perp.id.symbol.as_str(), "XAU-PERP");
1744                assert_eq!(perp.underlying, "XAU");
1745                assert_eq!(perp.asset_class, AssetClass::Commodity);
1746                assert!(perp.base_currency.is_none());
1747                assert_eq!(perp.quote_currency.code, "USD");
1748                assert_eq!(perp.price_precision, 1);
1749            }
1750            _ => panic!("Expected PerpetualContract instrument"),
1751        }
1752    }
1753
1754    #[rstest]
1755    fn test_parse_current_dated_instruments() {
1756        let test_data = include_str!("../../test_data/http_get_dated_instruments.json");
1757        let response: AxInstrumentsResponse = serde_json::from_str(test_data).unwrap();
1758        let ts_now = UnixNanos::default();
1759
1760        let instruments = response
1761            .instruments
1762            .iter()
1763            .map(|definition| parse_instrument(definition, ts_now, ts_now).unwrap())
1764            .collect::<Vec<_>>();
1765
1766        assert_eq!(instruments.len(), 2);
1767        for (instrument, expected_symbol, expected_expiration) in [
1768            (&instruments[0], "XAU-2026-SEP", "2026-09-30T15:00:00Z"),
1769            (&instruments[1], "XAU-2026-DEC", "2026-12-31T16:00:00Z"),
1770        ] {
1771            let InstrumentAny::FuturesContract(future) = instrument else {
1772                panic!("Expected FuturesContract instrument");
1773            };
1774            let expected_expiration_ns = u64::try_from(
1775                expected_expiration
1776                    .parse::<Timestamp>()
1777                    .unwrap()
1778                    .as_nanosecond(),
1779            )
1780            .unwrap();
1781            let info = future.info.as_ref().unwrap();
1782
1783            assert_eq!(future.id.symbol.as_str(), expected_symbol);
1784            assert_eq!(future.id.venue, *AX_VENUE);
1785            assert_eq!(future.underlying, Ustr::from("XAU"));
1786            assert_eq!(future.asset_class, AssetClass::Commodity);
1787            assert_eq!(future.activation_ns, UnixNanos::default());
1788            assert_eq!(
1789                future.expiration_ns,
1790                UnixNanos::from(expected_expiration_ns)
1791            );
1792            assert_eq!(future.currency.code, "USD");
1793            assert_eq!(future.price_increment.as_decimal(), dec!(0.1));
1794            assert_eq!(future.size_increment.as_decimal(), Decimal::ONE);
1795            assert_eq!(future.lot_size.as_decimal(), Decimal::ONE);
1796            assert_eq!(future.min_quantity.unwrap().as_decimal(), Decimal::ONE);
1797            assert_eq!(future.multiplier.as_decimal(), Decimal::ONE);
1798            assert_eq!(future.margin_init, dec!(0.125));
1799            assert_eq!(future.margin_maint, dec!(0.075));
1800            assert_eq!(info["product"], json!("XAU"));
1801            assert_eq!(
1802                info["expiration"],
1803                json!(expected_expiration.replace('Z', "+00:00"))
1804            );
1805            assert_eq!(info["activation_source"], json!("unavailable_from_ax"));
1806            assert_eq!(
1807                info["quantity_increment_source"],
1808                json!("integer_contract_wire_quantity")
1809            );
1810            assert_eq!(info["initial_margin_pct"], json!("12.5"));
1811            assert_eq!(info["maintenance_margin_pct"], json!("7.5"));
1812        }
1813    }
1814
1815    #[rstest]
1816    fn test_parse_dated_instrument_keeps_numeric_fields_distinct() {
1817        let test_data = include_str!("../../test_data/http_get_dated_instruments.json");
1818        let mut response: AxInstrumentsResponse = serde_json::from_str(test_data).unwrap();
1819        let definition = &mut response.instruments[0];
1820        definition.multiplier = dec!(2.5);
1821        definition.minimum_order_size = dec!(5);
1822
1823        let instrument =
1824            parse_instrument(definition, UnixNanos::default(), UnixNanos::default()).unwrap();
1825        let InstrumentAny::FuturesContract(future) = instrument else {
1826            panic!("Expected FuturesContract instrument");
1827        };
1828
1829        assert_eq!(future.size_increment.as_decimal(), Decimal::ONE);
1830        assert_eq!(future.lot_size.as_decimal(), Decimal::ONE);
1831        assert_eq!(future.min_quantity.unwrap().as_decimal(), dec!(5));
1832        assert_eq!(future.multiplier.as_decimal(), dec!(2.5));
1833    }
1834
1835    #[rstest]
1836    fn test_parse_perpetual_instrument_preserves_multiplier() {
1837        let mut definition = create_eurusd_instrument();
1838        definition.multiplier = dec!(2.5);
1839        let instrument =
1840            parse_instrument(&definition, UnixNanos::default(), UnixNanos::default()).unwrap();
1841
1842        assert_eq!(instrument.multiplier().as_decimal(), dec!(2.5));
1843        assert_eq!(instrument.size_increment().as_decimal(), Decimal::ONE);
1844    }
1845
1846    #[rstest]
1847    fn test_parse_perpetual_instrument_rejects_zero_multiplier() {
1848        let mut definition = create_eurusd_instrument();
1849        definition.multiplier = Decimal::ZERO;
1850        let error =
1851            parse_instrument(&definition, UnixNanos::default(), UnixNanos::default()).unwrap_err();
1852
1853        assert_eq!(
1854            error.to_string(),
1855            "failed to construct AX perpetual contract"
1856        );
1857    }
1858
1859    #[rstest]
1860    fn test_parse_dated_instrument_without_product_uses_symbol_fallback() {
1861        let test_data = include_str!("../../test_data/http_get_dated_instruments.json");
1862        let mut response: AxInstrumentsResponse = serde_json::from_str(test_data).unwrap();
1863        let definition = &mut response.instruments[0];
1864        definition.product = None;
1865
1866        let instrument =
1867            parse_instrument(definition, UnixNanos::default(), UnixNanos::default()).unwrap();
1868        let InstrumentAny::FuturesContract(future) = instrument else {
1869            panic!("Expected FuturesContract instrument");
1870        };
1871
1872        assert_eq!(future.underlying, Ustr::from("XAU"));
1873    }
1874
1875    #[rstest]
1876    fn test_parse_instrument_rejects_blank_product() {
1877        let mut definition = create_xau_instrument();
1878        definition.product = Some(Ustr::from(" "));
1879
1880        let result = parse_instrument(&definition, UnixNanos::default(), UnixNanos::default());
1881
1882        assert!(result.is_err());
1883    }
1884
1885    #[rstest]
1886    #[case(Decimal::ZERO)]
1887    #[case(dec!(-1))]
1888    #[case(dec!(1.5))]
1889    fn test_parse_instrument_rejects_invalid_minimum_order_size(
1890        #[case] minimum_order_size: Decimal,
1891    ) {
1892        let mut definition = create_xau_instrument();
1893        definition.minimum_order_size = minimum_order_size;
1894
1895        let result = parse_instrument(&definition, UnixNanos::default(), UnixNanos::default());
1896
1897        assert!(result.is_err());
1898    }
1899
1900    #[rstest]
1901    fn test_parse_dated_instrument_rejects_currency_mismatch() {
1902        let test_data = include_str!("../../test_data/http_get_dated_instruments.json");
1903        let mut response: AxInstrumentsResponse = serde_json::from_str(test_data).unwrap();
1904        let definition = &mut response.instruments[0];
1905        definition.funding_settlement_currency = Ustr::from("EUR");
1906
1907        let result = parse_instrument(definition, UnixNanos::default(), UnixNanos::default());
1908
1909        assert!(result.is_err());
1910    }
1911
1912    #[rstest]
1913    fn test_parse_settlement_differs_from_quote() {
1914        let mut definition = create_eurusd_instrument();
1915        definition.funding_settlement_currency = Ustr::from("EUR");
1916        let ts_now = UnixNanos::default();
1917
1918        let result = parse_instrument(&definition, ts_now, ts_now);
1919        let instrument = result.unwrap();
1920        match instrument {
1921            InstrumentAny::PerpetualContract(perp) => {
1922                assert_eq!(perp.quote_currency.code, "USD");
1923                assert_eq!(perp.settlement_currency.code, "EUR");
1924            }
1925            _ => panic!("Expected PerpetualContract instrument"),
1926        }
1927    }
1928
1929    #[rstest]
1930    fn test_margin_percent_to_rate_preserves_exact_scale() {
1931        let value = Decimal::from_i128_with_scale(1, 26);
1932        let result = margin_percent_to_rate(value, "test").unwrap();
1933
1934        assert_eq!(result.mantissa(), 1);
1935        assert_eq!(result.scale(), 28);
1936    }
1937
1938    #[rstest]
1939    fn test_margin_percent_to_rate_normalizes_trailing_zero() {
1940        let value = Decimal::from_i128_with_scale(10, 27);
1941        let result = margin_percent_to_rate(value, "test").unwrap();
1942
1943        assert_eq!(result.mantissa(), 1);
1944        assert_eq!(result.scale(), 28);
1945    }
1946
1947    #[rstest]
1948    fn test_margin_percent_to_rate_rejects_unrepresentable_scale() {
1949        let value = Decimal::from_i128_with_scale(1, 27);
1950        let result = margin_percent_to_rate(value, "test");
1951
1952        assert!(result.is_err());
1953    }
1954
1955    #[rstest]
1956    #[case(Decimal::ZERO, dec!(1))]
1957    #[case(dec!(-1), dec!(1))]
1958    #[case(dec!(1), Decimal::ZERO)]
1959    #[case(dec!(1), dec!(-1))]
1960    #[case(dec!(4), dec!(8))]
1961    fn test_parse_margin_rates_rejects_invalid_values(
1962        #[case] initial_margin_pct: Decimal,
1963        #[case] maintenance_margin_pct: Decimal,
1964    ) {
1965        let result = parse_margin_rates(initial_margin_pct, maintenance_margin_pct);
1966
1967        assert!(result.is_err());
1968    }
1969
1970    #[rstest]
1971    fn test_parse_unknown_category_falls_back_to_alternative() {
1972        let mut definition = create_eurusd_instrument();
1973        definition.category = AxCategory::Unknown;
1974        let ts_now = UnixNanos::default();
1975
1976        let result = parse_instrument(&definition, ts_now, ts_now);
1977        let instrument = result.unwrap();
1978        match instrument {
1979            InstrumentAny::PerpetualContract(perp) => {
1980                assert_eq!(perp.asset_class, AssetClass::Alternative);
1981            }
1982            _ => panic!("Expected PerpetualContract instrument"),
1983        }
1984    }
1985
1986    #[rstest]
1987    fn test_parse_all_instruments_from_test_data() {
1988        let test_data = include_str!("../../test_data/http_get_instruments.json");
1989        let response: AxInstrumentsResponse =
1990            serde_json::from_str(test_data).expect("Failed to deserialize test data");
1991
1992        let ts_now = UnixNanos::default();
1993
1994        let open_instruments: Vec<_> = response
1995            .instruments
1996            .iter()
1997            .filter(|i| i.state == AxInstrumentState::Open)
1998            .collect();
1999
2000        assert_eq!(open_instruments.len(), 3);
2001
2002        for instrument in open_instruments {
2003            let result = parse_instrument(instrument, ts_now, ts_now);
2004            assert!(
2005                result.is_ok(),
2006                "Failed to parse {}: {:?}",
2007                instrument.symbol,
2008                result.err()
2009            );
2010        }
2011    }
2012
2013    fn create_rest_trade() -> AxRestTrade {
2014        AxRestTrade {
2015            ts: 1_766_193_240,
2016            tn: 334_589_144,
2017            p: dec!(1.1719),
2018            q: 400,
2019            s: Ustr::from("EURUSD-PERP"),
2020            d: AxOrderSide::Buy,
2021        }
2022    }
2023
2024    #[rstest]
2025    fn test_parse_trade_tick_derives_trade_id_from_timestamp_and_content() {
2026        let instrument = parse_instrument(
2027            &create_eurusd_instrument(),
2028            UnixNanos::default(),
2029            UnixNanos::default(),
2030        )
2031        .unwrap();
2032        let trade = create_rest_trade();
2033
2034        let tick = parse_trade_tick(&trade, &instrument, UnixNanos::from(7u64)).unwrap();
2035
2036        assert_eq!(tick.instrument_id, instrument.id());
2037        assert_eq!(
2038            tick.trade_id.to_string(),
2039            "1766193240334589144-38b4fe5a94a253d0"
2040        );
2041        assert_eq!(tick.price, Price::from("1.1719"));
2042        assert_eq!(tick.size, Quantity::from(400));
2043        assert_eq!(tick.aggressor_side, AggressorSide::Buy);
2044        assert_eq!(tick.ts_event, UnixNanos::from(1_766_193_240_334_589_144u64));
2045        assert_eq!(tick.ts_init, UnixNanos::from(7u64));
2046    }
2047
2048    #[rstest]
2049    fn test_parse_trade_tick_separates_prints_within_one_timestamp() {
2050        // Two prints from one sweep share `ts` and `tn`, so only the content digest separates them
2051        let instrument = parse_instrument(
2052            &create_eurusd_instrument(),
2053            UnixNanos::default(),
2054            UnixNanos::default(),
2055        )
2056        .unwrap();
2057        let first = create_rest_trade();
2058        let mut second = create_rest_trade();
2059        second.p = dec!(1.1720);
2060        second.q = 100;
2061
2062        let first_tick = parse_trade_tick(&first, &instrument, UnixNanos::default()).unwrap();
2063        let second_tick = parse_trade_tick(&second, &instrument, UnixNanos::default()).unwrap();
2064
2065        assert_eq!(first_tick.ts_event, second_tick.ts_event);
2066        assert_ne!(first_tick.price, second_tick.price);
2067        assert_ne!(first_tick.size, second_tick.size);
2068        assert_ne!(first_tick.trade_id, second_tick.trade_id);
2069    }
2070
2071    #[rstest]
2072    fn test_parse_trade_tick_rejects_negative_timestamp() {
2073        let instrument = parse_instrument(
2074            &create_eurusd_instrument(),
2075            UnixNanos::default(),
2076            UnixNanos::default(),
2077        )
2078        .unwrap();
2079        let mut trade = create_rest_trade();
2080        trade.ts = -1;
2081
2082        let error = parse_trade_tick(&trade, &instrument, UnixNanos::default()).unwrap_err();
2083
2084        assert_eq!(
2085            error.to_string(),
2086            "AX timestamp must be non-negative, was -1"
2087        );
2088    }
2089
2090    #[rstest]
2091    fn test_deserialize_and_parse_funding_rates() {
2092        let test_data = include_str!("../../test_data/http_get_funding_rates.json");
2093        let response: AxFundingRatesResponse =
2094            serde_json::from_str(test_data).expect("Failed to deserialize test data");
2095
2096        assert_eq!(response.funding_rates.len(), 2);
2097        assert_eq!(response.funding_rates[0].symbol, "JPYUSD-PERP");
2098        assert_eq!(response.funding_rates[0].funding_rate, dec!(0.001234560000));
2099
2100        let instrument_id = InstrumentId::new(Symbol::new("JPYUSD-PERP"), *AX_VENUE);
2101        let ts_init = UnixNanos::from(1_000_000_000u64);
2102
2103        let update =
2104            parse_funding_rate(&response.funding_rates[1], instrument_id, ts_init).unwrap();
2105
2106        assert_eq!(update.instrument_id, instrument_id);
2107        assert_eq!(update.rate, dec!(0.003558290026));
2108        assert_eq!(update.next_funding_ns, None);
2109        assert_eq!(update.ts_event, UnixNanos::from(1770393600000000000u64));
2110        assert_eq!(update.ts_init, ts_init);
2111    }
2112
2113    #[rstest]
2114    #[case(true)]
2115    #[case(false)]
2116    fn test_order_reports_preserve_post_only_and_nanoseconds(#[case] post_only: bool) {
2117        let instrument = parse_instrument(
2118            &create_eurusd_instrument(),
2119            UnixNanos::default(),
2120            UnixNanos::default(),
2121        )
2122        .unwrap();
2123        let mut detail = create_order_detail(AxOrderStatus::Accepted, None, None);
2124        detail.po = post_only;
2125        detail.ts = 1700000000;
2126        detail.tn = 123456789;
2127        let open: AxOpenOrder =
2128            serde_json::from_value(serde_json::to_value(&detail).unwrap()).unwrap();
2129        let reports = [
2130            parse_order_detail_status_report(
2131                &detail,
2132                AccountId::from("AX-001"),
2133                &instrument,
2134                UnixNanos::default(),
2135                None::<&fn(u64) -> Option<ClientOrderId>>,
2136            )
2137            .unwrap(),
2138            parse_order_status_report(
2139                &open,
2140                AccountId::from("AX-001"),
2141                &instrument,
2142                UnixNanos::default(),
2143                None::<&fn(u64) -> Option<ClientOrderId>>,
2144            )
2145            .unwrap(),
2146        ];
2147
2148        for report in reports {
2149            assert_eq!(report.post_only, post_only);
2150            assert_eq!(report.ts_last, UnixNanos::from(1700000000123456789));
2151            assert_eq!(report.ts_accepted, UnixNanos::from(1700000000123456789));
2152            assert_eq!(report.quantity.as_decimal(), Decimal::from(detail.q));
2153            assert_eq!(report.filled_qty.as_decimal(), Decimal::from(detail.xq));
2154        }
2155    }
2156
2157    #[rstest]
2158    fn test_unknown_order_status_cannot_become_initialized_report() {
2159        let instrument = parse_instrument(
2160            &create_eurusd_instrument(),
2161            UnixNanos::default(),
2162            UnixNanos::default(),
2163        )
2164        .unwrap();
2165        let detail = create_order_detail(AxOrderStatus::Unknown, None, None);
2166        let error = parse_order_detail_status_report(
2167            &detail,
2168            AccountId::from("AX-001"),
2169            &instrument,
2170            UnixNanos::default(),
2171            None::<&fn(u64) -> Option<ClientOrderId>>,
2172        )
2173        .unwrap_err();
2174        assert_eq!(error.to_string(), "Unmapped AX order status");
2175    }
2176
2177    #[rstest]
2178    #[case::reduction(1, dec!(2) * dec!(100) - dec!(150), dec!(50))]
2179    #[case::short_reduction(-1, -dec!(2) * dec!(100) + dec!(150), dec!(50))]
2180    #[case::reversal(-1, dec!(2) * dec!(100) - dec!(3) * dec!(120), dec!(160))]
2181    #[case::short_reversal(1, -dec!(2) * dec!(100) + dec!(3) * dec!(120), dec!(160))]
2182    #[case::negative(1, dec!(-100), dec!(-100))]
2183    #[case::zero(1, dec!(0), dec!(0))]
2184    #[case::fraction(4, dec!(99), dec!(24.75))]
2185    #[case::flat(0, dec!(100), dec!(0))]
2186    fn test_position_ledger_average_contract(
2187        #[case] quantity: i64,
2188        #[case] basis: Decimal,
2189        #[case] expected: Decimal,
2190        #[values(false, true)] legacy_alias: bool,
2191    ) {
2192        let mut response: crate::http::models::AxPositionsResponse =
2193            serde_json::from_str(include_str!("../../test_data/http_get_positions.json")).unwrap();
2194        let position = &mut response.positions[0];
2195        position.signed_quantity = quantity;
2196
2197        position.signed_notional = if legacy_alias { basis } else { dec!(999) };
2198        position.signed_cost_basis = (!legacy_alias).then_some(basis);
2199        let instrument = parse_instrument(
2200            &create_eurusd_instrument(),
2201            UnixNanos::default(),
2202            UnixNanos::default(),
2203        )
2204        .unwrap();
2205        let result = parse_position_status_report(
2206            position,
2207            AccountId::from("AX-001"),
2208            &instrument,
2209            UnixNanos::default(),
2210        );
2211
2212        let report = result.unwrap();
2213        assert_eq!(report.avg_px_open, (quantity != 0).then_some(expected));
2214        assert_eq!(
2215            report.avg_px_open_reconciliation,
2216            AvgPxReconciliation::OpeningOnly
2217        );
2218        assert_eq!(report.avg_px_open_precision, None);
2219        assert_eq!(report.quantity.as_decimal(), Decimal::from(quantity).abs());
2220        assert_eq!(
2221            report.position_side,
2222            if quantity > 0 {
2223                PositionSide::Long
2224            } else if quantity < 0 {
2225                PositionSide::Short
2226            } else {
2227                PositionSide::Flat
2228            }
2229        );
2230    }
2231
2232    #[rstest]
2233    #[case(TimeInForce::Ioc, OrderStatus::Canceled)]
2234    #[case(TimeInForce::Fok, OrderStatus::Canceled)]
2235    #[case(TimeInForce::Gtc, OrderStatus::Expired)]
2236    #[case(TimeInForce::Day, OrderStatus::Expired)]
2237    fn test_expired_http_status_matches_websocket(
2238        #[case] tif: TimeInForce,
2239        #[case] expected: OrderStatus,
2240    ) {
2241        assert_eq!(
2242            parse_order_status(AxOrderStatus::Expired, tif).unwrap(),
2243            expected
2244        );
2245    }
2246    #[rstest]
2247    fn test_replaced_history_is_terminal() {
2248        let response: crate::http::models::AxOrdersResponse = serde_json::from_str(include_str!(
2249            "../../test_data/captured/history-replaced.json"
2250        ))
2251        .unwrap();
2252        let instrument = parse_instrument(
2253            &create_eurusd_instrument(),
2254            UnixNanos::default(),
2255            UnixNanos::default(),
2256        )
2257        .unwrap();
2258        let order = &response.orders[0];
2259        let report = parse_order_detail_status_report(
2260            order,
2261            AccountId::from("AX-001"),
2262            &instrument,
2263            UnixNanos::default(),
2264            None::<&fn(u64) -> Option<ClientOrderId>>,
2265        )
2266        .unwrap();
2267        assert_eq!(order.o, AxOrderStatus::Replaced);
2268        assert_eq!(report.order_status, OrderStatus::Canceled);
2269        assert!(report.order_status.is_closed());
2270        assert_eq!(report.filled_qty.as_decimal(), dec!(0));
2271        assert_eq!(report.venue_order_id.as_str(), order.oid);
2272    }
2273}