nautilus_databento/decode/
custom.rs1use std::ffi::c_char;
17
18use databento::dbn;
19use nautilus_core::UnixNanos;
20use nautilus_model::{
21 enums::FromU8,
22 identifiers::InstrumentId,
23 types::{Quantity, fixed::FIXED_PRECISION_STANDARD},
24};
25
26use super::primitives::{
27 decode_optional_price, decode_optional_quantity, decode_price_field, parse_order_side,
28};
29use crate::{
30 enums::{DatabentoStatisticType, DatabentoStatisticUpdateAction},
31 types::{DatabentoImbalance, DatabentoStatistics},
32};
33
34pub fn decode_imbalance_msg(
40 msg: &dbn::ImbalanceMsg,
41 instrument_id: InstrumentId,
42 price_precision: u8,
43 ts_init: Option<UnixNanos>,
44) -> anyhow::Result<DatabentoImbalance> {
45 let ts_event = msg.ts_recv.into();
46 let ts_init = ts_init.unwrap_or(ts_event);
47
48 Ok(DatabentoImbalance::new(
49 instrument_id,
50 decode_price_field(msg.ref_price, price_precision, instrument_id, "ref_price")?,
51 decode_price_field(
52 msg.cont_book_clr_price,
53 price_precision,
54 instrument_id,
55 "cont_book_clr_price",
56 )?,
57 decode_price_field(
58 msg.auct_interest_clr_price,
59 price_precision,
60 instrument_id,
61 "auct_interest_clr_price",
62 )?,
63 Quantity::from_mantissa_exponent(u64::from(msg.paired_qty), 0, 0),
64 Quantity::from_mantissa_exponent(u64::from(msg.total_imbalance_qty), 0, 0),
65 parse_order_side(msg.side),
66 msg.significant_imbalance as c_char,
67 msg.hd.ts_event.into(),
68 ts_event,
69 ts_init,
70 ))
71}
72
73pub fn decode_statistics_msg(
87 msg: &dbn::StatMsg,
88 instrument_id: InstrumentId,
89 price_precision: u8,
90 ts_init: Option<UnixNanos>,
91) -> anyhow::Result<Option<DatabentoStatistics>> {
92 let Some(stat_type) = u8::try_from(msg.stat_type)
93 .ok()
94 .and_then(DatabentoStatisticType::from_u8)
95 else {
96 log::warn!(
97 "Skipping unsupported `stat_type` {} for {instrument_id}",
98 msg.stat_type,
99 );
100 return Ok(None);
101 };
102 let update_action =
103 DatabentoStatisticUpdateAction::from_u8(msg.update_action).ok_or_else(|| {
104 anyhow::anyhow!("Invalid value for `update_action`: {}", msg.update_action)
105 })?;
106 let ts_event = msg.ts_recv.into();
107 let ts_init = ts_init.unwrap_or(ts_event);
108 let price_precision = price_precision.max(FIXED_PRECISION_STANDARD);
109
110 Ok(Some(DatabentoStatistics::new(
111 instrument_id,
112 stat_type,
113 update_action,
114 decode_optional_price(msg.price, price_precision)
115 .map_err(|e| anyhow::anyhow!("Invalid `price` for {instrument_id}: {e}"))?,
116 decode_optional_quantity(msg.quantity)?,
117 msg.channel_id,
118 msg.stat_flags,
119 msg.sequence,
120 msg.ts_ref.into(),
121 msg.ts_in_delta,
122 msg.hd.ts_event.into(),
123 ts_event,
124 ts_init,
125 )))
126}
127
128#[must_use]
134pub fn is_supported_stat_type(stat_type: u16) -> bool {
135 u8::try_from(stat_type)
136 .ok()
137 .and_then(DatabentoStatisticType::from_u8)
138 .is_some()
139}