1use crate::canvas::{Canvas, Marker};
4use crate::theme::{self, Theme};
5use crate::util::{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#[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 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_color: Color
62 );
63
64 opt_setter!(
65 ask_color: Color
67 );
68
69 theme_setter!(
70 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 marker: Marker
91 );
92
93 setter!(
94 show_mid: bool
96 );
97
98 setter!(
99 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 pub fn mid(&self) -> Option<f64> {
115 Some((self.best_bid()? + self.best_ask()?) / 2.0)
116 }
117
118 pub fn spread(&self) -> Option<f64> {
120 Some(self.best_ask()? - self.best_bid()?)
121 }
122
123 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 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; 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 for r in 0..plot_h as usize {
224 let y = top + plot_h - 1 - r as u16;
225 let have = units.saturating_sub(r * 8).min(8);
226 let style = Style::default().fg(color);
227 if have >= 8 {
228 put(buf, inner, x, y, "█", style);
229 } else if have > 0 {
230 put(buf, inner, x, y, &EIGHTHS[have - 1].to_string(), style);
231 } else if mid_col == Some(i) {
232 put(buf, inner, x, y, "│", Style::default().fg(dim_c));
233 }
234 }
235 }
236 if let Some(m) = self.marker.filter(|_| max > 0.0) {
237 let mut cv = Canvas::new(inner.width, plot_h, m);
238 let (pw, ph) = (cv.px_w(), cv.px_h());
239 for px in 0..pw {
240 let p = lo + (f64::from(px) + 0.5) / f64::from(pw) * (hi - lo);
241 let (b, a) = (self.bid_depth_at(p), self.ask_depth_at(p));
242 let (v, color) = if b > 0.0 {
243 (b, self.bid())
244 } else {
245 (a, self.ask())
246 };
247 let n = (v / max * f64::from(ph)).round() as i32;
248 for py in (ph - n.clamp(0, ph))..ph {
249 cv.set(px, py, color);
250 }
251 }
252 cv.render(buf, Rect::new(inner.x, top, inner.width, plot_h));
253 }
254 if self.show_spread {
255 if let (Some(s), Some(m)) = (self.spread(), self.mid()) {
256 let pct = if m != 0.0 { s / m * 100.0 } else { 0.0 };
257 let txt = format!(
258 "spread {} ({:.2}%)",
259 format_tick(s, (s.abs() / 10.0).max(1e-9)),
260 pct
261 );
262 let x = inner.x + (inner.width.saturating_sub(txt.chars().count() as u16)) / 2;
263 put_str(buf, inner, x, inner.y, &txt, Style::default().fg(txt_c));
264 }
265 }
266 let label_y = inner.bottom() - 1;
267 let step = ((hi - lo) / 4.0).max(1e-9);
268 let l = format_tick(lo, step);
269 let r = format_tick(hi, step);
270 let dim = Style::default().fg(txt_c);
271 put_str(buf, inner, inner.x, label_y, &l, dim);
272 let rx = inner.right().saturating_sub(r.chars().count() as u16);
273 put_str(buf, inner, rx.max(inner.x), label_y, &r, dim);
274 if let Some(m) = self.mid().filter(|_| self.show_mid) {
275 let t = format_tick(m, step);
276 let mx = inner.x + (inner.width.saturating_sub(t.chars().count() as u16)) / 2;
277 if mx > inner.x + l.chars().count() as u16 && mx + (t.len() as u16) < rx {
278 put_str(buf, inner, mx, label_y, &t, dim);
279 }
280 }
281 if max > 0.0 {
282 let t = format_compact(max);
283 put_str(buf, inner, inner.x, inner.y, &t, dim);
284 }
285 }
286}
287
288widget_impls!(DepthChart);
289
290#[cfg(feature = "theme")]
291impl tui_nuances::Themed for DepthChart {
292 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
293 self.theme(theme)
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300 use ratatui::widgets::Widget;
301
302 fn book() -> DepthChart {
303 DepthChart::new(
304 [(99.0, 5.0), (98.0, 10.0), (97.0, 20.0)],
305 [(101.0, 4.0), (102.0, 8.0), (103.0, 16.0)],
306 )
307 }
308
309 fn render(c: &DepthChart, w: u16, h: u16) -> Buffer {
310 let area = Rect::new(0, 0, w, h);
311 let mut buf = Buffer::empty(area);
312 c.render(area, &mut buf);
313 buf
314 }
315
316 #[test]
317 fn mid_and_spread() {
318 let c = book();
319 assert_eq!(c.mid(), Some(100.0));
320 assert_eq!(c.spread(), Some(2.0));
321 }
322
323 #[test]
324 fn cumulative_depth() {
325 let c = book();
326 assert_eq!(c.bid_depth_at(97.5), 15.0);
327 assert_eq!(c.bid_depth_at(100.0), 0.0);
328 assert_eq!(c.ask_depth_at(102.5), 12.0);
329 assert_eq!(c.ask_depth_at(100.0), 0.0);
330 }
331
332 #[test]
333 fn renders_both_colors() {
334 let buf = render(&book(), 40, 12);
335 let mut g = false;
336 let mut r = false;
337 for y in 0..12 {
338 for x in 0..40 {
339 let c = &buf[(x, y)];
340 if c.symbol() == "█" {
341 g |= c.fg == Color::Green;
342 r |= c.fg == Color::Red;
343 }
344 }
345 }
346 assert!(g && r);
347 }
348
349 #[cfg(feature = "theme")]
350 #[test]
351 fn theme_colors_and_override() {
352 let t = Theme::nord();
353 let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
354 let b = render(&book().theme(&t), 40, 12);
355 assert!(has(&b, t.bull) && has(&b, t.bear));
356 assert_eq!(b[(0, 5)].bg, t.background.unwrap());
357 let b = render(
358 &book()
359 .theme(&t)
360 .bid_color(Color::Yellow)
361 .ask_color(Color::Magenta),
362 40,
363 12,
364 );
365 assert!(has(&b, Color::Yellow) && has(&b, Color::Magenta) && !has(&b, t.bull));
366 }
367
368 #[test]
369 fn spread_text() {
370 let buf = render(&book(), 50, 10);
371 let row: String = (0..50).map(|x| buf[(x, 0)].symbol().to_string()).collect();
372 assert!(row.contains("spread"));
373 }
374
375 #[test]
376 fn robust() {
377 for (w, h) in [(0, 0), (1, 1), (3, 2), (5, 5)] {
378 render(&book(), w, h);
379 }
380 render(&DepthChart::new([], []), 20, 8);
381 render(
382 &DepthChart::new([(f64::NAN, 1.0)], [(1.0, f64::NAN)]),
383 20,
384 8,
385 );
386 render(&DepthChart::new([(1.0, 1.0)], []), 20, 8);
387 render(&DepthChart::new([(1.0, 1.0)], [(1.0, 1.0)]), 20, 8);
388 }
389}