nautilus_databento/decode/
primitives.rs1use std::ffi::c_char;
17
18use databento::dbn;
19use nautilus_core::UnixNanos;
20use nautilus_model::{
21 enums::{
22 AggressorSide, AssetClass, BookAction, ExerciseStyle, InstrumentClass, OptionKind,
23 OrderSide, SettlementType,
24 },
25 identifiers::{InstrumentId, Symbol},
26 types::{
27 Currency, Price, Quantity,
28 fixed::{FIXED_PRECISION, FIXED_PRECISION_STANDARD},
29 price::{PRICE_UNDEF, decode_raw_price_i64},
30 },
31};
32use ustr::Ustr;
33
34#[must_use]
35pub const fn parse_optional_bool(c: c_char) -> Option<bool> {
36 match c as u8 as char {
37 'Y' => Some(true),
38 'N' => Some(false),
39 _ => None,
40 }
41}
42
43#[must_use]
44pub const fn parse_order_side(c: c_char) -> Option<OrderSide> {
45 match c as u8 as char {
46 'A' => Some(OrderSide::Sell),
47 'B' => Some(OrderSide::Buy),
48 _ => None,
49 }
50}
51
52#[must_use]
53pub const fn parse_aggressor_side(c: c_char) -> AggressorSide {
54 match c as u8 as char {
55 'A' => AggressorSide::Sell,
56 'B' => AggressorSide::Buy,
57 _ => AggressorSide::NoAggressor,
58 }
59}
60
61pub fn parse_book_action(c: c_char) -> anyhow::Result<BookAction> {
67 match c as u8 as char {
68 'A' => Ok(BookAction::Add),
69 'C' => Ok(BookAction::Delete),
70 'M' => Ok(BookAction::Update),
71 'R' => Ok(BookAction::Clear),
72 invalid => anyhow::bail!("Invalid `BookAction`, was '{invalid}'"),
77 }
78}
79
80pub fn parse_option_kind(c: c_char) -> anyhow::Result<OptionKind> {
86 match c as u8 as char {
87 'C' => Ok(OptionKind::Call),
88 'P' => Ok(OptionKind::Put),
89 invalid => anyhow::bail!("Invalid `OptionKind`, was '{invalid}'"),
90 }
91}
92
93pub(super) fn parse_currency_or_usd_default(
94 value: Result<&str, impl std::error::Error>,
95) -> Currency {
96 match value {
97 Ok(value) if !value.is_empty() => Currency::try_from_str(value).unwrap_or_else(|| {
98 log::warn!("Unknown currency code '{value}', defaulting to USD");
99 Currency::USD()
100 }),
101 Ok(_) => Currency::USD(),
102 Err(e) => {
103 log::warn!("Error parsing currency: {e}");
104 Currency::USD()
105 }
106 }
107}
108
109#[must_use]
113pub fn parse_cfi_iso10926(value: &str) -> (Option<AssetClass>, Option<InstrumentClass>) {
114 let chars: Vec<char> = value.chars().collect();
115 if chars.len() < 3 {
116 return (None, None);
117 }
118
119 let cfi_category = chars[0];
121 let cfi_group = chars[1];
122 let cfi_attribute1 = chars[2];
123 let mut asset_class = match cfi_category {
128 'D' => Some(AssetClass::Debt),
129 'E' => Some(AssetClass::Equity),
130 'S' => None,
131 _ => None,
132 };
133
134 let instrument_class = match cfi_group {
135 'I' => Some(InstrumentClass::Future),
136 _ => None,
137 };
138
139 if cfi_attribute1 == 'I' {
140 asset_class = Some(AssetClass::Index);
141 }
142
143 (asset_class, instrument_class)
144}
145
146pub(super) fn parse_cfi_option_terms(
148 value: &str,
149) -> (Option<ExerciseStyle>, Option<SettlementType>) {
150 let code = value.as_bytes();
151
152 if !matches!(code, [b'O', b'C' | b'P', ..]) {
153 return (None, None);
154 }
155
156 let exercise_style = match code.get(2) {
157 Some(b'A') => Some(ExerciseStyle::American),
158 Some(b'E') => Some(ExerciseStyle::European),
159 Some(b'B') => Some(ExerciseStyle::Bermudan),
160 _ => None,
161 };
162
163 let settlement_type = match code.get(4) {
164 Some(b'C') => Some(SettlementType::Cash),
165 Some(b'P') => Some(SettlementType::Physical),
166 _ => None,
167 };
168
169 (exercise_style, settlement_type)
170}
171
172pub(super) fn decode_underlying(underlying_str: &str, symbol: &Symbol) -> Ustr {
173 if underlying_str.is_empty() {
174 symbol
176 .as_str()
177 .split_whitespace()
178 .next()
179 .map_or_else(|| symbol.inner(), Ustr::from)
180 } else {
181 Ustr::from(underlying_str)
182 }
183}
184
185pub fn parse_status_reason(value: u16) -> anyhow::Result<Option<Ustr>> {
193 let value_str = match value {
194 0 => return Ok(None),
195 1 => "Scheduled",
196 2 => "Surveillance intervention",
197 3 => "Market event",
198 4 => "Instrument activation",
199 5 => "Instrument expiration",
200 6 => "Recovery in process",
201 10 => "Regulatory",
202 11 => "Administrative",
203 12 => "Non-compliance",
204 13 => "Filings not current",
205 14 => "SEC trading suspension",
206 15 => "New issue",
207 16 => "Issue available",
208 17 => "Issues reviewed",
209 18 => "Filing requirements satisfied",
210 30 => "News pending",
211 31 => "News released",
212 32 => "News and resumption times",
213 33 => "News not forthcoming",
214 40 => "Order imbalance",
215 50 => "LULD pause",
216 60 => "Operational",
217 70 => "Additional information requested",
218 80 => "Merger effective",
219 90 => "ETF",
220 100 => "Corporate action",
221 110 => "New Security offering",
222 120 => "Market wide halt level 1",
223 121 => "Market wide halt level 2",
224 122 => "Market wide halt level 3",
225 123 => "Market wide halt carryover",
226 124 => "Market wide halt resumption",
227 130 => "Quotation not available",
228 invalid => anyhow::bail!("Invalid `StatusMsg` reason, was '{invalid}'"),
229 };
230
231 Ok(Some(Ustr::from(value_str)))
232}
233
234pub fn parse_status_trading_event(value: u16) -> anyhow::Result<Option<Ustr>> {
240 let value_str = match value {
241 0 => return Ok(None),
242 1 => "No cancel",
243 2 => "Change trading session",
244 3 => "Implied matching on",
245 4 => "Implied matching off",
246 _ => anyhow::bail!("Invalid `StatusMsg` trading_event, was '{value}'"),
247 };
248
249 Ok(Some(Ustr::from(value_str)))
250}
251
252#[inline(always)]
261pub fn decode_price(value: i64, precision: u8, field_name: &str) -> anyhow::Result<Price> {
262 if value == i64::MAX {
263 anyhow::bail!("Missing required price for `{field_name}`")
264 } else {
265 decode_price_or_undef(value, precision)
266 .map_err(|e| anyhow::anyhow!("Invalid price for `{field_name}`: {e}"))
267 }
268}
269
270#[inline(always)]
279pub fn decode_optional_price(value: i64, precision: u8) -> anyhow::Result<Option<Price>> {
280 if value == i64::MAX {
281 Ok(None)
282 } else {
283 decode_price_or_undef(value, precision).map(Some)
284 }
285}
286
287#[inline(always)]
288pub(super) fn decode_price_field(
289 value: i64,
290 precision: u8,
291 instrument_id: InstrumentId,
292 field_name: &str,
293) -> anyhow::Result<Price> {
294 decode_price_or_undef(value, precision)
295 .map_err(|e| anyhow::anyhow!("Invalid `{field_name}` for {instrument_id}: {e}"))
296}
297
298#[inline(always)]
307pub fn decode_price_or_undef(value: i64, precision: u8) -> anyhow::Result<Price> {
308 if value == i64::MAX {
309 Ok(Price::from_raw(PRICE_UNDEF, 0))
310 } else {
311 let raw = decode_raw_price_i64(value);
312
313 let result = if precision > FIXED_PRECISION {
315 Price::from_mantissa_exponent_checked(
316 value,
317 -(FIXED_PRECISION_STANDARD as i8),
318 precision,
319 )
320 } else {
321 Price::from_raw_checked(raw, precision)
322 };
323
324 result.map_err(|e| {
325 let required = precision_from_raw(value);
326 if required > precision
327 && let Ok(price) = Price::from_raw_checked(raw, FIXED_PRECISION_STANDARD)
328 {
329 let price = price.to_string();
330 let price = price.trim_end_matches('0').trim_end_matches('.');
331 anyhow::anyhow!(
332 "Price {price} requires at least {required} decimal places, \
333 but resolved precision is {precision}; increase `price_precision` explicitly"
334 )
335 } else {
336 anyhow::anyhow!("Invalid price raw {value} at precision {precision}: {e}")
337 }
338 })
339 }
340}
341
342#[inline(always)]
348#[must_use]
349pub fn precision_from_raw(value: i64) -> u8 {
350 let mut v = value.unsigned_abs();
351 if v == 0 {
352 return 0;
353 }
354 let mut trailing = 0u8;
355 while trailing < 9 && v.is_multiple_of(10) {
356 v /= 10;
357 trailing += 1;
358 }
359 9 - trailing
360}
361
362#[inline(always)]
372#[must_use]
373pub fn decode_price_increment(value: i64, precision: u8) -> Price {
374 match value {
375 0 | i64::MAX => {
376 let exponent = i8::try_from(precision).expect("precision exceeded i8 range");
377 Price::from_mantissa_exponent(1, -exponent, precision)
378 }
379 _ => {
380 let derived = precision_from_raw(value).max(precision);
381 Price::from_raw(decode_raw_price_i64(value), derived)
382 }
383 }
384}
385
386#[inline(always)]
388#[must_use]
389pub fn decode_quantity(value: u64) -> Quantity {
390 quantity_from_whole(value)
391}
392
393#[inline(always)]
399pub fn decode_optional_quantity(value: i64) -> anyhow::Result<Option<Quantity>> {
400 match value {
401 i64::MAX => Ok(None),
402 value if value >= 0 => Ok(Some(quantity_from_whole(value as u64))),
403 value => anyhow::bail!("Invalid negative quantity: {value}"),
404 }
405}
406
407#[inline(always)]
415pub fn decode_timestamp(value: u64, field_name: &str) -> anyhow::Result<UnixNanos> {
416 if value == dbn::UNDEF_TIMESTAMP {
417 anyhow::bail!("Missing required timestamp for `{field_name}`")
418 } else {
419 Ok(UnixNanos::from(value))
420 }
421}
422
423#[inline(always)]
427#[must_use]
428pub fn decode_optional_timestamp(value: u64) -> Option<UnixNanos> {
429 if value == dbn::UNDEF_TIMESTAMP {
430 None
431 } else {
432 Some(UnixNanos::from(value))
433 }
434}
435
436pub fn decode_multiplier(value: i64) -> anyhow::Result<Quantity> {
443 const SCALE: u64 = 1_000_000_000;
444
445 match value {
446 0 | i64::MAX => Ok(quantity_from_whole(1)),
447 v if v < 0 => anyhow::bail!("Invalid negative multiplier: {v}"),
448 v => {
449 let mantissa = v as u64;
450 let mut frac_part = mantissa % SCALE;
451 let mut precision = 9u8;
452 while precision > 0 && frac_part.is_multiple_of(10) {
453 frac_part /= 10;
454 precision -= 1;
455 }
456
457 Ok(Quantity::from_mantissa_exponent_checked(
458 mantissa, -9, precision,
459 )?)
460 }
461 }
462}
463
464#[inline(always)]
470#[must_use]
471pub fn decode_lot_size(value: i32) -> Quantity {
472 match value {
473 0 | i32::MAX => quantity_from_whole(1),
474 value => {
475 assert!(value >= 0, "Invalid negative lot size: {value}");
476 quantity_from_whole(value as u64)
477 }
478 }
479}
480
481#[inline(always)]
482#[must_use]
483fn quantity_from_whole(value: u64) -> Quantity {
484 Quantity::from_mantissa_exponent(value, 0, 0)
485}