Skip to main content

ferrochart_orderflow/
footprint.rs

1//! Footprint (rules in `docs/book/src/orderflow.md`): one column
2//! per bar with the sell and buy volume traded at each price level.
3
4use core::fmt;
5use core::ops::Range;
6
7use ferrochart_core::data::Timestamp;
8use ferrochart_core::drawing::{FrameBuilder, Label};
9use ferrochart_core::error::{Error, Result};
10use ferrochart_core::frame::TextAlign;
11use ferrochart_core::geom::{Css, PointPx, RectPx, Rgba};
12use ferrochart_core::plugin::{AxisMode, CustomSeries, SeriesCtx};
13use ferrochart_core::theme::Theme;
14
15use crate::grid::{Column, Combine, SparseGrid};
16use crate::levels::PriceLevels;
17use crate::trades::{Side, TickColumns, TickRule};
18
19/// The kind name of footprint series.
20pub const FOOTPRINT_KIND: &str = "orderflow.footprint";
21
22/// Below this bar spacing (CSS px) nothing is drawn.
23pub const CELLS_MIN_SPACING: f32 = 12.0;
24/// From this bar spacing (CSS px) the volumes are written in the cells.
25pub const NUMBERS_MIN_SPACING: f32 = 60.0;
26
27/// What a footprint cell shows.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum FootprintMode {
30    /// Sell volume on the left half, buy volume on the right half.
31    #[default]
32    BidAsk,
33    /// Buy minus sell volume.
34    Delta,
35    /// Total volume.
36    Volume,
37}
38
39/// Colors of a footprint.
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct FootprintColors {
42    /// Buy volume, positive delta, buy imbalances.
43    pub buy: Rgba,
44    /// Sell volume, negative delta, sell imbalances.
45    pub sell: Rgba,
46    /// Total volume ([`FootprintMode::Volume`]).
47    pub volume: Rgba,
48    /// Numbers.
49    pub text: Rgba,
50    /// Outline of each column's point of control.
51    pub poc: Rgba,
52}
53
54impl FootprintColors {
55    /// Colors matching `theme`'s candles and text.
56    pub fn from_theme(theme: &Theme) -> Self {
57        Self {
58            buy: theme.up,
59            sell: theme.down,
60            volume: theme.line,
61            text: theme.text,
62            poc: theme.text,
63        }
64    }
65}
66
67/// Options of a [`Footprint`].
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub struct FootprintOptions {
70    /// Minimum price increment.
71    pub tick_size: f64,
72    /// Ticks per row.
73    pub row_size: u32,
74    /// Bar period, ms (the host's candle period): columns start at
75    /// multiples of it (UTC).
76    pub timeframe_ms: i64,
77    /// What the cells show.
78    pub mode: FootprintMode,
79    /// Diagonal imbalance ratio (≥ 1); `None`: no imbalance highlights.
80    pub imbalance_ratio: Option<f64>,
81    /// Outline each column's point of control (the level with the most
82    /// volume).
83    pub show_poc: bool,
84    /// Colors.
85    pub colors: FootprintColors,
86}
87
88impl FootprintOptions {
89    /// Bid × ask cells of one tick per row, imbalance ratio 3, points of
90    /// control shown, colors from `theme`.
91    pub fn new(tick_size: f64, timeframe_ms: i64, theme: &Theme) -> Self {
92        Self {
93            tick_size,
94            row_size: 1,
95            timeframe_ms,
96            mode: FootprintMode::BidAsk,
97            imbalance_ratio: Some(3.0),
98            show_poc: true,
99            colors: FootprintColors::from_theme(theme),
100        }
101    }
102}
103
104/// A footprint series: add it with
105/// [`Chart::add_custom_series`](ferrochart_core::Chart::add_custom_series)
106/// and feed it with [`crate::append_trades`].
107///
108/// Columns share the slots of the host's candles (`AxisMode::Slots`): a
109/// column's time is the open time of its bar. Below 12 CSS px of bar
110/// spacing nothing is drawn (the candles stay visible); from 12 px the
111/// cells are shaded; from 60 px the volumes are written in them (raise
112/// `ChartOptions::max_bar_spacing`, 50 px by default, to zoom in that far).
113///
114/// # Examples
115///
116/// ```
117/// use ferrochart_core::chart::SeriesOptions;
118/// use ferrochart_core::theme::Theme;
119/// use ferrochart_core::{Chart, ChartOptions};
120/// use ferrochart_orderflow::{Footprint, FootprintOptions, Side, TickColumns, append_trades};
121///
122/// let mut chart = Chart::new(ChartOptions::default());
123/// let fp = Footprint::new(FootprintOptions::new(0.25, 60_000, &Theme::light()))?;
124/// let id = chart.add_custom_series(chart.main_pane(), Box::new(fp), SeriesOptions::default())?;
125/// let trades = TickColumns {
126///     time: vec![0, 1_000, 61_000],
127///     price: vec![100.0, 100.25, 100.0],
128///     size: vec![2.0, 1.0, 5.0],
129///     side: vec![Side::Buy, Side::Sell, Side::Unknown],
130/// };
131/// append_trades(&mut chart, id, &trades)?;
132/// let fp = chart.custom_series::<Footprint>(id).unwrap();
133/// assert_eq!(fp.grid().columns(), 2);
134/// // 100.0 is level 400: 2 bought; 100.25 is level 401: 1 sold.
135/// assert_eq!(fp.grid().column(0).unwrap().at(400), (0.0, 2.0));
136/// assert_eq!(fp.grid().column(0).unwrap().at(401), (1.0, 0.0));
137/// # Ok::<(), ferrochart_core::Error>(())
138/// ```
139#[derive(Clone, Debug)]
140pub struct Footprint {
141    opts: FootprintOptions,
142    grid: SparseGrid,
143    /// Last trade price of each column.
144    close: Vec<f64>,
145    rule: TickRule,
146}
147
148impl Footprint {
149    /// An empty footprint.
150    ///
151    /// # Errors
152    ///
153    /// [`Error::InvalidArgument`] for a bad price grid, a non-positive
154    /// timeframe or an imbalance ratio below 1.
155    pub fn new(opts: FootprintOptions) -> Result<Self> {
156        let levels = PriceLevels::new(opts.tick_size, opts.row_size)?;
157        if opts.timeframe_ms <= 0 {
158            return Err(Error::InvalidArgument("timeframe_ms must be positive"));
159        }
160        if opts
161            .imbalance_ratio
162            .is_some_and(|r| !(r.is_finite() && r >= 1.0))
163        {
164            return Err(Error::InvalidArgument("imbalance_ratio must be at least 1"));
165        }
166        Ok(Self {
167            opts,
168            grid: SparseGrid::new(levels),
169            close: Vec::new(),
170            rule: TickRule::default(),
171        })
172    }
173
174    /// The options.
175    pub fn options(&self) -> &FootprintOptions {
176        &self.opts
177    }
178
179    /// Changes what the cells show and their colors (the data stays).
180    pub fn set_display(
181        &mut self,
182        mode: FootprintMode,
183        imbalance_ratio: Option<f64>,
184        colors: FootprintColors,
185    ) {
186        self.opts.mode = mode;
187        self.opts.imbalance_ratio = imbalance_ratio.filter(|r| r.is_finite() && *r >= 1.0);
188        self.opts.colors = colors;
189    }
190
191    /// The cells: `a` is sell volume, `b` buy volume.
192    pub fn grid(&self) -> &SparseGrid {
193        &self.grid
194    }
195
196    /// Last trade price of column `i`.
197    pub fn close(&self, i: usize) -> Option<f64> {
198        self.close.get(i).copied()
199    }
200
201    /// Adds one trade; returns whether it opened a column.
202    ///
203    /// # Errors
204    ///
205    /// [`Error::InvalidArgument`] for a non-finite price or a negative size;
206    /// [`Error::TimeNotIncreasing`] if its bar is before the last column;
207    /// [`Error::OutOfMemory`].
208    pub fn push_trade(
209        &mut self,
210        time: Timestamp,
211        price: f64,
212        size: f64,
213        side: Side,
214    ) -> Result<bool> {
215        if !(size.is_finite() && size >= 0.0) {
216            return Err(Error::InvalidArgument(
217                "trade sizes must be finite and non-negative",
218            ));
219        }
220        let level = self
221            .grid
222            .price_levels()
223            .level(price)
224            .ok_or(Error::InvalidArgument("trade prices must be finite"))?;
225        let col = crate::column_start(time, self.opts.timeframe_ms);
226        if self.grid.times().last().is_some_and(|&t| col < t) {
227            return Err(Error::TimeNotIncreasing {
228                index: self.grid.columns(),
229            });
230        }
231        if size == 0.0 {
232            return Ok(false);
233        }
234        self.close.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
235        let side = self.rule.classify(price, side);
236        let v = size as f32;
237        let (a, b) = if side == Side::Sell {
238            (v, 0.0)
239        } else {
240            (0.0, v)
241        };
242        let opened = self.grid.add(col, level, a, b, Combine::Sum)?;
243        if opened {
244            self.close.push(price);
245        } else if let Some(c) = self.close.last_mut() {
246            *c = price;
247        }
248        Ok(opened)
249    }
250}
251
252impl crate::TradeSink for Footprint {
253    fn timeframe(&self) -> i64 {
254        self.opts.timeframe_ms
255    }
256
257    fn last_column(&self) -> Option<Timestamp> {
258        self.grid.times().last().copied()
259    }
260
261    fn apply(&mut self, trades: &TickColumns, range: Range<usize>) -> Result<()> {
262        for i in range {
263            let (t, p, s, side) = trades.get(i);
264            self.push_trade(t, p, s, side)?;
265        }
266        Ok(())
267    }
268}
269
270/// Opacity of a cell holding `v` of the column's `max`: 40–200 of 255,
271/// 0 for an empty cell.
272pub(crate) fn intensity(v: f32, max: f32) -> u8 {
273    if v > 0.0 && max > 0.0 {
274        (40.0 + 160.0 * (v / max).min(1.0)).round() as u8
275    } else {
276        0
277    }
278}
279
280fn tint(c: Rgba, intensity: u8) -> Rgba {
281    c.with_alpha(((f32::from(c.a) * f32::from(intensity)) / 255.0).round() as u8)
282}
283
284/// A volume as a footprint shows it: whole numbers without decimals,
285/// small fractional ones with two, the rest with one.
286struct Vol(f32, bool);
287
288impl fmt::Display for Vol {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        let (v, signed) = (self.0, self.1);
291        // Sums of f32 sizes: "whole" within rounding noise.
292        match ((v - v.round()).abs() < 1e-4, v.abs() < 10.0, signed) {
293            (true, _, true) => write!(f, "{v:+.0}"),
294            (true, _, false) => write!(f, "{v:.0}"),
295            (false, true, true) => write!(f, "{v:+.2}"),
296            (false, true, false) => write!(f, "{v:.2}"),
297            (false, false, true) => write!(f, "{v:+.1}"),
298            (false, false, false) => write!(f, "{v:.1}"),
299        }
300    }
301}
302
303/// Per-column maxima for shading and the point of control.
304struct Stats {
305    side: f32,
306    delta: f32,
307    total: f32,
308    poc: Option<i32>,
309}
310
311fn stats(col: &Column<'_>) -> Stats {
312    let mut s = Stats {
313        side: 0.0,
314        delta: 0.0,
315        total: 0.0,
316        poc: None,
317    };
318    for k in 0..col.len() {
319        let (a, b) = (col.a[k], col.b[k]);
320        s.side = s.side.max(a).max(b);
321        s.delta = s.delta.max((b - a).abs());
322        // Ties: the lowest level.
323        if a + b > s.total {
324            s.total = a + b;
325            s.poc = Some(col.levels[k]);
326        }
327    }
328    s
329}
330
331impl CustomSeries for Footprint {
332    fn kind(&self) -> &'static str {
333        FOOTPRINT_KIND
334    }
335
336    fn axis_mode(&self) -> AxisMode {
337        AxisMode::Slots
338    }
339
340    fn times(&self) -> &[Timestamp] {
341        self.grid.times()
342    }
343
344    fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
345        self.grid.extremes(from, to)
346    }
347
348    fn last_value(&self) -> Option<f64> {
349        self.close.last().copied()
350    }
351
352    fn crosshair_value(&self, point: usize) -> Option<f64> {
353        self.close(point)
354    }
355
356    #[allow(clippy::too_many_lines)]
357    fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
358        let c = ctx.coords();
359        let dpr = c.dpr();
360        let spacing = ctx.bar_spacing().0;
361        if spacing < CELLS_MIN_SPACING * dpr {
362            return;
363        }
364        let numbers = spacing >= NUMBERS_MIN_SPACING * dpr;
365        let levels = self.grid.price_levels();
366        let o = &self.opts;
367        let w = (spacing * 0.9).round().max(1.0);
368        let px1 = dpr.round().max(1.0);
369        let strip = (2.0 * dpr).round().max(1.0);
370        // Levels inside the plot (either scale direction).
371        let plot = c.plot();
372        let (pa, pb) = (c.price_at(plot.y), c.price_at(plot.y + plot.h));
373        let (Some(lo), Some(hi)) = (levels.level(pa.min(pb)), levels.level(pa.max(pb))) else {
374            return;
375        };
376        let (lo, hi) = (lo.saturating_sub(1), hi.saturating_add(1));
377        for i in from..to {
378            let (Some(col), Some(xc)) = (self.grid.column(i), ctx.x_of_point(i)) else {
379                continue;
380            };
381            let st = stats(&col);
382            let x0 = (xc - w / 2.0).round();
383            let xm = xc.round();
384            let first = col.levels.partition_point(|&l| l < lo);
385            let last = col.levels.partition_point(|&l| l <= hi);
386            for k in first..last {
387                let level = col.levels[k];
388                let (a, b) = (col.a[k], col.b[k]);
389                let (p_lo, p_hi) = levels.edges(level);
390                let (Some(y1), Some(y2)) = (c.y_of(p_hi), c.y_of(p_lo)) else {
391                    continue;
392                };
393                let (top, bottom) = (y1.min(y2).round(), y1.max(y2).round());
394                let h = bottom - top;
395                if h < 2.0 {
396                    continue;
397                }
398                let ch = if h >= 6.0 { h - px1 } else { h };
399                let cell = |x: f32, cw: f32| RectPx {
400                    x,
401                    y: top,
402                    w: cw,
403                    h: ch,
404                };
405                match o.mode {
406                    FootprintMode::BidAsk => {
407                        out.rect(
408                            cell(x0, xm - x0),
409                            tint(o.colors.sell, intensity(a, st.side)),
410                        );
411                        out.rect(
412                            cell(xm, x0 + w - xm),
413                            tint(o.colors.buy, intensity(b, st.side)),
414                        );
415                    }
416                    FootprintMode::Delta => {
417                        let d = b - a;
418                        let color = if d >= 0.0 {
419                            o.colors.buy
420                        } else {
421                            o.colors.sell
422                        };
423                        out.rect(cell(x0, w), tint(color, intensity(d.abs(), st.delta)));
424                    }
425                    FootprintMode::Volume => {
426                        out.rect(
427                            cell(x0, w),
428                            tint(o.colors.volume, intensity(a + b, st.total)),
429                        );
430                    }
431                }
432                // Diagonal imbalances: buys at this level against sells one
433                // level down, sells against buys one level up.
434                let (mut buy_imb, mut sell_imb) = (false, false);
435                if let Some(r) = o.imbalance_ratio {
436                    let below = k
437                        .checked_sub(1)
438                        .filter(|&j| Some(col.levels[j]) == level.checked_sub(1))
439                        .map_or(0.0, |j| col.a[j]);
440                    let above = col
441                        .levels
442                        .get(k + 1)
443                        .filter(|&&l| Some(l) == level.checked_add(1))
444                        .map_or(0.0, |_| col.b[k + 1]);
445                    buy_imb = below > 0.0 && f64::from(b) >= r * f64::from(below);
446                    sell_imb = above > 0.0 && f64::from(a) >= r * f64::from(above);
447                }
448                // Imbalances: a strip on the side's outer edge (numbers keep
449                // the text color, readable on any shade).
450                if sell_imb {
451                    out.rect(cell(x0, strip), o.colors.sell);
452                }
453                if buy_imb {
454                    out.rect(cell(x0 + w - strip, strip), o.colors.buy);
455                }
456                let font_css = (11.0_f32).min(ch / dpr * 0.75);
457                if numbers && font_css >= 7.0 {
458                    let label = |align: TextAlign| Label {
459                        font: c.font(Css(font_css)),
460                        color: o.colors.text,
461                        align,
462                        bg: None,
463                    };
464                    let y = top + ch / 2.0;
465                    let gap = (3.0 * dpr).round();
466                    match o.mode {
467                        FootprintMode::BidAsk => {
468                            out.text_fmt(
469                                PointPx { x: xm - gap, y },
470                                format_args!("{}", Vol(a, false)),
471                                label(TextAlign::Right),
472                            );
473                            out.text_fmt(
474                                PointPx { x: xm + gap, y },
475                                format_args!("{}", Vol(b, false)),
476                                label(TextAlign::Left),
477                            );
478                        }
479                        FootprintMode::Delta => out.text_fmt(
480                            PointPx { x: xm, y },
481                            format_args!("{}", Vol(b - a, true)),
482                            label(TextAlign::Center),
483                        ),
484                        FootprintMode::Volume => out.text_fmt(
485                            PointPx { x: xm, y },
486                            format_args!("{}", Vol(a + b, false)),
487                            label(TextAlign::Center),
488                        ),
489                    }
490                }
491                if o.show_poc && st.poc == Some(level) {
492                    let edge = |x: f32, y: f32, ew: f32, eh: f32| RectPx { x, y, w: ew, h: eh };
493                    out.rect(edge(x0, top, w, px1), o.colors.poc);
494                    out.rect(edge(x0, top + ch - px1, w, px1), o.colors.poc);
495                    out.rect(edge(x0, top + px1, px1, ch - 2.0 * px1), o.colors.poc);
496                    out.rect(
497                        edge(x0 + w - px1, top + px1, px1, ch - 2.0 * px1),
498                        o.colors.poc,
499                    );
500                }
501            }
502        }
503    }
504}
505
506#[cfg(test)]
507mod tests {
508    #![allow(clippy::unwrap_used, clippy::float_cmp)]
509
510    use super::*;
511
512    fn fp() -> Footprint {
513        Footprint::new(FootprintOptions::new(1.0, 60_000, &Theme::dark())).unwrap()
514    }
515
516    #[test]
517    fn trades_land_in_bars_and_levels() {
518        let mut f = fp();
519        assert!(f.push_trade(59_999, 10.0, 1.0, Side::Buy).unwrap());
520        assert!(!f.push_trade(30_000, 10.4, 2.0, Side::Sell).unwrap());
521        assert!(!f.push_trade(30_000, 11.0, 0.0, Side::Sell).unwrap());
522        assert!(f.push_trade(60_000, 9.0, 4.0, Side::Unknown).unwrap());
523        assert!(!f.push_trade(60_001, 9.0, 1.0, Side::Unknown).unwrap());
524        assert_eq!(f.grid().times(), &[0, 60_000]);
525        assert_eq!(f.grid().column(0).unwrap().at(10), (2.0, 1.0));
526        // Zero sizes add nothing.
527        assert_eq!(f.grid().column(0).unwrap().len(), 1);
528        // 9 < 10.4: sells by the tick rule, the same at the same price.
529        assert_eq!(f.grid().column(1).unwrap().at(9), (5.0, 0.0));
530        assert_eq!((f.close(0), f.close(1)), (Some(10.4), Some(9.0)));
531        assert!(matches!(
532            f.push_trade(1, 9.0, 1.0, Side::Buy),
533            Err(Error::TimeNotIncreasing { .. })
534        ));
535        assert!(f.push_trade(60_002, f64::NAN, 1.0, Side::Buy).is_err());
536        assert!(f.push_trade(60_002, 9.0, -1.0, Side::Buy).is_err());
537        // Bars before 1970 start at the multiple below.
538        let mut g = fp();
539        g.push_trade(-1, 1.0, 1.0, Side::Buy).unwrap();
540        assert_eq!(g.grid().times(), &[-60_000]);
541    }
542
543    #[test]
544    fn options_are_checked() {
545        let theme = Theme::dark();
546        let mut o = FootprintOptions::new(1.0, 0, &theme);
547        assert!(Footprint::new(o).is_err());
548        o.timeframe_ms = 1;
549        o.imbalance_ratio = Some(0.5);
550        assert!(Footprint::new(o).is_err());
551        o.imbalance_ratio = None;
552        o.tick_size = 0.0;
553        assert!(Footprint::new(o).is_err());
554    }
555
556    #[test]
557    fn numbers_and_shading() {
558        assert_eq!(Vol(12.0, false).to_string(), "12");
559        assert_eq!(Vol(-3.0, true).to_string(), "-3");
560        assert_eq!(Vol(3.0, true).to_string(), "+3");
561        assert_eq!(Vol(0.125, false).to_string(), "0.12");
562        assert_eq!(Vol(12.25, true).to_string(), "+12.2");
563        assert_eq!(
564            (
565                intensity(0.0, 5.0),
566                intensity(5.0, 5.0),
567                intensity(1.0, 0.0)
568            ),
569            (0, 200, 0)
570        );
571        assert_eq!(intensity(2.5, 5.0), 120);
572    }
573}