nautilus_databento/decode/
primitives.rs1use std::ffi::c_char;
17
18use databento::dbn;
19use nautilus_core::UnixNanos;
20use nautilus_model::{
21 enums::{AggressorSide, AssetClass, BookAction, InstrumentClass, OptionKind, OrderSide},
22 identifiers::{InstrumentId, Symbol},
23 types::{
24 Currency, Price, Quantity,
25 fixed::{FIXED_PRECISION, FIXED_PRECISION_STANDARD},
26 price::{PRICE_UNDEF, decode_raw_price_i64},
27 },
28};
29use ustr::Ustr;
30
31#[must_use]
32pub const fn parse_optional_bool(c: c_char) -> Option<bool> {
33 match c as u8 as char {
34 'Y' => Some(true),
35 'N' => Some(false),
36 _ => None,
37 }
38}
39
40#[must_use]
41pub const fn parse_order_side(c: c_char) -> Option<OrderSide> {
42 match c as u8 as char {
43 'A' => Some(OrderSide::Sell),
44 'B' => Some(OrderSide::Buy),
45 _ => None,
46 }
47}
48
49#[must_use]
50pub const fn parse_aggressor_side(c: c_char) -> AggressorSide {
51 match c as u8 as char {
52 'A' => AggressorSide::Sell,
53 'B' => AggressorSide::Buy,
54 _ => AggressorSide::NoAggressor,
55 }
56}
57
58pub fn parse_book_action(c: c_char) -> anyhow::Result<BookAction> {
64 match c as u8 as char {
65 'A' => Ok(BookAction::Add),
66 'C' => Ok(BookAction::Delete),
67 'M' => Ok(BookAction::Update),
68 'R' => Ok(BookAction::Clear),
69 invalid => anyhow::bail!("Invalid `BookAction`, was '{invalid}'"),
74 }
75}
76
77pub fn parse_option_kind(c: c_char) -> anyhow::Result<OptionKind> {
83 match c as u8 as char {
84 'C' => Ok(OptionKind::Call),
85 'P' => Ok(OptionKind::Put),
86 invalid => anyhow::bail!("Invalid `OptionKind`, was '{invalid}'"),
87 }
88}
89
90pub(super) fn parse_currency_or_usd_default(
91 value: Result<&str, impl std::error::Error>,
92) -> Currency {
93 match value {
94 Ok(value) if !value.is_empty() => Currency::try_from_str(value).unwrap_or_else(|| {
95 log::warn!("Unknown currency code '{value}', defaulting to USD");
96 Currency::USD()
97 }),
98 Ok(_) => Currency::USD(),
99 Err(e) => {
100 log::warn!("Error parsing currency: {e}");
101 Currency::USD()
102 }
103 }
104}
105
106#[must_use]
110pub fn parse_cfi_iso10926(value: &str) -> (Option<AssetClass>, Option<InstrumentClass>) {
111 let chars: Vec<char> = value.chars().collect();
112 if chars.len() < 3 {
113 return (None, None);
114 }
115
116 let cfi_category = chars[0];
118 let cfi_group = chars[1];
119 let cfi_attribute1 = chars[2];
120 let mut asset_class = match cfi_category {
125 'D' => Some(AssetClass::Debt),
126 'E' => Some(AssetClass::Equity),
127 'S' => None,
128 _ => None,
129 };
130
131 let instrument_class = match cfi_group {
132 'I' => Some(InstrumentClass::Future),
133 _ => None,
134 };
135
136 if cfi_attribute1 == 'I' {
137 asset_class = Some(AssetClass::Index);
138 }
139
140 (asset_class, instrument_class)
141}
142
143pub(super) fn decode_underlying(underlying_str: &str, symbol: &Symbol) -> Ustr {
144 if underlying_str.is_empty() {
145 symbol
147 .as_str()
148 .split_whitespace()
149 .next()
150 .map_or_else(|| symbol.inner(), Ustr::from)
151 } else {
152 Ustr::from(underlying_str)
153 }
154}
155
156pub fn parse_status_reason(value: u16) -> anyhow::Result<Option<Ustr>> {
164 let value_str = match value {
165 0 => return Ok(None),
166 1 => "Scheduled",
167 2 => "Surveillance intervention",
168 3 => "Market event",
169 4 => "Instrument activation",
170 5 => "Instrument expiration",
171 6 => "Recovery in process",
172 10 => "Regulatory",
173 11 => "Administrative",
174 12 => "Non-compliance",
175 13 => "Filings not current",
176 14 => "SEC trading suspension",
177 15 => "New issue",
178 16 => "Issue available",
179 17 => "Issues reviewed",
180 18 => "Filing requirements satisfied",
181 30 => "News pending",
182 31 => "News released",
183 32 => "News and resumption times",
184 33 => "News not forthcoming",
185 40 => "Order imbalance",
186 50 => "LULD pause",
187 60 => "Operational",
188 70 => "Additional information requested",
189 80 => "Merger effective",
190 90 => "ETF",
191 100 => "Corporate action",
192 110 => "New Security offering",
193 120 => "Market wide halt level 1",
194 121 => "Market wide halt level 2",
195 122 => "Market wide halt level 3",
196 123 => "Market wide halt carryover",
197 124 => "Market wide halt resumption",
198 130 => "Quotation not available",
199 invalid => anyhow::bail!("Invalid `StatusMsg` reason, was '{invalid}'"),
200 };
201
202 Ok(Some(Ustr::from(value_str)))
203}
204
205pub fn parse_status_trading_event(value: u16) -> anyhow::Result<Option<Ustr>> {
211 let value_str = match value {
212 0 => return Ok(None),
213 1 => "No cancel",
214 2 => "Change trading session",
215 3 => "Implied matching on",
216 4 => "Implied matching off",
217 _ => anyhow::bail!("Invalid `StatusMsg` trading_event, was '{value}'"),
218 };
219
220 Ok(Some(Ustr::from(value_str)))
221}
222
223#[inline(always)]
232pub fn decode_price(value: i64, precision: u8, field_name: &str) -> anyhow::Result<Price> {
233 if value == i64::MAX {
234 anyhow::bail!("Missing required price for `{field_name}`")
235 } else {
236 decode_price_or_undef(value, precision)
237 .map_err(|e| anyhow::anyhow!("Invalid price for `{field_name}`: {e}"))
238 }
239}
240
241#[inline(always)]
250pub fn decode_optional_price(value: i64, precision: u8) -> anyhow::Result<Option<Price>> {
251 if value == i64::MAX {
252 Ok(None)
253 } else {
254 decode_price_or_undef(value, precision).map(Some)
255 }
256}
257
258#[inline(always)]
259pub(super) fn decode_price_field(
260 value: i64,
261 precision: u8,
262 instrument_id: InstrumentId,
263 field_name: &str,
264) -> anyhow::Result<Price> {
265 decode_price_or_undef(value, precision)
266 .map_err(|e| anyhow::anyhow!("Invalid `{field_name}` for {instrument_id}: {e}"))
267}
268
269#[inline(always)]
278pub fn decode_price_or_undef(value: i64, precision: u8) -> anyhow::Result<Price> {
279 if value == i64::MAX {
280 Ok(Price::from_raw(PRICE_UNDEF, 0))
281 } else {
282 let raw = decode_raw_price_i64(value);
283
284 let result = if precision > FIXED_PRECISION {
286 Price::from_mantissa_exponent_checked(
287 value,
288 -(FIXED_PRECISION_STANDARD as i8),
289 precision,
290 )
291 } else {
292 Price::from_raw_checked(raw, precision)
293 };
294
295 result.map_err(|e| {
296 let required = precision_from_raw(value);
297 if required > precision
298 && let Ok(price) = Price::from_raw_checked(raw, FIXED_PRECISION_STANDARD)
299 {
300 let price = price.to_string();
301 let price = price.trim_end_matches('0').trim_end_matches('.');
302 anyhow::anyhow!(
303 "Price {price} requires at least {required} decimal places, \
304 but resolved precision is {precision}; increase `price_precision` explicitly"
305 )
306 } else {
307 anyhow::anyhow!("Invalid price raw {value} at precision {precision}: {e}")
308 }
309 })
310 }
311}
312
313#[inline(always)]
319#[must_use]
320pub fn precision_from_raw(value: i64) -> u8 {
321 let mut v = value.unsigned_abs();
322 if v == 0 {
323 return 0;
324 }
325 let mut trailing = 0u8;
326 while trailing < 9 && v.is_multiple_of(10) {
327 v /= 10;
328 trailing += 1;
329 }
330 9 - trailing
331}
332
333#[inline(always)]
343#[must_use]
344pub fn decode_price_increment(value: i64, precision: u8) -> Price {
345 match value {
346 0 | i64::MAX => {
347 let exponent = i8::try_from(precision).expect("precision exceeded i8 range");
348 Price::from_mantissa_exponent(1, -exponent, precision)
349 }
350 _ => {
351 let derived = precision_from_raw(value).max(precision);
352 Price::from_raw(decode_raw_price_i64(value), derived)
353 }
354 }
355}
356
357#[inline(always)]
359#[must_use]
360pub fn decode_quantity(value: u64) -> Quantity {
361 quantity_from_whole(value)
362}
363
364#[inline(always)]
370pub fn decode_optional_quantity(value: i64) -> anyhow::Result<Option<Quantity>> {
371 match value {
372 i64::MAX => Ok(None),
373 value if value >= 0 => Ok(Some(quantity_from_whole(value as u64))),
374 value => anyhow::bail!("Invalid negative quantity: {value}"),
375 }
376}
377
378#[inline(always)]
386pub fn decode_timestamp(value: u64, field_name: &str) -> anyhow::Result<UnixNanos> {
387 if value == dbn::UNDEF_TIMESTAMP {
388 anyhow::bail!("Missing required timestamp for `{field_name}`")
389 } else {
390 Ok(UnixNanos::from(value))
391 }
392}
393
394#[inline(always)]
398#[must_use]
399pub fn decode_optional_timestamp(value: u64) -> Option<UnixNanos> {
400 if value == dbn::UNDEF_TIMESTAMP {
401 None
402 } else {
403 Some(UnixNanos::from(value))
404 }
405}
406
407pub fn decode_multiplier(value: i64) -> anyhow::Result<Quantity> {
414 const SCALE: u64 = 1_000_000_000;
415
416 match value {
417 0 | i64::MAX => Ok(quantity_from_whole(1)),
418 v if v < 0 => anyhow::bail!("Invalid negative multiplier: {v}"),
419 v => {
420 let mantissa = v as u64;
421 let mut frac_part = mantissa % SCALE;
422 let mut precision = 9u8;
423 while precision > 0 && frac_part.is_multiple_of(10) {
424 frac_part /= 10;
425 precision -= 1;
426 }
427
428 Ok(Quantity::from_mantissa_exponent_checked(
429 mantissa, -9, precision,
430 )?)
431 }
432 }
433}
434
435#[inline(always)]
441#[must_use]
442pub fn decode_lot_size(value: i32) -> Quantity {
443 match value {
444 0 | i32::MAX => quantity_from_whole(1),
445 value => {
446 assert!(value >= 0, "Invalid negative lot size: {value}");
447 quantity_from_whole(value as u64)
448 }
449 }
450}
451
452#[inline(always)]
453#[must_use]
454fn quantity_from_whole(value: u64) -> Quantity {
455 Quantity::from_mantissa_exponent(value, 0, 0)
456}