Skip to main content

tui_chart/
depth.rs

1//! DepthChart: order-book depth chart (cumulative bids left, asks right).
2
3use crate::canvas::{Canvas, Marker};
4use crate::theme::{self, Theme};
5use crate::util::{darken, format_compact, format_tick};
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13const EIGHTHS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
14
15/// Order-book depth chart. Bids are drawn as a cumulative step-area on the
16/// left, asks on the right, with a mid-price marker and spread readout.
17#[derive(Debug, Clone)]
18pub struct DepthChart {
19    bids: Vec<(f64, f64)>,
20    asks: Vec<(f64, f64)>,
21    bid_color: Option<Color>,
22    ask_color: Option<Color>,
23    theme: Option<Theme>,
24    base: Option<Style>,
25    marker: Option<Marker>,
26    show_mid: bool,
27    show_spread: bool,
28    block: Option<Block<'static>>,
29}
30
31fn clean(levels: impl IntoIterator<Item = (f64, f64)>) -> Vec<(f64, f64)> {
32    levels
33        .into_iter()
34        .filter(|(p, q)| p.is_finite() && q.is_finite() && *q > 0.0)
35        .collect()
36}
37
38impl DepthChart {
39    /// Create from `(price, quantity)` bid and ask levels (any order;
40    /// non-finite or non-positive-quantity levels are ignored).
41    pub fn new(
42        bids: impl IntoIterator<Item = (f64, f64)>,
43        asks: impl IntoIterator<Item = (f64, f64)>,
44    ) -> Self {
45        Self {
46            bids: clean(bids),
47            asks: clean(asks),
48            bid_color: None,
49            ask_color: None,
50            theme: None,
51            base: None,
52            marker: None,
53            show_mid: true,
54            show_spread: true,
55            block: None,
56        }
57    }
58
59    opt_setter!(
60        /// Bid (buy side) color.
61        bid_color: Color
62    );
63
64    opt_setter!(
65        /// Ask (sell side) color.
66        ask_color: Color
67    );
68
69    theme_setter!(
70        /// Apply a [`Theme`]: bull/bear side colors, text colors and background
71        /// fill. Explicit [`DepthChart::bid_color`] / [`DepthChart::ask_color`] win.
72        theme
73    );
74
75    base_style_setter!(base);
76
77    fn bid(&self) -> Color {
78        self.bid_color
79            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
80    }
81
82    fn ask(&self) -> Color {
83        self.ask_color
84            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Red, |t| t.bear))
85    }
86
87    opt_setter!(
88        /// Draw the step-area with dot glyphs (e.g. [`Marker::Braille`] for
89        /// 2×4 sub-cell resolution) instead of eighth blocks (the default).
90        marker: Marker
91    );
92
93    setter!(
94        /// Show the mid-price marker line.
95        show_mid: bool
96    );
97
98    setter!(
99        /// Show the spread readout on the top row.
100        show_spread: bool
101    );
102
103    block_setter!(block, 'static);
104
105    fn best_bid(&self) -> Option<f64> {
106        self.bids.iter().map(|l| l.0).reduce(f64::max)
107    }
108
109    fn best_ask(&self) -> Option<f64> {
110        self.asks.iter().map(|l| l.0).reduce(f64::min)
111    }
112
113    /// Mid price, if both sides exist.
114    pub fn mid(&self) -> Option<f64> {
115        Some((self.best_bid()? + self.best_ask()?) / 2.0)
116    }
117
118    /// Spread (best ask - best bid), if both sides exist.
119    pub fn spread(&self) -> Option<f64> {
120        Some(self.best_ask()? - self.best_bid()?)
121    }
122
123    /// Cumulative bid quantity at or above `price` (0 inside/above the spread).
124    pub fn bid_depth_at(&self, price: f64) -> f64 {
125        match self.best_bid() {
126            Some(b) if price <= b => self.bids.iter().filter(|l| l.0 >= price).map(|l| l.1).sum(),
127            _ => 0.0,
128        }
129    }
130
131    /// Cumulative ask quantity at or below `price` (0 inside/below the spread).
132    pub fn ask_depth_at(&self, price: f64) -> f64 {
133        match self.best_ask() {
134            Some(a) if price >= a => self.asks.iter().filter(|l| l.0 <= price).map(|l| l.1).sum(),
135            _ => 0.0,
136        }
137    }
138
139    fn price_range(&self) -> Option<(f64, f64)> {
140        let all = self.bids.iter().chain(self.asks.iter()).map(|l| l.0);
141        let lo = all.clone().fold(f64::INFINITY, f64::min);
142        let hi = all.fold(f64::NEG_INFINITY, f64::max);
143        if !lo.is_finite() {
144            return None;
145        }
146        Some(if hi > lo {
147            (lo, hi)
148        } else {
149            (lo - 0.5, hi + 0.5)
150        })
151    }
152}
153
154fn put(buf: &mut Buffer, area: Rect, x: u16, y: u16, s: &str, style: Style) {
155    if x < area.right() && y < area.bottom() {
156        buf[(x, y)].set_symbol(s).set_style(style);
157    }
158}
159
160fn put_str(buf: &mut Buffer, area: Rect, x: u16, y: u16, s: &str, style: Style) {
161    for (i, ch) in s.chars().enumerate() {
162        let xx = x as usize + i;
163        if xx >= area.right() as usize {
164            break;
165        }
166        put(buf, area, xx as u16, y, &ch.to_string(), style);
167    }
168}
169
170impl DepthChart {
171    fn render_into(&self, area: Rect, buf: &mut Buffer) {
172        let area = area.intersection(buf.area);
173        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
174        if inner.width < 2 || inner.height < 3 {
175            return;
176        }
177        let dim_c = self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid);
178        let txt_c = self.theme.as_ref().map_or(Color::Gray, |t| t.muted);
179        let Some((lo, hi)) = self.price_range() else {
180            return;
181        };
182        let w = inner.width as usize;
183        let plot_h = inner.height - 2; // top: spread, bottom: price labels
184        let top = inner.y + 1;
185        let prices: Vec<f64> = (0..w)
186            .map(|i| lo + (i as f64 + 0.5) / w as f64 * (hi - lo))
187            .collect();
188        let depths: Vec<(f64, f64)> = prices
189            .iter()
190            .map(|&p| (self.bid_depth_at(p), self.ask_depth_at(p)))
191            .collect();
192        let max = depths
193            .iter()
194            .flat_map(|d| [d.0, d.1])
195            .fold(0.0_f64, f64::max);
196        let mid_col = self.mid().filter(|_| self.show_mid).map(|m| {
197            (((m - lo) / (hi - lo)) * w as f64)
198                .floor()
199                .clamp(0.0, w as f64 - 1.0) as usize
200        });
201
202        for (i, &(b, a)) in depths.iter().enumerate() {
203            let x = inner.x + i as u16;
204            let (v, color) = if b > 0.0 {
205                (b, self.bid())
206            } else {
207                (a, self.ask())
208            };
209            if self.marker.is_some() {
210                if mid_col == Some(i) {
211                    for r in 0..plot_h {
212                        put(buf, inner, x, top + r, "│", Style::default().fg(dim_c));
213                    }
214                }
215                continue;
216            }
217            let units = if max > 0.0 {
218                v / max * plot_h as f64 * 8.0
219            } else {
220                0.0
221            };
222            let units = units.round() as usize;
223            let top_row = units.div_ceil(8); // rows that hold fill
224            for r in 0..plot_h as usize {
225                let y = top + plot_h - 1 - r as u16;
226                let have = units.saturating_sub(r * 8).min(8);
227                // brightest at the edge, fading toward the baseline
228                let below = top_row.saturating_sub(r + 1) as f64 / plot_h.max(1) as f64;
229                let style = Style::default().fg(darken(color, (below * 0.6).min(0.6)));
230                if have >= 8 {
231                    put(buf, inner, x, y, "█", style);
232                } else if have > 0 {
233                    put(buf, inner, x, y, &EIGHTHS[have - 1].to_string(), style);
234                } else if mid_col == Some(i) {
235                    put(buf, inner, x, y, "│", Style::default().fg(dim_c));
236                } else if i % 2 == 0 && plot_h >= 8 && ((r + 1) * 4) % (plot_h as usize) < 4 {
237                    // faint quarter grid lines in empty space
238                    put(
239                        buf,
240                        inner,
241                        x,
242                        y,
243                        "·",
244                        Style::default().fg(darken(dim_c, 0.3)),
245                    );
246                }
247            }
248        }
249        if let Some(m) = self.marker.filter(|_| max > 0.0) {
250            let mut cv = Canvas::new(inner.width, plot_h, m);
251            let (pw, ph) = (cv.px_w(), cv.px_h());
252            for px in 0..pw {
253                let p = lo + (f64::from(px) + 0.5) / f64::from(pw) * (hi - lo);
254                let (b, a) = (self.bid_depth_at(p), self.ask_depth_at(p));
255                let (v, color) = if b > 0.0 {
256                    (b, self.bid())
257                } else {
258                    (a, self.ask())
259                };
260                let n = (v / max * f64::from(ph)).round() as i32;
261                for py in (ph - n.clamp(0, ph))..ph {
262                    cv.set(px, py, color);
263                }
264            }
265            cv.render(buf, Rect::new(inner.x, top, inner.width, plot_h));
266        }
267        if self.show_spread {
268            if let (Some(s), Some(m)) = (self.spread(), self.mid()) {
269                let pct = if m != 0.0 { s / m * 100.0 } else { 0.0 };
270                let txt = format!(
271                    "spread {} ({:.2}%)",
272                    format_tick(s, (s.abs() / 10.0).max(1e-9)),
273                    pct
274                );
275                let x = inner.x + (inner.width.saturating_sub(txt.chars().count() as u16)) / 2;
276                put_str(buf, inner, x, inner.y, &txt, Style::default().fg(txt_c));
277            }
278        }
279        let label_y = inner.bottom() - 1;
280        let step = ((hi - lo) / 4.0).max(1e-9);
281        let l = format_tick(lo, step);
282        let r = format_tick(hi, step);
283        let dim = Style::default().fg(txt_c);
284        put_str(buf, inner, inner.x, label_y, &l, dim);
285        let rx = inner.right().saturating_sub(r.chars().count() as u16);
286        put_str(buf, inner, rx.max(inner.x), label_y, &r, dim);
287        // quarter price ticks when there is room
288        for q in [1.0, 3.0] {
289            let t = format_tick(lo + (hi - lo) * q / 4.0, step);
290            let n = t.chars().count() as u16;
291            let x = inner.x + (inner.width as f64 * q / 4.0) as u16;
292            let x = x.saturating_sub(n / 2);
293            if x > inner.x + l.chars().count() as u16 + 1 && x + n + 1 < rx {
294                put_str(buf, inner, x, label_y, &t, dim);
295            }
296        }
297        if let Some(m) = self.mid().filter(|_| self.show_mid) {
298            let t = format_tick(m, step);
299            let mx = inner.x + (inner.width.saturating_sub(t.chars().count() as u16)) / 2;
300            if mx > inner.x + l.chars().count() as u16 && mx + (t.len() as u16) < rx {
301                put_str(buf, inner, mx, label_y, &t, dim);
302            }
303        }
304        if max > 0.0 {
305            let t = format_compact(max);
306            put_str(buf, inner, inner.x, inner.y, &t, dim);
307        }
308    }
309}
310
311widget_impls!(DepthChart);
312
313#[cfg(feature = "theme")]
314impl tui_nuances::Themed for DepthChart {
315    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
316        self.theme(theme)
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use ratatui::widgets::Widget;
324
325    fn book() -> DepthChart {
326        DepthChart::new(
327            [(99.0, 5.0), (98.0, 10.0), (97.0, 20.0)],
328            [(101.0, 4.0), (102.0, 8.0), (103.0, 16.0)],
329        )
330    }
331
332    fn render(c: &DepthChart, w: u16, h: u16) -> Buffer {
333        let area = Rect::new(0, 0, w, h);
334        let mut buf = Buffer::empty(area);
335        c.render(area, &mut buf);
336        buf
337    }
338
339    #[test]
340    fn mid_and_spread() {
341        let c = book();
342        assert_eq!(c.mid(), Some(100.0));
343        assert_eq!(c.spread(), Some(2.0));
344    }
345
346    #[test]
347    fn cumulative_depth() {
348        let c = book();
349        assert_eq!(c.bid_depth_at(97.5), 15.0);
350        assert_eq!(c.bid_depth_at(100.0), 0.0);
351        assert_eq!(c.ask_depth_at(102.5), 12.0);
352        assert_eq!(c.ask_depth_at(100.0), 0.0);
353    }
354
355    #[test]
356    fn renders_both_colors() {
357        let buf = render(&book(), 40, 12);
358        let mut g = false;
359        let mut r = false;
360        for y in 0..12 {
361            for x in 0..40 {
362                let c = &buf[(x, y)];
363                if c.symbol() == "█" {
364                    g |= c.fg == Color::Green;
365                    r |= c.fg == Color::Red;
366                }
367            }
368        }
369        assert!(g && r);
370    }
371
372    #[cfg(feature = "theme")]
373    #[test]
374    fn theme_colors_and_override() {
375        let t = Theme::nord();
376        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
377        let b = render(&book().theme(&t), 40, 12);
378        assert!(has(&b, t.bull) && has(&b, t.bear));
379        assert_eq!(b[(0, 5)].bg, t.background.unwrap());
380        let b = render(
381            &book()
382                .theme(&t)
383                .bid_color(Color::Yellow)
384                .ask_color(Color::Magenta),
385            40,
386            12,
387        );
388        assert!(has(&b, Color::Yellow) && has(&b, Color::Magenta) && !has(&b, t.bull));
389    }
390
391    #[test]
392    fn spread_text() {
393        let buf = render(&book(), 50, 10);
394        let row: String = (0..50).map(|x| buf[(x, 0)].symbol().to_string()).collect();
395        assert!(row.contains("spread"));
396    }
397
398    #[test]
399    fn robust() {
400        for (w, h) in [(0, 0), (1, 1), (3, 2), (5, 5)] {
401            render(&book(), w, h);
402        }
403        render(&DepthChart::new([], []), 20, 8);
404        render(
405            &DepthChart::new([(f64::NAN, 1.0)], [(1.0, f64::NAN)]),
406            20,
407            8,
408        );
409        render(&DepthChart::new([(1.0, 1.0)], []), 20, 8);
410        render(&DepthChart::new([(1.0, 1.0)], [(1.0, 1.0)]), 20, 8);
411    }
412}