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::{
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
34/// Decodes a Databento imbalance message into a `DatabentoImbalance` event.
35///
36/// # Errors
37///
38/// Returns an error if constructing `DatabentoImbalance` fails.
39pub 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
73/// Decodes a Databento statistics message into a `DatabentoStatistics` event.
74///
75/// The decoded price uses at least the nine-decimal wire precision, preserving statistics such as
76/// VWAP, volatility, and delta independently of the instrument tick size.
77///
78/// # Errors
79///
80/// Returns an error if constructing `DatabentoStatistics` fails or if `msg.update_action`
81/// is not a valid enum variant.
82///
83/// Returns `Ok(None)` when `msg.stat_type` does not map to a Nautilus variant: covers
84/// `VenueSpecificVolume1` (10001) and `VenueSpecificPrice1` (10002), which exceed the
85/// `u8` Arrow column width, plus any future dbn value.
86pub 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/// Returns `true` if `stat_type` maps to a modeled [`DatabentoStatisticType`] variant.
129///
130/// Callers should precheck with this function before resolving price precision or other
131/// per-record setup, so unmodeled records can be skipped without surfacing unrelated
132/// errors.
133#[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}