Skip to main content

nautilus_derive/common/
parse.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Parsing utilities for the Derive adapter.
17
18use anyhow::Context;
19use nautilus_core::{UnixNanos, datetime::NANOSECONDS_IN_SECOND, params::Params};
20use nautilus_model::{
21    enums::{
22        ExerciseStyle, OptionKind, OrderSide, OrderStatus, OrderType, SettlementType, TimeInForce,
23        TriggerType,
24    },
25    identifiers::{InstrumentId, Symbol},
26    instruments::{CryptoOption, CryptoPerpetual, CurrencyPair, InstrumentAny},
27    types::{Currency, Price, Quantity},
28};
29use rust_decimal::Decimal;
30use serde::{Deserialize, Deserializer, de::DeserializeOwned};
31use serde_json::{Value, value::RawValue};
32use ustr::Ustr;
33
34use crate::{
35    common::{
36        consts::DERIVE_VENUE,
37        enums::{
38            DeriveInstrumentType, DeriveOptionKind, DeriveOrderSide, DeriveOrderStatus,
39            DeriveOrderType, DeriveTimeInForce, DeriveTriggerPriceType, DeriveTriggerType,
40        },
41    },
42    http::models::DeriveInstrument,
43};
44
45const DERIVE_POST_ONLY_CROSS_MARKET_MESSAGE: &str = "post only order cannot cross the market";
46
47/// JSON-RPC error code returned when a post-only order crosses the market.
48pub const DERIVE_POST_ONLY_CROSS_MARKET_ERROR_CODE: i64 = 11008;
49
50/// Converts a Derive venue symbol to a Nautilus instrument ID.
51///
52/// # Errors
53///
54/// Returns an error if the venue symbol is empty or contains only whitespace.
55pub fn format_instrument_id(venue_symbol: impl AsRef<str>) -> anyhow::Result<InstrumentId> {
56    let symbol =
57        Symbol::new_checked(venue_symbol.as_ref()).context("invalid Derive instrument_name")?;
58    Ok(InstrumentId::new(symbol, *DERIVE_VENUE))
59}
60
61/// Converts a Nautilus Derive instrument ID back to the venue symbol.
62///
63/// # Errors
64///
65/// Returns an error if `instrument_id` is not for the Derive venue.
66pub fn format_venue_symbol(instrument_id: &InstrumentId) -> anyhow::Result<Ustr> {
67    anyhow::ensure!(
68        instrument_id.venue == *DERIVE_VENUE,
69        "instrument ID `{instrument_id}` is not for venue {}",
70        DERIVE_VENUE.as_str(),
71    );
72    Ok(instrument_id.symbol.inner())
73}
74
75/// Deserializes a JSON array into `Vec<T>`, salvaging the decodable elements
76/// (see [`salvage_elements`]).
77///
78/// # Errors
79///
80/// Returns an error if the value is not a JSON array.
81pub fn deserialize_salvaged_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
82where
83    D: Deserializer<'de>,
84    T: DeserializeOwned,
85{
86    Ok(salvage_rows(Vec::<Box<RawValue>>::deserialize(
87        deserializer,
88    )?))
89}
90
91/// Decodes each element of a JSON array into `T`, logging and skipping
92/// elements that fail to decode instead of failing the whole collection.
93///
94/// Venue enum sets drift over time, so one unmodeled trade or account row
95/// must degrade to a logged skip rather than discard its siblings (the
96/// Hyperliquid dust-conversion incident shape). Reserved for rows where a
97/// missed element is recoverable (fills backfill via reconciliation); order
98/// and position arrays feeding mass status stay strict because absence there
99/// is read as state. The log carries only the decode error (which names the
100/// failing field and value); private rows hold signatures and wallet
101/// addresses, so the raw payload stays out of the logs.
102pub fn salvage_elements<T: DeserializeOwned>(values: Vec<Value>) -> Vec<T> {
103    salvage_decoded(values.into_iter().map(serde_json::from_value))
104}
105
106pub(crate) fn salvage_rows<T: DeserializeOwned>(values: Vec<Box<RawValue>>) -> Vec<T> {
107    salvage_decoded(
108        values
109            .into_iter()
110            .map(|value| serde_json::from_str(value.get())),
111    )
112}
113
114fn salvage_decoded<T>(values: impl Iterator<Item = serde_json::Result<T>>) -> Vec<T> {
115    let context = std::any::type_name::<T>()
116        .rsplit("::")
117        .next()
118        .unwrap_or("element");
119    let mut elements = Vec::with_capacity(values.size_hint().0);
120    for value in values {
121        match value {
122            Ok(element) => elements.push(element),
123            Err(e) => log::warn!("Skipping undecodable {context} element: {e}"),
124        }
125    }
126
127    elements
128}
129
130pub(crate) fn deserialize_decimal<'de, D: Deserializer<'de>>(
131    deserializer: D,
132) -> Result<Decimal, D::Error> {
133    nautilus_core::serialization::deserialize_optional_decimal_token(deserializer)
134        .map(|value| value.unwrap_or(Decimal::ZERO))
135}
136
137/// Maps a Nautilus order side to the Derive direction string.
138pub fn order_side_to_derive(side: OrderSide) -> DeriveOrderSide {
139    match side {
140        OrderSide::Buy => DeriveOrderSide::Buy,
141        OrderSide::Sell => DeriveOrderSide::Sell,
142    }
143}
144
145/// Maps a Nautilus order type to the Derive order type string.
146///
147/// # Errors
148///
149/// Returns an error if Derive does not accept the order type.
150pub fn order_type_to_derive(order_type: OrderType) -> anyhow::Result<DeriveOrderType> {
151    match order_type {
152        OrderType::Limit => Ok(DeriveOrderType::Limit),
153        OrderType::Market => Ok(DeriveOrderType::Market),
154        other => anyhow::bail!("unsupported order type for Derive: {other:?}"),
155    }
156}
157
158/// Maps a supported Nautilus trigger order type to the child Derive order type.
159///
160/// # Errors
161///
162/// Returns an error if Derive trigger orders do not support the order type.
163pub fn trigger_order_type_to_derive(order_type: OrderType) -> anyhow::Result<DeriveOrderType> {
164    match order_type {
165        OrderType::StopMarket | OrderType::MarketIfTouched => Ok(DeriveOrderType::Market),
166        OrderType::StopLimit | OrderType::LimitIfTouched => Ok(DeriveOrderType::Limit),
167        other => anyhow::bail!(
168            "unsupported trigger order type for Derive: {other:?}; supported types are StopMarket, StopLimit, MarketIfTouched, and LimitIfTouched"
169        ),
170    }
171}
172
173/// Maps a Nautilus trigger order type to Derive's stop-loss/take-profit flag.
174///
175/// # Errors
176///
177/// Returns an error if Derive trigger orders do not support the order type.
178pub fn trigger_type_to_derive(order_type: OrderType) -> anyhow::Result<DeriveTriggerType> {
179    match order_type {
180        OrderType::StopMarket | OrderType::StopLimit => Ok(DeriveTriggerType::Stoploss),
181        OrderType::MarketIfTouched | OrderType::LimitIfTouched => Ok(DeriveTriggerType::Takeprofit),
182        other => anyhow::bail!(
183            "unsupported trigger order type for Derive: {other:?}; supported types are StopMarket, StopLimit, MarketIfTouched, and LimitIfTouched"
184        ),
185    }
186}
187
188/// Maps Nautilus trigger price source to Derive.
189///
190/// # Errors
191///
192/// Returns an error if the trigger source does not map to mark price, which is the only source
193/// Derive accepts for trigger orders.
194pub fn trigger_price_type_to_derive(
195    trigger_type: Option<TriggerType>,
196) -> anyhow::Result<DeriveTriggerPriceType> {
197    match trigger_type {
198        Some(TriggerType::Default | TriggerType::MarkPrice) => Ok(DeriveTriggerPriceType::Mark),
199        Some(TriggerType::IndexPrice) => anyhow::bail!(
200            "unsupported trigger price type for Derive: IndexPrice; Derive currently accepts only MarkPrice for trigger orders"
201        ),
202        Some(other) => anyhow::bail!(
203            "unsupported trigger price type for Derive: {other:?}; Derive trigger orders support only MarkPrice"
204        ),
205        None => anyhow::bail!(
206            "missing trigger price type for Derive trigger order; Derive trigger orders support only MarkPrice"
207        ),
208    }
209}
210
211/// Maps a Nautilus time-in-force flag to the Derive TIF.
212///
213/// # Errors
214///
215/// Returns an error if Derive does not accept the time-in-force flag.
216pub fn time_in_force_to_derive(
217    tif: TimeInForce,
218    post_only: bool,
219) -> anyhow::Result<DeriveTimeInForce> {
220    match tif {
221        TimeInForce::Gtc if post_only => Ok(DeriveTimeInForce::PostOnly),
222        TimeInForce::Ioc | TimeInForce::Fok if post_only => anyhow::bail!(
223            "post-only Derive orders only support GTC time in force; received {tif:?}"
224        ),
225        TimeInForce::Gtc => Ok(DeriveTimeInForce::Gtc),
226        TimeInForce::Ioc => Ok(DeriveTimeInForce::Ioc),
227        TimeInForce::Fok => Ok(DeriveTimeInForce::Fok),
228        other => anyhow::bail!("unsupported time in force for Derive: {other:?}"),
229    }
230}
231
232/// Maps a Derive order side back to Nautilus.
233#[must_use]
234pub fn derive_order_side_to_nautilus(side: DeriveOrderSide) -> OrderSide {
235    match side {
236        DeriveOrderSide::Buy => OrderSide::Buy,
237        DeriveOrderSide::Sell => OrderSide::Sell,
238    }
239}
240
241/// Maps a Derive order type back to Nautilus.
242///
243/// # Errors
244///
245/// Returns an error if the order type is unmodeled.
246pub fn derive_order_type_to_nautilus(order_type: DeriveOrderType) -> anyhow::Result<OrderType> {
247    match order_type {
248        DeriveOrderType::Limit => Ok(OrderType::Limit),
249        DeriveOrderType::Market => Ok(OrderType::Market),
250        DeriveOrderType::Unknown => anyhow::bail!("unmodeled Derive order type"),
251    }
252}
253
254/// Maps a Derive trigger order record back to the Nautilus order type.
255///
256/// # Errors
257///
258/// Returns an error if the order or trigger type is unmodeled.
259pub fn derive_order_type_to_nautilus_for_order(
260    order_type: DeriveOrderType,
261    trigger_type: Option<DeriveTriggerType>,
262) -> anyhow::Result<OrderType> {
263    match (order_type, trigger_type) {
264        (DeriveOrderType::Market, Some(DeriveTriggerType::Stoploss)) => Ok(OrderType::StopMarket),
265        (DeriveOrderType::Limit, Some(DeriveTriggerType::Stoploss)) => Ok(OrderType::StopLimit),
266        (DeriveOrderType::Market, Some(DeriveTriggerType::Takeprofit)) => {
267            Ok(OrderType::MarketIfTouched)
268        }
269        (DeriveOrderType::Limit, Some(DeriveTriggerType::Takeprofit)) => {
270            Ok(OrderType::LimitIfTouched)
271        }
272        (_, Some(DeriveTriggerType::Unknown)) => anyhow::bail!("unmodeled Derive trigger type"),
273        (order_type, _) => derive_order_type_to_nautilus(order_type),
274    }
275}
276
277/// Maps a Derive trigger price source back to Nautilus.
278///
279/// # Errors
280///
281/// Returns an error if the trigger price source is unmodeled.
282pub fn derive_trigger_price_type_to_nautilus(
283    trigger_price_type: DeriveTriggerPriceType,
284) -> anyhow::Result<TriggerType> {
285    match trigger_price_type {
286        DeriveTriggerPriceType::Mark => Ok(TriggerType::MarkPrice),
287        DeriveTriggerPriceType::Index => Ok(TriggerType::IndexPrice),
288        DeriveTriggerPriceType::Unknown => anyhow::bail!("unmodeled Derive trigger price type"),
289    }
290}
291
292/// Maps a Derive TIF back to Nautilus.
293///
294/// # Errors
295///
296/// Returns an error if the time-in-force flag is unmodeled.
297pub fn derive_tif_to_nautilus(tif: DeriveTimeInForce) -> anyhow::Result<TimeInForce> {
298    match tif {
299        DeriveTimeInForce::Gtc | DeriveTimeInForce::PostOnly => Ok(TimeInForce::Gtc),
300        DeriveTimeInForce::Ioc => Ok(TimeInForce::Ioc),
301        DeriveTimeInForce::Fok => Ok(TimeInForce::Fok),
302        DeriveTimeInForce::Unknown => anyhow::bail!("unmodeled Derive time in force"),
303    }
304}
305
306/// Maps a Derive order status to the Nautilus equivalent, given the current
307/// filled quantity.
308///
309/// # Errors
310///
311/// Returns an error if the order status is unmodeled.
312pub fn derive_status_to_nautilus(
313    status: DeriveOrderStatus,
314    filled_qty: Decimal,
315    quantity: Decimal,
316) -> anyhow::Result<OrderStatus> {
317    let status = match status {
318        DeriveOrderStatus::Open => {
319            if filled_qty > Decimal::ZERO && filled_qty < quantity {
320                OrderStatus::PartiallyFilled
321            } else {
322                OrderStatus::Accepted
323            }
324        }
325        DeriveOrderStatus::Filled => OrderStatus::Filled,
326        DeriveOrderStatus::Rejected => OrderStatus::Rejected,
327        DeriveOrderStatus::Cancelled => OrderStatus::Canceled,
328        DeriveOrderStatus::Expired => OrderStatus::Expired,
329        DeriveOrderStatus::Untriggered | DeriveOrderStatus::AlgoActive => OrderStatus::Accepted,
330        DeriveOrderStatus::Unknown => anyhow::bail!("unmodeled Derive order status"),
331    };
332
333    Ok(status)
334}
335
336/// Returns whether a Derive rejection means a post-only order crossed the market.
337#[must_use]
338pub fn derive_rejection_due_post_only(code: Option<i64>, reason: &str) -> bool {
339    match code {
340        Some(DERIVE_POST_ONLY_CROSS_MARKET_ERROR_CODE) => true,
341        Some(_) => false,
342        None => reason
343            .to_ascii_lowercase()
344            .contains(DERIVE_POST_ONLY_CROSS_MARKET_MESSAGE),
345    }
346}
347
348/// Parses a Derive instrument definition into a Nautilus instrument.
349///
350/// Perpetuals are normalized to USDC quote and settlement: the wire quotes
351/// perps in `"USD"` index terms, while all Derive collateral, fees, and PnL
352/// settle in USDC, so Money currencies must match the account balances. The
353/// raw wire values remain in the instrument `info` payload.
354///
355/// Derive can fill taker orders below `minimum_amount`, so that venue value
356/// remains in `info` rather than becoming an unconditional `min_quantity`.
357///
358/// # Errors
359///
360/// Returns an error if a Derive instrument is missing required details or contains invalid price,
361/// quantity, or timestamp fields.
362pub fn parse_derive_instrument_any(
363    instrument: &DeriveInstrument,
364    ts_init: UnixNanos,
365) -> anyhow::Result<Option<InstrumentAny>> {
366    match instrument.instrument_type {
367        DeriveInstrumentType::Perp => parse_perp_instrument(instrument, ts_init).map(Some),
368        DeriveInstrumentType::Option => parse_option_instrument(instrument, ts_init).map(Some),
369        DeriveInstrumentType::Erc20 => parse_spot_instrument(instrument, ts_init).map(Some),
370        DeriveInstrumentType::Unknown => {
371            log::warn!(
372                "Skipping Derive instrument {} with unmodeled instrument type",
373                instrument.instrument_name,
374            );
375            Ok(None)
376        }
377    }
378}
379
380fn parse_perp_instrument(
381    instrument: &DeriveInstrument,
382    ts_init: UnixNanos,
383) -> anyhow::Result<InstrumentAny> {
384    instrument
385        .perp_details
386        .as_ref()
387        .context("missing perp_details for Derive perp instrument")?;
388
389    let instrument_id = format_instrument_id(instrument.instrument_name)?;
390    let raw_symbol = instrument_id.symbol;
391    let base_currency = Currency::get_or_create_crypto(instrument.base_currency);
392    // Wire says "USD" but Derive settles everything in USDC
393    let quote_currency = Currency::USDC();
394    let settlement_currency = quote_currency;
395    let price_increment = price_from_decimal(instrument.tick_size, "tick_size")?;
396    let size_increment = quantity_from_decimal(instrument.amount_step, "amount_step")?;
397    let multiplier = quantity_from_decimal(Decimal::ONE, "multiplier")?;
398    let max_quantity = quantity_from_decimal(instrument.maximum_amount, "maximum_amount")?;
399    let info = derive_instrument_info(instrument)?;
400
401    let perp = CryptoPerpetual::builder()
402        .instrument_id(instrument_id)
403        .raw_symbol(raw_symbol)
404        .base_currency(base_currency)
405        .quote_currency(quote_currency)
406        .settlement_currency(settlement_currency)
407        .is_inverse(false)
408        .price_precision(price_increment.precision)
409        .size_precision(size_increment.precision)
410        .price_increment(price_increment)
411        .size_increment(size_increment)
412        .multiplier(multiplier)
413        .lot_size(size_increment)
414        .max_quantity(max_quantity)
415        .info(info)
416        .ts_event(ts_init)
417        .ts_init(ts_init)
418        .build()?;
419
420    Ok(InstrumentAny::CryptoPerpetual(perp))
421}
422
423fn parse_option_instrument(
424    instrument: &DeriveInstrument,
425    ts_init: UnixNanos,
426) -> anyhow::Result<InstrumentAny> {
427    let details = instrument
428        .option_details
429        .as_ref()
430        .context("missing option_details for Derive option instrument")?;
431
432    let instrument_id = format_instrument_id(instrument.instrument_name)?;
433    let raw_symbol = instrument_id.symbol;
434    let underlying = Currency::get_or_create_crypto(instrument.base_currency);
435    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
436    let settlement_currency = quote_currency;
437    let option_kind = parse_option_kind(details.option_type);
438    let strike_price = price_from_decimal(details.strike, "option_details.strike")?;
439    let activation_ns =
440        timestamp_seconds_to_nanos(instrument.scheduled_activation, "scheduled_activation")?;
441    let expiration_ns = timestamp_seconds_to_nanos(details.expiry, "option_details.expiry")?;
442    let price_increment = price_from_decimal(instrument.tick_size, "tick_size")?;
443    let size_increment = quantity_from_decimal(instrument.amount_step, "amount_step")?;
444    let multiplier = quantity_from_decimal(Decimal::ONE, "multiplier")?;
445    let max_quantity = quantity_from_decimal(instrument.maximum_amount, "maximum_amount")?;
446    let info = derive_instrument_info(instrument)?;
447
448    let option = CryptoOption::builder()
449        .instrument_id(instrument_id)
450        .raw_symbol(raw_symbol)
451        .underlying(underlying)
452        .quote_currency(quote_currency)
453        .settlement_currency(settlement_currency)
454        .is_inverse(false)
455        .option_kind(option_kind)
456        .strike_price(strike_price)
457        .activation_ns(activation_ns)
458        .expiration_ns(expiration_ns)
459        .price_precision(price_increment.precision)
460        .size_precision(size_increment.precision)
461        .price_increment(price_increment)
462        .size_increment(size_increment)
463        .multiplier(multiplier)
464        .lot_size(size_increment)
465        .max_quantity(max_quantity)
466        .info(info)
467        .exercise_style(ExerciseStyle::European)
468        .settlement_type(SettlementType::Cash)
469        .ts_event(ts_init)
470        .ts_init(ts_init)
471        .build()?;
472
473    Ok(InstrumentAny::CryptoOption(option))
474}
475
476fn parse_spot_instrument(
477    instrument: &DeriveInstrument,
478    ts_init: UnixNanos,
479) -> anyhow::Result<InstrumentAny> {
480    let instrument_id = format_instrument_id(instrument.instrument_name)?;
481    let raw_symbol = instrument_id.symbol;
482    let base_currency = Currency::get_or_create_crypto(instrument.base_currency);
483    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
484    let price_increment = price_from_decimal(instrument.tick_size, "tick_size")?;
485    let size_increment = quantity_from_decimal(instrument.amount_step, "amount_step")?;
486    let multiplier = quantity_from_decimal(Decimal::ONE, "multiplier")?;
487    let max_quantity = quantity_from_decimal(instrument.maximum_amount, "maximum_amount")?;
488    let info = derive_instrument_info(instrument)?;
489
490    let pair = CurrencyPair::builder()
491        .instrument_id(instrument_id)
492        .raw_symbol(raw_symbol)
493        .base_currency(base_currency)
494        .quote_currency(quote_currency)
495        .price_precision(price_increment.precision)
496        .size_precision(size_increment.precision)
497        .price_increment(price_increment)
498        .size_increment(size_increment)
499        .multiplier(multiplier)
500        .lot_size(size_increment)
501        .max_quantity(max_quantity)
502        .info(info)
503        .ts_event(ts_init)
504        .ts_init(ts_init)
505        .build()?;
506
507    Ok(InstrumentAny::CurrencyPair(pair))
508}
509
510fn parse_option_kind(kind: DeriveOptionKind) -> OptionKind {
511    match kind {
512        DeriveOptionKind::Call => OptionKind::Call,
513        DeriveOptionKind::Put => OptionKind::Put,
514    }
515}
516
517// Reconstruct metadata only for definitions created without a venue response
518fn derive_instrument_info(instrument: &DeriveInstrument) -> anyhow::Result<Params> {
519    if let Some(raw) = &instrument.raw {
520        return Ok(raw.clone());
521    }
522
523    let value = serde_json::to_value(instrument)
524        .context("failed to serialize DeriveInstrument for info field")?;
525    let object = value
526        .as_object()
527        .context("DeriveInstrument did not serialize to a JSON object")?
528        .clone();
529    Ok(Params::new(object.into_iter().collect()))
530}
531
532fn price_from_decimal(value: Decimal, field: &str) -> anyhow::Result<Price> {
533    Price::from_decimal_dp(value, value.scale() as u8)
534        .with_context(|| format!("invalid Derive {field}"))
535}
536
537fn quantity_from_decimal(value: Decimal, field: &str) -> anyhow::Result<Quantity> {
538    Quantity::from_decimal_dp(value, value.scale() as u8)
539        .with_context(|| format!("invalid Derive {field}"))
540}
541
542fn timestamp_seconds_to_nanos(value: i64, field: &str) -> anyhow::Result<UnixNanos> {
543    timestamp_to_nanos(value, NANOSECONDS_IN_SECOND, field)
544}
545
546fn timestamp_to_nanos(value: i64, multiplier: u64, field: &str) -> anyhow::Result<UnixNanos> {
547    let value = u64::try_from(value).with_context(|| format!("negative Derive {field}"))?;
548    let nanos = value
549        .checked_mul(multiplier)
550        .with_context(|| format!("Derive {field} overflows nanoseconds"))?;
551    Ok(UnixNanos::from(nanos))
552}
553
554pub(crate) const STRATEGY_REASON_MAX_CHARS: usize = 256;
555
556pub(crate) fn strategy_rejection_reason(message: &str) -> String {
557    let mut output = String::new();
558    let mut markup = false;
559    let mut length = 0;
560
561    for character in message.chars() {
562        let previous_size = output.len();
563
564        match character {
565            '<' => markup = true,
566            '>' => markup = false,
567            _ if markup => {}
568            _ if character.is_whitespace() => {
569                if !output.is_empty() && !output.ends_with(' ') {
570                    output.push(' ');
571                }
572            }
573            _ if character.is_control() => {}
574            _ => output.push(character),
575        }
576
577        length += usize::from(output.len() != previous_size);
578        if length >= STRATEGY_REASON_MAX_CHARS {
579            break;
580        }
581    }
582
583    let output = output.trim_end();
584    if output.is_empty() {
585        "Order command rejected".to_string()
586    } else {
587        output.to_string()
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use std::path::PathBuf;
594
595    use nautilus_core::{UnixNanos, serialization::ToMsgPack};
596    use nautilus_model::{
597        enums::{ExerciseStyle, OptionKind, OrderStatus, OrderType, SettlementType, TriggerType},
598        identifiers::InstrumentId,
599        instruments::{Instrument, InstrumentAny},
600        types::{Currency, Price, Quantity},
601    };
602    use rstest::rstest;
603    use rust_decimal_macros::dec;
604    use serde::Serialize;
605    use serde_json::{Value, json};
606
607    use super::*;
608
609    #[rstest]
610    fn test_json_numeric_params_keep_messagepack_scalar_encoding() {
611        #[derive(Serialize)]
612        #[serde(transparent)]
613        struct NumericParams(Params);
614        impl ToMsgPack for NumericParams {}
615
616        let params = Params::new(
617            [
618                ("integer".to_owned(), json!(42)),
619                ("fraction".to_owned(), json!(0.125)),
620            ]
621            .into(),
622        );
623        let encoded = NumericParams(params).to_msgpack_bytes().unwrap();
624
625        assert_eq!(
626            encoded.as_ref(),
627            &[
628                0x82, 0xa7, b'i', b'n', b't', b'e', b'g', b'e', b'r', 42, 0xa8, b'f', b'r', b'a',
629                b'c', b't', b'i', b'o', b'n', 0xcb, 0x3f, 0xc0, 0, 0, 0, 0, 0, 0,
630            ],
631        );
632    }
633
634    fn data_path() -> PathBuf {
635        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_data")
636    }
637
638    fn load_json(filename: &str) -> Value {
639        let content = std::fs::read_to_string(data_path().join(filename))
640            .unwrap_or_else(|_| panic!("failed to read {filename}"));
641        serde_json::from_str(&content).expect("invalid json")
642    }
643
644    fn perp_fixture() -> DeriveInstrument {
645        serde_json::from_value(load_json("perps/instrument_eth.json")).unwrap()
646    }
647
648    fn option_fixture() -> DeriveInstrument {
649        serde_json::from_value(load_json("options/instrument_eth.json")).unwrap()
650    }
651
652    fn spot_fixture() -> DeriveInstrument {
653        serde_json::from_value(load_json("spot/instrument_eth.json")).unwrap()
654    }
655
656    #[rstest]
657    #[case(OrderType::StopMarket, DeriveOrderType::Market)]
658    #[case(OrderType::MarketIfTouched, DeriveOrderType::Market)]
659    #[case(OrderType::StopLimit, DeriveOrderType::Limit)]
660    #[case(OrderType::LimitIfTouched, DeriveOrderType::Limit)]
661    fn test_trigger_order_type_to_derive(
662        #[case] order_type: OrderType,
663        #[case] expected: DeriveOrderType,
664    ) {
665        assert_eq!(trigger_order_type_to_derive(order_type).unwrap(), expected);
666    }
667
668    #[rstest]
669    fn test_trigger_order_type_to_derive_rejects_unsupported() {
670        let err = trigger_order_type_to_derive(OrderType::TrailingStopMarket)
671            .expect_err("trailing stops must be rejected");
672
673        assert!(
674            err.to_string()
675                .contains("unsupported trigger order type for Derive"),
676            "unexpected error: {err}",
677        );
678    }
679
680    #[rstest]
681    #[case(OrderType::StopMarket, DeriveTriggerType::Stoploss)]
682    #[case(OrderType::StopLimit, DeriveTriggerType::Stoploss)]
683    #[case(OrderType::MarketIfTouched, DeriveTriggerType::Takeprofit)]
684    #[case(OrderType::LimitIfTouched, DeriveTriggerType::Takeprofit)]
685    fn test_trigger_type_to_derive(
686        #[case] order_type: OrderType,
687        #[case] expected: DeriveTriggerType,
688    ) {
689        assert_eq!(trigger_type_to_derive(order_type).unwrap(), expected);
690    }
691
692    #[rstest]
693    fn test_trigger_price_type_to_derive_accepts_only_mark_price() {
694        assert_eq!(
695            trigger_price_type_to_derive(Some(TriggerType::MarkPrice)).unwrap(),
696            DeriveTriggerPriceType::Mark,
697        );
698        assert_eq!(
699            trigger_price_type_to_derive(Some(TriggerType::Default)).unwrap(),
700            DeriveTriggerPriceType::Mark,
701        );
702
703        for trigger_type in [
704            TriggerType::IndexPrice,
705            TriggerType::LastPrice,
706            TriggerType::BidAsk,
707        ] {
708            let err = trigger_price_type_to_derive(Some(trigger_type))
709                .expect_err("unsupported trigger price type must fail");
710            assert!(
711                err.to_string().contains("unsupported trigger price type"),
712                "unexpected error for {trigger_type:?}: {err}",
713            );
714        }
715    }
716
717    #[rstest]
718    #[case(
719        DeriveOrderType::Market,
720        Some(DeriveTriggerType::Stoploss),
721        OrderType::StopMarket
722    )]
723    #[case(
724        DeriveOrderType::Limit,
725        Some(DeriveTriggerType::Stoploss),
726        OrderType::StopLimit
727    )]
728    #[case(
729        DeriveOrderType::Market,
730        Some(DeriveTriggerType::Takeprofit),
731        OrderType::MarketIfTouched
732    )]
733    #[case(
734        DeriveOrderType::Limit,
735        Some(DeriveTriggerType::Takeprofit),
736        OrderType::LimitIfTouched
737    )]
738    #[case(DeriveOrderType::Limit, None, OrderType::Limit)]
739    fn test_derive_order_type_to_nautilus_for_order(
740        #[case] order_type: DeriveOrderType,
741        #[case] trigger_type: Option<DeriveTriggerType>,
742        #[case] expected: OrderType,
743    ) {
744        assert_eq!(
745            derive_order_type_to_nautilus_for_order(order_type, trigger_type).unwrap(),
746            expected,
747        );
748    }
749
750    #[rstest]
751    fn test_unknown_wire_variants_reject_domain_conversion() {
752        assert!(derive_order_type_to_nautilus(DeriveOrderType::Unknown).is_err());
753        assert!(
754            derive_order_type_to_nautilus_for_order(
755                DeriveOrderType::Limit,
756                Some(DeriveTriggerType::Unknown)
757            )
758            .is_err()
759        );
760        assert!(derive_tif_to_nautilus(DeriveTimeInForce::Unknown).is_err());
761        assert!(derive_trigger_price_type_to_nautilus(DeriveTriggerPriceType::Unknown).is_err());
762        assert!(derive_status_to_nautilus(DeriveOrderStatus::Unknown, dec!(0), dec!(1)).is_err());
763    }
764
765    #[rstest]
766    fn test_salvage_elements_skips_undecodable_rows() {
767        let values = vec![json!(1), json!("not a number"), json!(2)];
768
769        let salvaged: Vec<i64> = salvage_elements(values);
770
771        assert_eq!(salvaged, vec![1, 2]);
772    }
773
774    #[rstest]
775    fn test_derive_status_to_nautilus_maps_untriggered_to_accepted() {
776        assert_eq!(
777            derive_status_to_nautilus(DeriveOrderStatus::Untriggered, dec!(0), dec!(1)).unwrap(),
778            OrderStatus::Accepted,
779        );
780    }
781
782    #[rstest]
783    #[case(
784        Some(DERIVE_POST_ONLY_CROSS_MARKET_ERROR_CODE),
785        "Post only order cannot cross the market",
786        true
787    )]
788    #[case(
789        Some(DERIVE_POST_ONLY_CROSS_MARKET_ERROR_CODE),
790        "post only order cannot cross the market",
791        true
792    )]
793    #[case(None, "Post only order cannot cross the market", true)]
794    #[case(Some(-32602), "Post only order cannot cross the market", false)]
795    #[case(Some(DERIVE_POST_ONLY_CROSS_MARKET_ERROR_CODE), "Invalid params", true)]
796    fn test_derive_rejection_due_post_only(
797        #[case] code: Option<i64>,
798        #[case] reason: &str,
799        #[case] expected: bool,
800    ) {
801        assert_eq!(derive_rejection_due_post_only(code, reason), expected);
802    }
803
804    #[rstest]
805    #[case("perps/instrument_eth.json")]
806    #[case("options/instrument_eth.json")]
807    #[case("spot/instrument_eth.json")]
808    fn test_instrument_parser_rejects_blank_symbol_without_panic(
809        #[case] filename: &str,
810        #[values("", " ", "\t\n")] symbol: &str,
811    ) {
812        let mut instrument: DeriveInstrument = serde_json::from_value(load_json(filename)).unwrap();
813        instrument.instrument_name = symbol.into();
814        let result = std::panic::catch_unwind(|| {
815            parse_derive_instrument_any(&instrument, UnixNanos::from(17))
816        });
817
818        assert!(result.is_ok(), "untrusted symbols must not panic");
819        assert!(result.unwrap().is_err());
820    }
821
822    #[rstest]
823    fn test_parse_perp_instrument() {
824        let instrument = parse_derive_instrument_any(&perp_fixture(), UnixNanos::from(123))
825            .unwrap()
826            .unwrap();
827
828        let InstrumentAny::CryptoPerpetual(perp) = instrument else {
829            panic!("expected CryptoPerpetual");
830        };
831
832        assert_eq!(perp.id(), InstrumentId::from("ETH-PERP.DERIVE"));
833        assert_eq!(perp.raw_symbol().as_str(), "ETH-PERP");
834        assert_eq!(perp.base_currency(), Some(Currency::ETH()));
835        // Fixture carries the live wire quote "USD"; parser normalizes to USDC
836        assert_eq!(perp.quote_currency(), Currency::USDC());
837        assert_eq!(perp.settlement_currency(), Currency::USDC());
838        assert_eq!(perp.price_increment(), Price::from("0.01"));
839        assert_eq!(perp.size_increment(), Quantity::from("0.001"));
840        assert_eq!(perp.max_quantity(), Some(Quantity::from("10000")));
841        assert_eq!(perp.min_quantity(), None);
842        assert!(!perp.is_inverse());
843
844        // `info` mirrors the raw venue payload so downstream consumers can read
845        // fields the core model does not expose (asset address, sub-id, perp
846        // funding details, etc.).
847        let info = perp.info.as_ref().expect("info populated");
848        assert_eq!(info.get_str("instrument_name"), Some("ETH-PERP"));
849        assert_eq!(info.get_str("instrument_type"), Some("perp"));
850        assert_eq!(info.get_str("base_asset_sub_id"), Some("0"));
851        // Normalization must not rewrite the raw venue payload.
852        assert_eq!(info.get_str("quote_currency"), Some("USD"));
853        assert_eq!(info.get_str("minimum_amount"), Some("0.1"));
854        assert!(info.get("perp_details").is_some_and(|v| v.is_object()));
855    }
856
857    #[rstest]
858    fn test_parse_perp_instrument_money_flows_settle_in_usdc() {
859        // Linear notional and PnL come out in cost_currency (= quote), which
860        // must match the USDC-only account
861        let instrument = parse_derive_instrument_any(&perp_fixture(), UnixNanos::from(123))
862            .unwrap()
863            .unwrap();
864
865        let InstrumentAny::CryptoPerpetual(perp) = instrument else {
866            panic!("expected CryptoPerpetual");
867        };
868
869        let notional =
870            perp.calculate_notional_value(Quantity::from("2"), Price::from("3000.00"), None);
871
872        assert!(!perp.is_quanto());
873        assert_eq!(perp.cost_currency(), Currency::USDC());
874        assert_eq!(notional.currency, Currency::USDC());
875        assert_eq!(notional.as_decimal(), dec!(6000));
876    }
877
878    #[rstest]
879    fn test_parse_perp_instrument_pins_usdc_for_any_wire_quote() {
880        // The USDC pin is unconditional, not gated on the wire saying "USD".
881        let mut instrument = perp_fixture();
882        instrument.quote_currency = "XUSD".into();
883
884        let parsed = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
885            .unwrap()
886            .unwrap();
887
888        let InstrumentAny::CryptoPerpetual(perp) = parsed else {
889            panic!("expected CryptoPerpetual");
890        };
891
892        assert_eq!(perp.quote_currency(), Currency::USDC());
893        assert_eq!(perp.settlement_currency(), Currency::USDC());
894    }
895
896    #[rstest]
897    fn test_parse_option_instrument() {
898        let instrument = parse_derive_instrument_any(&option_fixture(), UnixNanos::from(456))
899            .unwrap()
900            .unwrap();
901
902        let InstrumentAny::CryptoOption(option) = instrument else {
903            panic!("expected CryptoOption");
904        };
905
906        assert_eq!(
907            option.id(),
908            InstrumentId::from("ETH-20261225-3500-C.DERIVE")
909        );
910        assert_eq!(option.raw_symbol().as_str(), "ETH-20261225-3500-C");
911        assert_eq!(option.base_currency(), Some(Currency::ETH()));
912        assert_eq!(option.quote_currency(), Currency::USDC());
913        assert_eq!(option.settlement_currency(), Currency::USDC());
914        assert_eq!(option.option_kind(), Some(OptionKind::Call));
915        assert_eq!(option.exercise_style, Some(ExerciseStyle::European));
916        assert_eq!(option.settlement_type, Some(SettlementType::Cash));
917        assert_eq!(option.strike_price(), Some(Price::from("3500")));
918        assert_eq!(
919            option.activation_ns(),
920            Some(UnixNanos::from(1_774_598_400_000_000_000)),
921        );
922        assert_eq!(
923            option.expiration_ns(),
924            Some(UnixNanos::from(1_798_185_600_000_000_000)),
925        );
926        assert_eq!(option.price_increment(), Price::from("0.1"));
927        assert_eq!(option.size_increment(), Quantity::from("0.01"));
928        assert_eq!(option.max_quantity(), Some(Quantity::from("10000")));
929        assert_eq!(option.min_quantity(), None);
930
931        let info = option.info.as_ref().expect("info populated");
932        assert_eq!(info.get_str("instrument_name"), Some("ETH-20261225-3500-C"));
933        assert_eq!(info.get_str("instrument_type"), Some("option"));
934        assert_eq!(info.get_str("minimum_amount"), Some("0.1"));
935        let option_details = info.get("option_details").expect("option_details present");
936        assert_eq!(
937            option_details.get("option_type").and_then(|v| v.as_str()),
938            Some("C")
939        );
940        assert_eq!(
941            option_details.get("strike").and_then(|v| v.as_str()),
942            Some("3500")
943        );
944    }
945
946    #[rstest]
947    fn test_symbol_instrument_id_mapping() {
948        let instrument_id = format_instrument_id("ETH-20260627-3500-C").unwrap();
949        let venue_symbol = format_venue_symbol(&instrument_id).unwrap();
950
951        assert_eq!(
952            instrument_id,
953            InstrumentId::from("ETH-20260627-3500-C.DERIVE")
954        );
955        assert_eq!(venue_symbol, "ETH-20260627-3500-C");
956    }
957
958    #[rstest]
959    fn test_format_venue_symbol_rejects_non_derive_venue() {
960        let instrument_id = InstrumentId::from("ETH-PERP.BINANCE");
961
962        let err = format_venue_symbol(&instrument_id).expect_err("must reject non-Derive venue");
963
964        assert!(err.to_string().contains("not for venue DERIVE"));
965    }
966
967    #[rstest]
968    fn test_parse_spot_instrument() {
969        let instrument = parse_derive_instrument_any(&spot_fixture(), UnixNanos::from(789))
970            .unwrap()
971            .unwrap();
972
973        let InstrumentAny::CurrencyPair(pair) = instrument else {
974            panic!("expected CurrencyPair");
975        };
976
977        assert_eq!(pair.id(), InstrumentId::from("ETH-USDC.DERIVE"));
978        assert_eq!(pair.raw_symbol().as_str(), "ETH-USDC");
979        assert_eq!(pair.base_currency(), Some(Currency::ETH()));
980        assert_eq!(pair.quote_currency(), Currency::USDC());
981        assert_eq!(pair.price_increment(), Price::from("0.1"));
982        assert_eq!(pair.size_increment(), Quantity::from("0.01"));
983        assert_eq!(pair.max_quantity(), Some(Quantity::from("10000")));
984        assert_eq!(pair.min_quantity(), None);
985
986        let info = pair.info.as_ref().expect("info populated");
987        assert_eq!(info.get_str("instrument_name"), Some("ETH-USDC"));
988        assert_eq!(info.get_str("instrument_type"), Some("erc20"));
989        assert_eq!(info.get_str("minimum_amount"), Some("0.1"));
990        assert_eq!(info.get_str("base_asset_sub_id"), Some("0"));
991        assert_eq!(
992            info.get_str("base_asset_address"),
993            Some("0x41675b7746AE0E464f2594d258CF399c392A179C"),
994        );
995    }
996
997    #[rstest]
998    fn test_parse_instrument_without_response_uses_typed_metadata() {
999        let mut instrument = perp_fixture();
1000        instrument.raw = None;
1001        instrument.minimum_amount = dec!(0.03);
1002
1003        let parsed = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1004            .unwrap()
1005            .unwrap();
1006        let info = parsed.info().unwrap();
1007
1008        assert_eq!(info.get_str("instrument_name"), Some("ETH-PERP"));
1009        assert_eq!(info.get_str("quote_currency"), Some("USD"));
1010        assert_eq!(info.get_str("minimum_amount"), Some("0.03"));
1011        assert_eq!(info.get("raw"), None);
1012    }
1013
1014    #[rstest]
1015    #[case::perp("perps/instrument_eth.json")]
1016    #[case::option("options/instrument_eth.json")]
1017    #[case::spot("spot/instrument_eth_mainnet.json")]
1018    fn test_parse_instrument_preserves_complete_response(#[case] filename: &str) {
1019        let mut response = load_json(filename);
1020        response["base_fee"] = json!(0.125);
1021        response["pro_rata_fraction"] = json!("0.8");
1022        response["fifo_min_allocation"] = json!("10");
1023        response["pro_rata_amount_step"] = json!("1");
1024        response["erc20_details"] = json!({
1025            "decimals": 18,
1026            "underlying_erc20_address": "0x15CEcd5190A43C7798dD2058308781D0662e678E",
1027            "borrow_index": "1.000000000000000001",
1028            "supply_index": "1.000000000000000002",
1029        });
1030        response["additional_data"] = json!([null, true, {"value": "0.000000000000000001"}]);
1031        for field in ["option_details", "perp_details"] {
1032            if let Some(details) = response[field].as_object_mut() {
1033                details.insert("additional_data".to_string(), json!({"value": 42}));
1034            }
1035        }
1036
1037        let instrument: DeriveInstrument = serde_json::from_value(response.clone()).unwrap();
1038
1039        let parsed = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1040            .unwrap()
1041            .unwrap();
1042
1043        assert_eq!(
1044            serde_json::to_value(parsed.info().unwrap()).unwrap(),
1045            response
1046        );
1047    }
1048
1049    #[rstest]
1050    #[case::perp("perps/instrument_eth.json")]
1051    #[case::option("options/instrument_eth.json")]
1052    #[case::spot("spot/instrument_eth.json")]
1053    fn test_parse_instrument_preserves_trading_parameters(#[case] filename: &str) {
1054        let mut response = load_json(filename);
1055        response["tick_size"] = json!("0.005");
1056        response["amount_step"] = json!("0.0002");
1057        response["maximum_amount"] = json!("1234.5678");
1058        response["minimum_amount"] = json!("0.03");
1059        let instrument: DeriveInstrument = serde_json::from_value(response).unwrap();
1060
1061        let parsed = parse_derive_instrument_any(&instrument, UnixNanos::from(987))
1062            .unwrap()
1063            .unwrap();
1064
1065        assert_eq!(parsed.price_increment(), Price::from("0.005"));
1066        assert_eq!(parsed.size_increment(), Quantity::from("0.0002"));
1067        assert_eq!(parsed.price_precision(), 3);
1068        assert_eq!(parsed.size_precision(), 4);
1069        assert_eq!(parsed.multiplier(), Quantity::from("1"));
1070        assert_eq!(parsed.lot_size(), Some(Quantity::from("0.0002")));
1071        assert_eq!(parsed.max_quantity(), Some(Quantity::from("1234.5678")));
1072        assert_eq!(parsed.min_quantity(), None);
1073        assert_eq!(parsed.ts_event(), UnixNanos::from(987));
1074        assert_eq!(parsed.ts_init(), UnixNanos::from(987));
1075        assert_eq!(
1076            parsed.info().unwrap().get_str("minimum_amount"),
1077            Some("0.03")
1078        );
1079    }
1080
1081    #[rstest]
1082    #[case::perp(DeriveInstrumentType::Perp)]
1083    #[case::option(DeriveInstrumentType::Option)]
1084    #[case::spot(DeriveInstrumentType::Erc20)]
1085    fn test_parse_instrument_rejects_non_positive_tick_size(
1086        #[case] instrument_type: DeriveInstrumentType,
1087    ) {
1088        let mut instrument = match instrument_type {
1089            DeriveInstrumentType::Perp => perp_fixture(),
1090            DeriveInstrumentType::Option => option_fixture(),
1091            DeriveInstrumentType::Erc20 => spot_fixture(),
1092            DeriveInstrumentType::Unknown => unreachable!(),
1093        };
1094
1095        instrument.tick_size = Decimal::ZERO;
1096
1097        let err = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1098            .expect_err("must reject non-positive tick size");
1099        let message = err.to_string();
1100
1101        assert!(message.contains("price_increment"), "{message}");
1102        assert!(message.contains("not positive"), "{message}");
1103    }
1104
1105    #[rstest]
1106    #[case("tick_size")]
1107    #[case("amount_step")]
1108    #[case("maximum_amount")]
1109    fn test_parse_instrument_rejects_excess_precision(
1110        #[case] field: &str,
1111        #[values(
1112            "perps/instrument_eth.json",
1113            "options/instrument_eth.json",
1114            "spot/instrument_eth.json"
1115        )]
1116        filename: &str,
1117    ) {
1118        let mut response = load_json(filename);
1119        response[field] = json!(Decimal::new(1, 28).to_string());
1120        let instrument: DeriveInstrument = serde_json::from_value(response).unwrap();
1121
1122        let error = parse_derive_instrument_any(&instrument, UnixNanos::from(123)).unwrap_err();
1123
1124        assert_eq!(error.to_string(), format!("invalid Derive {field}"));
1125    }
1126
1127    #[rstest]
1128    fn test_parse_perp_instrument_rejects_missing_perp_details() {
1129        let mut instrument = perp_fixture();
1130        instrument.perp_details = None;
1131
1132        let err = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1133            .expect_err("must reject missing perp details");
1134
1135        assert!(err.to_string().contains("missing perp_details"));
1136    }
1137
1138    #[rstest]
1139    fn test_parse_derive_instrument_any_skips_unknown_instrument_type() {
1140        let mut instrument = perp_fixture();
1141        instrument.instrument_type = DeriveInstrumentType::Unknown;
1142
1143        let parsed = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1144            .expect("unknown instrument type must not error");
1145
1146        assert!(parsed.is_none());
1147    }
1148
1149    #[rstest]
1150    fn test_parse_option_instrument_rejects_missing_option_details() {
1151        let mut instrument = option_fixture();
1152        instrument.option_details = None;
1153
1154        let err = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1155            .expect_err("must reject missing option details");
1156
1157        assert!(err.to_string().contains("missing option_details"));
1158    }
1159
1160    #[rstest]
1161    fn test_parse_option_instrument_rejects_negative_activation() {
1162        let mut instrument = option_fixture();
1163        instrument.scheduled_activation = -1;
1164
1165        let err = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1166            .expect_err("must reject negative activation timestamp");
1167
1168        assert!(
1169            err.to_string()
1170                .contains("negative Derive scheduled_activation")
1171        );
1172    }
1173
1174    #[rstest]
1175    fn test_parse_option_instrument_rejects_negative_expiry() {
1176        let mut instrument = option_fixture();
1177        instrument.option_details.as_mut().unwrap().expiry = -1;
1178
1179        let err = parse_derive_instrument_any(&instrument, UnixNanos::from(123))
1180            .expect_err("must reject negative expiry timestamp");
1181
1182        assert!(
1183            err.to_string()
1184                .contains("negative Derive option_details.expiry")
1185        );
1186    }
1187}