Skip to main content

nautilus_tardis/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
16use anyhow::Context;
17use nautilus_core::{UnixNanos, datetime::NANOSECONDS_IN_MICROSECOND};
18use nautilus_model::{
19    data::BarSpecification,
20    enums::{
21        AggressorSide, BarAggregation, BookAction, ExerciseStyle, OptionKind, OrderSide, PriceType,
22        SettlementType,
23    },
24    identifiers::{InstrumentId, Symbol, TradeId},
25    types::{PRICE_MAX, PRICE_MIN, Price, fixed::check_fixed_precision},
26};
27use rust_decimal::Decimal;
28use serde::{Deserialize, Deserializer, de};
29use ustr::Ustr;
30
31use super::enums::{TardisExchange, TardisInstrumentType, TardisOptionType};
32
33pub(crate) fn validate_non_zero_amount(value: f64, precision: u8) -> anyhow::Result<()> {
34    anyhow::ensure!(value != 0.0, "value was zero");
35    check_fixed_precision(precision)?;
36    let rounded_value =
37        (value * 10.0_f64.powi(i32::from(precision))).round() / 10.0_f64.powi(i32::from(precision));
38    anyhow::ensure!(
39        rounded_value != 0.0,
40        "value {value} was zero after rounding to precision {precision}"
41    );
42    Ok(())
43}
44
45// FNV-1a 64-bit constants (see http://www.isthe.com/chongo/tech/comp/fnv/).
46const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
47const FNV_PRIME: u64 = 0x0100_0000_01b3;
48
49/// Deserialize a string and convert to uppercase `Ustr`.
50///
51/// # Errors
52///
53/// Returns an error if the input is not a valid string.
54pub(crate) fn deserialize_uppercase<'de, D>(deserializer: D) -> Result<Ustr, D::Error>
55where
56    D: Deserializer<'de>,
57{
58    String::deserialize(deserializer).map(|s| Ustr::from(&s.to_uppercase()))
59}
60
61/// Deserializes an `f64` from a JSON number or numeric string.
62///
63/// # Errors
64///
65/// Returns an error if the input is not numeric or if the string cannot be parsed as `f64`.
66pub(crate) fn deserialize_f64_or_string<'de, D>(deserializer: D) -> Result<f64, D::Error>
67where
68    D: Deserializer<'de>,
69{
70    struct F64OrString;
71    impl<'de> de::Visitor<'de> for F64OrString {
72        type Value = f64;
73        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
74            f.write_str("f64 or string-encoded f64")
75        }
76        fn visit_f64<E: de::Error>(self, v: f64) -> Result<f64, E> {
77            Ok(v)
78        }
79        fn visit_i64<E: de::Error>(self, v: i64) -> Result<f64, E> {
80            Ok(v as f64)
81        }
82        fn visit_u64<E: de::Error>(self, v: u64) -> Result<f64, E> {
83            Ok(v as f64)
84        }
85        fn visit_str<E: de::Error>(self, v: &str) -> Result<f64, E> {
86            v.parse().map_err(de::Error::custom)
87        }
88        fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<f64, M::Error> {
89            serde_json::Number::deserialize(de::value::MapAccessDeserializer::new(map))?
90                .as_f64()
91                .ok_or_else(|| de::Error::custom("number is outside f64 bounds"))
92        }
93    }
94    deserializer.deserialize_any(F64OrString)
95}
96
97/// Deserializes an optional `f64` from null, a JSON number, or a numeric string.
98///
99/// # Errors
100///
101/// Returns an error if a non-null input is not numeric or if the string cannot be parsed as `f64`.
102pub(crate) fn deserialize_opt_f64_or_string<'de, D>(
103    deserializer: D,
104) -> Result<Option<f64>, D::Error>
105where
106    D: Deserializer<'de>,
107{
108    struct OptF64OrString;
109    impl<'de> de::Visitor<'de> for OptF64OrString {
110        type Value = Option<f64>;
111        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
112            f.write_str("null, f64, or string-encoded f64")
113        }
114        fn visit_none<E: de::Error>(self) -> Result<Option<f64>, E> {
115            Ok(None)
116        }
117        fn visit_unit<E: de::Error>(self) -> Result<Option<f64>, E> {
118            Ok(None)
119        }
120        fn visit_f64<E: de::Error>(self, v: f64) -> Result<Option<f64>, E> {
121            Ok(Some(v))
122        }
123        fn visit_i64<E: de::Error>(self, v: i64) -> Result<Option<f64>, E> {
124            Ok(Some(v as f64))
125        }
126        fn visit_u64<E: de::Error>(self, v: u64) -> Result<Option<f64>, E> {
127            Ok(Some(v as f64))
128        }
129        fn visit_str<E: de::Error>(self, v: &str) -> Result<Option<f64>, E> {
130            v.parse().map(Some).map_err(de::Error::custom)
131        }
132        fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Option<f64>, M::Error> {
133            deserialize_f64_or_string(de::value::MapAccessDeserializer::new(map)).map(Some)
134        }
135    }
136    deserializer.deserialize_any(OptF64OrString)
137}
138
139/// Derives a deterministic [`TradeId`] from trade fields.
140///
141/// Tardis records do not always carry a venue-provided trade ID (some venues
142/// publish empty strings or omit the field entirely). This hash combines the
143/// symbol, timestamp, price, amount, and side so replayed data yields the same
144/// identifier across runs. FNV-1a is stable across architectures and crate
145/// versions; the 0x1f delimiter keeps variable-length fields from colliding.
146///
147/// `price` and `amount` are plain decimal text without trailing zeros, such as the `Display`
148/// output of a normalized `Decimal` or of an `f64`, so equal values derive the same identifier
149/// from machine messages and CSV records.
150#[must_use]
151pub fn derive_trade_id(
152    symbol: Ustr,
153    ts_event_ns: u64,
154    price: &str,
155    amount: &str,
156    side: &str,
157) -> TradeId {
158    let mut hash: u64 = FNV_OFFSET_BASIS;
159
160    for bytes in [
161        symbol.as_bytes(),
162        b"\x1f",
163        &ts_event_ns.to_le_bytes(),
164        b"\x1f",
165        price.as_bytes(),
166        b"\x1f",
167        amount.as_bytes(),
168        b"\x1f",
169        side.as_bytes(),
170    ] {
171        for &byte in bytes {
172            hash ^= u64::from(byte);
173            hash = hash.wrapping_mul(FNV_PRIME);
174        }
175    }
176    TradeId::new(format!("{hash:016x}"))
177}
178
179#[must_use]
180#[inline]
181pub fn normalize_symbol_str(
182    symbol: Ustr,
183    exchange: &TardisExchange,
184    instrument_type: &TardisInstrumentType,
185    is_inverse: Option<bool>,
186) -> Ustr {
187    match exchange {
188        TardisExchange::Binance
189        | TardisExchange::BinanceFutures
190        | TardisExchange::BinanceUs
191        | TardisExchange::BinanceDex
192        | TardisExchange::BinanceJersey
193            if instrument_type == &TardisInstrumentType::Perpetual =>
194        {
195            append_suffix(symbol, "-PERP")
196        }
197
198        TardisExchange::Bybit | TardisExchange::BybitSpot | TardisExchange::BybitOptions => {
199            match instrument_type {
200                TardisInstrumentType::Spot => append_suffix(symbol, "-SPOT"),
201                TardisInstrumentType::Perpetual if !is_inverse.unwrap_or(false) => {
202                    append_suffix(symbol, "-LINEAR")
203                }
204                TardisInstrumentType::Future if !is_inverse.unwrap_or(false) => {
205                    append_suffix(symbol, "-LINEAR")
206                }
207                TardisInstrumentType::Perpetual if is_inverse == Some(true) => {
208                    append_suffix(symbol, "-INVERSE")
209                }
210                TardisInstrumentType::Future if is_inverse == Some(true) => {
211                    append_suffix(symbol, "-INVERSE")
212                }
213                TardisInstrumentType::Option => append_suffix(symbol, "-OPTION"),
214                _ => symbol,
215            }
216        }
217
218        TardisExchange::Dydx if instrument_type == &TardisInstrumentType::Perpetual => {
219            append_suffix(symbol, "-PERP")
220        }
221
222        TardisExchange::GateIoFutures if instrument_type == &TardisInstrumentType::Perpetual => {
223            append_suffix(symbol, "-PERP")
224        }
225
226        TardisExchange::MexcFutures if instrument_type == &TardisInstrumentType::Perpetual => {
227            append_suffix(symbol, "-PERP")
228        }
229
230        _ => symbol,
231    }
232}
233
234fn append_suffix(symbol: Ustr, suffix: &str) -> Ustr {
235    let mut symbol = symbol.to_string();
236    symbol.push_str(suffix);
237    Ustr::from(&symbol)
238}
239
240/// Parses a Nautilus instrument ID from the given Tardis `exchange` and `symbol` values.
241#[must_use]
242pub fn parse_instrument_id(exchange: &TardisExchange, symbol: Ustr) -> InstrumentId {
243    InstrumentId::new(Symbol::from_ustr_unchecked(symbol), exchange.as_venue())
244}
245
246/// Parses a Nautilus instrument ID with a normalized symbol from the given Tardis `exchange` and `symbol` values.
247#[must_use]
248pub fn normalize_instrument_id(
249    exchange: &TardisExchange,
250    symbol: Ustr,
251    instrument_type: &TardisInstrumentType,
252    is_inverse: Option<bool>,
253) -> InstrumentId {
254    let symbol = normalize_symbol_str(symbol, exchange, instrument_type, is_inverse);
255    parse_instrument_id(exchange, symbol)
256}
257
258/// Normalizes the given amount by truncating it to the specified decimal precision.
259///
260/// Amounts within 1e-9 of a step at `precision` (in units of that step) snap to the step
261/// instead, so upstream floating-point artifacts such as `2.9999999999999996` keep their
262/// intended size.
263///
264/// # Panics
265///
266/// Panics if `precision` exceeds 19, beyond which the tolerance is not representable.
267#[must_use]
268pub fn normalize_amount(amount: Decimal, precision: u8) -> Decimal {
269    let precision = u32::from(precision);
270    let rounded = amount.round_dp(precision);
271
272    if (rounded - amount).abs() < Decimal::new(1, 9 + precision) {
273        rounded
274    } else {
275        amount.trunc_with_scale(precision)
276    }
277}
278
279/// Parses a Nautilus price from the given `value`.
280///
281/// Values outside the representable range are capped to min/max price.
282#[must_use]
283pub fn parse_price(value: f64, precision: u8) -> Price {
284    match value {
285        v if (PRICE_MIN..=PRICE_MAX).contains(&v) => Price::new(value, precision),
286        v if v < PRICE_MIN => Price::min(precision),
287        _ => Price::max(precision),
288    }
289}
290
291/// Parses a Nautilus order side from the given Tardis string `value`.
292#[must_use]
293pub fn parse_order_side(value: &str) -> Option<OrderSide> {
294    match value {
295        "bid" => Some(OrderSide::Buy),
296        "ask" => Some(OrderSide::Sell),
297        _ => None,
298    }
299}
300
301/// Parses a Nautilus aggressor side from the given Tardis string `value`.
302#[must_use]
303pub fn parse_aggressor_side(value: &str) -> AggressorSide {
304    match value {
305        "buy" => AggressorSide::Buy,
306        "sell" => AggressorSide::Sell,
307        _ => AggressorSide::NoAggressor,
308    }
309}
310
311/// Parses a Nautilus option kind from the given Tardis enum `value`.
312#[must_use]
313pub const fn parse_option_kind(value: TardisOptionType) -> OptionKind {
314    match value {
315        TardisOptionType::Call => OptionKind::Call,
316        TardisOptionType::Put => OptionKind::Put,
317    }
318}
319
320/// Returns the option exercise style and settlement type for the given Tardis `exchange`.
321///
322/// Tardis metadata carries neither attribute, so each value follows the venue's contract
323/// specification. A value is `None` for an exchange with no verified specification, and for
324/// Deribit settlement, which no single settlement type represents.
325#[must_use]
326pub const fn option_terms(
327    exchange: TardisExchange,
328) -> (Option<ExerciseStyle>, Option<SettlementType>) {
329    match exchange {
330        TardisExchange::Deribit => (Some(ExerciseStyle::European), None),
331        TardisExchange::BybitOptions | TardisExchange::OkexOptions => {
332            (Some(ExerciseStyle::European), Some(SettlementType::Cash))
333        }
334        _ => (None, None),
335    }
336}
337
338/// Parses a UNIX nanoseconds timestamp from the given Tardis microseconds `value_us`.
339#[must_use]
340pub fn parse_timestamp(value_us: u64) -> UnixNanos {
341    value_us
342        .checked_mul(NANOSECONDS_IN_MICROSECOND)
343        .map_or_else(|| {
344            log::error!("Timestamp overflow: {value_us} microseconds exceeds maximum representable value");
345            UnixNanos::max()
346        }, UnixNanos::from)
347}
348
349/// Parses a Nautilus book action inferred from the given Tardis values.
350#[must_use]
351pub fn parse_book_action(is_snapshot: bool, amount: f64) -> BookAction {
352    if amount == 0.0 {
353        BookAction::Delete
354    } else if is_snapshot {
355        BookAction::Add
356    } else {
357        BookAction::Update
358    }
359}
360
361/// Parses a Nautilus bar specification from the given Tardis string `value`.
362///
363/// The [`PriceType`] is always `LAST` for Tardis trade bars.
364///
365/// # Errors
366///
367/// Returns an error if the specification format is invalid or if the aggregation suffix is unsupported.
368pub fn parse_bar_spec(value: &str) -> anyhow::Result<BarSpecification> {
369    let parts: Vec<&str> = value.split('_').collect();
370    let last_part = parts
371        .last()
372        .ok_or_else(|| anyhow::anyhow!("Invalid bar spec: empty string"))?;
373    let split_idx = last_part
374        .chars()
375        .position(|c| !c.is_ascii_digit())
376        .ok_or_else(|| anyhow::anyhow!("Invalid bar spec: no aggregation suffix in '{value}'"))?;
377
378    let (step_str, suffix) = last_part.split_at(split_idx);
379    let step: usize = step_str
380        .parse()
381        .map_err(|e| anyhow::anyhow!("Invalid step in bar spec '{value}': {e}"))?;
382
383    let aggregation = match suffix {
384        "ms" => BarAggregation::Millisecond,
385        "s" => BarAggregation::Second,
386        "m" => BarAggregation::Minute,
387        "ticks" => BarAggregation::Tick,
388        "vol" => BarAggregation::Volume,
389        _ => anyhow::bail!("Unsupported bar aggregation type: '{suffix}'"),
390    };
391
392    parse_canonical_bar_spec(step, aggregation)
393        .with_context(|| format!("Invalid bar spec '{value}'"))
394}
395
396fn parse_canonical_bar_spec(
397    step: usize,
398    aggregation: BarAggregation,
399) -> anyhow::Result<BarSpecification> {
400    match aggregation {
401        BarAggregation::Millisecond if step.is_multiple_of(1000) => {
402            parse_canonical_bar_spec(step / 1000, BarAggregation::Second)
403        }
404        BarAggregation::Second if step.is_multiple_of(60) => {
405            parse_canonical_bar_spec(step / 60, BarAggregation::Minute)
406        }
407        BarAggregation::Minute if step.is_multiple_of(60) => {
408            parse_canonical_bar_spec(step / 60, BarAggregation::Hour)
409        }
410        BarAggregation::Hour if step.is_multiple_of(24) => {
411            parse_canonical_bar_spec(step / 24, BarAggregation::Day)
412        }
413        _ => BarSpecification::new_checked(step, aggregation, PriceType::Last),
414    }
415}
416
417/// Converts a Nautilus `BarSpecification` to the Tardis trade bar string convention.
418///
419/// # Errors
420///
421/// Returns an error if the bar aggregation kind is unsupported.
422pub fn bar_spec_to_tardis_trade_bar_string(bar_spec: &BarSpecification) -> anyhow::Result<String> {
423    match bar_spec.aggregation {
424        BarAggregation::Hour => {
425            let minutes = bar_spec
426                .step
427                .get()
428                .checked_mul(60)
429                .context("bar specification step overflow")?;
430            return Ok(format!("trade_bar_{minutes}m"));
431        }
432        BarAggregation::Day => {
433            let minutes = bar_spec
434                .step
435                .get()
436                .checked_mul(1440)
437                .context("bar specification step overflow")?;
438            return Ok(format!("trade_bar_{minutes}m"));
439        }
440        _ => {}
441    }
442
443    let suffix = match bar_spec.aggregation {
444        BarAggregation::Millisecond => "ms",
445        BarAggregation::Second => "s",
446        BarAggregation::Minute => "m",
447        BarAggregation::Tick => "ticks",
448        BarAggregation::Volume => "vol",
449        _ => anyhow::bail!("Unsupported bar aggregation type: {}", bar_spec.aggregation),
450    };
451    Ok(format!("trade_bar_{}{}", bar_spec.step, suffix))
452}
453
454#[cfg(test)]
455mod tests {
456    use std::str::FromStr;
457
458    use rstest::rstest;
459    use rust_decimal_macros::dec;
460
461    use super::*;
462
463    #[rstest]
464    #[case("1e400")]
465    #[case("-1e400")]
466    fn test_deserialize_numeric_out_of_range(#[case] input: &str) {
467        let required = deserialize_f64_or_string(&mut serde_json::Deserializer::from_str(input));
468        let optional =
469            deserialize_opt_f64_or_string(&mut serde_json::Deserializer::from_str(input));
470
471        assert!(required.is_err());
472        assert!(optional.is_err());
473    }
474
475    #[rstest]
476    #[case(serde_json::json!(1.25), 1.25)]
477    #[case(serde_json::json!(25), 25.0)]
478    #[case(serde_json::json!(-3), -3.0)]
479    #[case(serde_json::json!("2.5e2"), 250.0)]
480    fn test_deserialize_numeric_fields(#[case] input: serde_json::Value, #[case] expected: f64) {
481        let json = input.to_string();
482        let required = deserialize_f64_or_string(&mut serde_json::Deserializer::from_str(&json));
483        let optional =
484            deserialize_opt_f64_or_string(&mut serde_json::Deserializer::from_str(&json));
485
486        assert_eq!(required.unwrap(), expected);
487        assert_eq!(optional.unwrap(), Some(expected));
488    }
489
490    #[rstest]
491    fn test_deserialize_numeric_null() {
492        let required = deserialize_f64_or_string(serde_json::Value::Null);
493        let optional = deserialize_opt_f64_or_string(serde_json::Value::Null);
494
495        assert!(required.is_err());
496        assert_eq!(optional.unwrap(), None);
497    }
498
499    #[rstest]
500    #[case(serde_json::json!({"number": "1.5"}))]
501    #[case(serde_json::json!(true))]
502    #[case(serde_json::json!("invalid"))]
503    fn test_deserialize_numeric_invalid(#[case] input: serde_json::Value) {
504        assert!(deserialize_f64_or_string(input.clone()).is_err());
505        assert!(deserialize_opt_f64_or_string(input).is_err());
506    }
507
508    #[rstest]
509    #[case(0.0, 0, false)]
510    #[case(0.0004, 3, false)]
511    #[case(0.0005, 3, true)]
512    #[case(123.456, 3, true)]
513    #[case(1.0, 255, false)]
514    fn test_validate_non_zero_amount(
515        #[case] amount: f64,
516        #[case] precision: u8,
517        #[case] expected: bool,
518    ) {
519        assert_eq!(
520            validate_non_zero_amount(amount, precision).is_ok(),
521            expected
522        );
523    }
524
525    #[rstest]
526    #[case(TardisExchange::Binance, "ETHUSDT", "ETHUSDT.BINANCE")]
527    #[case(TardisExchange::Bitmex, "XBTUSD", "XBTUSD.BITMEX")]
528    #[case(TardisExchange::Bybit, "BTCUSDT", "BTCUSDT.BYBIT")]
529    #[case(TardisExchange::OkexFutures, "BTC-USD-200313", "BTC-USD-200313.OKEX")]
530    #[case(TardisExchange::HuobiDmLinearSwap, "FOO-BAR", "FOO-BAR.HUOBI")]
531    #[case(TardisExchange::Mexc, "BTCUSDT", "BTCUSDT.MEXC")]
532    fn test_parse_instrument_id(
533        #[case] exchange: TardisExchange,
534        #[case] symbol: Ustr,
535        #[case] expected: &str,
536    ) {
537        let instrument_id = parse_instrument_id(&exchange, symbol);
538        let expected_instrument_id = InstrumentId::from_str(expected).unwrap();
539        assert_eq!(instrument_id, expected_instrument_id);
540    }
541
542    #[rstest]
543    #[case(
544        TardisExchange::Binance,
545        "SOLUSDT",
546        TardisInstrumentType::Spot,
547        None,
548        "SOLUSDT.BINANCE"
549    )]
550    #[case(
551        TardisExchange::BinanceFutures,
552        "SOLUSDT",
553        TardisInstrumentType::Perpetual,
554        None,
555        "SOLUSDT-PERP.BINANCE"
556    )]
557    #[case(
558        TardisExchange::Bybit,
559        "BTCUSDT",
560        TardisInstrumentType::Spot,
561        None,
562        "BTCUSDT-SPOT.BYBIT"
563    )]
564    #[case(
565        TardisExchange::Bybit,
566        "BTCUSDT",
567        TardisInstrumentType::Perpetual,
568        None,
569        "BTCUSDT-LINEAR.BYBIT"
570    )]
571    #[case(
572        TardisExchange::Bybit,
573        "BTCUSDT",
574        TardisInstrumentType::Perpetual,
575        Some(true),
576        "BTCUSDT-INVERSE.BYBIT"
577    )]
578    #[case(
579        TardisExchange::Dydx,
580        "BTC-USD",
581        TardisInstrumentType::Perpetual,
582        None,
583        "BTC-USD-PERP.DYDX"
584    )]
585    #[case(
586        TardisExchange::MexcFutures,
587        "BTC_USDT",
588        TardisInstrumentType::Perpetual,
589        None,
590        "BTC_USDT-PERP.MEXC"
591    )]
592    fn test_normalize_instrument_id(
593        #[case] exchange: TardisExchange,
594        #[case] symbol: Ustr,
595        #[case] instrument_type: TardisInstrumentType,
596        #[case] is_inverse: Option<bool>,
597        #[case] expected: &str,
598    ) {
599        let instrument_id =
600            normalize_instrument_id(&exchange, symbol, &instrument_type, is_inverse);
601        let expected_instrument_id = InstrumentId::from_str(expected).unwrap();
602        assert_eq!(instrument_id, expected_instrument_id);
603    }
604
605    #[rstest]
606    #[case(dec!(0.00001), 4, dec!(0))]
607    #[case(dec!(1.2345), 3, dec!(1.234))]
608    #[case(dec!(1.2345), 2, dec!(1.23))]
609    #[case(dec!(-1.2345), 3, dec!(-1.234))]
610    #[case(dec!(123.456), 0, dec!(123))]
611    #[case(dec!(0.1), 1, dec!(0.1))]
612    #[case(dec!(1.123456789), 9, dec!(1.123456789))]
613    #[case(dec!(0), 8, dec!(0))]
614    #[case(dec!(-0.1), 1, dec!(-0.1))]
615    #[case(dec!(2.9999999999999996), 0, dec!(3))]
616    #[case(dec!(0.29999999999999998), 1, dec!(0.3))]
617    #[case(dec!(2.999999998), 0, dec!(2))]
618    #[case(dec!(100000000.123456789), 8, dec!(100000000.12345678))]
619    fn test_normalize_amount(
620        #[case] amount: Decimal,
621        #[case] precision: u8,
622        #[case] expected: Decimal,
623    ) {
624        let result = normalize_amount(amount, precision);
625        assert_eq!(result, expected);
626    }
627
628    #[rstest]
629    #[case("bid", Some(OrderSide::Buy))]
630    #[case("ask", Some(OrderSide::Sell))]
631    #[case("unknown", None)]
632    #[case("", None)]
633    #[case("random", None)]
634    fn test_parse_order_side(#[case] input: &str, #[case] expected: Option<OrderSide>) {
635        assert_eq!(parse_order_side(input), expected);
636    }
637
638    #[rstest]
639    #[case("buy", AggressorSide::Buy)]
640    #[case("sell", AggressorSide::Sell)]
641    #[case("unknown", AggressorSide::NoAggressor)]
642    #[case("", AggressorSide::NoAggressor)]
643    #[case("random", AggressorSide::NoAggressor)]
644    fn test_parse_aggressor_side(#[case] input: &str, #[case] expected: AggressorSide) {
645        assert_eq!(parse_aggressor_side(input), expected);
646    }
647
648    #[rstest]
649    #[case::deribit(TardisExchange::Deribit, Some(ExerciseStyle::European), None)]
650    #[case::bybit_options(
651        TardisExchange::BybitOptions,
652        Some(ExerciseStyle::European),
653        Some(SettlementType::Cash)
654    )]
655    #[case::okex_options(
656        TardisExchange::OkexOptions,
657        Some(ExerciseStyle::European),
658        Some(SettlementType::Cash)
659    )]
660    #[case::binance_options(TardisExchange::BinanceOptions, None, None)]
661    #[case::binance_european_options(TardisExchange::BinanceEuropeanOptions, None, None)]
662    #[case::huobi_dm_options(TardisExchange::HuobiDmOptions, None, None)]
663    fn test_option_terms(
664        #[case] exchange: TardisExchange,
665        #[case] exercise_style: Option<ExerciseStyle>,
666        #[case] settlement_type: Option<SettlementType>,
667    ) {
668        assert_eq!(option_terms(exchange), (exercise_style, settlement_type));
669    }
670
671    #[rstest]
672    fn test_parse_timestamp() {
673        let input_timestamp: u64 = 1583020803145000;
674        let expected_nanos: UnixNanos =
675            UnixNanos::from(input_timestamp * NANOSECONDS_IN_MICROSECOND);
676
677        assert_eq!(parse_timestamp(input_timestamp), expected_nanos);
678    }
679
680    #[rstest]
681    #[case(true, 10.0, BookAction::Add)]
682    #[case(false, 0.0, BookAction::Delete)]
683    #[case(false, 10.0, BookAction::Update)]
684    fn test_parse_book_action(
685        #[case] is_snapshot: bool,
686        #[case] amount: f64,
687        #[case] expected: BookAction,
688    ) {
689        assert_eq!(parse_book_action(is_snapshot, amount), expected);
690    }
691
692    #[rstest]
693    #[case("trade_bar_10ms", 10, BarAggregation::Millisecond)]
694    #[case("trade_bar_10000ms", 10, BarAggregation::Second)]
695    #[case("trade_bar_5m", 5, BarAggregation::Minute)]
696    #[case("trade_bar_60m", 1, BarAggregation::Hour)]
697    #[case("trade_bar_100ticks", 100, BarAggregation::Tick)]
698    #[case("trade_bar_100000vol", 100000, BarAggregation::Volume)]
699    fn test_parse_bar_spec(
700        #[case] value: &str,
701        #[case] expected_step: usize,
702        #[case] expected_aggregation: BarAggregation,
703    ) {
704        let spec = parse_bar_spec(value).unwrap();
705        assert_eq!(spec.step.get(), expected_step);
706        assert_eq!(spec.aggregation, expected_aggregation);
707        assert_eq!(spec.price_type, PriceType::Last);
708    }
709
710    #[rstest]
711    #[case("trade_bar_10unknown", "Unsupported bar aggregation type")]
712    #[case("", "no aggregation suffix")]
713    #[case("trade_bar_notanumberms", "Invalid step")]
714    fn test_parse_bar_spec_errors(#[case] value: &str, #[case] expected_error: &str) {
715        let result = parse_bar_spec(value);
716        assert!(result.is_err());
717        assert!(
718            result.unwrap_err().to_string().contains(expected_error),
719            "Expected error containing '{expected_error}'"
720        );
721    }
722
723    #[rstest]
724    #[case(
725        BarSpecification::new(10, BarAggregation::Millisecond, PriceType::Last),
726        "trade_bar_10ms"
727    )]
728    #[case(
729        BarSpecification::new(5, BarAggregation::Minute, PriceType::Last),
730        "trade_bar_5m"
731    )]
732    #[case(
733        BarSpecification::new(1, BarAggregation::Hour, PriceType::Last),
734        "trade_bar_60m"
735    )]
736    #[case(
737        BarSpecification::new(2, BarAggregation::Day, PriceType::Last),
738        "trade_bar_2880m"
739    )]
740    #[case(
741        BarSpecification::new(100, BarAggregation::Tick, PriceType::Last),
742        "trade_bar_100ticks"
743    )]
744    #[case(
745        BarSpecification::new(100_000, BarAggregation::Volume, PriceType::Last),
746        "trade_bar_100000vol"
747    )]
748    fn test_to_tardis_string(#[case] bar_spec: BarSpecification, #[case] expected: &str) {
749        assert_eq!(
750            bar_spec_to_tardis_trade_bar_string(&bar_spec).unwrap(),
751            expected
752        );
753    }
754
755    #[rstest]
756    fn test_derive_trade_id_is_deterministic_and_16_hex_chars() {
757        let first = derive_trade_id(Ustr::from("XBTUSD"), 1_700_000_000, "7996", "50", "sell");
758        let second = derive_trade_id(Ustr::from("XBTUSD"), 1_700_000_000, "7996", "50", "sell");
759        assert_eq!(first, second);
760        assert_eq!(first.as_str().len(), 16);
761    }
762
763    #[rstest]
764    #[case::symbol_changed(derive_trade_id(Ustr::from("ETHUSD"), 1, "1", "1", "buy"))]
765    #[case::ts_changed(derive_trade_id(Ustr::from("XBTUSD"), 2, "1", "1", "buy"))]
766    #[case::price_changed(derive_trade_id(Ustr::from("XBTUSD"), 1, "2", "1", "buy"))]
767    #[case::amount_changed(derive_trade_id(Ustr::from("XBTUSD"), 1, "1", "2", "buy"))]
768    #[case::side_changed(derive_trade_id(Ustr::from("XBTUSD"), 1, "1", "1", "sell"))]
769    fn test_derive_trade_id_each_field_affects_output(#[case] altered: TradeId) {
770        let baseline = derive_trade_id(Ustr::from("XBTUSD"), 1, "1", "1", "buy");
771        assert_ne!(baseline, altered);
772    }
773
774    #[rstest]
775    fn test_derive_trade_id_field_delimiter_prevents_collision() {
776        // Without the 0x1f delimiter, concatenated bytes for these two inputs
777        // would collapse into the same stream.
778        let a = derive_trade_id(Ustr::from("A"), 1, "0", "0", "buy");
779        let b = derive_trade_id(Ustr::from("A\x00"), 256, "0", "0", "buy");
780        assert_ne!(a, b);
781    }
782
783    #[rstest]
784    fn test_derive_trade_id_matches_csv_and_machine_text() {
785        let price = dec!(7996.50).normalize().to_string();
786        let amount = dec!(0.000000150).normalize().to_string();
787
788        let machine = derive_trade_id(Ustr::from("XBTUSD"), 1, &price, &amount, "buy");
789        let csv = derive_trade_id(
790            Ustr::from("XBTUSD"),
791            1,
792            &7996.5_f64.to_string(),
793            &0.000_000_15_f64.to_string(),
794            "buy",
795        );
796
797        assert_eq!(machine, csv);
798    }
799}