Skip to main content

ferrochart_orderflow/
trades.rs

1//! Trade input: time-and-sales columns and the tick
2//! rule for trades whose aggressor is unknown.
3
4use ferrochart_core::data::Timestamp;
5use ferrochart_core::error::{Error, Result};
6
7/// The aggressor of a trade.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9pub enum Side {
10    /// A buyer lifted the ask.
11    Buy,
12    /// A seller hit the bid.
13    Sell,
14    /// Not reported: classified by the tick rule (see [`TickRule`]).
15    #[default]
16    Unknown,
17}
18
19/// Trades as columns of equal length.
20#[derive(Clone, Debug, Default, PartialEq)]
21pub struct TickColumns {
22    /// Trade times, UTC ms, non-decreasing.
23    pub time: Vec<Timestamp>,
24    /// Prices.
25    pub price: Vec<f64>,
26    /// Sizes (≥ 0; 0 is ignored).
27    pub size: Vec<f64>,
28    /// Aggressors; empty: all [`Side::Unknown`].
29    pub side: Vec<Side>,
30}
31
32impl TickColumns {
33    /// Number of trades.
34    pub fn len(&self) -> usize {
35        self.time.len()
36    }
37
38    /// Whether there are no trades.
39    pub fn is_empty(&self) -> bool {
40        self.time.is_empty()
41    }
42
43    /// Trade `i`.
44    pub(crate) fn get(&self, i: usize) -> (Timestamp, f64, f64, Side) {
45        (
46            self.time[i],
47            self.price[i],
48            self.size[i],
49            self.side.get(i).copied().unwrap_or_default(),
50        )
51    }
52
53    /// Checks lengths, values and order; `after`: no trade may be earlier.
54    ///
55    /// # Errors
56    ///
57    /// [`Error::InvalidArgument`] for columns of different lengths, a
58    /// non-finite price or a negative or non-finite size;
59    /// [`Error::TimeNotIncreasing`] for a time earlier than the previous
60    /// one (or than `after`).
61    pub(crate) fn check(&self, after: Option<Timestamp>) -> Result<()> {
62        let n = self.time.len();
63        if self.price.len() != n
64            || self.size.len() != n
65            || !(self.side.is_empty() || self.side.len() == n)
66        {
67            return Err(Error::InvalidArgument(
68                "trade columns must have the same length",
69            ));
70        }
71        let mut prev = after.unwrap_or(Timestamp::MIN);
72        for (i, &t) in self.time.iter().enumerate() {
73            if t < prev {
74                return Err(Error::TimeNotIncreasing { index: i });
75            }
76            prev = t;
77        }
78        if self.price.iter().any(|p| !p.is_finite()) {
79            return Err(Error::InvalidArgument("trade prices must be finite"));
80        }
81        if self.size.iter().any(|s| !(s.is_finite() && *s >= 0.0)) {
82            return Err(Error::InvalidArgument(
83                "trade sizes must be finite and non-negative",
84            ));
85        }
86        Ok(())
87    }
88}
89
90/// Classifies trades of unknown side by the tick rule: a trade above the
91/// previous price is a buy, below it a sell, at the same price the same as
92/// the previous trade. The first unknown trade with no reference is a buy.
93///
94/// # Examples
95///
96/// ```
97/// use ferrochart_orderflow::{Side, TickRule};
98///
99/// let mut rule = TickRule::default();
100/// assert_eq!(rule.classify(10.0, Side::Unknown), Side::Buy);
101/// assert_eq!(rule.classify(9.5, Side::Unknown), Side::Sell);
102/// assert_eq!(rule.classify(9.5, Side::Unknown), Side::Sell);
103/// assert_eq!(rule.classify(9.5, Side::Buy), Side::Buy);
104/// assert_eq!(rule.classify(9.5, Side::Unknown), Side::Buy);
105/// ```
106#[derive(Clone, Copy, Debug, Default, PartialEq)]
107pub struct TickRule {
108    last: Option<(f64, Side)>,
109}
110
111impl TickRule {
112    /// The side of a trade at `price` reported as `side` (never `Unknown`).
113    pub fn classify(&mut self, price: f64, side: Side) -> Side {
114        let side = match (side, self.last) {
115            (Side::Unknown, Some((p, s))) => match price.partial_cmp(&p) {
116                Some(core::cmp::Ordering::Greater) => Side::Buy,
117                Some(core::cmp::Ordering::Less) => Side::Sell,
118                _ => s,
119            },
120            (Side::Unknown, None) => Side::Buy,
121            (s, _) => s,
122        };
123        self.last = Some((price, side));
124        side
125    }
126}