Skip to main content

decimix_finance/
lib.rs

1//! # decimix-finance
2//!
3//! Domain types for trading, built on [`decimix`]: [`Price`], [`Qty`],
4//! [`DeltaQty`], [`Amt`] and [`Percentage`].
5//!
6//! Each wraps a 19-decimal-place number, and they can't be mixed by
7//! accident: adding a price to a quantity doesn't compile.
8//!
9//! The names and meanings follow the FIX 5 datatypes, so a FIX field maps to
10//! the type of the same name:
11//!
12//! | FIX datatype | Type             | Meaning                                  |
13//! |--------------|------------------|------------------------------------------|
14//! | `Price`      | [`Price`]        | a price; may be negative                 |
15//! | `Qty`        | [`Qty`]          | a quantity; here, never negative         |
16//! | —            | [`DeltaQty`]     | a quantity that may be negative          |
17//! | `Amt`        | [`Amt`]          | typically price × quantity: a cash value |
18//! | `Percentage` | [`Percentage`]   | a fraction: 0.05 means 5%                |
19//!
20//! FIX has no separate signed-quantity type; [`DeltaQty`] is this crate's
21//! addition, so that [`Qty`] can promise it is never negative. FIX's
22//! `PriceOffset` is not provided yet.
23//!
24//! ## Quantities: [`Qty`] and [`DeltaQty`]
25//!
26//! A quantity comes in two forms. [`Qty`] can never be negative: an order
27//! size, a fill, a lot. [`DeltaQty`] is a quantity that can be: a position,
28//! a net fill, a change in either. Both are the same kind of thing, so the rules
29//! for quantities apply to both. The [`Quantity`] trait expresses that:
30//! price × quantity is defined once, for either form, rather than once per
31//! sign.
32//!
33//! ```
34//! use decimix::{dec, udec};
35//! use decimix_finance::{DeltaQty, Qty};
36//!
37//! let ordered = Qty::new(udec!(1000));
38//! let filled = Qty::new(udec!(250));
39//! let leaves: Qty = ordered - filled; // panics if it would go negative
40//! assert_eq!(leaves, Qty::new(udec!(750)));
41//! let delta: DeltaQty = filled.signed_sub(ordered); // may be negative
42//! assert_eq!(delta, DeltaQty::new(dec!(-750)));
43//! assert_eq!(delta.unsigned_abs(), leaves);
44//! ```
45//!
46//! ## Price × quantity is an amount
47//!
48//! Multiplying a price by either form of quantity gives an [`Amt`]: the cash
49//! value (the consideration), negative when the price or quantity is. Like every decimal product,
50//! it names its rounding.
51//!
52//! ```
53//! use decimix::{Round, dec, udec};
54//! use decimix_finance::{DeltaQty, Amt, Price, Qty, Percentage};
55//!
56//! let px = Price::new(dec!(113.725));
57//!
58//! let bought: Amt = px.mul(Qty::new(udec!(250)), Round::HalfEven);
59//! assert_eq!(bought, Amt::new(dec!(28431.25)));
60//!
61//! let short: Amt = px.mul(DeltaQty::new(dec!(-250)), Round::HalfEven);
62//! assert_eq!(short, Amt::new(dec!(-28431.25)));
63//!
64//! let fee = bought.mul(Percentage::new(dec!(0.0002)), Round::HalfEven);
65//! assert_eq!(fee, Amt::new(dec!(5.68625)));
66//! ```
67//!
68//! ## What doesn't compile, on purpose
69//!
70//! A price times a quantity is neither a quantity nor a price:
71//!
72//! ```compile_fail
73//! use decimix::{Round, dec, udec};
74//! use decimix_finance::{DeltaQty, Price, Qty};
75//! let px = Price::new(dec!(1.5));
76//! let a: DeltaQty = px.mul(Qty::new(udec!(2)), Round::HalfEven);
77//! ```
78//!
79//! ```compile_fail
80//! use decimix::{Round, dec, udec};
81//! use decimix_finance::{Price, Qty};
82//! let px = Price::new(dec!(1.5));
83//! let p: Price = px.mul(Qty::new(udec!(2)), Round::HalfEven);
84//! ```
85//!
86//! Price × price, and price × amount, mean nothing:
87//!
88//! ```compile_fail
89//! use decimix::{Round, dec};
90//! use decimix_finance::Price;
91//! let px = Price::new(dec!(1.5));
92//! let x = px.mul(px, Round::HalfEven);
93//! ```
94//!
95//! ```compile_fail
96//! use decimix::{Round, dec};
97//! use decimix_finance::{Amt, Price};
98//! let x = Price::new(dec!(1.5)).mul(Amt::new(dec!(2)), Round::HalfEven);
99//! ```
100//!
101//! Different kinds don't add, and signed and unsigned quantities don't mix
102//! without saying how:
103//!
104//! ```compile_fail
105//! use decimix::{dec, udec};
106//! use decimix_finance::{Price, Qty};
107//! let x = Price::new(dec!(1.5)) + Qty::new(udec!(2));
108//! ```
109//!
110//! ```compile_fail
111//! use decimix::{dec, udec};
112//! use decimix_finance::{DeltaQty, Qty};
113//! let x = DeltaQty::new(dec!(-1)) + Qty::new(udec!(2));
114//! ```
115//!
116//! ```compile_fail
117//! use decimix::udec;
118//! use decimix_finance::Qty;
119//! let q = -Qty::new(udec!(2));
120//! ```
121//!
122//! Domain types have no `f64` methods; floats go through the base type, where
123//! a lint can catch them:
124//!
125//! ```compile_fail
126//! use decimix::dec;
127//! use decimix_finance::Price;
128//! let f = Price::new(dec!(1.5)).to_f64_lossy();
129//! ```
130#![no_std]
131#![warn(missing_docs)]
132
133use decimix::{Dec19, Fixed19, OutOfRange, ProductSum, Round, UDec19, newtype};
134
135newtype! {
136  /// A price. May be negative (spreads, some futures and power markets).
137  /// FIX datatype `Price`.
138  pub struct Price(Dec19);
139}
140
141newtype! {
142  /// A quantity that can't be negative: an order size, a fill, a lot. FIX
143  /// datatype `Qty`.
144  ///
145  /// For a quantity that can be negative, use [`DeltaQty`].
146  pub struct Qty(UDec19);
147}
148
149newtype! {
150  /// A quantity that can be negative: a position, a net fill, a change in
151  /// either. FIX has no datatype for this; it uses `Qty` for both.
152  ///
153  /// The same kind of thing as [`Qty`], so it takes part in the same
154  /// products (see [`Quantity`]).
155  pub struct DeltaQty(Dec19);
156}
157
158newtype! {
159  /// An amount of money: typically price × quantity (the consideration),
160  /// or a fee, a P&L. FIX datatype `Amt`.
161  pub struct Amt(Dec19);
162}
163
164newtype! {
165  /// A percentage, held as a fraction: 0.05 means 5%, 0.9525 means 95.25%.
166  /// FIX datatype `Percentage`. For fee rates, FX rates and other ratios.
167  pub struct Percentage(Dec19);
168}
169
170mod sealed {
171  pub trait Sealed {}
172  impl Sealed for super::Qty {
173  }
174  impl Sealed for super::DeltaQty {
175  }
176}
177
178/// Either form of quantity: [`Qty`] (never negative) or [`DeltaQty`] (may be).
179///
180/// Products are defined on the kind of value, not its sign, so price ×
181/// quantity is written once and works for both. Sealed.
182pub trait Quantity: Copy + sealed::Sealed {
183  /// The plain value, signed or not.
184  type Base: Fixed19;
185
186  /// The plain value.
187  fn to_base(self) -> Self::Base;
188}
189
190impl Quantity for Qty {
191  type Base = UDec19;
192
193  fn to_base(self) -> UDec19 {
194    self.get()
195  }
196}
197
198impl Quantity for DeltaQty {
199  type Base = Dec19;
200
201  fn to_base(self) -> Dec19 {
202    self.get()
203  }
204}
205
206impl Price {
207  /// Price × quantity, rounded to 19 places with `mode`. `qty` may be a
208  /// [`Qty`] or a [`DeltaQty`]; the result is negative when the quantity is.
209  ///
210  /// # Panics
211  ///
212  /// On overflow. See [`checked_mul`](Self::checked_mul).
213  #[track_caller]
214  pub fn mul<Q: Quantity>(self, qty: Q, mode: Round) -> Amt {
215    Amt::new(self.get().mul(qty.to_base(), mode))
216  }
217
218  /// Price × quantity, rounded to 19 places with `mode`, or `None` on
219  /// overflow.
220  #[must_use]
221  pub fn checked_mul<Q: Quantity>(self, qty: Q, mode: Round) -> Option<Amt> {
222    self.get().checked_mul(qty.to_base(), mode).map(Amt::new)
223  }
224
225  /// The volume-weighted average price of some fills: Σ(price × quantity) ÷
226  /// Σ quantity, rounded once with `mode`.
227  ///
228  /// `None` if there are no fills, the total quantity is zero, or a total
229  /// overflows.
230  ///
231  /// ```
232  /// use decimix::{Round, dec, udec};
233  /// use decimix_finance::{Price, Qty};
234  ///
235  /// let fills = [
236  ///   (Price::new(dec!(113.725)), Qty::new(udec!(100))),
237  ///   (Price::new(dec!(113.73)), Qty::new(udec!(250))),
238  /// ];
239  /// let vwap = Price::vwap(fills, Round::HalfEven);
240  /// assert_eq!(vwap, Some(Price::new(dec!(113.7285714285714285714))));
241  /// ```
242  #[must_use]
243  pub fn vwap<I>(fills: I, mode: Round) -> Option<Price>
244  where
245    I: IntoIterator<Item = (Price, Qty)>,
246  {
247    let mut acc = ProductSum::new();
248    let mut total = UDec19::ZERO;
249    for (px, qty) in fills {
250      acc.checked_add(px.get(), qty.get()).ok()?;
251      total = total.checked_add(qty.get())?;
252    }
253    if total.is_zero() {
254      return None;
255    }
256    acc.div(total, mode).ok().map(Price::new)
257  }
258}
259
260impl Amt {
261  /// Amount × percentage (a fee, an FX conversion), rounded to 19 places
262  /// with `mode`.
263  ///
264  /// # Panics
265  ///
266  /// On overflow.
267  #[track_caller]
268  pub fn mul(self, pct: Percentage, mode: Round) -> Amt {
269    Amt::new(self.get().mul(pct.get(), mode))
270  }
271
272  /// Σ(price × quantity), with every product kept exactly and one rounding
273  /// at the end. With [`DeltaQty`] quantities this is the net amount
274  /// (buys positive, sells negative).
275  pub fn sum_products<I, Q>(fills: I, mode: Round) -> Result<Amt, OutOfRange>
276  where
277    I: IntoIterator<Item = (Price, Q)>,
278    Q: Quantity,
279  {
280    let mut acc = ProductSum::new();
281    for (px, qty) in fills {
282      acc.checked_add(px.get(), qty.to_base())?;
283    }
284    acc.finish(mode).map(Amt::new)
285  }
286}
287
288impl Qty {
289  /// `self - other` as a signed [`DeltaQty`], which may be negative.
290  ///
291  /// # Panics
292  ///
293  /// If the difference is outside [`DeltaQty`]'s range (only possible for
294  /// quantities above about 1.7 × 10¹⁹).
295  #[track_caller]
296  pub fn signed_sub(self, other: Qty) -> DeltaQty {
297    DeltaQty::new(self.get().signed_sub(other.get()))
298  }
299
300  /// The same quantity as a signed [`DeltaQty`].
301  ///
302  /// # Panics
303  ///
304  /// Above about 1.7 × 10¹⁹, which [`DeltaQty`] can't hold.
305  #[track_caller]
306  pub fn to_delta_qty(self) -> DeltaQty {
307    DeltaQty::try_from(self).expect("Qty too large for DeltaQty")
308  }
309}
310
311impl DeltaQty {
312  /// The size of the quantity, whichever its sign. Always fits.
313  pub fn unsigned_abs(self) -> Qty {
314    Qty::new(self.get().unsigned_abs())
315  }
316}
317
318impl TryFrom<Qty> for DeltaQty {
319  type Error = OutOfRange;
320
321  /// Fails only for quantities above about 1.7 × 10¹⁹.
322  fn try_from(qty: Qty) -> Result<Self, OutOfRange> {
323    Dec19::try_from(qty.get()).map(DeltaQty::new)
324  }
325}
326
327impl TryFrom<DeltaQty> for Qty {
328  type Error = OutOfRange;
329
330  /// Fails if the quantity is negative.
331  fn try_from(delta: DeltaQty) -> Result<Self, OutOfRange> {
332    UDec19::try_from(delta.get()).map(Qty::new)
333  }
334}