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