Skip to main content

nautilus_derive/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//! HTTP response parsing utilities for the Derive execution client.
17
18use anyhow::Context;
19#[cfg(test)]
20use nautilus_core::string::secret::SecretString;
21use nautilus_core::{Params, UUID4, UnixNanos, datetime::NANOSECONDS_IN_MILLISECOND};
22use nautilus_model::{
23    enums::{AvgPxReconciliation, LiquiditySide, OrderType, PositionSide},
24    identifiers::{AccountId, ClientOrderId, InstrumentId, TradeId, VenueOrderId},
25    reports::{FillReport, OrderStatusReport, PositionStatusReport},
26    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
27};
28use rust_decimal::Decimal;
29use serde_json::Value;
30use thiserror::Error;
31
32use crate::{
33    common::{
34        enums::{
35            DeriveInstrumentType, DeriveLiquidityRole, DeriveOrderSide, DeriveOrderStatus,
36            DeriveOrderType, DeriveTimeInForce, DeriveTriggerType,
37        },
38        parse::{
39            derive_order_side_to_nautilus, derive_order_type_to_nautilus_for_order,
40            derive_rejection_due_post_only, derive_status_to_nautilus, derive_tif_to_nautilus,
41            derive_trigger_price_type_to_nautilus, format_instrument_id, strategy_rejection_reason,
42        },
43    },
44    http::models::{DeriveOrder, DerivePosition, DeriveSubaccount, DeriveTrade},
45};
46
47/// Builds an [`OrderStatusReport`] from a Derive order record.
48///
49/// `client_order_id` is sourced from the `label` field on the order when the
50/// label is a valid Nautilus identifier; callers that need a specific client_order_id should
51/// override via `with_client_order_id` after this call.
52/// Trailing zero padding is removed without changing the value.
53///
54/// # Errors
55///
56/// Returns an error if the venue order identifier is invalid or the amount or filled amount cannot
57/// be converted to a Nautilus `Quantity`.
58pub fn parse_derive_order_to_report(
59    order: &DeriveOrder,
60    account_id: AccountId,
61    ts_init: UnixNanos,
62) -> anyhow::Result<OrderStatusReport> {
63    parse_derive_order_to_report_with_precision(order, account_id, None, None, ts_init)
64}
65
66pub(crate) fn parse_derive_order_to_report_with_precision(
67    order: &DeriveOrder,
68    account_id: AccountId,
69    price_precision: Option<u8>,
70    size_precision: Option<u8>,
71    ts_init: UnixNanos,
72) -> anyhow::Result<OrderStatusReport> {
73    let instrument_id = format_instrument_id(order.instrument_name)?;
74    let venue_order_id =
75        VenueOrderId::new_checked(order.order_id.as_str()).context("invalid Derive order_id")?;
76    let order_side = derive_order_side_to_nautilus(order.direction);
77    let order_type = derive_order_type_to_nautilus_for_report(order)?;
78    let post_only = matches!(order.time_in_force, DeriveTimeInForce::PostOnly);
79    let time_in_force = derive_tif_to_nautilus(order.time_in_force)?;
80    let order_status =
81        derive_status_to_nautilus(order.order_status, order.filled_amount, order.amount)?;
82    let quantity = quantity_from_decimal(order.amount, size_precision, "amount")?;
83    let filled_qty = quantity_from_decimal(order.filled_amount, size_precision, "filled_amount")?;
84
85    let ts_accepted = ms_to_nanos(order.creation_timestamp);
86    let ts_last = ms_to_nanos(order.last_update_timestamp);
87
88    let mut report = OrderStatusReport::new(
89        account_id,
90        instrument_id,
91        None,
92        venue_order_id,
93        order_side.into(),
94        order_type,
95        time_in_force,
96        order_status,
97        quantity,
98        filled_qty,
99        ts_accepted,
100        ts_last,
101        ts_init,
102        Some(UUID4::new()),
103    );
104
105    if let Some(client_order_id) =
106        parse_client_order_id(order.label.as_str(), venue_order_id, instrument_id)
107    {
108        report = report.with_client_order_id(client_order_id);
109    }
110
111    if order_type_has_limit_price(order_type) {
112        anyhow::ensure!(
113            order.limit_price > Decimal::ZERO,
114            "Derive limit_price must be positive"
115        );
116        report = report.with_price(price_from_decimal(
117            order.limit_price,
118            price_precision,
119            "limit_price",
120        )?);
121    }
122
123    if let Some(trigger_price) = order.trigger_price {
124        anyhow::ensure!(
125            trigger_price > Decimal::ZERO,
126            "Derive trigger_price must be positive"
127        );
128        report = report.with_trigger_price(price_from_decimal(
129            trigger_price,
130            price_precision,
131            "trigger_price",
132        )?);
133    }
134
135    if let Some(trigger_price_type) = order.trigger_price_type {
136        report =
137            report.with_trigger_type(derive_trigger_price_type_to_nautilus(trigger_price_type)?);
138    }
139
140    if order.average_price > Decimal::ZERO {
141        report.avg_px = Some(order.average_price);
142    }
143
144    report.post_only = post_only;
145    let trigger_reject_message = order
146        .trigger_reject_message
147        .as_deref()
148        .filter(|message| !message.is_empty())
149        .map(str::to_string);
150    let cancel_reason = trigger_reject_message
151        .clone()
152        .unwrap_or_else(|| order.cancel_reason.to_string());
153    if order.order_status == DeriveOrderStatus::Cancelled
154        || (order.order_status == DeriveOrderStatus::Rejected
155            && (trigger_reject_message.is_some()
156                || derive_rejection_due_post_only(None, &cancel_reason)))
157    {
158        report.cancel_reason = Some(if order.order_status == DeriveOrderStatus::Rejected {
159            log::debug!(
160                "Derive native rejection for {}: {cancel_reason}",
161                order.order_id
162            );
163            strategy_rejection_reason(&cancel_reason)
164        } else {
165            cancel_reason
166        });
167    }
168
169    Ok(report)
170}
171
172fn order_type_has_limit_price(order_type: OrderType) -> bool {
173    matches!(
174        order_type,
175        OrderType::Limit | OrderType::StopLimit | OrderType::LimitIfTouched
176    )
177}
178
179fn derive_order_type_to_nautilus_for_report(order: &DeriveOrder) -> anyhow::Result<OrderType> {
180    let order_type = derive_order_type_to_nautilus_for_order(order.order_type, order.trigger_type)?;
181    if order_type != OrderType::LimitIfTouched {
182        return Ok(order_type);
183    }
184
185    Ok(
186        match (order.order_type, order.trigger_type, order.trigger_price) {
187            (DeriveOrderType::Limit, Some(DeriveTriggerType::Takeprofit), Some(trigger_price))
188                if !limit_if_touched_prices_are_valid(
189                    order.direction,
190                    order.limit_price,
191                    trigger_price,
192                ) =>
193            {
194                OrderType::StopLimit
195            }
196            _ => order_type,
197        },
198    )
199}
200
201fn limit_if_touched_prices_are_valid(
202    direction: DeriveOrderSide,
203    limit_price: Decimal,
204    trigger_price: Decimal,
205) -> bool {
206    match direction {
207        DeriveOrderSide::Buy => trigger_price <= limit_price,
208        DeriveOrderSide::Sell => trigger_price >= limit_price,
209    }
210}
211
212/// Builds a [`FillReport`] from a Derive trade record.
213///
214/// Quote-currency commission is reported in the same currency as the
215/// instrument's settlement (USDC for perps and options). `client_order_id`
216/// is sourced from the trade `label` when it is a valid Nautilus identifier.
217/// Trailing zero padding is removed without changing the value.
218/// Returns `Ok(None)` with a warning when the trade or order identifier is empty.
219///
220/// # Errors
221///
222/// Returns an error if a nonempty required identifier is invalid or a decimal field cannot be
223/// converted to a Nautilus `Price`, `Quantity`, or `Money`.
224pub fn parse_derive_trade_to_fill_report(
225    trade: &DeriveTrade,
226    account_id: AccountId,
227    fee_currency: Currency,
228    ts_init: UnixNanos,
229) -> anyhow::Result<Option<FillReport>> {
230    parse_derive_trade_to_fill_report_with_precision(
231        trade,
232        account_id,
233        fee_currency,
234        None,
235        None,
236        ts_init,
237    )
238}
239
240pub(crate) fn parse_derive_trade_to_fill_report_with_precision(
241    trade: &DeriveTrade,
242    account_id: AccountId,
243    fee_currency: Currency,
244    price_precision: Option<u8>,
245    size_precision: Option<u8>,
246    ts_init: UnixNanos,
247) -> anyhow::Result<Option<FillReport>> {
248    if trade.trade_id.is_empty() || trade.order_id.is_empty() {
249        log::warn!(
250            "Skipping Derive trade for {}: missing trade_id={}, missing order_id={}",
251            trade.instrument_name,
252            trade.trade_id.is_empty(),
253            trade.order_id.is_empty(),
254        );
255        return Ok(None);
256    }
257
258    let instrument_id = format_instrument_id(trade.instrument_name)?;
259    let venue_order_id =
260        VenueOrderId::new_checked(trade.order_id.as_str()).context("invalid Derive order_id")?;
261    let trade_id =
262        TradeId::new_checked(trade.trade_id.as_str()).context("invalid Derive trade_id")?;
263    let order_side = derive_order_side_to_nautilus(trade.direction);
264    let last_qty = quantity_from_decimal(trade.trade_amount, size_precision, "trade_amount")?;
265    anyhow::ensure!(
266        !last_qty.is_zero(),
267        "invalid Derive trade_amount: zero fill quantity after conversion (trade_id={trade_id}, instrument_id={instrument_id}, trade_amount={}, size_precision={})",
268        trade.trade_amount,
269        last_qty.precision,
270    );
271    let last_px = price_from_decimal(trade.trade_price, price_precision, "trade_price")?;
272    let commission = commission_from_decimal(trade.trade_fee, fee_currency)?;
273
274    let liquidity_side = match trade.liquidity_role {
275        DeriveLiquidityRole::Maker => LiquiditySide::Maker,
276        DeriveLiquidityRole::Taker => LiquiditySide::Taker,
277        DeriveLiquidityRole::Unknown => LiquiditySide::NoLiquiditySide,
278    };
279
280    let client_order_id =
281        parse_client_order_id(trade.label.as_str(), venue_order_id, instrument_id);
282
283    let ts_event = ms_to_nanos(trade.timestamp);
284
285    Ok(Some(FillReport::new(
286        account_id,
287        instrument_id,
288        venue_order_id,
289        trade_id,
290        order_side,
291        last_qty,
292        last_px,
293        commission,
294        liquidity_side,
295        client_order_id,
296        None,
297        ts_event,
298        ts_init,
299        Some(UUID4::new()),
300    )))
301}
302
303/// Builds a [`PositionStatusReport`] from a Derive position record.
304///
305/// Trailing zero padding is removed without changing the value.
306///
307/// # Errors
308///
309/// Returns an error if the position amount cannot be converted to a Nautilus `Quantity` without
310/// changing its value.
311pub fn parse_derive_position_to_report(
312    position: &DerivePosition,
313    account_id: AccountId,
314    ts_init: UnixNanos,
315) -> anyhow::Result<PositionStatusReport> {
316    parse_derive_position_to_report_with_precision(position, account_id, None, ts_init)
317}
318
319pub(crate) fn parse_derive_position_to_report_with_precision(
320    position: &DerivePosition,
321    account_id: AccountId,
322    size_precision: Option<u8>,
323    ts_init: UnixNanos,
324) -> anyhow::Result<PositionStatusReport> {
325    let instrument_id = format_instrument_id(position.instrument_name)?;
326    let signed_amount = position.amount;
327
328    let side = if signed_amount > Decimal::ZERO {
329        PositionSide::Long
330    } else if signed_amount < Decimal::ZERO {
331        PositionSide::Short
332    } else {
333        PositionSide::Flat
334    };
335
336    let abs_amount = signed_amount.abs();
337    let quantity = quantity_from_decimal(abs_amount, size_precision, "position.amount")?;
338    anyhow::ensure!(
339        quantity.as_decimal() == abs_amount,
340        "Derive position.amount {signed_amount} cannot be represented exactly for {instrument_id}",
341    );
342
343    let report = PositionStatusReport::new(
344        account_id,
345        instrument_id,
346        side,
347        quantity,
348        ts_init,
349        ts_init,
350        Some(UUID4::new()),
351        None,
352        Some(position.average_price),
353    );
354
355    // Perpetual and option averages include opening fees, which Nautilus books as fill commissions
356    if matches!(
357        position.instrument_type,
358        DeriveInstrumentType::Perp | DeriveInstrumentType::Option
359    ) {
360        Ok(report.with_avg_px_open_reconciliation(AvgPxReconciliation::OpeningOnly))
361    } else {
362        Ok(report)
363    }
364}
365
366/// Derives balances, margins, and supplemental info from a [`DeriveSubaccount`] snapshot.
367///
368/// Each collateral row becomes one [`AccountBalance`] in the collateral's own
369/// units, rounded to its registered currency precision, with `total = amount`
370/// and `locked = 0`. A subset of each collateral row remains in [`Params`]
371/// with decimal strings exact within `Decimal` range and scale. The venue's
372/// `collaterals[].initial_margin` is USD credit, not locked funds. Pending
373/// vault-deposit holds remain metadata because their inclusion in
374/// collateral amounts is not specified by the venue.
375///
376/// Portfolio requirements form one account-wide [`MarginBalance`] in USD:
377/// `initial = positions_value - positions_initial_margin - open_orders_margin` and
378/// `maintenance = positions_value - positions_maintenance_margin`. The source margin
379/// fields are signed health contributions; position value removes their mark-to-market
380/// credit, and open-order margin is a signed reservation. These aggregates preserve the
381/// venue's portfolio offsets and round to native USD precision. Source margin
382/// components and signed net health remain decimal strings in [`Params`] within
383/// `Decimal` range and scale. Metadata also includes the manager, risk universe,
384/// margin model, and liquidation status.
385///
386/// # Errors
387///
388/// Returns an error if the venue marks the snapshot `failed_to_fetch`, an embedded position cannot
389/// be represented exactly, a balance exceeds the native range, or aggregate requirements overflow.
390pub fn parse_derive_subaccount_to_balances(
391    subaccount: &DeriveSubaccount,
392) -> anyhow::Result<(Vec<AccountBalance>, Vec<MarginBalance>, Params)> {
393    anyhow::ensure!(
394        !subaccount.failed_to_fetch,
395        "Derive subaccount snapshot is incomplete"
396    );
397
398    for position in &subaccount.positions {
399        quantity_from_decimal(position.amount.abs(), None, "position.amount")?;
400    }
401
402    let mut balances = Vec::with_capacity(subaccount.collaterals.len());
403    for collateral in &subaccount.collaterals {
404        let currency = Currency::get_or_create_crypto(collateral.asset_name);
405
406        let balance =
407            AccountBalance::from_total_and_locked(collateral.amount, Decimal::ZERO, currency)
408                .map_err(|e| {
409                    anyhow::anyhow!(
410                        "failed to build collateral balance for {} (total={}): {e}",
411                        collateral.asset_name,
412                        collateral.amount,
413                    )
414                })?;
415
416        balances.push(balance);
417    }
418
419    let currency = Currency::USD();
420    let initial_dec = subaccount
421        .positions_value
422        .checked_sub(subaccount.positions_initial_margin)
423        .and_then(|value| value.checked_sub(subaccount.open_orders_margin))
424        .context("Derive initial margin requirement exceeds Decimal range")?;
425    let maintenance_dec = subaccount
426        .positions_value
427        .checked_sub(subaccount.positions_maintenance_margin)
428        .context("Derive maintenance margin requirement exceeds Decimal range")?;
429
430    let initial = Money::from_decimal(initial_dec, currency).with_context(|| {
431        format!(
432            "initial margin requirement {initial_dec} cannot be represented at {currency} precision",
433        )
434    })?;
435
436    let maintenance =
437        Money::from_decimal(maintenance_dec, currency).with_context(|| {
438            format!(
439                "maintenance margin requirement {maintenance_dec} cannot be represented at {currency} precision",
440            )
441        })?;
442
443    let margins = vec![MarginBalance::new(initial, maintenance, None)];
444
445    let info = Params::new(
446        [
447            (
448                "collaterals".to_string(),
449                serde_json::to_value(&subaccount.collaterals)?,
450            ),
451            (
452                "currency".to_string(),
453                serde_json::to_value(&subaccount.currency)?,
454            ),
455            (
456                "margin_type".to_string(),
457                Value::String(subaccount.margin_type.clone()),
458            ),
459            ("manager_id".to_string(), Value::from(subaccount.manager_id)),
460            (
461                "risk_universe_id".to_string(),
462                Value::from(subaccount.risk_universe_id),
463            ),
464            (
465                "mm_credits".to_string(),
466                Value::String(subaccount.mm_credits.to_string()),
467            ),
468            (
469                "projected_margin_change".to_string(),
470                Value::String(subaccount.projected_margin_change.to_string()),
471            ),
472            (
473                "vault_deposit_holds".to_string(),
474                serde_json::to_value(&subaccount.vault_deposit_holds)?,
475            ),
476            (
477                "net_initial_margin".to_string(),
478                Value::String(subaccount.initial_margin.to_string()),
479            ),
480            (
481                "net_maintenance_margin".to_string(),
482                Value::String(subaccount.maintenance_margin.to_string()),
483            ),
484            (
485                "positions_value".to_string(),
486                Value::String(subaccount.positions_value.to_string()),
487            ),
488            (
489                "positions_initial_margin".to_string(),
490                Value::String(subaccount.positions_initial_margin.to_string()),
491            ),
492            (
493                "positions_maintenance_margin".to_string(),
494                Value::String(subaccount.positions_maintenance_margin.to_string()),
495            ),
496            (
497                "open_orders_margin".to_string(),
498                Value::String(subaccount.open_orders_margin.to_string()),
499            ),
500            (
501                "is_under_liquidation".to_string(),
502                Value::Bool(subaccount.is_under_liquidation),
503            ),
504        ]
505        .into(),
506    );
507
508    Ok((balances, margins, info))
509}
510
511fn price_from_decimal(value: Decimal, precision: Option<u8>, field: &str) -> anyhow::Result<Price> {
512    let precision = precision.unwrap_or_else(|| value.normalize().scale() as u8);
513    Price::from_decimal_dp(value, precision).with_context(|| format!("invalid Derive {field}"))
514}
515
516fn quantity_from_decimal(
517    value: Decimal,
518    precision: Option<u8>,
519    field: &str,
520) -> anyhow::Result<Quantity> {
521    let precision = precision.unwrap_or_else(|| value.normalize().scale() as u8);
522    Quantity::from_decimal_dp(value, precision).with_context(|| format!("invalid Derive {field}"))
523}
524
525fn parse_client_order_id(
526    label: &str,
527    venue_order_id: VenueOrderId,
528    instrument_id: InstrumentId,
529) -> Option<ClientOrderId> {
530    if label.is_empty() {
531        return None;
532    }
533
534    match ClientOrderId::new_checked(label) {
535        Ok(client_order_id) => Some(client_order_id),
536        Err(_) => {
537            log::warn!(
538                "Ignoring unrepresentable Derive client label for order {:?} on {:?}",
539                venue_order_id.as_str(),
540                instrument_id.to_string(),
541            );
542            None
543        }
544    }
545}
546
547fn commission_from_decimal(value: Decimal, currency: Currency) -> anyhow::Result<Money> {
548    Money::from_decimal(value, currency).with_context(|| CommissionError { value, currency })
549}
550
551#[derive(Debug, Error)]
552#[error("trade_fee {value} cannot be represented at {currency} precision")]
553pub(crate) struct CommissionError {
554    value: Decimal,
555    currency: Currency,
556}
557
558pub(crate) fn ms_to_nanos(value: i64) -> UnixNanos {
559    let clamped = u64::try_from(value.max(0)).unwrap_or(0);
560    UnixNanos::from(clamped.saturating_mul(NANOSECONDS_IN_MILLISECOND))
561}
562
563#[cfg(test)]
564mod tests {
565    use indexmap::IndexMap;
566    use nautilus_model::enums::{OrderSide, OrderStatus, OrderType, TimeInForce, TriggerType};
567    use rstest::rstest;
568    use rust_decimal_macros::dec;
569
570    use super::*;
571    use crate::{
572        common::{
573            enums::{
574                DeriveAssetType, DeriveLiquidityRole, DeriveOrderCancelReason, DeriveOrderSide,
575                DeriveOrderStatus, DeriveOrderType, DeriveTimeInForce, DeriveTriggerPriceType,
576                DeriveTriggerType,
577            },
578            parse::{
579                derive_status_to_nautilus, order_side_to_derive, order_type_to_derive,
580                time_in_force_to_derive,
581            },
582        },
583        http::models::DeriveCollateral,
584    };
585
586    fn sample_order() -> DeriveOrder {
587        DeriveOrder {
588            amount: dec!(10),
589            average_price: dec!(3500),
590            cancel_reason: DeriveOrderCancelReason::Empty,
591            creation_timestamp: 1_700_000_000_000,
592            direction: DeriveOrderSide::Buy,
593            filled_amount: dec!(4),
594            instrument_name: "ETH-PERP".into(),
595            is_transfer: false,
596            label: "STRATEGY-1-O-1".into(),
597            last_update_timestamp: 1_700_000_001_000,
598            limit_price: dec!(3500),
599            max_fee: dec!(1),
600            mmp: false,
601            nonce: 1,
602            order_fee: dec!(0),
603            order_id: "ord-1".to_string(),
604            order_status: DeriveOrderStatus::Open,
605            order_type: DeriveOrderType::Limit,
606            quote_id: None,
607            replaced_order_id: None,
608            signature: SecretString::from("0x00"),
609            signature_expiry_sec: 1_700_000_999,
610            signer: "0xsigner".into(),
611            subaccount_id: 30769,
612            time_in_force: DeriveTimeInForce::Gtc,
613            trigger_price: None,
614            trigger_price_type: None,
615            trigger_reject_message: None,
616            trigger_type: None,
617        }
618    }
619
620    fn sample_trade() -> DeriveTrade {
621        DeriveTrade {
622            direction: DeriveOrderSide::Sell,
623            index_price: dec!(3500),
624            instrument_name: "ETH-PERP".into(),
625            is_transfer: false,
626            label: "STRATEGY-1-O-2".into(),
627            liquidity_role: DeriveLiquidityRole::Taker,
628            mark_price: dec!(3500),
629            order_id: "ord-2".to_string(),
630            quote_id: None,
631            realized_pnl: dec!(0),
632            subaccount_id: 30769,
633            timestamp: 1_700_000_002_000,
634            trade_amount: dec!(2),
635            trade_fee: dec!(0.5),
636            trade_id: "tr-1".to_string(),
637            trade_price: dec!(3505),
638            tx_hash: Some("0xabc".to_string()),
639            batch_status: Some("Settled".to_string()),
640            op_uuid: None,
641            wallet: Some("0xwallet".into()),
642        }
643    }
644
645    #[rstest]
646    fn test_order_side_round_trip() {
647        assert_eq!(order_side_to_derive(OrderSide::Buy), DeriveOrderSide::Buy,);
648        assert_eq!(order_side_to_derive(OrderSide::Sell), DeriveOrderSide::Sell,);
649    }
650
651    #[rstest]
652    fn test_order_type_rejects_unsupported() {
653        assert_eq!(
654            order_type_to_derive(OrderType::Limit).unwrap(),
655            DeriveOrderType::Limit,
656        );
657        assert_eq!(
658            order_type_to_derive(OrderType::Market).unwrap(),
659            DeriveOrderType::Market,
660        );
661        assert!(order_type_to_derive(OrderType::StopMarket).is_err());
662    }
663
664    #[rstest]
665    #[case(TimeInForce::Gtc, false, DeriveTimeInForce::Gtc)]
666    #[case(TimeInForce::Gtc, true, DeriveTimeInForce::PostOnly)]
667    #[case(TimeInForce::Ioc, false, DeriveTimeInForce::Ioc)]
668    #[case(TimeInForce::Fok, false, DeriveTimeInForce::Fok)]
669    fn test_time_in_force_maps_supported_values(
670        #[case] tif: TimeInForce,
671        #[case] post_only: bool,
672        #[case] expected: DeriveTimeInForce,
673    ) {
674        assert_eq!(time_in_force_to_derive(tif, post_only).unwrap(), expected);
675    }
676
677    #[rstest]
678    #[case(TimeInForce::Ioc)]
679    #[case(TimeInForce::Fok)]
680    fn test_time_in_force_rejects_post_only_immediate_values(#[case] tif: TimeInForce) {
681        let err = time_in_force_to_derive(tif, true)
682            .expect_err("post-only immediate TIF must be rejected");
683
684        assert!(
685            err.to_string()
686                .contains("post-only Derive orders only support GTC"),
687            "unexpected error: {err}",
688        );
689    }
690
691    #[rstest]
692    #[case(TimeInForce::Gtd, false)]
693    #[case(TimeInForce::Gtd, true)]
694    #[case(TimeInForce::Day, false)]
695    #[case(TimeInForce::Day, true)]
696    #[case(TimeInForce::AtTheOpen, false)]
697    #[case(TimeInForce::AtTheOpen, true)]
698    #[case(TimeInForce::AtTheClose, false)]
699    #[case(TimeInForce::AtTheClose, true)]
700    fn test_time_in_force_rejects_unsupported(#[case] tif: TimeInForce, #[case] post_only: bool) {
701        let err = time_in_force_to_derive(tif, post_only).expect_err("must reject unsupported TIF");
702
703        assert!(
704            err.to_string().contains("unsupported time in force"),
705            "unexpected error: {err}",
706        );
707    }
708
709    #[rstest]
710    #[case("order_type")]
711    #[case("time_in_force")]
712    #[case("trigger_type")]
713    #[case("trigger_price_type")]
714    fn test_order_report_rejects_unknown_semantics(#[case] field: &str) {
715        let mut value = serde_json::to_value(sample_order()).unwrap();
716        value[field] = serde_json::json!("future-variant");
717        let order: DeriveOrder = serde_json::from_value(value).unwrap();
718        assert!(
719            parse_derive_order_to_report(
720                &order,
721                AccountId::from("DERIVE-001"),
722                UnixNanos::from(17)
723            )
724            .is_err()
725        );
726    }
727
728    #[rstest]
729    #[case(false)]
730    #[case(true)]
731    fn test_order_report_rejects_unrepresentable_price(#[case] trigger: bool) {
732        let mut order = sample_order();
733        if trigger {
734            order.trigger_type = Some(DeriveTriggerType::Stoploss);
735            order.trigger_price = Some(Decimal::MAX);
736        } else {
737            order.limit_price = Decimal::MAX;
738        }
739
740        assert!(
741            parse_derive_order_to_report(
742                &order,
743                AccountId::from("DERIVE-001"),
744                UnixNanos::from(17)
745            )
746            .is_err()
747        );
748    }
749
750    #[rstest]
751    fn test_derive_status_partial_fill_classification() {
752        assert_eq!(
753            derive_status_to_nautilus(DeriveOrderStatus::Open, dec!(0), dec!(10)).unwrap(),
754            OrderStatus::Accepted,
755        );
756        assert_eq!(
757            derive_status_to_nautilus(DeriveOrderStatus::Open, dec!(4), dec!(10)).unwrap(),
758            OrderStatus::PartiallyFilled,
759        );
760        assert_eq!(
761            derive_status_to_nautilus(DeriveOrderStatus::Filled, dec!(10), dec!(10)).unwrap(),
762            OrderStatus::Filled,
763        );
764        assert_eq!(
765            derive_status_to_nautilus(DeriveOrderStatus::Cancelled, dec!(0), dec!(10)).unwrap(),
766            OrderStatus::Canceled,
767        );
768    }
769
770    #[rstest]
771    fn test_parse_order_report_assigns_partial_fill_status() {
772        let account_id = AccountId::new("DERIVE-001");
773        let report =
774            parse_derive_order_to_report(&sample_order(), account_id, UnixNanos::from(1)).unwrap();
775        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
776        assert_eq!(report.quantity, Quantity::from("10"));
777        assert_eq!(report.filled_qty, Quantity::from("4"));
778        assert_eq!(report.client_order_id.unwrap().as_str(), "STRATEGY-1-O-1");
779        assert_eq!(report.venue_order_id.as_str(), "ord-1");
780    }
781
782    #[rstest]
783    fn test_parse_order_report_normalizes_without_instrument_precision() {
784        let mut order = sample_order();
785        order.amount = Decimal::from_str_exact("0.100000000000000000").unwrap();
786        order.filled_amount = Decimal::from_str_exact("0.000000000000000000").unwrap();
787        order.limit_price = Decimal::from_str_exact("0.100000000000000000").unwrap();
788        order.average_price = Decimal::ZERO;
789        order.order_status = DeriveOrderStatus::Cancelled;
790        let account_id = AccountId::new("DERIVE-001");
791
792        let report = parse_derive_order_to_report(&order, account_id, UnixNanos::from(1)).unwrap();
793
794        assert_eq!(report.quantity, Quantity::from("0.1"));
795        assert_eq!(report.filled_qty, Quantity::from("0"));
796        assert_eq!(report.price, Some(Price::from("0.1")));
797    }
798
799    #[rstest]
800    fn test_parse_order_report_uses_instrument_precision() {
801        let mut order = sample_order();
802        order.amount = Decimal::from_str_exact("25.000").unwrap();
803        order.filled_amount = Decimal::from_str_exact("5.000").unwrap();
804        order.limit_price = Decimal::from_str_exact("25.000").unwrap();
805
806        let report = parse_derive_order_to_report_with_precision(
807            &order,
808            AccountId::new("DERIVE-001"),
809            Some(2),
810            Some(2),
811            UnixNanos::from(1),
812        )
813        .unwrap();
814
815        assert_eq!(report.quantity, Quantity::from("25.00"));
816        assert_eq!(report.quantity.precision, 2);
817        assert_eq!(report.filled_qty, Quantity::from("5.00"));
818        assert_eq!(report.filled_qty.precision, 2);
819        assert_eq!(report.price, Some(Price::from("25.00")));
820        assert_eq!(report.price.unwrap().precision, 2);
821    }
822
823    #[rstest]
824    fn test_parse_order_report_maps_untriggered_stop_market() {
825        let mut order = sample_order();
826        order.average_price = Decimal::ZERO;
827        order.filled_amount = Decimal::ZERO;
828        order.limit_price = dec!(3400);
829        order.order_status = DeriveOrderStatus::Untriggered;
830        order.order_type = DeriveOrderType::Market;
831        order.trigger_price = Some(dec!(3450));
832        order.trigger_price_type = Some(DeriveTriggerPriceType::Mark);
833        order.trigger_type = Some(DeriveTriggerType::Stoploss);
834        let account_id = AccountId::new("DERIVE-001");
835
836        let report = parse_derive_order_to_report(&order, account_id, UnixNanos::from(1)).unwrap();
837
838        assert_eq!(report.order_type, OrderType::StopMarket);
839        assert_eq!(report.order_status, OrderStatus::Accepted);
840        assert_eq!(report.price, None);
841        assert_eq!(report.trigger_price, Some(Price::from("3450")));
842        assert_eq!(report.trigger_type, Some(TriggerType::MarkPrice));
843    }
844
845    #[rstest]
846    #[case(DeriveOrderSide::Buy, dec!(3700), dec!(3600))]
847    #[case(DeriveOrderSide::Buy, dec!(3700), dec!(3700))]
848    #[case(DeriveOrderSide::Sell, dec!(3700), dec!(3800))]
849    #[case(DeriveOrderSide::Sell, dec!(3700), dec!(3700))]
850    fn test_parse_order_report_maps_limit_if_touched_trigger(
851        #[case] direction: DeriveOrderSide,
852        #[case] limit_price: Decimal,
853        #[case] trigger_price: Decimal,
854    ) {
855        let mut order = sample_order();
856        order.average_price = Decimal::ZERO;
857        order.direction = direction;
858        order.filled_amount = Decimal::ZERO;
859        order.limit_price = limit_price;
860        order.order_status = DeriveOrderStatus::Untriggered;
861        order.order_type = DeriveOrderType::Limit;
862        order.trigger_price = Some(trigger_price);
863        order.trigger_price_type = Some(DeriveTriggerPriceType::Index);
864        order.trigger_type = Some(DeriveTriggerType::Takeprofit);
865        let account_id = AccountId::new("DERIVE-001");
866
867        let report = parse_derive_order_to_report(&order, account_id, UnixNanos::from(1)).unwrap();
868
869        assert_eq!(report.order_type, OrderType::LimitIfTouched);
870        assert_eq!(
871            report.price,
872            Some(Price::from_decimal(limit_price.normalize()).unwrap())
873        );
874        assert_eq!(
875            report.trigger_price,
876            Some(Price::from_decimal(trigger_price.normalize()).unwrap())
877        );
878        assert_eq!(report.trigger_type, Some(TriggerType::IndexPrice));
879    }
880
881    #[rstest]
882    #[case(DeriveOrderSide::Buy, dec!(3700), dec!(3800))]
883    #[case(DeriveOrderSide::Sell, dec!(3700), dec!(3600))]
884    fn test_parse_order_report_maps_take_profit_limit_with_stop_shape(
885        #[case] direction: DeriveOrderSide,
886        #[case] limit_price: Decimal,
887        #[case] trigger_price: Decimal,
888    ) {
889        let mut order = sample_order();
890        order.average_price = Decimal::ZERO;
891        order.direction = direction;
892        order.filled_amount = Decimal::ZERO;
893        order.limit_price = limit_price;
894        order.order_status = DeriveOrderStatus::Untriggered;
895        order.order_type = DeriveOrderType::Limit;
896        order.trigger_price = Some(trigger_price);
897        order.trigger_price_type = Some(DeriveTriggerPriceType::Index);
898        order.trigger_type = Some(DeriveTriggerType::Takeprofit);
899        let account_id = AccountId::new("DERIVE-001");
900
901        let report = parse_derive_order_to_report(&order, account_id, UnixNanos::from(1)).unwrap();
902
903        assert_eq!(report.order_type, OrderType::StopLimit);
904        assert_eq!(
905            report.price,
906            Some(Price::from_decimal(limit_price.normalize()).unwrap())
907        );
908        assert_eq!(
909            report.trigger_price,
910            Some(Price::from_decimal(trigger_price.normalize()).unwrap())
911        );
912        assert_eq!(report.trigger_type, Some(TriggerType::IndexPrice));
913    }
914
915    #[rstest]
916    fn test_parse_rejected_post_only_report_keeps_cross_market_reason() {
917        let mut order = sample_order();
918        order.cancel_reason = DeriveOrderCancelReason::PostOnlyCrossMarket;
919        order.order_status = DeriveOrderStatus::Rejected;
920        order.time_in_force = DeriveTimeInForce::PostOnly;
921        let account_id = AccountId::new("DERIVE-001");
922
923        let report = parse_derive_order_to_report(&order, account_id, UnixNanos::from(1)).unwrap();
924
925        assert_eq!(report.order_status, OrderStatus::Rejected);
926        assert!(report.post_only);
927        assert_eq!(
928            report.cancel_reason.as_deref(),
929            Some("Post only order cannot cross the market")
930        );
931    }
932
933    #[rstest]
934    #[case(
935        "trigger price moved through limit",
936        "trigger price moved through limit"
937    )]
938    #[case(" <p>risk\t limit</p>\0\n exceeded ", "risk limit exceeded")]
939    #[case("<p>\0</p>", "Order command rejected")]
940    fn test_parse_rejected_trigger_report_uses_trigger_message(
941        #[case] message: &str,
942        #[case] expected: &str,
943    ) {
944        let mut order = sample_order();
945        order.cancel_reason = DeriveOrderCancelReason::TriggerFailed;
946        order.order_status = DeriveOrderStatus::Rejected;
947        order.trigger_reject_message = Some(message.to_string());
948        let account_id = AccountId::new("DERIVE-001");
949
950        let report = parse_derive_order_to_report(&order, account_id, UnixNanos::from(1)).unwrap();
951
952        assert_eq!(report.order_status, OrderStatus::Rejected);
953        assert_eq!(report.cancel_reason.as_deref(), Some(expected));
954    }
955
956    #[rstest]
957    fn test_parse_trade_report_emits_taker_fill() {
958        let account_id = AccountId::new("DERIVE-001");
959        let usdc = Currency::USDC();
960        let report = parse_derive_trade_to_fill_report(
961            &sample_trade(),
962            account_id,
963            usdc,
964            UnixNanos::from(2),
965        )
966        .unwrap()
967        .unwrap();
968        assert_eq!(report.order_side, OrderSide::Sell);
969        assert_eq!(report.last_qty, Quantity::from("2"));
970        assert_eq!(report.last_px, Price::from("3505"));
971        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
972        assert_eq!(report.commission.as_decimal(), dec!(0.5));
973    }
974
975    #[rstest]
976    #[case::literal_zero(dec!(0), Some(2), true)]
977    #[case::unconfigured_zero(dec!(0), None, true)]
978    #[case::rounded_zero(dec!(0.004), Some(2), true)]
979    #[case::half_even_zero(dec!(0.005), Some(2), true)]
980    #[case::positive(dec!(0.006), Some(2), false)]
981    fn test_parse_trade_report_zero_quantity(
982        #[case] amount: Decimal,
983        #[case] precision: Option<u8>,
984        #[case] rejected: bool,
985    ) {
986        let mut trade = sample_trade();
987        trade.trade_amount = amount;
988
989        let result = parse_derive_trade_to_fill_report_with_precision(
990            &trade,
991            AccountId::new("DERIVE-001"),
992            Currency::USDC(),
993            None,
994            precision,
995            UnixNanos::from(2),
996        );
997
998        if rejected {
999            let message = result.unwrap_err().to_string();
1000            assert!(message.contains(&format!("trade_id={}", trade.trade_id)));
1001            assert!(message.contains(&format!("instrument_id={}.DERIVE", trade.instrument_name)));
1002            assert!(message.contains(&format!("trade_amount={amount}")));
1003            assert!(message.contains(&format!("size_precision={}", precision.unwrap_or(0))));
1004        } else {
1005            assert_eq!(result.unwrap().unwrap().last_qty, Quantity::from("0.01"));
1006        }
1007    }
1008
1009    #[rstest]
1010    #[case("")]
1011    #[case(" ")]
1012    #[case("external-\u{03bb}")]
1013    fn test_parse_reports_preserve_external_order_without_client_label(#[case] label: &str) {
1014        let mut order = sample_order();
1015        order.label = label.into();
1016        let mut trade = sample_trade();
1017        trade.label = label.into();
1018        let account_id = AccountId::from("DERIVE-001");
1019        let ts_init = UnixNanos::from(123);
1020        let order_report = parse_derive_order_to_report(&order, account_id, ts_init).unwrap();
1021        let fill_report =
1022            parse_derive_trade_to_fill_report(&trade, account_id, Currency::USDC(), ts_init)
1023                .unwrap()
1024                .unwrap();
1025
1026        assert_eq!(order_report.client_order_id, None);
1027        assert_eq!(order_report.venue_order_id, VenueOrderId::from("ord-1"));
1028        assert_eq!(order_report.quantity.as_decimal(), dec!(10));
1029        assert_eq!(order_report.filled_qty.as_decimal(), dec!(4));
1030        assert_eq!(fill_report.client_order_id, None);
1031        assert_eq!(fill_report.venue_order_id, VenueOrderId::from("ord-2"));
1032        assert_eq!(fill_report.trade_id, TradeId::from("tr-1"));
1033        assert_eq!(fill_report.last_qty.as_decimal(), dec!(2));
1034        assert_eq!(fill_report.last_px.as_decimal(), dec!(3505));
1035        assert_eq!(fill_report.commission.as_decimal(), dec!(0.5));
1036        assert_eq!(fill_report.commission.currency, Currency::USDC());
1037    }
1038
1039    #[rstest]
1040    #[case(" ")]
1041    #[case("external-\u{03bb}")]
1042    #[case("1234567890123456789012345678901234567")]
1043    fn test_parse_trade_report_rejects_invalid_trade_id(#[case] trade_id: &str) {
1044        let mut trade = sample_trade();
1045        trade.trade_id = trade_id.to_string();
1046        let result = parse_derive_trade_to_fill_report(
1047            &trade,
1048            AccountId::from("DERIVE-001"),
1049            Currency::USDC(),
1050            UnixNanos::default(),
1051        );
1052
1053        assert_eq!(result.unwrap_err().to_string(), "invalid Derive trade_id");
1054    }
1055
1056    #[rstest]
1057    #[case(" ")]
1058    #[case("external-\u{03bb}")]
1059    fn test_parse_reports_reject_invalid_venue_order_id(#[case] order_id: &str) {
1060        let mut order = sample_order();
1061        order.order_id = order_id.to_string();
1062        let mut trade = sample_trade();
1063        trade.order_id = order_id.to_string();
1064        let account_id = AccountId::from("DERIVE-001");
1065        let order_result = parse_derive_order_to_report(&order, account_id, UnixNanos::default());
1066        let fill_result = parse_derive_trade_to_fill_report(
1067            &trade,
1068            account_id,
1069            Currency::USDC(),
1070            UnixNanos::default(),
1071        );
1072
1073        assert_eq!(
1074            order_result.unwrap_err().to_string(),
1075            "invalid Derive order_id"
1076        );
1077        assert_eq!(
1078            fill_result.unwrap_err().to_string(),
1079            "invalid Derive order_id"
1080        );
1081    }
1082
1083    #[rstest]
1084    fn test_parse_reports_preserve_valid_identity_bytes() {
1085        let label = " external-label ";
1086        let order_id = " external-order ";
1087        let trade_id = "123456789012345678901234567890123456";
1088        let mut order = sample_order();
1089        order.label = label.into();
1090        order.order_id = order_id.to_string();
1091        let mut trade = sample_trade();
1092        trade.label = label.into();
1093        trade.order_id = order_id.to_string();
1094        trade.trade_id = trade_id.to_string();
1095        let account_id = AccountId::from("DERIVE-001");
1096        let order_report =
1097            parse_derive_order_to_report(&order, account_id, UnixNanos::default()).unwrap();
1098        let fill_report = parse_derive_trade_to_fill_report(
1099            &trade,
1100            account_id,
1101            Currency::USDC(),
1102            UnixNanos::default(),
1103        )
1104        .unwrap()
1105        .unwrap();
1106
1107        assert_eq!(order_report.client_order_id.unwrap().as_str(), label);
1108        assert_eq!(order_report.venue_order_id.as_str(), order_id);
1109        assert_eq!(fill_report.client_order_id.unwrap().as_str(), label);
1110        assert_eq!(fill_report.venue_order_id.as_str(), order_id);
1111        assert_eq!(fill_report.trade_id.as_str(), trade_id);
1112        assert_eq!(fill_report.last_qty.as_decimal(), dec!(2));
1113        assert_eq!(fill_report.last_px.as_decimal(), dec!(3505));
1114        assert_eq!(fill_report.commission.as_decimal(), dec!(0.5));
1115    }
1116
1117    #[rstest]
1118    fn test_parse_trade_report_uses_instrument_precision() {
1119        let mut trade = sample_trade();
1120        trade.trade_amount = Decimal::from_str_exact("25.000").unwrap();
1121        trade.trade_price = Decimal::from_str_exact("25.000").unwrap();
1122
1123        let report = parse_derive_trade_to_fill_report_with_precision(
1124            &trade,
1125            AccountId::new("DERIVE-001"),
1126            Currency::USDC(),
1127            Some(2),
1128            Some(3),
1129            UnixNanos::from(2),
1130        )
1131        .unwrap()
1132        .unwrap();
1133
1134        assert_eq!(report.last_px, Price::from("25.00"));
1135        assert_eq!(report.last_px.precision, 2);
1136        assert_eq!(report.last_qty, Quantity::from("25.000"));
1137        assert_eq!(report.last_qty.precision, 3);
1138    }
1139
1140    #[rstest]
1141    #[case(DeriveLiquidityRole::Taker, LiquiditySide::Taker)]
1142    #[case(DeriveLiquidityRole::Maker, LiquiditySide::Maker)]
1143    fn test_parse_trade_report_preserves_exact_decimal_commission(
1144        #[case] liquidity_role: DeriveLiquidityRole,
1145        #[case] expected_liquidity_side: LiquiditySide,
1146    ) {
1147        let mut trade = sample_trade();
1148        trade.trade_fee = dec!(0.12345678);
1149        trade.liquidity_role = liquidity_role;
1150        let account_id = AccountId::new("DERIVE-001");
1151        let usdc = Currency::USDC();
1152        let report =
1153            parse_derive_trade_to_fill_report(&trade, account_id, usdc, UnixNanos::from(2))
1154                .unwrap()
1155                .expect("exact USDC-precision fee must emit the fill");
1156        assert_eq!(report.commission.as_decimal(), dec!(0.12345678));
1157        assert_eq!(report.commission.currency, usdc);
1158        assert_eq!(report.liquidity_side, expected_liquidity_side);
1159    }
1160
1161    #[rstest]
1162    #[case(dec!(0.000000025), dec!(0.00000002))]
1163    #[case(dec!(0.000000015), dec!(0.00000002))]
1164    fn test_parse_trade_report_rounds_half_unit_commission_from_decimal(
1165        #[case] trade_fee: Decimal,
1166        #[case] expected: Decimal,
1167    ) {
1168        // These half-unit values are where the old f64 path diverged
1169        let mut trade = sample_trade();
1170        trade.trade_fee = trade_fee;
1171        let account_id = AccountId::new("DERIVE-001");
1172        let report = parse_derive_trade_to_fill_report(
1173            &trade,
1174            account_id,
1175            Currency::USDC(),
1176            UnixNanos::from(2),
1177        )
1178        .unwrap()
1179        .expect("sub-precision fee must still emit the fill");
1180        assert_eq!(report.commission.as_decimal(), expected);
1181    }
1182
1183    #[rstest]
1184    fn test_parse_trade_report_errors_on_out_of_range_commission() {
1185        let mut trade = sample_trade();
1186        trade.trade_fee = Decimal::MAX;
1187        let account_id = AccountId::new("DERIVE-001");
1188        let err = parse_derive_trade_to_fill_report(
1189            &trade,
1190            account_id,
1191            Currency::USDC(),
1192            UnixNanos::from(2),
1193        )
1194        .expect_err("out-of-range fee must error instead of panicking");
1195        assert!(
1196            err.to_string().contains("trade_fee"),
1197            "unexpected error: {err}",
1198        );
1199    }
1200
1201    #[rstest]
1202    fn test_v3_trade_reports_preserve_execution_across_batch_stages() {
1203        let stages: Vec<Option<String>> = serde_json::from_str(include_str!(
1204            "../../test_data/common/trade_batch_stages.json"
1205        ))
1206        .unwrap();
1207        let trades: Vec<DeriveTrade> = serde_json::from_str(include_str!(
1208            "../../test_data/perps/http_trades_v3_native.json"
1209        ))
1210        .unwrap();
1211        let account_id = AccountId::new("DERIVE-001");
1212
1213        for stage in stages {
1214            for (i, original) in trades.iter().enumerate() {
1215                let mut trade = original.clone();
1216                trade.batch_status = stage.clone();
1217                trade.tx_hash = None;
1218                trade.op_uuid = None;
1219                let report = parse_derive_trade_to_fill_report_with_precision(
1220                    &trade,
1221                    account_id,
1222                    Currency::USDC(),
1223                    Some(2),
1224                    Some(3),
1225                    UnixNanos::from(91),
1226                )
1227                .unwrap()
1228                .unwrap();
1229                assert_eq!(report.account_id, account_id);
1230                assert_eq!(report.instrument_id, InstrumentId::from("ETH-PERP.DERIVE"));
1231                assert_eq!(report.venue_order_id, VenueOrderId::new(&trade.order_id));
1232                assert_eq!(report.trade_id, TradeId::new(&trade.trade_id));
1233                assert_eq!(
1234                    report.client_order_id,
1235                    Some(ClientOrderId::new(trade.label))
1236                );
1237                assert_eq!(report.venue_position_id, None);
1238                assert_eq!(report.order_side, [OrderSide::Sell, OrderSide::Buy][i]);
1239                assert_eq!(report.last_qty, Quantity::from("0.100"));
1240                assert_eq!(
1241                    report.last_px,
1242                    [Price::from("2568.50"), Price::from("2568.89")][i]
1243                );
1244                assert_eq!(report.commission.currency, Currency::USDC());
1245                assert_eq!(
1246                    report.commission.as_decimal(),
1247                    [dec!(0.08705248), dec!(0.08705274)][i]
1248                );
1249                assert_eq!(report.liquidity_side, LiquiditySide::Taker);
1250                assert_eq!(
1251                    report.ts_event,
1252                    UnixNanos::from([1_751_600_001_000_000_000, 1_751_600_000_000_000_000][i])
1253                );
1254                assert_eq!(report.ts_init, UnixNanos::from(91));
1255                assert_eq!(report.avg_px, None);
1256            }
1257        }
1258    }
1259
1260    #[rstest]
1261    #[case("", "order-1")]
1262    #[case("trade-1", "")]
1263    fn test_trade_reports_require_execution_identities(
1264        #[case] trade_id: &str,
1265        #[case] order_id: &str,
1266    ) {
1267        let mut trade = sample_trade();
1268        trade.trade_id = trade_id.to_string();
1269        trade.order_id = order_id.to_string();
1270        let report = parse_derive_trade_to_fill_report(
1271            &trade,
1272            AccountId::new("DERIVE-001"),
1273            Currency::USDC(),
1274            UnixNanos::from(91),
1275        )
1276        .unwrap();
1277        assert_eq!(report, None);
1278    }
1279
1280    #[rstest]
1281    fn test_parse_trade_report_preserves_batch_error_fill() {
1282        let mut trade = sample_trade();
1283        trade.batch_status = Some("SettlingError".to_string());
1284        let account_id = AccountId::new("DERIVE-001");
1285        let usdc = Currency::USDC();
1286        let report =
1287            parse_derive_trade_to_fill_report(&trade, account_id, usdc, UnixNanos::from(2))
1288                .unwrap();
1289        assert_eq!(report.unwrap().trade_id, TradeId::new("tr-1"));
1290    }
1291
1292    #[rstest]
1293    fn test_parse_trade_report_degrades_unknown_liquidity_role() {
1294        let mut trade = sample_trade();
1295        trade.liquidity_role = DeriveLiquidityRole::Unknown;
1296        let account_id = AccountId::new("DERIVE-001");
1297        let usdc = Currency::USDC();
1298
1299        let report =
1300            parse_derive_trade_to_fill_report(&trade, account_id, usdc, UnixNanos::from(2))
1301                .unwrap()
1302                .expect("unknown liquidity role must still emit the fill");
1303
1304        assert_eq!(report.liquidity_side, LiquiditySide::NoLiquiditySide);
1305    }
1306
1307    #[rstest]
1308    #[case("order")]
1309    #[case("trade")]
1310    #[case("position")]
1311    fn test_execution_parser_rejects_blank_symbol_without_panic(
1312        #[case] record: &str,
1313        #[values("", " ", "\t\n")] symbol: &str,
1314    ) {
1315        let account_id = AccountId::from("DERIVE-001");
1316
1317        let result = std::panic::catch_unwind(|| match record {
1318            "order" => {
1319                let mut order = sample_order();
1320                order.instrument_name = symbol.into();
1321                parse_derive_order_to_report(&order, account_id, UnixNanos::from(17)).map(|_| ())
1322            }
1323            "trade" => {
1324                let mut trade = sample_trade();
1325                trade.instrument_name = symbol.into();
1326                parse_derive_trade_to_fill_report(
1327                    &trade,
1328                    account_id,
1329                    Currency::USDC(),
1330                    UnixNanos::from(17),
1331                )
1332                .map(|_| ())
1333            }
1334            "position" => {
1335                let mut position = sample_position();
1336                position.instrument_name = symbol.into();
1337                parse_derive_position_to_report(&position, account_id, UnixNanos::from(17))
1338                    .map(|_| ())
1339            }
1340            _ => unreachable!(),
1341        });
1342
1343        assert!(result.is_ok(), "untrusted symbols must not panic");
1344        assert!(result.unwrap().is_err());
1345    }
1346
1347    #[rstest]
1348    fn test_parse_position_long_short_flat() {
1349        let account_id = AccountId::new("DERIVE-001");
1350
1351        let mut long_pos = sample_position();
1352        long_pos.amount = dec!(3);
1353        let report =
1354            parse_derive_position_to_report(&long_pos, account_id, UnixNanos::from(3)).unwrap();
1355        assert_eq!(report.position_side, PositionSide::Long);
1356        assert_eq!(report.quantity, Quantity::from("3"));
1357
1358        let mut short_pos = sample_position();
1359        short_pos.amount = dec!(-2);
1360        let report =
1361            parse_derive_position_to_report(&short_pos, account_id, UnixNanos::from(3)).unwrap();
1362        assert_eq!(report.position_side, PositionSide::Short);
1363        assert_eq!(report.quantity, Quantity::from("2"));
1364
1365        let mut flat_pos = sample_position();
1366        flat_pos.amount = dec!(0);
1367        let report =
1368            parse_derive_position_to_report(&flat_pos, account_id, UnixNanos::from(3)).unwrap();
1369        assert_eq!(report.position_side, PositionSide::Flat);
1370    }
1371
1372    #[rstest]
1373    #[case::perp(DeriveInstrumentType::Perp, AvgPxReconciliation::OpeningOnly)]
1374    #[case::option(DeriveInstrumentType::Option, AvgPxReconciliation::OpeningOnly)]
1375    #[case::spot(DeriveInstrumentType::Erc20, AvgPxReconciliation::Match)]
1376    fn test_parse_position_report_uses_instrument_precision(
1377        #[case] instrument_type: DeriveInstrumentType,
1378        #[case] reconciliation: AvgPxReconciliation,
1379    ) {
1380        let mut position = sample_position();
1381        position.amount = Decimal::from_str_exact("25.000").unwrap();
1382        position.average_price = dec!(2553.87589666777);
1383        position.instrument_type = instrument_type;
1384
1385        let report = parse_derive_position_to_report_with_precision(
1386            &position,
1387            AccountId::new("DERIVE-001"),
1388            Some(3),
1389            UnixNanos::from(3),
1390        )
1391        .unwrap();
1392
1393        assert_eq!(
1394            report,
1395            PositionStatusReport::new(
1396                AccountId::new("DERIVE-001"),
1397                InstrumentId::from("ETH-PERP.DERIVE"),
1398                PositionSide::Long,
1399                Quantity::from("25.000"),
1400                UnixNanos::from(3),
1401                UnixNanos::from(3),
1402                Some(report.report_id),
1403                None,
1404                Some(position.average_price),
1405            )
1406            .with_avg_px_open_reconciliation(reconciliation)
1407        );
1408        assert_eq!(report.quantity.precision, 3);
1409    }
1410
1411    fn sample_position() -> DerivePosition {
1412        DerivePosition {
1413            amount: dec!(0),
1414            average_price: dec!(3500),
1415            creation_timestamp: 0,
1416            cumulative_funding: dec!(0),
1417            delta: dec!(0),
1418            gamma: dec!(0),
1419            index_price: dec!(3500),
1420            initial_margin: dec!(0),
1421            instrument_name: "ETH-PERP".into(),
1422            instrument_type: DeriveInstrumentType::Perp,
1423            leverage: None,
1424            liquidation_price: None,
1425            maintenance_margin: dec!(0),
1426            mark_price: dec!(3500),
1427            mark_value: dec!(0),
1428            net_settlements: dec!(0),
1429            open_orders_margin: dec!(0),
1430            pending_funding: dec!(0),
1431            realized_pnl: dec!(0),
1432            theta: dec!(0),
1433            unrealized_pnl: dec!(0),
1434            vega: dec!(0),
1435        }
1436    }
1437
1438    #[rstest]
1439    #[case("order_type")]
1440    #[case("time_in_force")]
1441    #[case("order_status")]
1442    #[case("trigger_price_type")]
1443    fn test_parse_subaccount_balances_ignore_order_classification(#[case] field: &str) {
1444        let mut subaccount = sample_subaccount();
1445        let expected = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1446        let mut order = serde_json::to_value(sample_order()).unwrap();
1447        order[field] = serde_json::json!("future-native-value");
1448        subaccount.open_orders = vec![serde_json::from_value(order).unwrap()];
1449
1450        let actual = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1451
1452        assert_eq!(actual, expected);
1453    }
1454
1455    #[rstest]
1456    fn test_parse_subaccount_emits_balances_margins_and_info() {
1457        let subaccount = sample_subaccount();
1458        let (balances, margins, info) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1459        assert_eq!(balances.len(), 1);
1460        assert_eq!(balances[0].total.as_decimal(), dec!(1000));
1461        assert_eq!(balances[0].locked.as_decimal(), dec!(0));
1462        assert_eq!(balances[0].free.as_decimal(), dec!(1000));
1463        assert_eq!(margins.len(), 1);
1464        assert_eq!(margins[0].initial.as_decimal(), dec!(0));
1465        assert_eq!(margins[0].maintenance.as_decimal(), dec!(0));
1466        assert_eq!(
1467            info.get("net_initial_margin"),
1468            Some(&serde_json::json!("100")),
1469        );
1470        assert_eq!(
1471            info.get("net_maintenance_margin"),
1472            Some(&serde_json::json!("50")),
1473        );
1474        assert_eq!(
1475            info.get("is_under_liquidation"),
1476            Some(&serde_json::json!(false)),
1477        );
1478    }
1479
1480    #[rstest]
1481    fn test_parse_subaccount_preserves_multi_collateral_units() {
1482        // 2.5 ETH collateral reporting $1000 of credit stays 2.5 ETH total
1483        // with nothing locked: credit is not a reservation on the collateral,
1484        // so no mark-price conversion applies
1485        let mut subaccount = sample_subaccount();
1486        subaccount.collaterals = vec![
1487            DeriveCollateral {
1488                amount: dec!(2.5),
1489                asset_name: "ETH".into(),
1490                asset_type: DeriveAssetType::Erc20,
1491                cumulative_interest: dec!(0),
1492                currency: "ETH".into(),
1493                initial_margin: dec!(1000),
1494                maintenance_margin: dec!(500),
1495                mark_price: dec!(3500),
1496                mark_value: dec!(8750),
1497                pending_interest: dec!(0),
1498            },
1499            DeriveCollateral {
1500                amount: dec!(1000),
1501                asset_name: "USDC".into(),
1502                asset_type: DeriveAssetType::Erc20,
1503                cumulative_interest: dec!(0),
1504                currency: "USDC".into(),
1505                initial_margin: dec!(1000),
1506                maintenance_margin: dec!(1000),
1507                mark_price: dec!(1),
1508                mark_value: dec!(1000),
1509                pending_interest: dec!(0),
1510            },
1511        ];
1512
1513        let (balances, _, _) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1514        assert_eq!(balances.len(), 2);
1515        assert_eq!(balances[0].total.currency, Currency::ETH());
1516        assert_eq!(balances[1].total.currency, Currency::USDC());
1517        assert_eq!(balances[0].total.as_decimal(), dec!(2.5));
1518        assert_eq!(balances[0].locked.as_decimal(), dec!(0));
1519        assert_eq!(balances[0].free.as_decimal(), dec!(2.5));
1520        assert_eq!(balances[1].total.as_decimal(), dec!(1000));
1521        assert_eq!(balances[1].locked.as_decimal(), dec!(0));
1522        assert_eq!(balances[1].free.as_decimal(), dec!(1000));
1523    }
1524
1525    #[rstest]
1526    fn test_parse_subaccount_aggregates_requirements_and_keeps_health_in_info() {
1527        // Requirements aggregate position IM with open-order margin; the
1528        // signed net health values must not appear as requirements
1529        let mut subaccount = sample_subaccount();
1530        subaccount.positions_initial_margin = dec!(-350);
1531        subaccount.positions_maintenance_margin = dec!(-175);
1532        subaccount.open_orders_margin = dec!(-40);
1533        subaccount.initial_margin = dec!(650);
1534        subaccount.maintenance_margin = dec!(825);
1535
1536        let (balances, margins, info) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1537        assert_eq!(balances[0].locked.as_decimal(), dec!(0));
1538        assert_eq!(margins.len(), 1);
1539        assert_eq!(margins[0].initial.as_decimal(), dec!(390));
1540        assert_eq!(margins[0].maintenance.as_decimal(), dec!(175));
1541        assert_eq!(
1542            info.get("positions_initial_margin"),
1543            Some(&serde_json::json!("-350")),
1544        );
1545        assert_eq!(
1546            info.get("positions_maintenance_margin"),
1547            Some(&serde_json::json!("-175")),
1548        );
1549        assert_eq!(
1550            info.get("open_orders_margin"),
1551            Some(&serde_json::json!("-40")),
1552        );
1553        assert_eq!(
1554            info.get("net_initial_margin"),
1555            Some(&serde_json::json!("650")),
1556        );
1557        assert_eq!(
1558            info.get("net_maintenance_margin"),
1559            Some(&serde_json::json!("825")),
1560        );
1561    }
1562
1563    #[rstest]
1564    fn test_parse_subaccount_funded_positionless_fixture_reports_no_locked() {
1565        let (balances, margins, info) =
1566            parse_subaccount_fixture("common/http_subaccount_usdc.json");
1567        assert_eq!(balances.len(), 1);
1568        assert_eq!(balances[0].total.as_decimal(), dec!(1000));
1569        assert_eq!(balances[0].locked.as_decimal(), dec!(0));
1570        assert_eq!(balances[0].free.as_decimal(), dec!(1000));
1571        assert_eq!(margins.len(), 1);
1572        assert_eq!(margins[0].initial.as_decimal(), dec!(0));
1573        assert_eq!(margins[0].maintenance.as_decimal(), dec!(0));
1574        // Net health equals the collateral credit with no requirements,
1575        // matching observed mainnet responses for funded positionless accounts
1576        assert_eq!(
1577            info.get("net_initial_margin"),
1578            Some(&serde_json::json!("1000")),
1579        );
1580        assert_eq!(
1581            info.get("net_maintenance_margin"),
1582            Some(&serde_json::json!("1000")),
1583        );
1584    }
1585
1586    #[rstest]
1587    fn test_parse_subaccount_positions_margin_fixture_maps_requirements() {
1588        let (balances, margins, info) =
1589            parse_subaccount_fixture("common/http_subaccount_positions_margin.json");
1590        assert_eq!(balances[0].locked.as_decimal(), dec!(0));
1591        assert_eq!(margins[0].initial.as_decimal(), dec!(350));
1592        assert_eq!(margins[0].maintenance.as_decimal(), dec!(175));
1593        assert_eq!(
1594            info.get("net_initial_margin"),
1595            Some(&serde_json::json!("655")),
1596        );
1597        assert_eq!(
1598            info.get("net_maintenance_margin"),
1599            Some(&serde_json::json!("830")),
1600        );
1601    }
1602
1603    #[rstest]
1604    fn test_parse_subaccount_open_orders_margin_fixture_maps_reservation() {
1605        let (_, margins, info) =
1606            parse_subaccount_fixture("common/http_subaccount_open_orders_margin.json");
1607        assert_eq!(margins[0].initial.as_decimal(), dec!(40));
1608        assert_eq!(margins[0].maintenance.as_decimal(), dec!(0));
1609        assert_eq!(
1610            info.get("open_orders_margin"),
1611            Some(&serde_json::json!("-40")),
1612        );
1613    }
1614
1615    #[rstest]
1616    fn test_parse_subaccount_negative_health_fixture_preserves_signs() {
1617        let (balances, margins, info) =
1618            parse_subaccount_fixture("common/http_subaccount_negative_health.json");
1619        assert_eq!(balances[0].locked.as_decimal(), dec!(0));
1620        assert_eq!(margins[0].initial.as_decimal(), dec!(1095));
1621        assert_eq!(margins[0].maintenance.as_decimal(), dec!(1025));
1622        assert_eq!(
1623            info.get("net_initial_margin"),
1624            Some(&serde_json::json!("-50")),
1625        );
1626        assert_eq!(
1627            info.get("net_maintenance_margin"),
1628            Some(&serde_json::json!("-20")),
1629        );
1630        assert_eq!(
1631            info.get("is_under_liquidation"),
1632            Some(&serde_json::json!(true)),
1633        );
1634    }
1635
1636    #[rstest]
1637    fn test_parse_subaccount_with_no_collateral_emits_margins_only() {
1638        let mut subaccount = sample_subaccount();
1639        subaccount.collaterals = vec![];
1640        subaccount.positions_initial_margin = dec!(-350);
1641        subaccount.positions_maintenance_margin = dec!(-175);
1642
1643        let (balances, margins, _) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1644        assert!(balances.is_empty());
1645        assert_eq!(margins.len(), 1);
1646        assert_eq!(margins[0].initial.as_decimal(), dec!(350));
1647        assert_eq!(margins[0].maintenance.as_decimal(), dec!(175));
1648    }
1649
1650    #[rstest]
1651    fn test_parse_subaccount_errors_on_unrepresentable_amount() {
1652        let mut subaccount = sample_subaccount();
1653        subaccount.collaterals[0].amount = Decimal::MAX;
1654
1655        let err = parse_derive_subaccount_to_balances(&subaccount)
1656            .expect_err("out-of-range collateral amount must error instead of panicking");
1657        assert!(
1658            err.to_string().contains("collateral balance"),
1659            "unexpected error: {err}",
1660        );
1661    }
1662
1663    #[rstest]
1664    fn test_parse_subaccount_v3_preserves_exact_collaterals_and_portfolio_risk() {
1665        let mut subaccount = sample_subaccount();
1666        subaccount.margin_type = "PM2-next".into();
1667        subaccount.manager_id = 57;
1668        subaccount.risk_universe_id = 19;
1669        subaccount.collaterals[0].amount = dec!(1.234567895);
1670        subaccount.initial_margin = dec!(-7.123456789123);
1671        subaccount.maintenance_margin = dec!(-8.234567891234);
1672        subaccount.positions_initial_margin = dec!(3.125);
1673        subaccount.open_orders_margin = dec!(-0.01);
1674        subaccount.positions_maintenance_margin = dec!(3.905);
1675        subaccount.positions_value = dec!(6.25);
1676        subaccount.mm_credits = dec!(0.123456789123);
1677        subaccount.projected_margin_change = dec!(-0.987654321987);
1678        let mut position = sample_position();
1679        position.amount = dec!(-2.125);
1680        position.initial_margin = dec!(400.123);
1681        position.maintenance_margin = dec!(300.234);
1682        subaccount.positions = vec![position];
1683        subaccount.vault_deposit_holds = vec![crate::http::models::DeriveVaultDepositHold {
1684            amount: dec!(0.000000000123456789),
1685            asset_name: "ETH".into(),
1686            currency: "ETH".into(),
1687            vault_id: 123,
1688        }];
1689
1690        let (balances, margins, info) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1691
1692        assert_eq!(
1693            balances,
1694            vec![
1695                AccountBalance::from_total_and_locked(
1696                    dec!(1.23456790),
1697                    Decimal::ZERO,
1698                    Currency::USDC(),
1699                )
1700                .unwrap()
1701            ]
1702        );
1703        assert_eq!(
1704            margins,
1705            vec![MarginBalance::new(
1706                Money::from_decimal(dec!(3.14), Currency::USD()).unwrap(),
1707                Money::from_decimal(dec!(2.34), Currency::USD()).unwrap(),
1708                None,
1709            )]
1710        );
1711        assert_eq!(info, serde_json::from_value(serde_json::json!({
1712            "currency": ["ETH", "BTC"],
1713            "margin_type": "PM2-next",
1714            "manager_id": 57,
1715            "risk_universe_id": 19,
1716            "mm_credits": "0.123456789123",
1717            "projected_margin_change": "-0.987654321987",
1718            "vault_deposit_holds": [{"amount": "0.000000000123456789", "asset_name": "ETH", "currency": "ETH", "vault_id": 123}],
1719            "net_initial_margin": "-7.123456789123",
1720            "net_maintenance_margin": "-8.234567891234",
1721            "positions_initial_margin": "3.125",
1722            "positions_maintenance_margin": "3.905",
1723            "positions_value": "6.25",
1724            "open_orders_margin": "-0.01",
1725            "is_under_liquidation": false,
1726            "collaterals": [{"amount": "1.234567895", "asset_name": "USDC", "asset_type": "erc20", "cumulative_interest": "0", "currency": "USDC", "initial_margin": "100", "maintenance_margin": "50", "mark_price": "1", "mark_value": "1000", "pending_interest": "0"}],
1727        })).unwrap());
1728    }
1729
1730    #[rstest]
1731    #[case(dec!(0.000000001), dec!(0))]
1732    #[case(dec!(0.123456785), dec!(0.12345678))]
1733    fn test_parse_subaccount_retains_collateral_below_native_precision(
1734        #[case] amount: Decimal,
1735        #[case] rounded: Decimal,
1736    ) {
1737        let mut subaccount = sample_subaccount();
1738        subaccount.collaterals[0].amount = amount;
1739
1740        let (balances, _, info) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1741
1742        assert_eq!(balances[0].total.as_decimal(), rounded);
1743        assert_eq!(balances[0].free.as_decimal(), rounded);
1744        assert_eq!(balances[0].locked.as_decimal(), Decimal::ZERO);
1745        assert_eq!(info["collaterals"][0]["amount"], amount.to_string());
1746    }
1747
1748    #[rstest]
1749    fn test_parse_subaccount_rejects_failed_snapshot() {
1750        let mut subaccount = sample_subaccount();
1751        subaccount.failed_to_fetch = true;
1752
1753        let err = parse_derive_subaccount_to_balances(&subaccount).unwrap_err();
1754
1755        assert_eq!(err.to_string(), "Derive subaccount snapshot is incomplete");
1756    }
1757
1758    #[rstest]
1759    #[case(Decimal::MAX, -Decimal::ONE, Decimal::ZERO, Decimal::ZERO, "initial")]
1760    #[case(Decimal::ZERO, Decimal::MIN, -Decimal::ONE, Decimal::ZERO, "initial")]
1761    #[case(Decimal::MAX, Decimal::ZERO, Decimal::ZERO, -Decimal::ONE, "maintenance")]
1762    fn test_parse_subaccount_rejects_requirement_overflow(
1763        #[case] value: Decimal,
1764        #[case] initial: Decimal,
1765        #[case] orders: Decimal,
1766        #[case] maintenance: Decimal,
1767        #[case] field: &str,
1768    ) {
1769        let mut subaccount = sample_subaccount();
1770        subaccount.positions_value = value;
1771        subaccount.positions_initial_margin = initial;
1772        subaccount.open_orders_margin = orders;
1773        subaccount.positions_maintenance_margin = maintenance;
1774
1775        let err = parse_derive_subaccount_to_balances(&subaccount).unwrap_err();
1776
1777        assert_eq!(
1778            err.to_string(),
1779            format!("Derive {field} margin requirement exceeds Decimal range")
1780        );
1781    }
1782
1783    #[rstest]
1784    #[case(dec!(0.0000000000000000001))]
1785    #[case(Decimal::MAX)]
1786    fn test_parse_subaccount_rejects_unrepresentable_embedded_position(#[case] amount: Decimal) {
1787        let mut subaccount = sample_subaccount();
1788        let mut position = sample_position();
1789        position.amount = amount;
1790        subaccount.positions = vec![position];
1791
1792        let expected = Quantity::from_decimal_dp(amount, amount.scale() as u8)
1793            .expect_err("unrepresentable test amount");
1794        let err = parse_derive_subaccount_to_balances(&subaccount).unwrap_err();
1795
1796        assert_eq!(
1797            format!("{err:#}"),
1798            format!("invalid Derive position.amount: {expected}")
1799        );
1800    }
1801
1802    #[rstest]
1803    #[case(dec!(0.0001))]
1804    #[case(dec!(-2.1234))]
1805    fn test_parse_position_rejects_rounding_at_instrument_precision(#[case] amount: Decimal) {
1806        let mut position = sample_position();
1807        position.amount = amount;
1808
1809        let err = parse_derive_position_to_report_with_precision(
1810            &position,
1811            AccountId::new("DERIVE-001"),
1812            Some(3),
1813            UnixNanos::from(3),
1814        )
1815        .unwrap_err();
1816
1817        assert!(err.to_string().contains("cannot be represented exactly"));
1818    }
1819
1820    #[rstest]
1821    #[case(include_str!("../../test_data/common/http_subaccount_pm2_open_orders.json"), dec!(44.84), dec!(0), "0", "0", "0", "-44.842739996872")]
1822    #[case(include_str!("../../test_data/common/http_subaccount_pm2_positions.json"), dec!(44.95), dec!(34.81), "0.000318767368", "-44.951666892242", "-34.805466288178", "0")]
1823    fn test_parse_subaccount_live_pm2_requirements(
1824        #[case] fixture: &str,
1825        #[case] initial: Decimal,
1826        #[case] maintenance: Decimal,
1827        #[case] value: &str,
1828        #[case] contribution_initial: &str,
1829        #[case] contribution_maintenance: &str,
1830        #[case] orders: &str,
1831    ) {
1832        let body: Value = serde_json::from_str(fixture).unwrap();
1833        let subaccount: DeriveSubaccount = serde_json::from_str(fixture).unwrap();
1834        let (balances, margins, info) = parse_derive_subaccount_to_balances(&subaccount).unwrap();
1835
1836        let total = if orders == "0" {
1837            dec!(45.89433238)
1838        } else {
1839            dec!(46.00000318)
1840        };
1841
1842        let mut expected = IndexMap::new();
1843        for name in [
1844            "collaterals",
1845            "currency",
1846            "margin_type",
1847            "manager_id",
1848            "risk_universe_id",
1849            "mm_credits",
1850            "projected_margin_change",
1851            "vault_deposit_holds",
1852            "positions_value",
1853            "positions_initial_margin",
1854            "positions_maintenance_margin",
1855            "open_orders_margin",
1856            "is_under_liquidation",
1857        ] {
1858            expected.insert(name.to_string(), body[name].clone());
1859        }
1860
1861        expected.insert(
1862            "net_initial_margin".to_string(),
1863            body["initial_margin"].clone(),
1864        );
1865        expected.insert(
1866            "net_maintenance_margin".to_string(),
1867            body["maintenance_margin"].clone(),
1868        );
1869
1870        assert_eq!(
1871            balances,
1872            vec![
1873                AccountBalance::from_total_and_locked(total, Decimal::ZERO, Currency::USDC())
1874                    .unwrap()
1875            ]
1876        );
1877        assert_eq!(
1878            margins,
1879            vec![MarginBalance::new(
1880                Money::from_decimal(initial, Currency::USD()).unwrap(),
1881                Money::from_decimal(maintenance, Currency::USD()).unwrap(),
1882                None
1883            )]
1884        );
1885        assert_eq!(info, Params::new(expected));
1886        assert_eq!(info["positions_value"], value);
1887        assert_eq!(info["positions_initial_margin"], contribution_initial);
1888        assert_eq!(
1889            info["positions_maintenance_margin"],
1890            contribution_maintenance
1891        );
1892        assert_eq!(info["open_orders_margin"], orders);
1893        assert_eq!(info["margin_type"], "PM2");
1894        assert_eq!(info["manager_id"], 5);
1895        assert_eq!(info["risk_universe_id"], 1);
1896    }
1897
1898    #[rstest]
1899    fn test_parse_subaccount_current_pm2_fixture() {
1900        let (balances, margins, info) = parse_subaccount_fixture("common/http_subaccount_pm2.json");
1901
1902        assert_eq!(
1903            balances,
1904            vec![
1905                AccountBalance::from_total_and_locked(dec!(6), Decimal::ZERO, Currency::USDC())
1906                    .unwrap()
1907            ]
1908        );
1909        assert_eq!(
1910            margins,
1911            vec![MarginBalance::new(
1912                Money::from_decimal(Decimal::ZERO, Currency::USD()).unwrap(),
1913                Money::from_decimal(Decimal::ZERO, Currency::USD()).unwrap(),
1914                None
1915            )]
1916        );
1917        assert_eq!(info["currency"], serde_json::json!(["BTC", "ETH"]));
1918        assert_eq!(info["margin_type"], "PM2");
1919        assert_eq!(info["manager_id"], 5);
1920        assert_eq!(info["risk_universe_id"], 1);
1921        assert_eq!(info["net_initial_margin"], "6.000000127922");
1922        assert_eq!(info["net_maintenance_margin"], "6.000000127922");
1923        assert_eq!(info["collaterals"][0]["pending_interest"], "0.000000127922");
1924    }
1925
1926    fn parse_subaccount_fixture(
1927        filename: &str,
1928    ) -> (Vec<AccountBalance>, Vec<MarginBalance>, Params) {
1929        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1930            .join("test_data")
1931            .join(filename);
1932        let content =
1933            std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("failed to read {filename}"));
1934        let subaccount: DeriveSubaccount = serde_json::from_str(&content)
1935            .unwrap_or_else(|e| panic!("failed to parse {filename}: {e}"));
1936        parse_derive_subaccount_to_balances(&subaccount).expect("subaccount maps")
1937    }
1938
1939    fn sample_subaccount() -> DeriveSubaccount {
1940        DeriveSubaccount {
1941            collaterals: vec![DeriveCollateral {
1942                amount: dec!(1000),
1943                asset_name: "USDC".into(),
1944                asset_type: DeriveAssetType::Erc20,
1945                cumulative_interest: dec!(0),
1946                currency: "USDC".into(),
1947                initial_margin: dec!(100),
1948                maintenance_margin: dec!(50),
1949                mark_price: dec!(1),
1950                mark_value: dec!(1000),
1951                pending_interest: dec!(0),
1952            }],
1953            collaterals_initial_margin: dec!(100),
1954            collaterals_maintenance_margin: dec!(50),
1955            collaterals_value: dec!(1000),
1956            currency: vec!["ETH".into(), "BTC".into()],
1957            failed_to_fetch: false,
1958            initial_margin: dec!(100),
1959            is_under_liquidation: false,
1960            label: None,
1961            maintenance_margin: dec!(50),
1962            manager_id: 3,
1963            margin_type: "SM".into(),
1964            mm_credits: dec!(0),
1965            open_orders: vec![],
1966            open_orders_margin: dec!(0),
1967            positions: vec![],
1968            positions_initial_margin: dec!(0),
1969            positions_maintenance_margin: dec!(0),
1970            positions_value: dec!(0),
1971            projected_margin_change: dec!(0),
1972            risk_universe_id: 1,
1973            subaccount_id: 30769,
1974            subaccount_value: dec!(1000),
1975            vault_deposit_holds: vec![],
1976        }
1977    }
1978}