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