Skip to main content

tui_chart/
renko.rs

1//! RenkoChart: renko bricks (or point-and-figure columns) from a price series.
2
3use crate::theme::{self, Theme};
4use crate::util::format_tick;
5use ratatui::{
6    buffer::Buffer,
7    layout::Rect,
8    style::{Color, Style},
9    widgets::Block,
10};
11
12/// A single renko brick.
13#[derive(Debug, Clone, Copy, PartialEq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub struct RenkoBrick {
16    /// Price at the brick's start.
17    pub open: f64,
18    /// Price at the brick's end.
19    pub close: f64,
20}
21
22impl RenkoBrick {
23    /// `true` for an up brick.
24    pub fn is_up(&self) -> bool {
25        self.close > self.open
26    }
27
28    /// Lower edge.
29    pub fn low(&self) -> f64 {
30        self.open.min(self.close)
31    }
32
33    /// Upper edge.
34    pub fn high(&self) -> f64 {
35        self.open.max(self.close)
36    }
37}
38
39/// Rendering style.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub enum RenkoStyle {
43    /// Solid renko bricks.
44    #[default]
45    Bricks,
46    /// Point-and-figure: columns of `X` (up) and `O` (down).
47    PointAndFigure,
48}
49
50/// Compute renko bricks from closes with a fixed brick size.
51///
52/// A reversal needs a move of one brick beyond the opposite edge of the last
53/// brick. Non-finite closes are skipped; `brick_size <= 0` yields no bricks.
54pub fn renko_bricks(closes: &[f64], brick_size: f64) -> Vec<RenkoBrick> {
55    let mut out: Vec<RenkoBrick> = Vec::new();
56    if !(brick_size.is_finite() && brick_size > 0.0) {
57        return out;
58    }
59    let mut it = closes.iter().copied().filter(|v| v.is_finite());
60    let Some(base) = it.next() else {
61        return out;
62    };
63    for p in it {
64        // Cap iterations against absurd ratios.
65        for _ in 0..100_000 {
66            let (up_at, down_at) = match out.last() {
67                None => (base + brick_size, base - brick_size),
68                Some(b) if b.is_up() => (b.close + brick_size, b.open - brick_size),
69                Some(b) => (b.open + brick_size, b.close - brick_size),
70            };
71            let from = match out.last() {
72                None => base,
73                Some(b) => b.close,
74            };
75            if p >= up_at - 1e-12 {
76                let open = match out.last() {
77                    Some(b) if !b.is_up() => b.open,
78                    _ => from,
79                };
80                out.push(RenkoBrick {
81                    open,
82                    close: open + brick_size,
83                });
84            } else if p <= down_at + 1e-12 {
85                let open = match out.last() {
86                    Some(b) if b.is_up() => b.open,
87                    _ => from,
88                };
89                out.push(RenkoBrick {
90                    open,
91                    close: open - brick_size,
92                });
93            } else {
94                break;
95            }
96        }
97    }
98    out
99}
100
101/// Renko / point-and-figure chart widget.
102///
103/// # Example
104///
105/// ```
106/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
107/// use tui_chart::{RenkoChart};
108///
109/// let chart = RenkoChart::new(&[10.0, 12.0, 15.0, 13.0, 9.0], 1.0);
110/// let area = Rect::new(0, 0, 40, 12);
111/// let mut buf = Buffer::empty(area);
112/// chart.render(area, &mut buf);
113/// ```
114#[derive(Debug, Clone)]
115pub struct RenkoChart {
116    bricks: Vec<RenkoBrick>,
117    brick_size: f64,
118    up_color: Option<Color>,
119    down_color: Option<Color>,
120    theme: Option<Theme>,
121    base: Option<Style>,
122    style: RenkoStyle,
123    brick_width: u16,
124    block: Option<Block<'static>>,
125}
126
127impl RenkoChart {
128    /// Build from closing prices and a fixed brick size.
129    pub fn new(closes: &[f64], brick_size: f64) -> Self {
130        Self::from_bricks(renko_bricks(closes, brick_size), brick_size)
131    }
132
133    /// Build from precomputed bricks.
134    pub fn from_bricks(bricks: Vec<RenkoBrick>, brick_size: f64) -> Self {
135        Self {
136            bricks,
137            brick_size,
138            up_color: None,
139            down_color: None,
140            theme: None,
141            base: None,
142            style: RenkoStyle::Bricks,
143            brick_width: 2,
144            block: None,
145        }
146    }
147
148    opt_setter!(
149        /// Up brick / `X` color.
150        up_color: Color
151    );
152
153    opt_setter!(
154        /// Down brick / `O` color.
155        down_color: Color
156    );
157
158    theme_setter!(
159        /// Apply a [`Theme`]: bull/bear brick colors, axis label color and
160        /// background fill. Explicit [`RenkoChart::up_color`] /
161        /// [`RenkoChart::down_color`] win.
162        theme
163    );
164
165    base_style_setter!(base);
166
167    fn up(&self) -> Color {
168        self.up_color
169            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
170    }
171
172    fn down(&self) -> Color {
173        self.down_color
174            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Red, |t| t.bear))
175    }
176
177    setter!(
178        /// Rendering style.
179        style: RenkoStyle
180    );
181
182    /// RenkoBrick width in cells (min 1, bricks style only).
183    pub fn brick_width(mut self, w: u16) -> Self {
184        self.brick_width = w.max(1);
185        self
186    }
187
188    block_setter!(block, 'static);
189
190    /// The bricks.
191    pub fn bricks(&self) -> &[RenkoBrick] {
192        &self.bricks
193    }
194
195    /// Point-and-figure columns `(low, high, is_up)` built from the bricks.
196    pub fn columns(&self) -> Vec<(f64, f64, bool)> {
197        let mut cols: Vec<(f64, f64, bool)> = Vec::new();
198        for b in &self.bricks {
199            match cols.last_mut() {
200                Some(c) if c.2 == b.is_up() => {
201                    c.0 = c.0.min(b.low());
202                    c.1 = c.1.max(b.high());
203                }
204                _ => cols.push((b.low(), b.high(), b.is_up())),
205            }
206        }
207        cols
208    }
209}
210
211impl RenkoChart {
212    fn render_into(&self, area: Rect, buf: &mut Buffer) {
213        let area = area.intersection(buf.area);
214        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
215        if self.bricks.is_empty() || inner.height == 0 || inner.width < 2 {
216            return;
217        }
218        let pf = self.style == RenkoStyle::PointAndFigure;
219        let cols = self.columns();
220        let items = if pf { cols.len() } else { self.bricks.len() };
221        // Y range
222        let lo = self
223            .bricks
224            .iter()
225            .map(|b| b.low())
226            .fold(f64::INFINITY, f64::min);
227        let hi = self
228            .bricks
229            .iter()
230            .map(|b| b.high())
231            .fold(f64::NEG_INFINITY, f64::max);
232        let step = if self.brick_size.is_finite() && self.brick_size > 0.0 {
233            self.brick_size
234        } else {
235            ((hi - lo) / 4.0).max(1e-9)
236        };
237        let l1 = format_tick(lo, step);
238        let l2 = format_tick(hi, step);
239        let gutter = (l1.chars().count().max(l2.chars().count()) as u16 + 1).min(inner.width / 2);
240        let plot = Rect::new(
241            inner.x + gutter,
242            inner.y,
243            inner.width - gutter,
244            inner.height,
245        );
246        if plot.width == 0 {
247            return;
248        }
249        let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.muted));
250        for (txt, y) in [(&l2, plot.y), (&l1, plot.bottom() - 1)] {
251            for (i, ch) in txt.chars().take(gutter as usize).enumerate() {
252                buf[(inner.x + i as u16, y)]
253                    .set_symbol(&ch.to_string())
254                    .set_style(dim);
255            }
256        }
257        let span = (hi - lo).max(1e-12);
258        let h = plot.height as f64;
259        let cw = if pf { 2 } else { self.brick_width };
260        let fit = (plot.width / cw).max(1) as usize;
261        let skip = items.saturating_sub(fit);
262        // price at the centre of row r (r=0 is the top)
263        let row_price = |r: u16| hi - (r as f64 + 0.5) / h * span;
264        for (n, idx) in (skip..items).enumerate() {
265            let x0 = plot.x + n as u16 * cw;
266            if x0 >= plot.right() {
267                break;
268            }
269            for r in 0..plot.height {
270                let p = row_price(r);
271                let y = plot.y + r;
272                if pf {
273                    let (l, u, up) = cols[idx];
274                    let tol = span / h / 2.0;
275                    if p >= l - tol && p <= u + tol {
276                        let (s, c) = if up {
277                            ("X", self.up())
278                        } else {
279                            ("O", self.down())
280                        };
281                        buf[(x0, y)].set_symbol(s).set_style(Style::default().fg(c));
282                    }
283                } else {
284                    let b = self.bricks[idx];
285                    if p >= b.low() && p <= b.high() {
286                        let c = if b.is_up() { self.up() } else { self.down() };
287                        for dx in 0..cw {
288                            if x0 + dx < plot.right() {
289                                buf[(x0 + dx, y)]
290                                    .set_symbol("█")
291                                    .set_style(Style::default().fg(c));
292                            }
293                        }
294                    }
295                }
296            }
297        }
298    }
299}
300
301widget_impls!(RenkoChart);
302
303#[cfg(feature = "theme")]
304impl tui_nuances::Themed for RenkoChart {
305    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
306        self.theme(theme)
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use ratatui::widgets::Widget;
314
315    #[test]
316    fn up_bricks() {
317        let b = renko_bricks(&[10.0, 13.5], 1.0);
318        assert_eq!(b.len(), 3);
319        assert!(b.iter().all(|b| b.is_up()));
320        assert_eq!(b[2].close, 13.0);
321    }
322
323    #[test]
324    fn reversal_needs_extra_brick() {
325        // up to 12, then fall to 11.0: not enough (needs <= 10)
326        assert_eq!(renko_bricks(&[10.0, 12.0, 11.0], 1.0).len(), 2);
327        let b = renko_bricks(&[10.0, 12.0, 10.0], 1.0);
328        assert_eq!(b.len(), 3);
329        assert!(!b[2].is_up());
330        assert_eq!((b[2].open, b[2].close), (11.0, 10.0));
331    }
332
333    #[test]
334    fn bad_input() {
335        assert!(renko_bricks(&[], 1.0).is_empty());
336        assert!(renko_bricks(&[1.0, 5.0], 0.0).is_empty());
337        assert!(renko_bricks(&[1.0, 5.0], f64::NAN).is_empty());
338        assert!(renko_bricks(&[f64::NAN, 1.0], 1.0).is_empty());
339    }
340
341    #[test]
342    fn columns_group() {
343        let c = RenkoChart::new(&[10.0, 13.0, 10.0], 1.0);
344        let cols = c.columns();
345        assert_eq!(cols.len(), 2);
346        assert!(cols[0].2 && !cols[1].2);
347    }
348
349    fn draw(c: RenkoChart, w: u16, h: u16) -> Buffer {
350        let area = Rect::new(0, 0, w, h);
351        let mut buf = Buffer::empty(area);
352        c.render(area, &mut buf);
353        buf
354    }
355
356    #[test]
357    fn renders_bricks_and_pf() {
358        let data = [10.0, 14.0, 11.0, 15.0, 9.0];
359        let buf = draw(RenkoChart::new(&data, 1.0), 40, 12);
360        assert!((0..40).any(|x| (0..12).any(|y| buf[(x, y)].symbol() == "█")));
361        let buf = draw(
362            RenkoChart::new(&data, 1.0).style(RenkoStyle::PointAndFigure),
363            40,
364            12,
365        );
366        let s: String = (0..40)
367            .flat_map(|x| (0..12).map(move |y| (x, y)))
368            .map(|p| buf[p].symbol().to_string())
369            .collect();
370        assert!(s.contains('X') && s.contains('O'));
371    }
372
373    #[cfg(feature = "theme")]
374    #[test]
375    fn theme_colors_and_override() {
376        let t = Theme::tokyo_night();
377        let data = [10.0, 14.0, 11.0, 15.0, 9.0];
378        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
379        let b = draw(RenkoChart::new(&data, 1.0).theme(&t), 40, 12);
380        assert!(has(&b, t.bull) && has(&b, t.bear));
381        assert_eq!(b[(39, 0)].bg, t.background.unwrap());
382        let b = draw(
383            RenkoChart::new(&data, 1.0)
384                .theme(&t)
385                .up_color(Color::Yellow)
386                .down_color(Color::Magenta),
387            40,
388            12,
389        );
390        assert!(has(&b, Color::Yellow) && has(&b, Color::Magenta) && !has(&b, t.bull));
391    }
392
393    #[test]
394    fn tiny_ok() {
395        for (w, h) in [(0, 0), (1, 1), (2, 1), (3, 3)] {
396            draw(
397                RenkoChart::new(&[1.0, 5.0, 2.0], 1.0).block(Block::bordered()),
398                w,
399                h,
400            );
401        }
402        draw(RenkoChart::new(&[], 1.0), 10, 5);
403    }
404}