Skip to main content

Module precision

Module precision 

Source
Expand description

Price and quantity arithmetic in whole steps, exactly.

Exchange prices move in steps (for example 0.05) and an order price must sit on the step grid, or the exchange refuses it. The numbers are [Decimal]s, so the step arithmetic has no noise: 101.05 / 0.05 is exactly 2021 (in f64 it is 2020.9999999999998). The functions here count the value in whole steps and give it back. The step comes from the instrument data, see TradingParamsSnapshot::price_step.

All functions are pure and return a PrecisionError for a step that cannot be used. The grid starts at zero.

§Examples

use brokapi_bcs_protocol::utils::precision::{precise_down, precise_up, precise_to_nearest};
use rust_decimal::Decimal;

let price = Decimal::new(10103, 2); // 101.03
let step = Decimal::new(5, 2); // 0.05
// A buy price is rounded down, a sell price up, so you never pay or sell worse than computed.
assert_eq!(precise_down(price, step)?, Decimal::new(10100, 2));
assert_eq!(precise_up(price, step)?, Decimal::new(10105, 2));
assert_eq!(precise_to_nearest(price, step)?, Decimal::new(10105, 2));

Enums§

PrecisionError
Why a step calculation was refused.

Functions§

precise_down
Rounds a value down to the step grid.
precise_to_nearest
Rounds a value to the nearest point of the step grid.
precise_up
Rounds a value up to the step grid.
steps_to_value
Converts a whole number of steps back to a value, exactly: 2001 steps of 0.05 is 100.05.
value_to_steps_down
Converts a value to a whole number of steps, rounding down (towards negative infinity).
value_to_steps_nearest
Converts a value to a whole number of steps, rounding to the nearest step (halves go away from zero).
value_to_steps_up
Converts a value to a whole number of steps, rounding up (towards positive infinity).