Skip to main content

ferrochart_orderflow/
heatmap.rs

1//! Heatmap (rules in `docs/book/src/orderflow.md`):
2//! resting size from order book snapshots, or traded volume, per time column
3//! and price level, colored by a log or linear scale.
4//!
5//! Both drawing paths share one pixel [`Layout`] computed on the core side:
6//! the pixel columns each data column covers, the pixel rows of each level
7//! and the color-scale range. The portable path aggregates on the CPU and
8//! writes rectangles; the native path (`crate::gpu`, feature `gpu`) does the
9//! same aggregation in a compute shader.
10
11use core::cell::{Cell, Ref, RefCell};
12use core::ops::Range;
13
14use ferrochart_core::data::Timestamp;
15use ferrochart_core::drawing::FrameBuilder;
16use ferrochart_core::error::{Error, Result};
17use ferrochart_core::geom::{RectPx, Rgba};
18use ferrochart_core::plugin::{AxisMode, CustomSeries, SeriesCtx};
19
20use crate::grid::{Combine, SparseGrid};
21use crate::levels::PriceLevels;
22use crate::trades::TickColumns;
23
24/// The kind name of heatmap series.
25pub const HEATMAP_KIND: &str = "orderflow.heatmap";
26
27/// Nothing is drawn when the plot shows more than this many levels per
28/// pixel row (levels are far below a pixel; zoom the price scale in).
29pub const MAX_LEVELS_PER_ROW: u32 = 8;
30
31/// What a heatmap aggregates.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
33pub enum HeatmapSource {
34    /// Order book snapshots ([`crate::append_depth`]): the largest resting
35    /// size of each level within a column.
36    #[default]
37    Depth,
38    /// Trades ([`crate::append_trades`]): the volume traded at each level
39    /// within a column.
40    Trades,
41}
42
43/// How values map to the color ramp.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub enum ColorScale {
46    /// Proportional to the value.
47    Linear,
48    /// Proportional to `ln(1 + value)`.
49    #[default]
50    Log,
51}
52
53/// The value range of the color ramp.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub enum HeatmapRange {
56    /// From 0 to the given quantile (in (0, 1]) of the visible cells, rounded
57    /// up to a quarter of its octave so it does not flicker while panning.
58    Auto {
59        /// E.g. 0.99: the top 1% of cells get the last color.
60        percentile: f32,
61    },
62    /// Fixed.
63    Fixed {
64        /// Value of the first color (≥ 0).
65        lo: f32,
66        /// Value of the last color (> `lo`).
67        hi: f32,
68    },
69}
70
71impl Default for HeatmapRange {
72    fn default() -> Self {
73        Self::Auto { percentile: 0.99 }
74    }
75}
76
77/// Colors of a heatmap: five evenly spaced stops, from the smallest to the
78/// largest value, interpolated per channel (alpha included).
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct HeatmapColors {
81    /// The stops.
82    pub stops: [Rgba; 5],
83}
84
85impl Default for HeatmapColors {
86    /// Translucent blue through cyan and yellow to opaque orange-red.
87    fn default() -> Self {
88        Self {
89            stops: [
90                Rgba::hex(0x0D_47A1).with_alpha(80),
91                Rgba::hex(0x1E_88E5).with_alpha(150),
92                Rgba::hex(0x26_C6DA).with_alpha(200),
93                Rgba::hex(0xFF_EE58).with_alpha(235),
94                Rgba::hex(0xFF_5722),
95            ],
96        }
97    }
98}
99
100/// Options of a [`Heatmap`].
101#[derive(Clone, Copy, Debug, PartialEq)]
102pub struct HeatmapOptions {
103    /// Minimum price increment.
104    pub tick_size: f64,
105    /// Ticks per row.
106    pub row_size: u32,
107    /// Column length, ms (e.g. 1 000; may be finer than the candles).
108    /// Columns start at multiples of it (UTC).
109    pub column_ms: i64,
110    /// Depth snapshots or trades.
111    pub source: HeatmapSource,
112    /// Log or linear colors.
113    pub scale: ColorScale,
114    /// Range of the colors.
115    pub range: HeatmapRange,
116    /// Whether the heatmap's levels take part in auto scaling. Off by
117    /// default: a book usually spans far more than the candles.
118    pub auto_scale: bool,
119    /// Colors.
120    pub colors: HeatmapColors,
121}
122
123impl HeatmapOptions {
124    /// One tick per row, log colors from 0 to the visible p99, no auto
125    /// scaling, the default colors.
126    pub fn new(tick_size: f64, column_ms: i64, source: HeatmapSource) -> Self {
127        Self {
128            tick_size,
129            row_size: 1,
130            column_ms,
131            source,
132            scale: ColorScale::Log,
133            range: HeatmapRange::default(),
134            auto_scale: false,
135            colors: HeatmapColors::default(),
136        }
137    }
138}
139
140/// One order book snapshot: the resting size at each price (bids and asks
141/// together). Prices are expected in book order (sorted either way):
142/// adjacent prices in the same row are added up.
143#[derive(Clone, Copy, Debug, PartialEq)]
144pub struct DepthSnapshot<'a> {
145    /// Time, UTC ms.
146    pub time: Timestamp,
147    /// Prices.
148    pub prices: &'a [f64],
149    /// Resting sizes (≥ 0; 0 is ignored).
150    pub sizes: &'a [f64],
151}
152
153impl DepthSnapshot<'_> {
154    fn check(&self, levels: PriceLevels) -> Result<()> {
155        if self.prices.len() != self.sizes.len() {
156            return Err(Error::InvalidArgument(
157                "depth prices and sizes must have the same length",
158            ));
159        }
160        if self.prices.iter().any(|&p| levels.level(p).is_none()) {
161            return Err(Error::InvalidArgument(
162                "depth prices must be finite and in range",
163            ));
164        }
165        if self.sizes.iter().any(|s| !(s.is_finite() && *s >= 0.0)) {
166            return Err(Error::InvalidArgument(
167                "depth sizes must be finite and non-negative",
168            ));
169        }
170        Ok(())
171    }
172}
173
174/// The color-scale range of a frame.
175#[derive(Clone, Copy, Debug, Default, PartialEq)]
176pub(crate) struct Scale {
177    pub(crate) lo: f32,
178    pub(crate) hi: f32,
179    pub(crate) log: bool,
180}
181
182/// Where a frame's cells go, in whole pixels; shared by both paths.
183#[derive(Clone, Debug, Default)]
184pub(crate) struct Layout {
185    /// Whether there is anything to draw.
186    pub(crate) valid: bool,
187    /// The plot: left, top, width, height.
188    pub(crate) x0: i32,
189    pub(crate) y0: i32,
190    pub(crate) w: u32,
191    pub(crate) h: u32,
192    /// Column of `col_px[0]`.
193    pub(crate) first: usize,
194    /// Per column: pixel columns `[p0, p1)` from the plot's left (empty
195    /// when off the plot).
196    pub(crate) col_px: Vec<[u32; 2]>,
197    /// Level of `level_band[0]`.
198    pub(crate) level_lo: i32,
199    /// Per level from `level_lo`: its band, or -1 when it has no pixel row.
200    pub(crate) level_band: Vec<i32>,
201    /// Per plot row: its band, or -1.
202    pub(crate) row_band: Vec<i32>,
203    /// Per band: plot rows `[r0, r1)`.
204    pub(crate) band_rows: Vec<[u32; 2]>,
205    pub(crate) scale: Scale,
206}
207
208type AutoKey = (u64, usize, usize, i32, i32, u32);
209
210/// A heatmap series: add it with
211/// [`Chart::add_custom_series`](ferrochart_core::Chart::add_custom_series)
212/// and feed it with [`crate::append_depth`] or [`crate::append_trades`].
213///
214/// Columns are placed by time between the candles' slots
215/// (`AxisMode::Overlay`), so 1 s columns on a 1 min chart add no slots.
216/// Each pixel column shows the largest value of the data columns it
217/// covers; each level fills the pixel rows between its rounded edges.
218///
219/// # Examples
220///
221/// ```
222/// use ferrochart_core::chart::SeriesOptions;
223/// use ferrochart_core::testing::MonoMeasurer;
224/// use ferrochart_core::{Chart, ChartOptions};
225/// use ferrochart_orderflow::{DepthSnapshot, Heatmap, HeatmapOptions, HeatmapSource, append_depth};
226///
227/// let mut chart = Chart::new(ChartOptions::default());
228/// let opts = HeatmapOptions::new(0.5, 1_000, HeatmapSource::Depth);
229/// let id = chart.add_custom_series(chart.main_pane(), Box::new(Heatmap::new(opts)?), SeriesOptions::default())?;
230/// let (prices, sizes) = ([99.5, 100.0, 100.5], [12.0, 3.0, 40.0]);
231/// append_depth(&mut chart, id, &DepthSnapshot { time: 0, prices: &prices, sizes: &sizes })?;
232/// append_depth(&mut chart, id, &DepthSnapshot { time: 500, prices: &prices[..1], sizes: &[20.0] })?;
233/// let h = chart.custom_series::<Heatmap>(id).unwrap();
234/// // One column; the largest size of each level (100.0 is level 200).
235/// assert_eq!(h.grid().columns(), 1);
236/// assert_eq!(h.grid().column(0).unwrap().at(199), (20.0, 0.0));
237/// chart.build_frame(0.0, &MonoMeasurer);
238/// # Ok::<(), ferrochart_core::Error>(())
239/// ```
240#[derive(Debug)]
241pub struct Heatmap {
242    opts: HeatmapOptions,
243    grid: SparseGrid,
244    /// Bumped on every data change (keys the auto range).
245    version: u64,
246    layout: RefCell<Layout>,
247    /// Portable path: band × pixel column maxima.
248    scratch: RefCell<Vec<f32>>,
249    auto: Cell<Option<(AutoKey, f32)>>,
250}
251
252fn check_display(range: HeatmapRange) -> Result<()> {
253    let ok = match range {
254        HeatmapRange::Auto { percentile } => percentile > 0.0 && percentile <= 1.0,
255        HeatmapRange::Fixed { lo, hi } => lo.is_finite() && hi.is_finite() && lo >= 0.0 && hi > lo,
256    };
257    if ok {
258        Ok(())
259    } else {
260        Err(Error::InvalidArgument(
261            "heatmap range: percentile in (0, 1], or 0 <= lo < hi",
262        ))
263    }
264}
265
266impl Heatmap {
267    /// An empty heatmap.
268    ///
269    /// # Errors
270    ///
271    /// [`Error::InvalidArgument`] for a bad price grid, a non-positive
272    /// column length or a bad range.
273    pub fn new(opts: HeatmapOptions) -> Result<Self> {
274        let levels = PriceLevels::new(opts.tick_size, opts.row_size)?;
275        if opts.column_ms <= 0 {
276            return Err(Error::InvalidArgument("column_ms must be positive"));
277        }
278        check_display(opts.range)?;
279        Ok(Self {
280            opts,
281            grid: SparseGrid::new(levels),
282            version: 0,
283            layout: RefCell::new(Layout::default()),
284            scratch: RefCell::new(Vec::new()),
285            auto: Cell::new(None),
286        })
287    }
288
289    /// The options.
290    pub fn options(&self) -> &HeatmapOptions {
291        &self.opts
292    }
293
294    /// Changes the colors and their scale (the data stays).
295    ///
296    /// # Errors
297    ///
298    /// [`Error::InvalidArgument`] for a bad range (nothing changes).
299    pub fn set_display(
300        &mut self,
301        scale: ColorScale,
302        range: HeatmapRange,
303        colors: HeatmapColors,
304    ) -> Result<()> {
305        check_display(range)?;
306        self.opts.scale = scale;
307        self.opts.range = range;
308        self.opts.colors = colors;
309        self.auto.set(None);
310        Ok(())
311    }
312
313    /// The cells: `a` is the size (`b` is unused).
314    pub fn grid(&self) -> &SparseGrid {
315        &self.grid
316    }
317
318    fn check_column(&self, time: Timestamp) -> Result<Timestamp> {
319        let col = crate::column_start(time, self.opts.column_ms);
320        if self.grid.times().last().is_some_and(|&t| col < t) {
321            return Err(Error::TimeNotIncreasing {
322                index: self.grid.columns(),
323            });
324        }
325        Ok(col)
326    }
327
328    /// Adds one trade to a trade heatmap; returns whether it opened a column.
329    ///
330    /// # Errors
331    ///
332    /// [`Error::InvalidArgument`] for a depth heatmap, a non-finite price
333    /// or a negative size; [`Error::TimeNotIncreasing`] if its column is
334    /// before the last one; [`Error::OutOfMemory`].
335    pub fn push_trade(&mut self, time: Timestamp, price: f64, size: f64) -> Result<bool> {
336        if self.opts.source != HeatmapSource::Trades {
337            return Err(Error::InvalidArgument("the heatmap takes depth snapshots"));
338        }
339        if !(size.is_finite() && size >= 0.0) {
340            return Err(Error::InvalidArgument(
341                "trade sizes must be finite and non-negative",
342            ));
343        }
344        let level = self
345            .grid
346            .price_levels()
347            .level(price)
348            .ok_or(Error::InvalidArgument("trade prices must be finite"))?;
349        let col = self.check_column(time)?;
350        if size == 0.0 {
351            return Ok(false);
352        }
353        let opened = self.grid.add(col, level, size as f32, 0.0, Combine::Sum)?;
354        self.version = self.version.wrapping_add(1);
355        Ok(opened)
356    }
357
358    /// Adds an order book snapshot to a depth heatmap; returns whether it
359    /// opened a column. Within a column each level keeps its largest size.
360    ///
361    /// # Errors
362    ///
363    /// [`Error::InvalidArgument`] for a trade heatmap or a bad snapshot
364    /// (lengths, non-finite prices, negative sizes; nothing changes);
365    /// [`Error::TimeNotIncreasing`] if its column is before the last one;
366    /// [`Error::OutOfMemory`] (the levels added so far stay).
367    pub fn push_depth(&mut self, snapshot: &DepthSnapshot<'_>) -> Result<bool> {
368        if self.opts.source != HeatmapSource::Depth {
369            return Err(Error::InvalidArgument("the heatmap takes trades"));
370        }
371        let levels = self.grid.price_levels();
372        snapshot.check(levels)?;
373        let col = self.check_column(snapshot.time)?;
374        let mut opened = false;
375        let mut run: Option<(i32, f64)> = None;
376        for (&price, &size) in snapshot.prices.iter().zip(snapshot.sizes) {
377            if size == 0.0 {
378                continue;
379            }
380            let Some(level) = levels.level(price) else {
381                continue;
382            };
383            match run {
384                Some((l, sum)) if l == level => run = Some((l, sum + size)),
385                _ => {
386                    if let Some((l, sum)) = run {
387                        opened |= self.grid.add(col, l, sum as f32, 0.0, Combine::Max)?;
388                        self.version = self.version.wrapping_add(1);
389                    }
390                    run = Some((level, size));
391                }
392            }
393        }
394        if let Some((l, sum)) = run {
395            opened |= self.grid.add(col, l, sum as f32, 0.0, Combine::Max)?;
396            self.version = self.version.wrapping_add(1);
397        }
398        Ok(opened)
399    }
400
401    /// Bumped on every data change.
402    pub(crate) fn version(&self) -> u64 {
403        self.version
404    }
405
406    /// The layout of the last frame (native path).
407    #[cfg_attr(not(feature = "gpu"), allow(dead_code))]
408    pub(crate) fn layout(&self) -> Option<Ref<'_, Layout>> {
409        self.layout.try_borrow().ok()
410    }
411
412    /// Fills `l` for points `from..to`.
413    fn compute_layout(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, l: &mut Layout) {
414        l.valid = false;
415        l.col_px.clear();
416        l.level_band.clear();
417        l.row_band.clear();
418        l.band_rows.clear();
419        let c = ctx.coords();
420        let plot = c.plot();
421        let (x0, x1) = (plot.x.round(), (plot.x + plot.w).round());
422        let (y0, y1) = (plot.y.round(), (plot.y + plot.h).round());
423        if !(x1 > x0 && y1 > y0) {
424            return;
425        }
426        let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
427        (l.x0, l.y0, l.w, l.h) = (x0 as i32, y0 as i32, w, h);
428
429        // Levels: the plot's price range plus one on each side.
430        let levels = self.grid.price_levels();
431        let (pa, pb) = (c.price_at(plot.y), c.price_at(plot.y + plot.h));
432        let (Some(lo), Some(hi)) = (levels.level(pa.min(pb)), levels.level(pa.max(pb))) else {
433            return;
434        };
435        let (lo, hi) = (i64::from(lo) - 1, i64::from(hi) + 1);
436        if hi - lo + 1 > i64::from(h) * i64::from(MAX_LEVELS_PER_ROW) {
437            return;
438        }
439        let Ok(level_lo) = i32::try_from(lo) else {
440            return;
441        };
442        l.level_lo = level_lo;
443        l.row_band.resize(h as usize, -1);
444        let step = levels.step();
445        // Lower edge of level k; level k spans edge(k)..edge(k + 1), so
446        // neighbours share an edge and their rows never overlap.
447        let edge = |k: i64| (k as f64 - 0.5) * step;
448        let fh = h as f32;
449        for k in lo..=hi {
450            let band = match (c.y_of(edge(k + 1)), c.y_of(edge(k))) {
451                (Some(ya), Some(yb)) => {
452                    let r0 = (ya.min(yb).round() - y0).clamp(0.0, fh) as u32;
453                    let r1 = (ya.max(yb).round() - y0).clamp(0.0, fh) as u32;
454                    if r1 > r0 {
455                        let b = l.band_rows.len() as i32;
456                        l.band_rows.push([r0, r1]);
457                        l.row_band[r0 as usize..r1 as usize].fill(b);
458                        b
459                    } else {
460                        -1
461                    }
462                }
463                _ => -1,
464            };
465            l.level_band.push(band);
466        }
467
468        // Columns: from the column's start to its end, at least one pixel.
469        // x of a time plus the series' shift (constant in pixels); a column
470        // that starts where the previous one ended reuses its end.
471        let times = self.grid.times();
472        let period = self.opts.column_ms;
473        l.first = from;
474        let clip = |p: i64| p.clamp(0, i64::from(w)) as u32;
475        let shift = match (times.get(from), ctx.x_of_point(from)) {
476            (Some(&t), Some(x)) => c.x_of(t).map_or(0.0, |a| x - a),
477            _ => 0.0,
478        };
479        let x_at = |t: Timestamp| c.x_of(t).map(|x| x + shift);
480        let mut prev_end: Option<(Timestamp, Option<f32>)> = None;
481        for i in from..to {
482            let px = match times.get(i) {
483                Some(&t) => {
484                    let xl = match prev_end {
485                        Some((end, x)) if end == t => x,
486                        _ => x_at(t),
487                    };
488                    let end = t.saturating_add(period);
489                    let xr = x_at(end);
490                    prev_end = Some((end, xr));
491                    match (xl, xr) {
492                        (Some(xl), Some(xr)) => {
493                            let p0 = (xl.round() - x0) as i64;
494                            let p1 = ((xr.round() - x0) as i64).max(p0 + 1);
495                            [clip(p0), clip(p1)]
496                        }
497                        _ => [0, 0],
498                    }
499                }
500                None => [0, 0],
501            };
502            l.col_px.push(px);
503        }
504
505        l.scale = match self.opts.range {
506            HeatmapRange::Fixed { lo, hi } => Scale {
507                lo,
508                hi,
509                log: self.opts.scale == ColorScale::Log,
510            },
511            HeatmapRange::Auto { percentile } => Scale {
512                lo: 0.0,
513                hi: self.auto_hi(from, to, level_lo, hi as i32, percentile, w),
514                log: self.opts.scale == ColorScale::Log,
515            },
516        };
517        l.valid = true;
518    }
519
520    /// The `percentile` quantile of the non-zero cells of columns
521    /// `from..to` and levels `lo..=hi`, rounded up to a quarter of its
522    /// octave. With more than 4 columns per pixel column (`w` wide), only
523    /// columns whose number is a multiple of `ceil(columns / 4w)` count, so
524    /// the sample does not change while panning.
525    fn auto_hi(&self, from: usize, to: usize, lo: i32, hi: i32, percentile: f32, w: u32) -> f32 {
526        let key = (self.version, from, to, lo, hi, percentile.to_bits());
527        if let Some((k, v)) = self.auto.get()
528            && k == key
529        {
530            return v;
531        }
532        let mut bins = [0_u32; BINS];
533        let mut n = 0_u64;
534        let stride = (to - from).div_ceil(4 * w.max(1) as usize).max(1);
535        for i in (from.next_multiple_of(stride)..to).step_by(stride) {
536            let Some(col) = self.grid.column(i) else {
537                continue;
538            };
539            let a = col.levels.partition_point(|&x| x < lo);
540            let b = col.levels.partition_point(|&x| x <= hi);
541            for &v in &col.a[a..b.max(a)] {
542                if v > 0.0 {
543                    bins[bin(v)] += 1;
544                    n += 1;
545                }
546            }
547        }
548        let v = if n == 0 {
549            1.0
550        } else {
551            let target = ((f64::from(percentile) * n as f64).ceil() as u64).clamp(1, n);
552            let mut acc = 0_u64;
553            let mut k = BINS - 1;
554            for (j, &count) in bins.iter().enumerate() {
555                acc += u64::from(count);
556                if acc >= target {
557                    k = j;
558                    break;
559                }
560            }
561            bin_upper(k)
562        };
563        self.auto.set(Some((key, v)));
564        v
565    }
566
567    /// Portable path: per-pixel maxima, then one rectangle per run of equal
568    /// color in each band.
569    fn draw_cells(&self, l: &Layout, out: &mut FrameBuilder<'_>) {
570        let Ok(mut buf) = self.scratch.try_borrow_mut() else {
571            return;
572        };
573        let w = l.w as usize;
574        buf.clear();
575        buf.resize(w * l.band_rows.len(), 0.0);
576        let lo = l.level_lo;
577        let hi = i64::from(lo) + l.level_band.len() as i64 - 1;
578        for (j, &[p0, p1]) in l.col_px.iter().enumerate() {
579            if p0 >= p1 {
580                continue;
581            }
582            let Some(col) = self.grid.column(l.first + j) else {
583                continue;
584            };
585            let a = col.levels.partition_point(|&x| x < lo);
586            let b = col.levels.partition_point(|&x| i64::from(x) <= hi);
587            for k in a..b.max(a) {
588                let rel = (i64::from(col.levels[k]) - i64::from(lo)) as usize;
589                let (Some(&band), v) = (l.level_band.get(rel), col.a[k]) else {
590                    continue;
591                };
592                if band < 0 || v <= 0.0 {
593                    continue;
594                }
595                let start = band as usize * w;
596                for c in &mut buf[start + p0 as usize..start + p1 as usize] {
597                    if v > *c {
598                        *c = v;
599                    }
600                }
601            }
602        }
603        let stops = &self.opts.colors.stops;
604        for (band, &[r0, r1]) in l.band_rows.iter().enumerate() {
605            let row = &buf[band * w..(band + 1) * w];
606            let mut run: Option<(usize, Rgba)> = None;
607            let mut last = (0_u32, None::<Rgba>);
608            for x in 0..=w {
609                let color = match row.get(x) {
610                    Some(&v) if v > 0.0 => {
611                        if last.0 != v.to_bits() || last.1.is_none() {
612                            last = (v.to_bits(), Some(ramp(scale_t(v, l.scale), stops)));
613                        }
614                        last.1
615                    }
616                    _ => None,
617                };
618                if run.map(|r| r.1) == color {
619                    continue;
620                }
621                if let Some((s, c)) = run
622                    && c.a > 0
623                {
624                    out.rect(
625                        RectPx {
626                            x: (l.x0 + s as i32) as f32,
627                            y: (l.y0 + r0 as i32) as f32,
628                            w: (x - s) as f32,
629                            h: (r1 - r0) as f32,
630                        },
631                        c,
632                    );
633                }
634                run = color.map(|c| (x, c));
635            }
636        }
637    }
638}
639
640/// Octaves from 2^-32 to 2^32, each split into 4 equal parts.
641const BINS: usize = 256;
642
643/// The bin of a positive finite `v`, from its bits: the exponent and the two
644/// top mantissa bits (no `log2` per cell).
645fn bin(v: f32) -> usize {
646    let bits = v.to_bits();
647    let exp = ((bits >> 23) & 0xFF) as i32 - 127;
648    let quarter = ((bits >> 21) & 3) as i32;
649    ((exp + 32) * 4 + quarter).clamp(0, BINS as i32 - 1) as usize
650}
651
652/// The upper edge of bin `k`: `2^e × (1 + (q + 1)/4)`.
653fn bin_upper(k: usize) -> f32 {
654    let (e, q) = ((k / 4) as i32 - 32, (k % 4) as f32);
655    (e as f32).exp2() * (1.0 + (q + 1.0) / 4.0)
656}
657
658/// Position of `v` on the ramp, 0–1. Shader: `scale_t()` in
659/// `heatmap.wgsl`, same operations in the same order.
660pub(crate) fn scale_t(v: f32, s: Scale) -> f32 {
661    let (fv, flo, fhi) = if s.log {
662        ((1.0 + v).ln(), (1.0 + s.lo).ln(), (1.0 + s.hi).ln())
663    } else {
664        (v, s.lo, s.hi)
665    };
666    let d = fhi - flo;
667    if d.is_nan() || d <= 0.0 {
668        return 1.0;
669    }
670    ((fv - flo) / d).clamp(0.0, 1.0)
671}
672
673/// The ramp's color at `t`. Shader: `ramp()` in `heatmap.wgsl`.
674pub(crate) fn ramp(t: f32, stops: &[Rgba; 5]) -> Rgba {
675    let s = t * 4.0;
676    let k = s.floor().clamp(0.0, 3.0);
677    let f = s - k;
678    let (a, b) = (stops[k as usize], stops[k as usize + 1]);
679    let mix = |x: u8, y: u8| {
680        let (x, y) = (f32::from(x), f32::from(y));
681        (x + (y - x) * f + 0.5).floor() as u8
682    };
683    Rgba {
684        r: mix(a.r, b.r),
685        g: mix(a.g, b.g),
686        b: mix(a.b, b.b),
687        a: mix(a.a, b.a),
688    }
689}
690
691impl crate::TradeSink for Heatmap {
692    fn timeframe(&self) -> i64 {
693        self.opts.column_ms
694    }
695
696    fn last_column(&self) -> Option<Timestamp> {
697        self.grid.times().last().copied()
698    }
699
700    fn apply(&mut self, trades: &TickColumns, range: Range<usize>) -> Result<()> {
701        for i in range {
702            let (t, p, s, _) = trades.get(i);
703            self.push_trade(t, p, s)?;
704        }
705        Ok(())
706    }
707}
708
709impl CustomSeries for Heatmap {
710    fn kind(&self) -> &'static str {
711        HEATMAP_KIND
712    }
713
714    fn axis_mode(&self) -> AxisMode {
715        AxisMode::Overlay
716    }
717
718    fn times(&self) -> &[Timestamp] {
719        self.grid.times()
720    }
721
722    fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
723        if self.opts.auto_scale {
724            self.grid.extremes(from, to)
725        } else {
726            None
727        }
728    }
729
730    fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
731        let Ok(mut l) = self.layout.try_borrow_mut() else {
732            return;
733        };
734        self.compute_layout(ctx, from, to, &mut l);
735        if l.valid {
736            self.draw_cells(&l, out);
737        }
738    }
739
740    /// `[lo, hi, log (1/0), …]` of the color scale; also lays out the frame
741    /// for the native path.
742    fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
743        let Ok(mut l) = self.layout.try_borrow_mut() else {
744            return;
745        };
746        let (from, to) = ctx.visible();
747        self.compute_layout(ctx, from, to, &mut l);
748        params[0] = l.scale.lo;
749        params[1] = l.scale.hi;
750        params[2] = if l.scale.log { 1.0 } else { 0.0 };
751    }
752}
753
754#[cfg(test)]
755mod tests {
756    #![allow(clippy::unwrap_used, clippy::float_cmp)]
757
758    use super::*;
759
760    fn depth() -> Heatmap {
761        Heatmap::new(HeatmapOptions::new(1.0, 1_000, HeatmapSource::Depth)).unwrap()
762    }
763
764    #[test]
765    fn snapshots_keep_the_largest_size() {
766        let mut h = depth();
767        let snap = |time, prices: &'static [f64], sizes: &'static [f64]| DepthSnapshot {
768            time,
769            prices,
770            sizes,
771        };
772        assert!(
773            h.push_depth(&snap(10, &[1.0, 2.0, 3.0], &[5.0, 0.0, 2.0]))
774                .unwrap()
775        );
776        assert!(!h.push_depth(&snap(900, &[1.0, 3.0], &[4.0, 6.0])).unwrap());
777        assert!(h.push_depth(&snap(1_000, &[2.0], &[1.0])).unwrap());
778        let c = h.grid().column(0).unwrap();
779        assert_eq!((c.levels, c.a), (&[1, 3][..], &[5.0, 6.0][..]));
780        assert_eq!(h.grid().times(), &[0, 1_000]);
781        // Adjacent prices in one row add up.
782        let mut g = Heatmap::new(HeatmapOptions {
783            row_size: 2,
784            ..HeatmapOptions::new(1.0, 1_000, HeatmapSource::Depth)
785        })
786        .unwrap();
787        g.push_depth(&snap(0, &[4.0, 4.4, 5.0], &[1.0, 2.0, 3.0]))
788            .unwrap();
789        assert_eq!(g.grid().column(0).unwrap().at(2), (3.0, 0.0));
790        // Errors leave the data alone.
791        assert!(h.push_depth(&snap(1, &[1.0], &[1.0])).is_err());
792        assert!(h.push_depth(&snap(2_000, &[1.0, 2.0], &[1.0])).is_err());
793        assert!(h.push_depth(&snap(2_000, &[f64::NAN], &[1.0])).is_err());
794        assert!(h.push_depth(&snap(2_000, &[1.0], &[-1.0])).is_err());
795        assert!(h.push_trade(2_000, 1.0, 1.0).is_err());
796        assert_eq!(h.grid().columns(), 2);
797    }
798
799    #[test]
800    fn options_are_checked() {
801        let mut o = HeatmapOptions::new(1.0, 0, HeatmapSource::Trades);
802        assert!(Heatmap::new(o).is_err());
803        o.column_ms = 1_000;
804        for range in [
805            HeatmapRange::Auto { percentile: 0.0 },
806            HeatmapRange::Auto { percentile: 1.5 },
807            HeatmapRange::Auto {
808                percentile: f32::NAN,
809            },
810            HeatmapRange::Fixed { lo: 2.0, hi: 1.0 },
811            HeatmapRange::Fixed { lo: -1.0, hi: 1.0 },
812        ] {
813            o.range = range;
814            assert!(Heatmap::new(o).is_err(), "{range:?}");
815        }
816        o.range = HeatmapRange::Fixed { lo: 0.0, hi: 10.0 };
817        let mut h = Heatmap::new(o).unwrap();
818        assert!(
819            h.push_depth(&DepthSnapshot {
820                time: 0,
821                prices: &[1.0],
822                sizes: &[1.0]
823            })
824            .is_err()
825        );
826        h.push_trade(5, 1.0, 2.0).unwrap();
827        h.push_trade(6, 1.0, 3.0).unwrap();
828        assert_eq!(h.grid().column(0).unwrap().at(1), (5.0, 0.0));
829        let colors = HeatmapColors::default();
830        assert!(
831            h.set_display(
832                ColorScale::Linear,
833                HeatmapRange::Auto { percentile: 2.0 },
834                colors
835            )
836            .is_err()
837        );
838        assert_eq!(h.options().scale, ColorScale::Log);
839    }
840
841    #[test]
842    fn scale_and_ramp() {
843        let lin = Scale {
844            lo: 0.0,
845            hi: 10.0,
846            log: false,
847        };
848        assert_eq!(scale_t(5.0, lin), 0.5);
849        assert_eq!(scale_t(50.0, lin), 1.0);
850        let log = Scale {
851            lo: 0.0,
852            hi: 99.0,
853            log: true,
854        };
855        assert!((scale_t(9.0, log) - 0.5).abs() < 1e-6);
856        assert_eq!(
857            scale_t(
858                1.0,
859                Scale {
860                    lo: 2.0,
861                    hi: 2.0,
862                    log: false
863                }
864            ),
865            1.0
866        );
867        let stops = HeatmapColors::default().stops;
868        assert_eq!(ramp(0.0, &stops), stops[0]);
869        assert_eq!(ramp(1.0, &stops), stops[4]);
870        assert_eq!(ramp(0.5, &stops), stops[2]);
871        let mid = ramp(0.125, &stops);
872        assert_eq!(mid.a, 115);
873        // 3 = 2 × 1.5 is in [2 × 1.5, 2 × 1.75).
874        assert_eq!(bin_upper(bin(3.0)), 3.5);
875        assert_eq!(bin_upper(bin(1.0)), 1.25);
876        assert_eq!(bin_upper(bin(1.9)), 2.0);
877        assert_eq!(bin(0.0), 0);
878        assert_eq!(bin(f32::MAX), 255);
879    }
880}