stock-bot/apps/stock/engine/src/financial/scalar.rs

183 lines
7.2 KiB
Rust

use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::ToPrimitive;
use rust_decimal::{Decimal, RoundingStrategy};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, str::FromStr};
pub const POSTING_SCALE: u32 = 8;
/// The entire 96-bit coefficient remains available at the fixed posting scale.
pub const MAX_POSTING: &str = "792281625142643375935.43950335";
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ScalarError {
#[error("expected a plain decimal string with at most 8 fractional digits")]
InvalidDecimal,
#[error("financial posting exceeds the fixed-8 decimal range")]
Overflow,
}
/// Money/quantity transport uses strings, never f64. No float constructor or
/// unchecked arithmetic operator is exposed. Operation-specific notional and
/// basis calculations use exact rational intermediates; generic decimal
/// multiplication/division could silently reduce intermediate precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Posting(Decimal);
impl Posting {
pub const ZERO: Self = Self(Decimal::ZERO);
pub fn is_negative(self) -> bool {
self.0.is_sign_negative() && !self.0.is_zero()
}
pub fn is_zero(self) -> bool {
self.0.is_zero()
}
pub fn checked_add(self, other: Self) -> Result<Self, ScalarError> {
Self::from_exact_decimal(self.0.checked_add(other.0).ok_or(ScalarError::Overflow)?)
}
pub fn checked_sub(self, other: Self) -> Result<Self, ScalarError> {
Self::from_exact_decimal(self.0.checked_sub(other.0).ok_or(ScalarError::Overflow)?)
}
/// Exact integer coefficient at the declared posting scale. ZERO is the
/// only internal value whose Decimal scale can be smaller than eight.
fn units(self) -> BigInt {
BigInt::from(self.0.mantissa()) * BigInt::from(10u32).pow(POSTING_SCALE - self.0.scale())
}
fn from_units(units: BigInt) -> Result<Self, ScalarError> {
let coefficient = units.to_i128().ok_or(ScalarError::Overflow)?;
let decimal = Decimal::try_from_i128_with_scale(coefficient, POSTING_SCALE)
.map_err(|_| ScalarError::Overflow)?;
Self::from_exact_decimal(decimal)
}
/// Quantity * price, rounded once at the posting boundary. BigRational
/// avoids rust_decimal's possible intermediate precision reduction. Its
/// round() is explicitly nearest with half ties away from zero.
pub(super) fn notional(quantity: Self, price: Self) -> Result<Self, ScalarError> {
let units = BigRational::new(
quantity.units() * price.units(),
BigInt::from(100_000_000u32),
);
Self::rounded_units(units)
}
/// Rate-only execution fee: multiply all three exact values before the
/// single posting boundary (never charge a percentage of rounded notional).
pub(super) fn rate_fee(quantity: Self, price: Self, rate: Self) -> Result<Self, ScalarError> {
Self::rounded_units(BigRational::new(
quantity.units() * price.units() * rate.units(),
BigInt::from(10u32).pow(POSTING_SCALE * 2),
))
}
/// Quote midpoint, with one rounding boundary and no overflowing a+b.
pub(super) fn midpoint(a: Self, b: Self) -> Result<Self, ScalarError> {
Self::rounded_units(BigRational::new(a.units() + b.units(), BigInt::from(2)))
}
/// Partial disposal only: quantity is positive and <= owned quantity.
/// A final disposal deliberately bypasses division and releases residue.
pub(super) fn released_basis(
cost: Self,
quantity: Self,
owned_quantity: Self,
) -> Result<Self, ScalarError> {
if quantity.is_negative() || quantity.is_zero() || quantity > owned_quantity {
return Err(ScalarError::InvalidDecimal);
}
if quantity == owned_quantity {
return Ok(cost);
}
Self::rounded_units(BigRational::new(
cost.units() * quantity.units(),
owned_quantity.units(),
))
}
fn rounded_units(exact: BigRational) -> Result<Self, ScalarError> {
// As with from_exact_decimal, reject an out-of-range exact value even
// if rounding down would have brought it back inside the range.
let max = BigRational::from_integer(BigInt::from((1u128 << 96) - 1));
if exact > max || exact < -max {
return Err(ScalarError::Overflow);
}
Self::from_units(exact.round().to_integer())
}
/// Exact sum of already quantized postings, without rejecting a valid
/// final result solely because an intermediate partial sum overflows.
pub(super) fn sum(values: impl IntoIterator<Item = Self>) -> Result<Self, ScalarError> {
Self::from_units(values.into_iter().map(Self::units).sum())
}
/// Posting boundary for an already exact internal decimal calculation.
/// Callers must not pass a previously precision-losing intermediate.
/// https://docs.rs/rust_decimal/1.43.0/rust_decimal/enum.RoundingStrategy.html
pub fn from_exact_decimal(value: Decimal) -> Result<Self, ScalarError> {
let max = Decimal::from_str_exact(MAX_POSTING).expect("fixed decimal constant");
// Reject out-of-range intermediates before rounding as well as after it.
if value.abs() > max {
return Err(ScalarError::Overflow);
}
let mut rounded =
value.round_dp_with_strategy(POSTING_SCALE, RoundingStrategy::MidpointAwayFromZero);
if rounded.abs() > max {
return Err(ScalarError::Overflow);
}
if rounded.is_zero() {
rounded = Decimal::ZERO;
}
rounded.rescale(POSTING_SCALE);
// rescale is infallible and may silently use less precision. Never allow
// that behavior through the authoritative fixed-8 boundary.
if rounded.scale() != POSTING_SCALE {
return Err(ScalarError::Overflow);
}
Ok(Self(rounded))
}
}
impl FromStr for Posting {
type Err = ScalarError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
let (integer, fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
if integer.is_empty()
|| !integer.bytes().all(|c| c.is_ascii_digit())
|| (integer.len() > 1 && integer.starts_with('0'))
|| (unsigned.contains('.') && fraction.is_empty())
|| fraction.len() > POSTING_SCALE as usize
|| !fraction.bytes().all(|c| c.is_ascii_digit())
{
return Err(ScalarError::InvalidDecimal);
}
let value = Decimal::from_str_exact(text).map_err(|_| ScalarError::Overflow)?;
Self::from_exact_decimal(value)
}
}
impl fmt::Display for Posting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.8}", self.0)
}
}
impl Serialize for Posting {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for Posting {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(de::Error::custom)
}
}