Skip to main content

flexpool_core/
quantize.rs

1//! The single boundary where a planner's `f64` becomes a market quantity.
2//!
3//! The planner and the forecasts compute in `f64`. Everything that leaves the system — bids,
4//! orders, schedules, setpoints — passes [`quantize`], which refuses non-finite input, converts
5//! through the shortest decimal representation that round-trips the `f64` (so `0.1` becomes
6//! exactly `0.1`, not `0.1000000000000000055…`), and rounds to the product's granularity in a
7//! stated direction. The result carries the rule it applied, for the decision record.
8//!
9//! This is the only module allowed to turn a float into a `Decimal`; `cargo xtask
10//! check-conversions` and the clippy bans in `clippy.toml` enforce that.
11
12use std::str::FromStr as _;
13
14use rust_decimal::{Decimal, RoundingStrategy};
15use serde::{Deserialize, Serialize};
16
17/// Rounding direction to a granularity step.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum RoundDirection {
21    /// Towards zero — an offer never promises more than planned, for consumption (positive) and
22    /// feed-in (negative) alike.
23    TowardZero,
24    /// Away from zero.
25    AwayFromZero,
26    /// To the nearest step, ties to even.
27    NearestHalfEven,
28}
29
30/// The smallest tradable step of a quantity or price, with the rounding direction to use.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32pub struct Granularity {
33    #[serde(with = "rust_decimal::serde::str")]
34    step: Decimal,
35    direction: RoundDirection,
36}
37
38impl Granularity {
39    /// A granularity of `step` (must be > 0) rounded in `direction`.
40    ///
41    /// # Errors
42    /// [`QuantizeError::InvalidStep`] if `step` is not positive.
43    pub fn new(step: Decimal, direction: RoundDirection) -> Result<Self, QuantizeError> {
44        if step > Decimal::ZERO {
45            Ok(Self { step, direction })
46        } else {
47            Err(QuantizeError::InvalidStep(step))
48        }
49    }
50
51    /// The step.
52    #[must_use]
53    pub const fn step(&self) -> Decimal {
54        self.step
55    }
56
57    /// The direction.
58    #[must_use]
59    pub const fn direction(&self) -> RoundDirection {
60        self.direction
61    }
62}
63
64/// Why a value could not be quantised.
65#[derive(Debug, Clone, PartialEq, thiserror::Error)]
66pub enum QuantizeError {
67    /// NaN or ±∞ — a solver failure, never a quantity.
68    #[error("non-finite planner value {0}")]
69    NonFinite(f64),
70    /// Finite but outside the exact decimal range.
71    #[error("planner value {0} is outside the exact decimal range")]
72    OutOfRange(f64),
73    /// A granularity step that is zero or negative.
74    #[error("granularity step {0} must be positive")]
75    InvalidStep(Decimal),
76}
77
78/// A market quantity together with the rule that produced it.
79#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
80pub struct Quantized {
81    /// The exact market quantity.
82    #[serde(with = "rust_decimal::serde::str")]
83    pub value: Decimal,
84    /// The planner value it came from.
85    pub input: f64,
86    /// The rule applied.
87    pub granularity: Granularity,
88}
89
90/// Turns a planner number into a market quantity on `granularity`.
91///
92/// # Errors
93/// [`QuantizeError::NonFinite`] for NaN or ±∞; [`QuantizeError::OutOfRange`] beyond `Decimal`.
94pub fn quantize(value: f64, granularity: Granularity) -> Result<Quantized, QuantizeError> {
95    if !value.is_finite() {
96        return Err(QuantizeError::NonFinite(value));
97    }
98    // `Display` for f64 prints the shortest representation that round-trips; `{:e}` handles
99    // magnitudes Display would expand to hundreds of digits.
100    let exact = Decimal::from_str(&value.to_string())
101        .or_else(|_| Decimal::from_scientific(&format!("{value:e}")))
102        .map_err(|_| QuantizeError::OutOfRange(value))?;
103    // Below Decimal's precision (|x| < 1e-28) the shortest representation rounds to zero; keep the
104    // sign so that away-from-zero still yields one step.
105    let exact = if exact.is_zero() && value != 0.0 {
106        Decimal::new(if value < 0.0 { -1 } else { 1 }, 28)
107    } else {
108        exact
109    };
110    let steps = exact
111        .checked_div(granularity.step)
112        .ok_or(QuantizeError::OutOfRange(value))?;
113    let rounded = match granularity.direction {
114        RoundDirection::TowardZero => steps.trunc(),
115        RoundDirection::AwayFromZero => {
116            if steps == steps.trunc() {
117                steps
118            } else if steps.is_sign_negative() {
119                steps.floor()
120            } else {
121                steps.ceil()
122            }
123        }
124        RoundDirection::NearestHalfEven => {
125            steps.round_dp_with_strategy(0, RoundingStrategy::MidpointNearestEven)
126        }
127    };
128    let quantity = rounded
129        .checked_mul(granularity.step)
130        .ok_or(QuantizeError::OutOfRange(value))?
131        .normalize();
132    Ok(Quantized {
133        value: quantity,
134        input: value,
135        granularity,
136    })
137}