1use 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#[derive(Debug, Clone, Copy, PartialEq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub struct RenkoBrick {
16 pub open: f64,
18 pub close: f64,
20}
21
22impl RenkoBrick {
23 pub fn is_up(&self) -> bool {
25 self.close > self.open
26 }
27
28 pub fn low(&self) -> f64 {
30 self.open.min(self.close)
31 }
32
33 pub fn high(&self) -> f64 {
35 self.open.max(self.close)
36 }
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub enum RenkoStyle {
43 #[default]
45 Bricks,
46 PointAndFigure,
48}
49
50pub 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 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#[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 pub fn new(closes: &[f64], brick_size: f64) -> Self {
130 Self::from_bricks(renko_bricks(closes, brick_size), brick_size)
131 }
132
133 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_color: Color
151 );
152
153 opt_setter!(
154 down_color: Color
156 );
157
158 theme_setter!(
159 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 style: RenkoStyle
180 );
181
182 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 pub fn bricks(&self) -> &[RenkoBrick] {
192 &self.bricks
193 }
194
195 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 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 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 if crate::interact::recording() {
270 let (low, high, up) = if pf {
271 cols[idx]
272 } else {
273 let b = self.bricks[idx];
274 (b.low(), b.high(), b.is_up())
275 };
276 let row = |p: f64| ((hi - p) / span * h).clamp(0.0, h - 1.0) as u16;
277 let (t, b) = (row(high), row(low));
278 crate::interact::record_point(
279 Rect::new(x0, plot.y + t, if pf { 1 } else { cw }, b.max(t) - t + 1)
280 .intersection(plot),
281 usize::from(!up),
282 idx,
283 || {
284 (
285 format!("{} #{}", if up { "up" } else { "down" }, idx + 1),
286 vec![
287 format!("low {}", format_tick(low, step)),
288 format!("high {}", format_tick(high, step)),
289 ],
290 )
291 },
292 );
293 }
294 for r in 0..plot.height {
295 let p = row_price(r);
296 let y = plot.y + r;
297 if pf {
298 let (l, u, up) = cols[idx];
299 let tol = span / h / 2.0;
300 if p >= l - tol && p <= u + tol {
301 let (s, c) = if up {
302 ("X", self.up())
303 } else {
304 ("O", self.down())
305 };
306 buf[(x0, y)].set_symbol(s).set_style(Style::default().fg(c));
307 }
308 } else {
309 let b = self.bricks[idx];
310 if p >= b.low() && p <= b.high() {
311 let c = if b.is_up() { self.up() } else { self.down() };
312 for dx in 0..cw {
313 if x0 + dx < plot.right() {
314 buf[(x0 + dx, y)]
315 .set_symbol("█")
316 .set_style(Style::default().fg(c));
317 }
318 }
319 }
320 }
321 }
322 }
323 }
324}
325
326widget_impls!(RenkoChart);
327
328#[cfg(feature = "theme")]
329impl tui_nuances::Themed for RenkoChart {
330 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
331 self.theme(theme)
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use ratatui::widgets::Widget;
339
340 #[test]
341 fn up_bricks() {
342 let b = renko_bricks(&[10.0, 13.5], 1.0);
343 assert_eq!(b.len(), 3);
344 assert!(b.iter().all(|b| b.is_up()));
345 assert_eq!(b[2].close, 13.0);
346 }
347
348 #[test]
349 fn reversal_needs_extra_brick() {
350 assert_eq!(renko_bricks(&[10.0, 12.0, 11.0], 1.0).len(), 2);
352 let b = renko_bricks(&[10.0, 12.0, 10.0], 1.0);
353 assert_eq!(b.len(), 3);
354 assert!(!b[2].is_up());
355 assert_eq!((b[2].open, b[2].close), (11.0, 10.0));
356 }
357
358 #[test]
359 fn bad_input() {
360 assert!(renko_bricks(&[], 1.0).is_empty());
361 assert!(renko_bricks(&[1.0, 5.0], 0.0).is_empty());
362 assert!(renko_bricks(&[1.0, 5.0], f64::NAN).is_empty());
363 assert!(renko_bricks(&[f64::NAN, 1.0], 1.0).is_empty());
364 }
365
366 #[test]
367 fn columns_group() {
368 let c = RenkoChart::new(&[10.0, 13.0, 10.0], 1.0);
369 let cols = c.columns();
370 assert_eq!(cols.len(), 2);
371 assert!(cols[0].2 && !cols[1].2);
372 }
373
374 fn draw(c: RenkoChart, w: u16, h: u16) -> Buffer {
375 let area = Rect::new(0, 0, w, h);
376 let mut buf = Buffer::empty(area);
377 c.render(area, &mut buf);
378 buf
379 }
380
381 #[test]
382 fn renders_bricks_and_pf() {
383 let data = [10.0, 14.0, 11.0, 15.0, 9.0];
384 let buf = draw(RenkoChart::new(&data, 1.0), 40, 12);
385 assert!((0..40).any(|x| (0..12).any(|y| buf[(x, y)].symbol() == "█")));
386 let buf = draw(
387 RenkoChart::new(&data, 1.0).style(RenkoStyle::PointAndFigure),
388 40,
389 12,
390 );
391 let s: String = (0..40)
392 .flat_map(|x| (0..12).map(move |y| (x, y)))
393 .map(|p| buf[p].symbol().to_string())
394 .collect();
395 assert!(s.contains('X') && s.contains('O'));
396 }
397
398 #[cfg(feature = "theme")]
399 #[test]
400 fn theme_colors_and_override() {
401 let t = Theme::tokyo_night();
402 let data = [10.0, 14.0, 11.0, 15.0, 9.0];
403 let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
404 let b = draw(RenkoChart::new(&data, 1.0).theme(&t), 40, 12);
405 assert!(has(&b, t.bull) && has(&b, t.bear));
406 assert_eq!(b[(39, 0)].bg, t.background.unwrap());
407 let b = draw(
408 RenkoChart::new(&data, 1.0)
409 .theme(&t)
410 .up_color(Color::Yellow)
411 .down_color(Color::Magenta),
412 40,
413 12,
414 );
415 assert!(has(&b, Color::Yellow) && has(&b, Color::Magenta) && !has(&b, t.bull));
416 }
417
418 #[test]
419 fn tiny_ok() {
420 for (w, h) in [(0, 0), (1, 1), (2, 1), (3, 3)] {
421 draw(
422 RenkoChart::new(&[1.0, 5.0, 2.0], 1.0).block(Block::bordered()),
423 w,
424 h,
425 );
426 }
427 draw(RenkoChart::new(&[], 1.0), 10, 5);
428 }
429}