Skip to main content

ferrochart_orderflow/
lib.rs

1//! Order flow series for FerroChart: footprint,
2//! heatmap and TPO, as [`CustomSeries`] plugins. The exact rules (price
3//! levels, aggressor classification, imbalances, color scales, value area)
4//! are in `docs/book/src/orderflow.md`.
5//!
6//! Prices are stored as level numbers of a fixed grid ([`PriceLevels`]).
7//! The footprint and the heatmap share a sparse "time column × level" grid
8//! ([`SparseGrid`]); only the last column changes, so real-time trades cost
9//! O(levels of the last column).
10//!
11//! With the default feature `gpu`, `register_gpu` adds the heatmap's
12//! native wgpu path (a compute shader) to a renderer whose device supports
13//! it; elsewhere (WebGL2, the CPU backend) the heatmap draws through its
14//! portable path with the same output.
15//!
16//! ```
17//! use ferrochart_core::chart::SeriesOptions;
18//! use ferrochart_core::testing::MonoMeasurer;
19//! use ferrochart_core::theme::Theme;
20//! use ferrochart_core::{Chart, ChartOptions};
21//! use ferrochart_orderflow::{Footprint, FootprintOptions, Side, TickColumns, append_trades};
22//!
23//! let mut chart = Chart::new(ChartOptions::default());
24//! let fp = Footprint::new(FootprintOptions::new(0.5, 60_000, &Theme::light()))?;
25//! let id = chart.add_custom_series(chart.main_pane(), Box::new(fp), SeriesOptions::default())?;
26//! let trades = TickColumns {
27//!     time: (0..600).map(|i| i * 1_000).collect(),
28//!     price: (0..600).map(|i| 100.0 + f64::from(i % 7) * 0.5).collect(),
29//!     size: vec![1.0; 600],
30//!     side: vec![Side::Unknown; 600],
31//! };
32//! append_trades(&mut chart, id, &trades)?;
33//! chart.build_frame(0.0, &MonoMeasurer);
34//! # Ok::<(), ferrochart_core::Error>(())
35//! ```
36//!
37//! [`CustomSeries`]: ferrochart_core::plugin::CustomSeries
38#![forbid(unsafe_code)]
39
40mod footprint;
41#[cfg(feature = "gpu")]
42mod gpu;
43mod grid;
44mod heatmap;
45mod levels;
46#[cfg(feature = "testing")]
47pub mod testing;
48mod tpo;
49mod trades;
50
51use core::ops::Range;
52
53use ferrochart_core::Chart;
54use ferrochart_core::data::{DataChange, OhlcColumns, SeriesId, Timestamp};
55use ferrochart_core::error::{Error, Result};
56use ferrochart_core::plugin::CustomSeries;
57
58pub use footprint::{
59    CELLS_MIN_SPACING, FOOTPRINT_KIND, Footprint, FootprintColors, FootprintMode, FootprintOptions,
60    NUMBERS_MIN_SPACING,
61};
62#[cfg(feature = "gpu")]
63pub use gpu::{HeatmapGpu, register_gpu, supports_native_heatmap};
64pub use grid::{Column, SparseGrid};
65pub use heatmap::{
66    ColorScale, DepthSnapshot, HEATMAP_KIND, Heatmap, HeatmapColors, HeatmapOptions, HeatmapRange,
67    HeatmapSource, MAX_LEVELS_PER_ROW,
68};
69pub use levels::PriceLevels;
70pub use tpo::{
71    SessionProfile, TPO_KIND, TPO_MIN_FONT, TPO_MIN_SPACING, Tpo, TpoColors, TpoOptions, tpo_letter,
72};
73pub use trades::{Side, TickColumns, TickRule};
74
75/// Start of the time unit of `period` ms that contains `time` (UTC
76/// multiples of `period`).
77pub(crate) fn column_start(time: Timestamp, period: i64) -> Timestamp {
78    time.div_euclid(period).checked_mul(period).unwrap_or(time)
79}
80
81/// A series built from trades in time columns.
82pub(crate) trait TradeSink: CustomSeries {
83    /// Length of a column, ms.
84    fn timeframe(&self) -> i64;
85    /// Start of the last column.
86    fn last_column(&self) -> Option<Timestamp>;
87    /// Adds `trades[range]` (already checked).
88    fn apply(&mut self, trades: &TickColumns, range: Range<usize>) -> Result<()>;
89}
90
91/// Adds trades to a footprint (or a trade heatmap) in `chart`.
92///
93/// Trades in the last column update it; later ones open new columns. Times
94/// must be non-decreasing, and no trade may fall in a column before the
95/// last one.
96///
97/// # Errors
98///
99/// [`Error::UnknownId`]; [`Error::InvalidArgument`] if `id` is not such a
100/// series or for bad trade columns (see [`TickColumns`]);
101/// [`Error::TimeNotIncreasing`]; [`Error::OutOfMemory`]. Nothing changes
102/// when the trades are rejected up front; an allocation failure part way
103/// keeps the trades added so far.
104pub fn append_trades(chart: &mut Chart, id: SeriesId, trades: &TickColumns) -> Result<()> {
105    trades.check(None)?;
106    if chart.custom_series::<Footprint>(id).is_some() {
107        return append::<Footprint>(chart, id, trades);
108    }
109    if let Some(h) = chart.custom_series::<Heatmap>(id) {
110        if h.options().source != HeatmapSource::Trades {
111            return Err(Error::InvalidArgument("the heatmap takes depth snapshots"));
112        }
113        return append::<Heatmap>(chart, id, trades);
114    }
115    chart.series_kind(id).ok_or(Error::UnknownId)?;
116    Err(Error::InvalidArgument("the series takes no trades"))
117}
118
119/// Adds an order book snapshot to a depth heatmap in `chart`.
120///
121/// A snapshot in the last column updates it (each level keeps its largest
122/// size); a later one opens a new column.
123///
124/// # Errors
125///
126/// [`Error::UnknownId`]; [`Error::InvalidArgument`] if `id` is not a depth
127/// heatmap or for a bad snapshot (see [`DepthSnapshot`]);
128/// [`Error::TimeNotIncreasing`] if the snapshot falls in a column before the
129/// last one; [`Error::OutOfMemory`]. Nothing changes when the snapshot is
130/// rejected up front; an allocation failure part way keeps the levels
131/// added so far.
132pub fn append_depth(chart: &mut Chart, id: SeriesId, snapshot: &DepthSnapshot<'_>) -> Result<()> {
133    if chart.custom_series::<Heatmap>(id).is_none() {
134        chart.series_kind(id).ok_or(Error::UnknownId)?;
135        return Err(Error::InvalidArgument(
136            "the series takes no depth snapshots",
137        ));
138    }
139    let mut failed = None;
140    chart.update_custom(id, |h: &mut Heatmap| {
141        let (before, version) = (h.grid().columns(), h.version());
142        let result = h.push_depth(snapshot);
143        let change = match h.grid().columns() - before {
144            _ if h.version() == version => DataChange::Append { count: 0 },
145            0 => DataChange::UpdateLast,
146            count if result.is_ok() => DataChange::Append { count },
147            _ => DataChange::Replace,
148        };
149        failed = result.err();
150        change
151    })?;
152    failed.map_or(Ok(()), Err)
153}
154
155fn append<T: TradeSink>(chart: &mut Chart, id: SeriesId, trades: &TickColumns) -> Result<()> {
156    let s = chart.custom_series::<T>(id).ok_or(Error::UnknownId)?;
157    let (period, last) = (s.timeframe(), s.last_column());
158    let n = trades.len();
159    // Trades in the last column, then trades opening new ones.
160    let split = match (last, trades.time.first()) {
161        (Some(last), Some(&t0)) if column_start(t0, period) < last => {
162            return Err(Error::TimeNotIncreasing { index: 0 });
163        }
164        (Some(last), _) => trades
165            .time
166            .partition_point(|&t| column_start(t, period) <= last),
167        (None, _) => 0,
168    };
169    let mut failed = None;
170    if split > 0 {
171        chart.update_custom(id, |s: &mut T| match s.apply(trades, 0..split) {
172            Ok(()) => DataChange::UpdateLast,
173            Err(e) => {
174                failed = Some(e);
175                DataChange::Replace
176            }
177        })?;
178    }
179    if failed.is_none() && split < n {
180        chart.update_custom(id, |s: &mut T| {
181            let before = s.times().len();
182            match s.apply(trades, split..n) {
183                Ok(()) => DataChange::Append {
184                    count: s.times().len() - before,
185                },
186                Err(e) => {
187                    failed = Some(e);
188                    DataChange::Replace
189                }
190            }
191        })?;
192    }
193    failed.map_or(Ok(()), Err)
194}
195
196/// Adds bars (time, high and low are used) to a TPO series in `chart`.
197///
198/// Each bar marks the levels from its low to its high in the period that
199/// contains its time; bars must be no longer than a period. Bars in the last
200/// session update it (a bar sent again, e.g. a live candle, widens its
201/// period); later ones open new sessions. Bars outside the sessions are
202/// skipped.
203///
204/// # Errors
205///
206/// [`Error::UnknownId`]; [`Error::InvalidArgument`] if `id` is not a TPO
207/// series or for bad bars (columns of different lengths, non-finite prices,
208/// `high < low`); [`Error::TimeNotIncreasing`] for times out of order or a
209/// session before the last one; [`Error::OutOfMemory`]. Nothing changes
210/// when the bars are rejected up front; an allocation failure part way
211/// keeps the bars added so far.
212pub fn append_bars(chart: &mut Chart, id: SeriesId, bars: &OhlcColumns) -> Result<()> {
213    let Some(t) = chart.custom_series::<Tpo>(id) else {
214        chart.series_kind(id).ok_or(Error::UnknownId)?;
215        return Err(Error::InvalidArgument("the series takes no bars"));
216    };
217    tpo::check_bars(bars, t.price_levels())?;
218    let n = bars.time.len();
219    let split = match (t.last_session(), bars.time.first()) {
220        (Some(last), Some(&t0)) if t.session_start(t0) < last => {
221            return Err(Error::TimeNotIncreasing { index: 0 });
222        }
223        (Some(last), _) => bars.time.partition_point(|&x| t.session_start(x) <= last),
224        (None, _) => 0,
225    };
226    let apply = |t: &mut Tpo, range: Range<usize>| -> Result<()> {
227        let result = range.into_iter().try_for_each(|i| {
228            t.push_raw(bars.time[i], bars.high[i], bars.low[i])
229                .map(drop)
230        });
231        t.finish_last();
232        result
233    };
234    let mut failed = None;
235    if split > 0 {
236        chart.update_custom(id, |t: &mut Tpo| match apply(t, 0..split) {
237            Ok(()) => DataChange::UpdateLast,
238            Err(e) => {
239                failed = Some(e);
240                DataChange::Replace
241            }
242        })?;
243    }
244    if failed.is_none() && split < n {
245        chart.update_custom(id, |t: &mut Tpo| {
246            let before = t.sessions().len();
247            match apply(t, split..n) {
248                Ok(()) => DataChange::Append {
249                    count: t.sessions().len() - before,
250                },
251                Err(e) => {
252                    failed = Some(e);
253                    DataChange::Replace
254                }
255            }
256        })?;
257    }
258    failed.map_or(Ok(()), Err)
259}