flexpool-core 0.3.0

flexpool domain core: exact energy and money units, the Europe/Berlin quarter-hour calendar, portfolio identities and the single quantisation boundary. No I/O, no clock.
Documentation
//! The single boundary where a planner's `f64` becomes a market quantity.
//!
//! The planner and the forecasts compute in `f64`. Everything that leaves the system — bids,
//! orders, schedules, setpoints — passes [`quantize`], which refuses non-finite input, converts
//! through the shortest decimal representation that round-trips the `f64` (so `0.1` becomes
//! exactly `0.1`, not `0.1000000000000000055…`), and rounds to the product's granularity in a
//! stated direction. The result carries the rule it applied, for the decision record.
//!
//! This is the only module allowed to turn a float into a `Decimal`; `cargo xtask
//! check-conversions` and the clippy bans in `clippy.toml` enforce that.

use std::str::FromStr as _;

use rust_decimal::{Decimal, RoundingStrategy};
use serde::{Deserialize, Serialize};

/// Rounding direction to a granularity step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RoundDirection {
    /// Towards zero — an offer never promises more than planned, for consumption (positive) and
    /// feed-in (negative) alike.
    TowardZero,
    /// Away from zero.
    AwayFromZero,
    /// To the nearest step, ties to even.
    NearestHalfEven,
}

/// The smallest tradable step of a quantity or price, with the rounding direction to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Granularity {
    #[serde(with = "rust_decimal::serde::str")]
    step: Decimal,
    direction: RoundDirection,
}

impl Granularity {
    /// A granularity of `step` (must be > 0) rounded in `direction`.
    ///
    /// # Errors
    /// [`QuantizeError::InvalidStep`] if `step` is not positive.
    pub fn new(step: Decimal, direction: RoundDirection) -> Result<Self, QuantizeError> {
        if step > Decimal::ZERO {
            Ok(Self { step, direction })
        } else {
            Err(QuantizeError::InvalidStep(step))
        }
    }

    /// The step.
    #[must_use]
    pub const fn step(&self) -> Decimal {
        self.step
    }

    /// The direction.
    #[must_use]
    pub const fn direction(&self) -> RoundDirection {
        self.direction
    }
}

/// Why a value could not be quantised.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum QuantizeError {
    /// NaN or ±∞ — a solver failure, never a quantity.
    #[error("non-finite planner value {0}")]
    NonFinite(f64),
    /// Finite but outside the exact decimal range.
    #[error("planner value {0} is outside the exact decimal range")]
    OutOfRange(f64),
    /// A granularity step that is zero or negative.
    #[error("granularity step {0} must be positive")]
    InvalidStep(Decimal),
}

/// A market quantity together with the rule that produced it.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Quantized {
    /// The exact market quantity.
    #[serde(with = "rust_decimal::serde::str")]
    pub value: Decimal,
    /// The planner value it came from.
    pub input: f64,
    /// The rule applied.
    pub granularity: Granularity,
}

/// Turns a planner number into a market quantity on `granularity`.
///
/// # Errors
/// [`QuantizeError::NonFinite`] for NaN or ±∞; [`QuantizeError::OutOfRange`] beyond `Decimal`.
pub fn quantize(value: f64, granularity: Granularity) -> Result<Quantized, QuantizeError> {
    if !value.is_finite() {
        return Err(QuantizeError::NonFinite(value));
    }
    // `Display` for f64 prints the shortest representation that round-trips; `{:e}` handles
    // magnitudes Display would expand to hundreds of digits.
    let exact = Decimal::from_str(&value.to_string())
        .or_else(|_| Decimal::from_scientific(&format!("{value:e}")))
        .map_err(|_| QuantizeError::OutOfRange(value))?;
    // Below Decimal's precision (|x| < 1e-28) the shortest representation rounds to zero; keep the
    // sign so that away-from-zero still yields one step.
    let exact = if exact.is_zero() && value != 0.0 {
        Decimal::new(if value < 0.0 { -1 } else { 1 }, 28)
    } else {
        exact
    };
    let steps = exact
        .checked_div(granularity.step)
        .ok_or(QuantizeError::OutOfRange(value))?;
    let rounded = match granularity.direction {
        RoundDirection::TowardZero => steps.trunc(),
        RoundDirection::AwayFromZero => {
            if steps == steps.trunc() {
                steps
            } else if steps.is_sign_negative() {
                steps.floor()
            } else {
                steps.ceil()
            }
        }
        RoundDirection::NearestHalfEven => {
            steps.round_dp_with_strategy(0, RoundingStrategy::MidpointNearestEven)
        }
    };
    let quantity = rounded
        .checked_mul(granularity.step)
        .ok_or(QuantizeError::OutOfRange(value))?
        .normalize();
    Ok(Quantized {
        value: quantity,
        input: value,
        granularity,
    })
}