Skip to main content

nautilus_databento/decode/
custom.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 std::ffi::c_char;
17
18use databento::dbn;
19use nautilus_core::UnixNanos;
20use nautilus_model::{enums::FromU8, identifiers::InstrumentId, types::Quantity};
21
22use super::primitives::{
23    decode_optional_price, decode_optional_quantity, decode_price_or_undef, parse_order_side,
24};
25use crate::{
26    enums::{DatabentoStatisticType, DatabentoStatisticUpdateAction},
27    types::{DatabentoImbalance, DatabentoStatistics},
28};
29
30/// Decodes a Databento imbalance message into a `DatabentoImbalance` event.
31///
32/// # Errors
33///
34/// Returns an error if constructing `DatabentoImbalance` fails.
35pub fn decode_imbalance_msg(
36    msg: &dbn::ImbalanceMsg,
37    instrument_id: InstrumentId,
38    price_precision: u8,
39    ts_init: Option<UnixNanos>,
40) -> anyhow::Result<DatabentoImbalance> {
41    let ts_event = msg.ts_recv.into();
42    let ts_init = ts_init.unwrap_or(ts_event);
43
44    Ok(DatabentoImbalance::new(
45        instrument_id,
46        decode_price_or_undef(msg.ref_price, price_precision),
47        decode_price_or_undef(msg.cont_book_clr_price, price_precision),
48        decode_price_or_undef(msg.auct_interest_clr_price, price_precision),
49        Quantity::new(f64::from(msg.paired_qty), 0),
50        Quantity::new(f64::from(msg.total_imbalance_qty), 0),
51        parse_order_side(msg.side),
52        msg.significant_imbalance as c_char,
53        msg.hd.ts_event.into(),
54        ts_event,
55        ts_init,
56    ))
57}
58
59/// Decodes a Databento statistics message into a `DatabentoStatistics` event.
60///
61/// # Errors
62///
63/// Returns an error if constructing `DatabentoStatistics` fails or if `msg.update_action`
64/// is not a valid enum variant.
65///
66/// Returns `Ok(None)` when `msg.stat_type` does not map to a Nautilus variant: covers
67/// `VenueSpecificVolume1` (10001) and `VenueSpecificPrice1` (10002), which exceed the
68/// `u8` Arrow column width, plus any future dbn value.
69pub fn decode_statistics_msg(
70    msg: &dbn::StatMsg,
71    instrument_id: InstrumentId,
72    price_precision: u8,
73    ts_init: Option<UnixNanos>,
74) -> anyhow::Result<Option<DatabentoStatistics>> {
75    let Some(stat_type) = u8::try_from(msg.stat_type)
76        .ok()
77        .and_then(DatabentoStatisticType::from_u8)
78    else {
79        log::warn!(
80            "Skipping unsupported `stat_type` {} for {instrument_id}",
81            msg.stat_type,
82        );
83        return Ok(None);
84    };
85    let update_action =
86        DatabentoStatisticUpdateAction::from_u8(msg.update_action).ok_or_else(|| {
87            anyhow::anyhow!("Invalid value for `update_action`: {}", msg.update_action)
88        })?;
89    let ts_event = msg.ts_recv.into();
90    let ts_init = ts_init.unwrap_or(ts_event);
91
92    Ok(Some(DatabentoStatistics::new(
93        instrument_id,
94        stat_type,
95        update_action,
96        decode_optional_price(msg.price, price_precision),
97        decode_optional_quantity(msg.quantity)?,
98        msg.channel_id,
99        msg.stat_flags,
100        msg.sequence,
101        msg.ts_ref.into(),
102        msg.ts_in_delta,
103        msg.hd.ts_event.into(),
104        ts_event,
105        ts_init,
106    )))
107}
108
109/// Returns `true` if `stat_type` maps to a modeled [`DatabentoStatisticType`] variant.
110///
111/// Callers should precheck with this function before resolving price precision or other
112/// per-record setup, so unmodeled records can be skipped without surfacing unrelated
113/// errors.
114#[must_use]
115pub fn is_supported_stat_type(stat_type: u16) -> bool {
116    u8::try_from(stat_type)
117        .ok()
118        .and_then(DatabentoStatisticType::from_u8)
119        .is_some()
120}