1use crate::axis::Axis;
4use crate::canvas::{Canvas, Marker};
5use crate::indicator;
6use crate::layout::{self, text_width};
7use crate::theme::{self, Theme};
8use crate::util::{format_compact, nice_bounds};
9use ratatui::{
10 buffer::Buffer,
11 layout::Rect,
12 style::{Color, Modifier, Style},
13 widgets::Block,
14};
15
16#[derive(Debug, Clone, PartialEq, Default)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub struct Candle {
20 pub open: f64,
22 pub high: f64,
24 pub low: f64,
26 pub close: f64,
28 pub volume: f64,
30 pub label: Option<String>,
32}
33
34impl Candle {
35 pub fn new(open: f64, high: f64, low: f64, close: f64) -> Self {
37 Self {
38 open,
39 high: high.max(open).max(close),
40 low: low.min(open).min(close),
41 close,
42 volume: 0.0,
43 label: None,
44 }
45 }
46
47 setter!(
48 volume: f64
50 );
51
52 pub fn label(mut self, label: impl Into<String>) -> Self {
54 self.label = Some(label.into());
55 self
56 }
57
58 pub fn is_bullish(&self) -> bool {
60 self.close >= self.open
61 }
62
63 fn is_valid(&self) -> bool {
64 [self.open, self.high, self.low, self.close]
65 .iter()
66 .all(|v| v.is_finite())
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73pub enum CandleStyle {
74 #[default]
76 Candle,
77 Ohlc,
79 HeikinAshi,
81 Braille,
86}
87
88#[derive(Debug, Clone)]
90pub struct Overlay {
91 pub name: String,
93 pub values: Vec<Option<f64>>,
95 pub color: Color,
97}
98
99impl Overlay {
100 pub fn new(name: impl Into<String>, values: Vec<Option<f64>>, color: Color) -> Self {
102 Self {
103 name: name.into(),
104 values,
105 color,
106 }
107 }
108}
109
110#[derive(Debug, Clone)]
112pub struct BandOverlay {
113 pub name: String,
115 pub upper: Vec<Option<f64>>,
117 pub lower: Vec<Option<f64>>,
119 pub color: Color,
121}
122
123impl BandOverlay {
124 pub fn new(
126 name: impl Into<String>,
127 upper: Vec<Option<f64>>,
128 lower: Vec<Option<f64>>,
129 color: Color,
130 ) -> Self {
131 Self {
132 name: name.into(),
133 upper,
134 lower,
135 color,
136 }
137 }
138
139 pub fn bollinger(candles: &[Candle], period: usize, k: f64, color: Color) -> Self {
141 let (_, up, lo) = indicator::bollinger(candles, period, k);
142 Self::new(format!("BB{period}"), up, lo, color)
143 }
144}
145
146#[derive(Debug, Clone)]
148pub enum IndicatorPane {
149 Rsi {
151 period: usize,
153 },
154 Macd {
156 fast: usize,
158 slow: usize,
160 signal: usize,
162 },
163 Custom {
165 name: String,
167 values: Vec<Option<f64>>,
169 color: Color,
171 },
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
177pub enum TradeSide {
178 Buy,
180 Sell,
182}
183
184#[derive(Debug, Clone, PartialEq)]
186#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
187pub struct TradeMarker {
188 pub index: usize,
190 pub price: f64,
192 pub side: TradeSide,
194 pub label: Option<String>,
196}
197
198impl TradeMarker {
199 pub fn new(index: usize, price: f64, side: TradeSide) -> Self {
201 Self {
202 index,
203 price,
204 side,
205 label: None,
206 }
207 }
208
209 pub fn label(mut self, label: impl Into<String>) -> Self {
211 self.label = Some(label.into());
212 self
213 }
214}
215
216#[derive(Debug, Clone, PartialEq)]
218#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
219pub struct HLine {
220 pub price: f64,
222 pub label: Option<String>,
224 pub color: Color,
226}
227
228impl HLine {
229 pub fn new(price: f64, color: Color) -> Self {
231 Self {
232 price,
233 label: None,
234 color,
235 }
236 }
237
238 pub fn label(mut self, label: impl Into<String>) -> Self {
240 self.label = Some(label.into());
241 self
242 }
243}
244
245pub fn sma(candles: &[Candle], period: usize) -> Vec<Option<f64>> {
247 let period = period.max(1);
248 (0..candles.len())
249 .map(|i| {
250 if i + 1 < period {
251 None
252 } else {
253 let s: f64 = candles[i + 1 - period..=i].iter().map(|c| c.close).sum();
254 Some(s / period as f64)
255 }
256 })
257 .collect()
258}
259
260pub fn ema(candles: &[Candle], period: usize) -> Vec<Option<f64>> {
262 let period = period.max(1);
263 let k = 2.0 / (period as f64 + 1.0);
264 let mut prev: Option<f64> = None;
265 candles
266 .iter()
267 .enumerate()
268 .map(|(i, c)| {
269 if i + 1 < period {
270 return None;
271 }
272 let v = match prev {
273 None => {
274 candles[i + 1 - period..=i]
275 .iter()
276 .map(|c| c.close)
277 .sum::<f64>()
278 / period as f64
279 }
280 Some(p) => c.close * k + p * (1.0 - k),
281 };
282 prev = Some(v);
283 Some(v)
284 })
285 .collect()
286}
287
288pub fn heikin_ashi(candles: &[Candle]) -> Vec<Candle> {
290 let mut out: Vec<Candle> = Vec::with_capacity(candles.len());
291 for (i, c) in candles.iter().enumerate() {
292 let close = (c.open + c.high + c.low + c.close) / 4.0;
293 let open = if i == 0 {
294 (c.open + c.close) / 2.0
295 } else {
296 (out[i - 1].open + out[i - 1].close) / 2.0
297 };
298 out.push(Candle {
299 open,
300 high: c.high.max(open).max(close),
301 low: c.low.min(open).min(close),
302 close,
303 volume: c.volume,
304 label: c.label.clone(),
305 });
306 }
307 out
308}
309
310fn hline_row(buf: &mut Buffer, area: Rect, row: u16, ch: char, style: Style) {
311 for x in area.x..area.right() {
312 if let Some(cell) = buf.cell_mut((x, area.y + row)) {
313 if cell.symbol() == " " || cell.symbol() == "·" || cell.symbol() == "░" {
314 cell.set_char(ch).set_style(style);
315 }
316 }
317 }
318}
319
320fn tag(buf: &mut Buffer, area: Rect, row: u16, text: &str, style: Style) {
322 let w = text_width(text);
323 if w + 2 > area.width {
324 return;
325 }
326 buf.set_string(area.right() - w, area.y + row, text, style);
327}
328
329const EIGHTHS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
330
331#[derive(Debug, Clone)]
333pub struct CandlestickChart {
334 candles: Vec<Candle>,
335 style: CandleStyle,
336 colors: Option<(Color, Color)>,
337 hollow: bool,
338 theme: Option<Theme>,
339 base: Option<Style>,
340 candle_width: u16,
341 gap: u16,
342 show_volume: bool,
343 last_price_line: bool,
344 scroll: usize,
345 overlays: Vec<Overlay>,
346 bands: Vec<BandOverlay>,
347 panes: Vec<IndicatorPane>,
348 markers: Vec<TradeMarker>,
349 hlines: Vec<HLine>,
350 volume_profile: bool,
351 block: Option<Block<'static>>,
352 x_axis: Axis,
353 y_axis: Axis,
354}
355
356impl CandlestickChart {
357 pub fn new(candles: Vec<Candle>) -> Self {
359 Self {
360 candles,
361 style: CandleStyle::Candle,
362 colors: None,
363 hollow: false,
364 theme: None,
365 base: None,
366 candle_width: 1,
367 gap: 1,
368 show_volume: false,
369 last_price_line: true,
370 scroll: 0,
371 overlays: vec![],
372 bands: vec![],
373 panes: vec![],
374 markers: vec![],
375 hlines: vec![],
376 volume_profile: false,
377 block: None,
378 x_axis: Axis::new().ticks(6),
379 y_axis: Axis::new().grid(true),
380 }
381 }
382
383 setter!(
384 style: CandleStyle
386 );
387
388 pub fn colors(mut self, up: Color, down: Color) -> Self {
390 self.colors = Some((up, down));
391 self
392 }
393
394 setter!(
395 hollow: bool
397 );
398
399 #[cfg(feature = "theme")]
402 pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
403 let t = theme.into();
404 self.x_axis.theme_in_place(&t);
405 self.y_axis.theme_in_place(&t);
406 self.theme = Some(t);
407 self
408 }
409
410 base_style_setter!(base);
411
412 fn up_color(&self) -> Color {
413 match (&self.colors, &self.theme) {
414 (Some((u, _)), _) => *u,
415 (None, Some(t)) => t.bull,
416 _ => Color::Green,
417 }
418 }
419
420 fn down_color(&self) -> Color {
421 match (&self.colors, &self.theme) {
422 (Some((_, d)), _) => *d,
423 (None, Some(t)) => t.bear,
424 _ => Color::Red,
425 }
426 }
427
428 fn dim_color(&self) -> Color {
429 self.theme.as_ref().map_or(Color::DarkGray, |t| t.axis)
430 }
431
432 fn label_color(&self) -> Color {
433 self.theme.as_ref().map_or(Color::Gray, |t| t.muted)
434 }
435
436 pub fn candle_width(mut self, w: u16) -> Self {
438 self.candle_width = w.max(1);
439 self
440 }
441
442 setter!(
443 gap: u16
445 );
446
447 setter!(
448 show_volume: bool
450 );
451
452 setter!(
453 last_price_line: bool
455 );
456
457 setter!(
458 scroll: usize
460 );
461
462 pub fn overlay(mut self, overlay: Overlay) -> Self {
464 self.overlays.push(overlay);
465 self
466 }
467
468 pub fn band(mut self, band: BandOverlay) -> Self {
470 self.bands.push(band);
471 self
472 }
473
474 pub fn pane(mut self, pane: IndicatorPane) -> Self {
476 self.panes.push(pane);
477 self
478 }
479
480 pub fn marker(mut self, marker: TradeMarker) -> Self {
482 self.markers.push(marker);
483 self
484 }
485
486 pub fn hline(mut self, line: HLine) -> Self {
488 self.hlines.push(line);
489 self
490 }
491
492 pub fn support(self, price: f64) -> Self {
494 self.hline(HLine::new(price, Color::Green).label(format!("S {price:.2}")))
495 }
496
497 pub fn resistance(self, price: f64) -> Self {
499 self.hline(HLine::new(price, Color::Red).label(format!("R {price:.2}")))
500 }
501
502 setter!(
503 volume_profile: bool
505 );
506
507 block_setter!(block, 'static);
508
509 pub fn x_axis(mut self, axis: Axis) -> Self {
511 self.x_axis = axis;
512 if let Some(t) = &self.theme {
513 self.x_axis.theme_in_place(t);
514 }
515 self
516 }
517
518 pub fn y_axis(mut self, axis: Axis) -> Self {
520 self.y_axis = axis;
521 if let Some(t) = &self.theme {
522 self.y_axis.theme_in_place(t);
523 }
524 self
525 }
526
527 fn slot_cells(&self) -> usize {
529 let gap = if self.style == CandleStyle::Braille {
530 self.gap.saturating_sub(1)
531 } else {
532 self.gap
533 };
534 (self.bar_width() + gap) as usize
535 }
536
537 fn bar_width(&self) -> u16 {
538 match self.style {
539 CandleStyle::Ohlc => 1,
540 _ => self.candle_width,
541 }
542 }
543
544 pub(crate) fn visible_range(&self, slots: usize) -> (usize, usize) {
546 let end = self.candles.len().saturating_sub(self.scroll);
547 (end.saturating_sub(slots), end)
548 }
549
550 fn color_of(&self, c: &Candle) -> Color {
551 if c.is_bullish() {
552 self.up_color()
553 } else {
554 self.down_color()
555 }
556 }
557
558 fn draw_profile(
559 &self,
560 buf: &mut Buffer,
561 price: Rect,
562 vis: &[&Candle],
563 sub: &dyn Fn(f64) -> i32,
564 ) {
565 let mut bins = vec![0.0f64; price.height as usize];
566 for c in vis.iter().filter(|c| c.is_valid() && c.volume.is_finite()) {
567 let (r0, r1) = ((sub(c.high) / 2) as usize, (sub(c.low) / 2) as usize);
568 let share = c.volume / (r1 - r0 + 1) as f64;
569 for b in bins.iter_mut().take(r1 + 1).skip(r0) {
570 *b += share;
571 }
572 }
573 let max = bins.iter().cloned().fold(0.0, f64::max);
574 if max <= 0.0 {
575 return;
576 }
577 let w = (price.width / 5).clamp(1, 20) as f64;
578 let st = Style::default().fg(self.dim_color());
579 for (r, v) in bins.iter().enumerate() {
580 let len = (v / max * w).round() as u16;
581 for dx in 0..len {
582 buf.set_string(price.right() - 1 - dx, price.y + r as u16, "▒", st);
583 }
584 }
585 }
586
587 #[allow(clippy::too_many_arguments)]
588 fn draw_pane(
589 &self,
590 buf: &mut Buffer,
591 r: Rect,
592 gutter: Rect,
593 pane: &IndicatorPane,
594 start: usize,
595 n_vis: usize,
596 slot: usize,
597 bw: u16,
598 ) {
599 if r.height == 0 || r.width == 0 {
600 return;
601 }
602 let dim = Style::default().fg(self.dim_color());
603 let (name, lines, hist, (lo, hi), refs): (String, Vec<_>, Option<Vec<_>>, _, Vec<f64>) =
605 match pane {
606 IndicatorPane::Rsi { period } => (
607 format!("RSI {period}"),
608 vec![(indicator::rsi(&self.candles, *period), Color::Cyan)],
609 None,
610 (0.0, 100.0),
611 vec![70.0, 30.0],
612 ),
613 IndicatorPane::Macd { fast, slow, signal } => {
614 let (m, s, h) = indicator::macd(&self.candles, *fast, *slow, *signal);
615 let range = (start..start + n_vis)
616 .flat_map(|i| [m.get(i), s.get(i), h.get(i)])
617 .flatten()
618 .flatten()
619 .fold(0.0f64, |a, v| a.max(v.abs()));
620 let range = if range > 0.0 { range } else { 1.0 };
621 (
622 format!("MACD {fast},{slow},{signal}"),
623 vec![(m, Color::Cyan), (s, Color::Yellow)],
624 Some(h),
625 (-range, range),
626 vec![0.0],
627 )
628 }
629 IndicatorPane::Custom {
630 name,
631 values,
632 color,
633 } => {
634 let vals = || {
635 (start..start + n_vis)
636 .filter_map(|i| values.get(i).copied().flatten())
637 .filter(|v| v.is_finite())
638 };
639 let lo = vals().fold(f64::INFINITY, f64::min);
640 let hi = vals().fold(f64::NEG_INFINITY, f64::max);
641 let b = if hi > lo { (lo, hi) } else { (0.0, 1.0) };
642 (
643 name.clone(),
644 vec![(values.clone(), *color)],
645 None,
646 b,
647 vec![],
648 )
649 }
650 };
651 let h = r.height as f64;
652 let row = |v: f64| -> u16 {
653 ((hi - v) / (hi - lo) * (h - 1.0))
654 .round()
655 .clamp(0.0, h - 1.0) as u16
656 };
657 let mut ticks = vec![];
658 for rv in &refs {
659 let rr = row(*rv);
660 hline_row(buf, r, rr, '┄', dim);
661 ticks.push((rr, format!("{rv:.0}")));
662 }
663 layout::draw_y_labels(buf, gutter, &ticks, dim);
664 let xs = |i: usize| r.x + (i * slot) as u16;
665 if let Some(hs) = &hist {
666 let z = row(0.0);
667 for i in 0..n_vis {
668 let Some(Some(v)) = hs.get(start + i) else {
669 continue;
670 };
671 if !v.is_finite() {
672 continue;
673 }
674 let col = if *v >= 0.0 {
675 self.up_color()
676 } else {
677 self.down_color()
678 };
679 let rv = row(*v);
680 for dx in 0..bw {
681 let x = xs(i) + dx;
682 if x >= r.right() {
683 break;
684 }
685 for y in z.min(rv)..=z.max(rv) {
686 buf.set_string(x, r.y + y, "█", Style::default().fg(col));
687 }
688 }
689 }
690 }
691 for (vals, col) in &lines {
692 for i in 0..n_vis {
693 let Some(Some(v)) = vals.get(start + i) else {
694 continue;
695 };
696 let x = xs(i) + bw / 2;
697 if !v.is_finite() || x >= r.right() {
698 continue;
699 }
700 buf.set_string(x, r.y + row(*v), "●", Style::default().fg(*col));
701 }
702 }
703 if text_width(&name) < r.width {
704 buf.set_string(r.x + 1, r.y, &name, dim);
705 }
706 }
707
708 fn render_inner(&self, area: Rect, buf: &mut Buffer) {
709 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
710 let src: Vec<Candle> = match self.style {
711 CandleStyle::HeikinAshi => heikin_ashi(&self.candles),
712 _ => self.candles.clone(),
713 };
714 let bw = self.bar_width();
715 let slot = self.slot_cells();
716 let (start, end) = self.visible_range((inner.width as usize).max(1) / slot);
718 let vis: Vec<&Candle> = src[start.min(src.len())..end.min(src.len())]
719 .iter()
720 .collect();
721 let valid: Vec<&&Candle> = vis.iter().filter(|c| c.is_valid()).collect();
722
723 let (lo, hi) = self.y_axis.bounds.unwrap_or_else(|| {
724 if valid.is_empty() {
725 (0.0, 1.0)
726 } else {
727 let lo = valid.iter().map(|c| c.low).fold(f64::INFINITY, f64::min);
728 let hi = valid
729 .iter()
730 .map(|c| c.high)
731 .fold(f64::NEG_INFINITY, f64::max);
732 nice_bounds(lo, hi, self.y_axis.ticks)
733 }
734 });
735 if hi <= lo {
736 return;
737 }
738 let y_marks = self.y_axis.tick_marks((lo, hi));
739 let yw = y_marks
740 .iter()
741 .map(|(_, l)| text_width(l))
742 .max()
743 .unwrap_or(0);
744 let has_labels = vis.iter().any(|c| c.label.is_some());
745 let Some(a) = layout::compute(
746 inner,
747 yw,
748 has_labels,
749 self.x_axis.title.is_some(),
750 self.y_axis.title.is_some(),
751 ) else {
752 return;
753 };
754 let plot = a.plot;
755 let (start, end) =
757 self.visible_range((plot.width as usize + slot - bw as usize) / slot.max(1));
758 let vis: Vec<&Candle> = src[start.min(src.len())..end.min(src.len())]
759 .iter()
760 .collect();
761
762 let vol_h = if self.show_volume && plot.height >= 8 {
763 (plot.height / 4).max(2)
764 } else {
765 0
766 };
767 let pane_each = (plot.height / 6).max(3);
768 let mut panes_n = 0usize;
769 let mut panes_h = 0u16;
770 for _ in &self.panes {
771 let nh = panes_h + pane_each;
772 if plot.height.saturating_sub(nh + vol_h) < 5 {
773 break;
774 }
775 panes_n += 1;
776 panes_h = nh;
777 }
778 let vol_bottom = plot.bottom() - panes_h;
779 let price = Rect::new(plot.x, plot.y, plot.width, plot.height - vol_h - panes_h);
780 let sub_n = price.height as f64 * 2.0;
781 let sub = |p: f64| -> i32 {
782 ((hi - p) / (hi - lo) * (sub_n - 1.0))
783 .round()
784 .clamp(0.0, sub_n - 1.0) as i32
785 };
786
787 let y_ticks: Vec<(u16, String)> = y_marks
789 .iter()
790 .map(|(f, l)| (layout::frac_row(*f, price.height, 2), l.clone()))
791 .collect();
792 if self.y_axis.grid {
793 let rows: Vec<u16> = y_ticks.iter().map(|t| t.0).collect();
794 layout::draw_grid(
795 buf,
796 price,
797 &[],
798 &rows,
799 self.y_axis.grid_style,
800 self.y_axis.grid_kind,
801 );
802 }
803
804 if self.volume_profile && price.width >= 20 {
806 self.draw_profile(buf, price, &vis, &sub);
807 }
808 for band in &self.bands {
809 let st = Style::default().fg(band.color);
810 for i in 0..vis.len() {
811 let (Some(Some(u)), Some(Some(l))) =
812 (band.upper.get(start + i), band.lower.get(start + i))
813 else {
814 continue;
815 };
816 if !u.is_finite() || !l.is_finite() || (*u < lo && *l < lo) || (*u > hi && *l > hi)
817 {
818 continue;
819 }
820 let x0 = price.x + (i * slot) as u16;
821 for dx in 0..slot.min(2).max(bw as usize) as u16 {
822 let x = x0 + dx;
823 if x >= price.right() {
824 break;
825 }
826 for r in (sub(*u) / 2)..=(sub(*l) / 2) {
827 if let Some(cell) = buf.cell_mut((x, price.y + r as u16)) {
828 if cell.symbol() == " " || cell.symbol() == "·" {
829 cell.set_char('░').set_style(st);
830 }
831 }
832 }
833 }
834 }
835 }
836
837 for h in &self.hlines {
839 if h.price.is_finite() && h.price >= lo && h.price <= hi {
840 let row = (sub(h.price) / 2) as u16;
841 let label = h.label.clone().unwrap_or_else(|| format!("{:.2}", h.price));
842 hline_row(buf, price, row, '┄', Style::default().fg(h.color));
843 tag(buf, price, row, &label, Style::default().fg(h.color));
844 }
845 }
846 let last_tag = if self.last_price_line {
847 vis.iter().rev().find(|c| c.is_valid()).map(|c| {
848 let row = (sub(c.close) / 2) as u16;
849 hline_row(buf, price, row, '┈', Style::default().fg(self.color_of(c)));
850 (row, format!("{:.2}", c.close), self.color_of(c))
851 })
852 } else {
853 None
854 };
855
856 let max_vol = vis
857 .iter()
858 .map(|c| c.volume)
859 .filter(|v| v.is_finite())
860 .fold(0.0f64, f64::max);
861 let mut x_ticks: Vec<(u16, String)> = vec![];
862 let mut dots = (self.style == CandleStyle::Braille)
863 .then(|| Canvas::new(price.width, price.height, Marker::Braille));
864 let dot_n = price.height as f64 * 4.0;
865 let dsub = |p: f64| -> i32 {
866 ((hi - p) / (hi - lo) * (dot_n - 1.0))
867 .round()
868 .clamp(0.0, dot_n - 1.0) as i32
869 };
870 for (i, c) in vis.iter().enumerate() {
871 let x0 = price.x + (i * slot) as u16;
872 if x0 + bw > price.right() {
873 break;
874 }
875 let centre = x0 + bw / 2;
876 if let Some(l) = &c.label {
877 x_ticks.push((centre - plot.x, l.clone()));
878 }
879 if !c.is_valid() {
880 continue;
881 }
882 let color = self.color_of(c);
883 let st = Style::default().fg(color);
884 if let Some(cv) = dots.as_mut() {
885 let px0 = i32::from(x0 - price.x) * 2;
886 let pw = i32::from(bw) * 2;
887 let wick = px0 + (pw - 1) / 2;
888 let (w0, w1) = (dsub(c.high), dsub(c.low));
889 for py in w0..=w1 {
890 cv.set(wick, py, color);
891 }
892 let (oa, ob) = (dsub(c.open), dsub(c.close));
893 let (b0, b1) = (oa.min(ob), oa.max(ob));
894 let hollow = self.hollow && c.is_bullish();
895 for py in b0..=b1 {
896 for px in px0..px0 + pw {
897 let edge = py == b0 || py == b1 || px == px0 || px == px0 + pw - 1;
898 if !hollow || edge {
899 cv.set(px, py, color);
900 }
901 }
902 }
903 } else if self.style == CandleStyle::Ohlc {
904 let (r_h, r_l) = ((sub(c.high) / 2) as u16, (sub(c.low) / 2) as u16);
905 let (r_o, r_c) = ((sub(c.open) / 2) as u16, (sub(c.close) / 2) as u16);
906 for r in r_h..=r_l {
907 let ch = match (r == r_o, r == r_c) {
908 (true, true) => '┼',
909 (true, false) => '┤',
910 (false, true) => '├',
911 _ => '│',
912 };
913 buf.set_string(centre, price.y + r, ch.to_string(), st);
914 }
915 } else {
916 let (b0, b1) = {
917 let (a_, b_) = (sub(c.open), sub(c.close));
918 (a_.min(b_), a_.max(b_))
919 };
920 let (w0, w1) = (sub(c.high), sub(c.low));
921 for r in (w0 / 2)..=(w1 / 2) {
922 let (t, b) = (2 * r, 2 * r + 1);
923 let body_t = t >= b0 && t <= b1;
924 let body_b = b >= b0 && b <= b1;
925 let wick_t = t >= w0 && t <= w1;
926 let wick_b = b >= w0 && b <= w1;
927 let hollow = self.hollow && c.is_bullish();
928 let body_ch = match (body_t, body_b) {
929 (true, true) => Some('█'),
930 (true, false) => Some('▀'),
931 (false, true) => Some('▄'),
932 _ => None,
933 };
934 let wick_ch = match (wick_t, wick_b) {
935 (true, true) => Some('│'),
936 (true, false) => Some('╵'),
937 (false, true) => Some('╷'),
938 _ => None,
939 };
940 for dx in 0..bw {
941 let ch = if dx == bw / 2 {
942 body_ch.or(wick_ch)
943 } else {
944 body_ch
945 };
946 let ch = match ch {
947 Some('█') if hollow => {
948 let (top_r, bot_r) = (b0 / 2, b1 / 2);
949 if bw == 1 {
950 Some('┃')
951 } else if dx == 0 {
952 Some('▌')
953 } else if dx == bw - 1 {
954 Some('▐')
955 } else if r == top_r {
956 Some('▔')
957 } else if r == bot_r {
958 Some('▁')
959 } else {
960 Some(' ')
961 }
962 }
963 other => other,
964 };
965 if let Some(ch) = ch {
966 buf.set_string(x0 + dx, price.y + r as u16, ch.to_string(), st);
967 }
968 }
969 }
970 if b0 == b1 && bw > 1 {
972 }
974 }
975 if vol_h > 0 && max_vol > 0.0 && c.volume.is_finite() && c.volume > 0.0 {
977 let total = (c.volume / max_vol * vol_h as f64 * 8.0).round().max(1.0) as i32;
978 for r in 0..vol_h as i32 {
979 let fill = (total - r * 8).clamp(0, 8) as usize;
980 if fill == 0 {
981 break;
982 }
983 let y = vol_bottom - 1 - r as u16;
984 for dx in 0..bw {
985 buf.set_string(x0 + dx, y, EIGHTHS[fill].to_string(), st);
986 }
987 }
988 }
989 }
990
991 if let Some(cv) = &dots {
992 cv.render(buf, price);
993 }
994
995 for ov in &self.overlays {
997 for (i, _) in vis.iter().enumerate() {
998 let Some(Some(v)) = ov.values.get(start + i) else {
999 continue;
1000 };
1001 if !v.is_finite() || *v < lo || *v > hi {
1002 continue;
1003 }
1004 let x = price.x + (i * slot) as u16 + bw / 2;
1005 if x >= price.right() {
1006 continue;
1007 }
1008 let row = (sub(*v) / 2) as u16;
1009 buf.set_string(x, price.y + row, "●", Style::default().fg(ov.color));
1010 }
1011 }
1012
1013 for m in &self.markers {
1015 if m.index < start || m.index >= start + vis.len() || !m.price.is_finite() {
1016 continue;
1017 }
1018 if m.price < lo || m.price > hi {
1019 continue;
1020 }
1021 let i = m.index - start;
1022 let x = price.x + (i * slot) as u16 + bw / 2;
1023 if x >= price.right() {
1024 continue;
1025 }
1026 let row = (sub(m.price) / 2) as u16;
1027 let (g, col) = match m.side {
1028 TradeSide::Buy => ('▲', self.up_color()),
1029 TradeSide::Sell => ('▼', self.down_color()),
1030 };
1031 let st = Style::default().fg(col).add_modifier(Modifier::BOLD);
1032 buf.set_string(x, price.y + row, g.to_string(), st);
1033 if let Some(l) = &m.label {
1034 if x + 1 + text_width(l) < price.right() {
1035 buf.set_string(x + 1, price.y + row, l, Style::default().fg(col));
1036 }
1037 }
1038 }
1039 if let Some((row, text, col)) = last_tag {
1040 let st = Style::default().fg(Color::Black).bg(col);
1041 tag(buf, price, row, &format!(" {text} "), st);
1042 }
1043
1044 for (k, pane) in self.panes.iter().take(panes_n).enumerate() {
1046 let r = Rect::new(
1047 plot.x,
1048 plot.bottom() - panes_h + k as u16 * pane_each,
1049 plot.width,
1050 pane_each,
1051 );
1052 let gutter = Rect::new(a.y_labels.x, r.y, a.y_labels.width, r.height);
1053 self.draw_pane(buf, r, gutter, pane, start, vis.len(), slot, bw);
1054 }
1055
1056 layout::draw_axes(buf, &a, self.x_axis.style, self.y_axis.style);
1057 layout::draw_y_labels(
1058 buf,
1059 Rect::new(a.y_labels.x, price.y, a.y_labels.width, price.height),
1060 &y_ticks,
1061 self.y_axis.label_style,
1062 );
1063 if vol_h > 0 {
1064 let top = Rect::new(a.y_labels.x, vol_bottom - vol_h, a.y_labels.width, vol_h);
1065 let label = format_compact(max_vol);
1066 layout::draw_y_labels(
1067 buf,
1068 top,
1069 &[(0, label)],
1070 Style::default().fg(self.dim_color()),
1071 );
1072 }
1073 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.x_axis.label_style);
1074 layout::draw_titles(
1075 buf,
1076 inner,
1077 &a,
1078 self.x_axis
1079 .title
1080 .as_deref()
1081 .map(|t| (t, self.x_axis.label_style)),
1082 self.y_axis
1083 .title
1084 .as_deref()
1085 .map(|t| (t, self.y_axis.label_style)),
1086 );
1087 let mut x = plot.x + 1;
1089 for ov in &self.overlays {
1090 let w = text_width(&ov.name) + 3;
1091 if x + w > plot.right() {
1092 break;
1093 }
1094 buf.set_string(x, plot.y, "●", Style::default().fg(ov.color));
1095 buf.set_string(
1096 x + 2,
1097 plot.y,
1098 &ov.name,
1099 Style::default().fg(self.label_color()),
1100 );
1101 x += w + 1;
1102 }
1103 }
1104}
1105
1106impl CandlestickChart {
1107 fn render_into(&self, area: Rect, buf: &mut Buffer) {
1108 self.render_inner(area, buf);
1109 }
1110}
1111
1112widget_impls!(CandlestickChart);
1113
1114#[cfg(feature = "theme")]
1115impl tui_nuances::Themed for CandlestickChart {
1116 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
1117 self.theme(theme)
1118 }
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123 use super::*;
1124 use ratatui::widgets::Widget;
1125
1126 fn data(n: usize) -> Vec<Candle> {
1127 (0..n)
1128 .map(|i| {
1129 let b = 100.0 + (i as f64 * 0.7).sin() * 10.0;
1130 let up = i % 2 == 0;
1131 let (o, c) = if up { (b, b + 3.0) } else { (b + 3.0, b) };
1132 Candle::new(o, b + 5.0, b - 2.0, c)
1133 .volume(100.0 + i as f64 * 10.0)
1134 .label(format!("{i}"))
1135 })
1136 .collect()
1137 }
1138
1139 fn dump(buf: &Buffer, area: Rect) -> String {
1140 (area.y..area.bottom())
1141 .flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
1142 .map(|p| buf[p].symbol().to_string())
1143 .collect()
1144 }
1145
1146 #[test]
1147 fn candle_new_widens_range() {
1148 let c = Candle::new(10.0, 9.0, 11.0, 12.0);
1149 assert_eq!(c.high, 12.0);
1150 assert_eq!(c.low, 10.0);
1151 assert!(c.is_bullish());
1152 assert!(!Candle::new(5.0, 6.0, 1.0, 2.0).is_bullish());
1153 }
1154
1155 #[test]
1156 fn sma_values() {
1157 let c: Vec<Candle> = [1.0, 2.0, 3.0, 4.0]
1158 .iter()
1159 .map(|&p| Candle::new(p, p, p, p))
1160 .collect();
1161 let s = sma(&c, 2);
1162 assert_eq!(s, vec![None, Some(1.5), Some(2.5), Some(3.5)]);
1163 assert_eq!(sma(&c, 0).len(), 4);
1164 }
1165
1166 #[test]
1167 fn ema_values() {
1168 let c: Vec<Candle> = [1.0, 2.0, 3.0, 4.0]
1169 .iter()
1170 .map(|&p| Candle::new(p, p, p, p))
1171 .collect();
1172 let e = ema(&c, 2);
1173 assert_eq!(e[0], None);
1174 assert_eq!(e[1], Some(1.5));
1175 let k = 2.0 / 3.0;
1176 assert!((e[2].unwrap() - (3.0 * k + 1.5 * (1.0 - k))).abs() < 1e-12);
1177 }
1178
1179 #[test]
1180 fn heikin_ashi_first_bar() {
1181 let c = vec![Candle::new(10.0, 14.0, 8.0, 12.0)];
1182 let h = heikin_ashi(&c);
1183 assert_eq!(h[0].close, 11.0);
1184 assert_eq!(h[0].open, 11.0);
1185 assert_eq!(h.len(), 1);
1186 }
1187
1188 #[test]
1189 fn visible_range_scrolls() {
1190 let ch = CandlestickChart::new(data(20));
1191 assert_eq!(ch.visible_range(5), (15, 20));
1192 let ch = ch.scroll(3);
1193 assert_eq!(ch.visible_range(5), (12, 17));
1194 assert_eq!(CandlestickChart::new(data(3)).visible_range(10), (0, 3));
1195 assert_eq!(
1196 CandlestickChart::new(data(3)).scroll(10).visible_range(4),
1197 (0, 0)
1198 );
1199 }
1200
1201 #[test]
1202 fn renders_all_styles() {
1203 for style in [
1204 CandleStyle::Candle,
1205 CandleStyle::Ohlc,
1206 CandleStyle::HeikinAshi,
1207 CandleStyle::Braille,
1208 ] {
1209 let area = Rect::new(0, 0, 60, 20);
1210 let mut buf = Buffer::empty(area);
1211 let d = data(30);
1212 let s = sma(&d, 5);
1213 CandlestickChart::new(d)
1214 .style(style)
1215 .show_volume(true)
1216 .overlay(Overlay::new("SMA5", s, Color::Yellow))
1217 .block(Block::bordered())
1218 .render(area, &mut buf);
1219 let t = dump(&buf, area);
1220 assert!(t.contains('└'), "{style:?}");
1221 assert!(t.contains('●'), "{style:?}");
1222 }
1223 }
1224
1225 #[test]
1226 fn candle_glyphs_present() {
1227 let area = Rect::new(0, 0, 40, 16);
1228 let mut buf = Buffer::empty(area);
1229 CandlestickChart::new(data(10))
1230 .candle_width(3)
1231 .render(area, &mut buf);
1232 let t = dump(&buf, area);
1233 assert!(t.contains('█'));
1234 assert!(t.contains('│'));
1235 }
1236
1237 #[cfg(feature = "theme")]
1238 #[test]
1239 fn braille_candles_dense_and_colored() {
1240 let area = Rect::new(0, 0, 40, 16);
1241 let braille_cols = |style| {
1242 let mut buf = Buffer::empty(area);
1243 CandlestickChart::new(data(30))
1244 .style(style)
1245 .colors(Color::Green, Color::Red)
1246 .last_price_line(false)
1247 .render(area, &mut buf);
1248 let mut cols = std::collections::HashSet::new();
1249 let mut colors = std::collections::HashSet::new();
1250 for y in 0..16 {
1251 for x in 0..40 {
1252 let c = &buf[(x, y)];
1253 let ch = c.symbol().chars().next().unwrap();
1254 if ('\u{2801}'..='\u{28FF}').contains(&ch) {
1255 cols.insert(x);
1256 colors.insert(c.fg);
1257 }
1258 }
1259 }
1260 (cols.len(), colors)
1261 };
1262 let (n, colors) = braille_cols(CandleStyle::Braille);
1263 assert!(n >= 25, "{n}");
1264 assert!(colors.contains(&Color::Green) || colors.contains(&Color::Red));
1265 assert_eq!(braille_cols(CandleStyle::Candle).0, 0);
1266 let mut buf = Buffer::empty(area);
1268 CandlestickChart::new(data(30))
1269 .style(CandleStyle::Braille)
1270 .theme(Theme::nord())
1271 .hollow(true)
1272 .gap(2)
1273 .candle_width(2)
1274 .show_volume(true)
1275 .render(area, &mut buf);
1276 }
1277
1278 #[test]
1279 fn ohlc_glyphs_present() {
1280 let area = Rect::new(0, 0, 40, 16);
1281 let mut buf = Buffer::empty(area);
1282 CandlestickChart::new(data(10))
1283 .style(CandleStyle::Ohlc)
1284 .render(area, &mut buf);
1285 let t = dump(&buf, area);
1286 assert!(t.contains('┤') || t.contains('┼'));
1287 assert!(t.contains('├') || t.contains('┼'));
1288 }
1289
1290 #[test]
1291 fn bullish_bearish_colors() {
1292 let area = Rect::new(0, 0, 20, 12);
1293 let mut buf = Buffer::empty(area);
1294 let c = vec![
1295 Candle::new(10.0, 20.0, 5.0, 18.0),
1296 Candle::new(18.0, 20.0, 5.0, 8.0),
1297 ];
1298 CandlestickChart::new(c)
1299 .colors(Color::Blue, Color::Magenta)
1300 .last_price_line(false)
1301 .render(area, &mut buf);
1302 let fgs: Vec<Color> = (0..20)
1303 .flat_map(|x| (0..12).map(move |y| (x, y)))
1304 .filter(|p| buf[*p].symbol() == "█")
1305 .map(|p| buf[p].fg)
1306 .collect();
1307 assert!(fgs.contains(&Color::Blue));
1308 assert!(fgs.contains(&Color::Magenta));
1309 }
1310
1311 #[test]
1312 fn volume_panel_draws_eighths() {
1313 let area = Rect::new(0, 0, 40, 20);
1314 let mut buf = Buffer::empty(area);
1315 CandlestickChart::new(data(10))
1316 .show_volume(true)
1317 .render(area, &mut buf);
1318 let t = dump(&buf, area);
1319 assert!(t.contains('▇') || t.contains('█'));
1320 }
1321
1322 #[test]
1323 fn handles_empty_and_invalid() {
1324 let area = Rect::new(0, 0, 30, 10);
1325 let mut buf = Buffer::empty(area);
1326 CandlestickChart::new(vec![]).render(area, &mut buf);
1327 CandlestickChart::new(vec![Candle {
1328 open: f64::NAN,
1329 high: 1.0,
1330 low: 0.0,
1331 close: 1.0,
1332 ..Default::default()
1333 }])
1334 .render(area, &mut buf);
1335 }
1336
1337 #[test]
1338 fn single_flat_candle() {
1339 let area = Rect::new(0, 0, 30, 10);
1340 let mut buf = Buffer::empty(area);
1341 CandlestickChart::new(vec![Candle::new(5.0, 5.0, 5.0, 5.0)]).render(area, &mut buf);
1342 }
1343
1344 #[test]
1345 fn tiny_areas_safe() {
1346 for (w, h) in [(0, 0), (3, 3), (8, 4), (12, 5)] {
1347 let area = Rect::new(0, 0, w, h);
1348 let mut buf = Buffer::empty(area);
1349 CandlestickChart::new(data(5))
1350 .show_volume(true)
1351 .render(area, &mut buf);
1352 }
1353 }
1354}