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#[derive(Debug, Clone)]
103pub struct RenkoChart {
104    bricks: Vec<RenkoBrick>,
105    brick_size: f64,
106    up_color: Option<Color>,
107    down_color: Option<Color>,
108    theme: Option<Theme>,
109    base: Option<Style>,
110    style: RenkoStyle,
111    brick_width: u16,
112    block: Option<Block<'static>>,
113}
114
115impl RenkoChart {
116    /// Build from closing prices and a fixed brick size.
117    pub fn new(closes: &[f64], brick_size: f64) -> Self {
118        Self::from_bricks(renko_bricks(closes, brick_size), brick_size)
119    }
120
121    /// Build from precomputed bricks.
122    pub fn from_bricks(bricks: Vec<RenkoBrick>, brick_size: f64) -> Self {
123        Self {
124            bricks,
125            brick_size,
126            up_color: None,
127            down_color: None,
128            theme: None,
129            base: None,
130            style: RenkoStyle::Bricks,
131            brick_width: 2,
132            block: None,
133        }
134    }
135
136    opt_setter!(
137        /// Up brick / `X` color.
138        up_color: Color
139    );
140
141    opt_setter!(
142        /// Down brick / `O` color.
143        down_color: Color
144    );
145
146    theme_setter!(
147        /// Apply a [`Theme`]: bull/bear brick colors, axis label color and
148        /// background fill. Explicit [`RenkoChart::up_color`] /
149        /// [`RenkoChart::down_color`] win.
150        theme
151    );
152
153    base_style_setter!(base);
154
155    fn up(&self) -> Color {
156        self.up_color
157            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
158    }
159
160    fn down(&self) -> Color {
161        self.down_color
162            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Red, |t| t.bear))
163    }
164
165    setter!(
166        /// Rendering style.
167        style: RenkoStyle
168    );
169
170    /// RenkoBrick width in cells (min 1, bricks style only).
171    pub fn brick_width(mut self, w: u16) -> Self {
172        self.brick_width = w.max(1);
173        self
174    }
175
176    block_setter!(block, 'static);
177
178    /// The bricks.
179    pub fn bricks(&self) -> &[RenkoBrick] {
180        &self.bricks
181    }
182
183    /// Point-and-figure columns `(low, high, is_up)` built from the bricks.
184    pub fn columns(&self) -> Vec<(f64, f64, bool)> {
185        let mut cols: Vec<(f64, f64, bool)> = Vec::new();
186        for b in &self.bricks {
187            match cols.last_mut() {
188                Some(c) if c.2 == b.is_up() => {
189                    c.0 = c.0.min(b.low());
190                    c.1 = c.1.max(b.high());
191                }
192                _ => cols.push((b.low(), b.high(), b.is_up())),
193            }
194        }
195        cols
196    }
197}
198
199impl RenkoChart {
200    fn render_into(&self, area: Rect, buf: &mut Buffer) {
201        let area = area.intersection(buf.area);
202        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
203        if self.bricks.is_empty() || inner.height == 0 || inner.width < 2 {
204            return;
205        }
206        let pf = self.style == RenkoStyle::PointAndFigure;
207        let cols = self.columns();
208        let items = if pf { cols.len() } else { self.bricks.len() };
209        // Y range
210        let lo = self
211            .bricks
212            .iter()
213            .map(|b| b.low())
214            .fold(f64::INFINITY, f64::min);
215        let hi = self
216            .bricks
217            .iter()
218            .map(|b| b.high())
219            .fold(f64::NEG_INFINITY, f64::max);
220        let step = if self.brick_size.is_finite() && self.brick_size > 0.0 {
221            self.brick_size
222        } else {
223            ((hi - lo) / 4.0).max(1e-9)
224        };
225        let l1 = format_tick(lo, step);
226        let l2 = format_tick(hi, step);
227        let gutter = (l1.chars().count().max(l2.chars().count()) as u16 + 1).min(inner.width / 2);
228        let plot = Rect::new(
229            inner.x + gutter,
230            inner.y,
231            inner.width - gutter,
232            inner.height,
233        );
234        if plot.width == 0 {
235            return;
236        }
237        let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.muted));
238        for (txt, y) in [(&l2, plot.y), (&l1, plot.bottom() - 1)] {
239            for (i, ch) in txt.chars().take(gutter as usize).enumerate() {
240                buf[(inner.x + i as u16, y)]
241                    .set_symbol(&ch.to_string())
242                    .set_style(dim);
243            }
244        }
245        let span = (hi - lo).max(1e-12);
246        let h = plot.height as f64;
247        let cw = if pf { 2 } else { self.brick_width };
248        let fit = (plot.width / cw).max(1) as usize;
249        let skip = items.saturating_sub(fit);
250        // price at the centre of row r (r=0 is the top)
251        let row_price = |r: u16| hi - (r as f64 + 0.5) / h * span;
252        for (n, idx) in (skip..items).enumerate() {
253            let x0 = plot.x + n as u16 * cw;
254            if x0 >= plot.right() {
255                break;
256            }
257            for r in 0..plot.height {
258                let p = row_price(r);
259                let y = plot.y + r;
260                if pf {
261                    let (l, u, up) = cols[idx];
262                    let tol = span / h / 2.0;
263                    if p >= l - tol && p <= u + tol {
264                        let (s, c) = if up {
265                            ("X", self.up())
266                        } else {
267                            ("O", self.down())
268                        };
269                        buf[(x0, y)].set_symbol(s).set_style(Style::default().fg(c));
270                    }
271                } else {
272                    let b = self.bricks[idx];
273                    if p >= b.low() && p <= b.high() {
274                        let c = if b.is_up() { self.up() } else { self.down() };
275                        for dx in 0..cw {
276                            if x0 + dx < plot.right() {
277                                buf[(x0 + dx, y)]
278                                    .set_symbol("█")
279                                    .set_style(Style::default().fg(c));
280                            }
281                        }
282                    }
283                }
284            }
285        }
286    }
287}
288
289widget_impls!(RenkoChart);
290
291#[cfg(feature = "theme")]
292impl tui_nuances::Themed for RenkoChart {
293    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
294        self.theme(theme)
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use ratatui::widgets::Widget;
302
303    #[test]
304    fn up_bricks() {
305        let b = renko_bricks(&[10.0, 13.5], 1.0);
306        assert_eq!(b.len(), 3);
307        assert!(b.iter().all(|b| b.is_up()));
308        assert_eq!(b[2].close, 13.0);
309    }
310
311    #[test]
312    fn reversal_needs_extra_brick() {
313        // up to 12, then fall to 11.0: not enough (needs <= 10)
314        assert_eq!(renko_bricks(&[10.0, 12.0, 11.0], 1.0).len(), 2);
315        let b = renko_bricks(&[10.0, 12.0, 10.0], 1.0);
316        assert_eq!(b.len(), 3);
317        assert!(!b[2].is_up());
318        assert_eq!((b[2].open, b[2].close), (11.0, 10.0));
319    }
320
321    #[test]
322    fn bad_input() {
323        assert!(renko_bricks(&[], 1.0).is_empty());
324        assert!(renko_bricks(&[1.0, 5.0], 0.0).is_empty());
325        assert!(renko_bricks(&[1.0, 5.0], f64::NAN).is_empty());
326        assert!(renko_bricks(&[f64::NAN, 1.0], 1.0).is_empty());
327    }
328
329    #[test]
330    fn columns_group() {
331        let c = RenkoChart::new(&[10.0, 13.0, 10.0], 1.0);
332        let cols = c.columns();
333        assert_eq!(cols.len(), 2);
334        assert!(cols[0].2 && !cols[1].2);
335    }
336
337    fn draw(c: RenkoChart, w: u16, h: u16) -> Buffer {
338        let area = Rect::new(0, 0, w, h);
339        let mut buf = Buffer::empty(area);
340        c.render(area, &mut buf);
341        buf
342    }
343
344    #[test]
345    fn renders_bricks_and_pf() {
346        let data = [10.0, 14.0, 11.0, 15.0, 9.0];
347        let buf = draw(RenkoChart::new(&data, 1.0), 40, 12);
348        assert!((0..40).any(|x| (0..12).any(|y| buf[(x, y)].symbol() == "█")));
349        let buf = draw(
350            RenkoChart::new(&data, 1.0).style(RenkoStyle::PointAndFigure),
351            40,
352            12,
353        );
354        let s: String = (0..40)
355            .flat_map(|x| (0..12).map(move |y| (x, y)))
356            .map(|p| buf[p].symbol().to_string())
357            .collect();
358        assert!(s.contains('X') && s.contains('O'));
359    }
360
361    #[cfg(feature = "theme")]
362    #[test]
363    fn theme_colors_and_override() {
364        let t = Theme::tokyo_night();
365        let data = [10.0, 14.0, 11.0, 15.0, 9.0];
366        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
367        let b = draw(RenkoChart::new(&data, 1.0).theme(&t), 40, 12);
368        assert!(has(&b, t.bull) && has(&b, t.bear));
369        assert_eq!(b[(39, 0)].bg, t.background.unwrap());
370        let b = draw(
371            RenkoChart::new(&data, 1.0)
372                .theme(&t)
373                .up_color(Color::Yellow)
374                .down_color(Color::Magenta),
375            40,
376            12,
377        );
378        assert!(has(&b, Color::Yellow) && has(&b, Color::Magenta) && !has(&b, t.bull));
379    }
380
381    #[test]
382    fn tiny_ok() {
383        for (w, h) in [(0, 0), (1, 1), (2, 1), (3, 3)] {
384            draw(
385                RenkoChart::new(&[1.0, 5.0, 2.0], 1.0).block(Block::bordered()),
386                w,
387                h,
388            );
389        }
390        draw(RenkoChart::new(&[], 1.0), 10, 5);
391    }
392}