Skip to main content

tui_chart/
candle.rs

1//! Candlestick / OHLC chart for price data (stocks, crypto, FX…).
2
3use 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/// One OHLC(V) bar.
17#[derive(Debug, Clone, PartialEq, Default)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub struct Candle {
20    /// Opening price.
21    pub open: f64,
22    /// Highest price.
23    pub high: f64,
24    /// Lowest price.
25    pub low: f64,
26    /// Closing price.
27    pub close: f64,
28    /// Traded volume.
29    pub volume: f64,
30    /// Optional x-axis label (e.g. time).
31    pub label: Option<String>,
32}
33
34impl Candle {
35    /// Create a candle; `high`/`low` are widened to include open and close.
36    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        /// Attach volume.
49        volume: f64
50    );
51
52    /// Attach an x-axis label.
53    pub fn label(mut self, label: impl Into<String>) -> Self {
54        self.label = Some(label.into());
55        self
56    }
57
58    /// Close ≥ open.
59    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/// Visual style of each bar.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73pub enum CandleStyle {
74    /// Japanese candlesticks with body and wicks.
75    #[default]
76    Candle,
77    /// OHLC bars: vertical range with open (left) / close (right) ticks.
78    Ohlc,
79    /// Heikin-Ashi smoothed candles.
80    HeikinAshi,
81    /// High-resolution braille candles: 1-dot wicks and 2-dot-wide bodies
82    /// (per cell of body width) with 4 dots of vertical resolution per row.
83    /// Bodies sit edge to edge, so about twice as many candles fit per width
84    /// (`gap(1)`, the default, means no gap; `gap(2)` leaves one cell).
85    Braille,
86}
87
88/// Technical overlay (e.g. moving average) aligned to the candle index.
89#[derive(Debug, Clone)]
90pub struct Overlay {
91    /// Legend name.
92    pub name: String,
93    /// One value per candle (`None` = no value).
94    pub values: Vec<Option<f64>>,
95    /// Dot color.
96    pub color: Color,
97}
98
99impl Overlay {
100    /// Create an overlay.
101    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/// Shaded band between two series (e.g. Bollinger bands) aligned to the candle index.
111#[derive(Debug, Clone)]
112pub struct BandOverlay {
113    /// Legend name.
114    pub name: String,
115    /// Upper bound per candle.
116    pub upper: Vec<Option<f64>>,
117    /// Lower bound per candle.
118    pub lower: Vec<Option<f64>>,
119    /// Shading color.
120    pub color: Color,
121}
122
123impl BandOverlay {
124    /// Create a band overlay.
125    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    /// Bollinger band (`period`, `k` standard deviations) over `candles`.
140    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/// Sub-pane drawn below the price (and volume) panel, sharing the x axis.
147#[derive(Debug, Clone)]
148pub enum IndicatorPane {
149    /// RSI with 30/70 reference lines.
150    Rsi {
151        /// Lookback period (commonly 14).
152        period: usize,
153    },
154    /// MACD lines plus histogram bars.
155    Macd {
156        /// Fast EMA period (commonly 12).
157        fast: usize,
158        /// Slow EMA period (commonly 26).
159        slow: usize,
160        /// Signal EMA period (commonly 9).
161        signal: usize,
162    },
163    /// Arbitrary line series, auto-scaled.
164    Custom {
165        /// Pane label.
166        name: String,
167        /// One value per candle.
168        values: Vec<Option<f64>>,
169        /// Line color.
170        color: Color,
171    },
172}
173
174/// Side of a [`TradeMarker`].
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
177pub enum TradeSide {
178    /// Buy (drawn as ▲ in the up color).
179    Buy,
180    /// Sell (drawn as ▼ in the down color).
181    Sell,
182}
183
184/// A buy/sell marker placed at a candle index and price.
185#[derive(Debug, Clone, PartialEq)]
186#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
187pub struct TradeMarker {
188    /// Index into the full candle list.
189    pub index: usize,
190    /// Price level of the marker.
191    pub price: f64,
192    /// Buy or sell.
193    pub side: TradeSide,
194    /// Optional text drawn next to the glyph.
195    pub label: Option<String>,
196}
197
198impl TradeMarker {
199    /// Create a marker without label.
200    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    /// Attach a label.
210    pub fn label(mut self, label: impl Into<String>) -> Self {
211        self.label = Some(label.into());
212        self
213    }
214}
215
216/// Horizontal reference line (support / resistance / target…).
217#[derive(Debug, Clone, PartialEq)]
218#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
219pub struct HLine {
220    /// Price level.
221    pub price: f64,
222    /// Optional label (defaults to the price).
223    pub label: Option<String>,
224    /// Line color.
225    pub color: Color,
226}
227
228impl HLine {
229    /// Create a line at `price`.
230    pub fn new(price: f64, color: Color) -> Self {
231        Self {
232            price,
233            label: None,
234            color,
235        }
236    }
237
238    /// Attach a label.
239    pub fn label(mut self, label: impl Into<String>) -> Self {
240        self.label = Some(label.into());
241        self
242    }
243}
244
245/// Simple moving average of closes (`None` until `period` values exist).
246pub 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
260/// Exponential moving average of closes.
261pub 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
288/// Convert candles to Heikin-Ashi candles.
289pub 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
320/// Right-aligned text tag on a row of `area`.
321fn 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/// Candlestick / OHLC chart with optional volume panel and overlays.
332///
333/// # Example
334///
335/// ```
336/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
337/// use tui_chart::{Candle, CandlestickChart};
338///
339/// let chart = CandlestickChart::new(vec![Candle::new(10.0, 12.0, 9.0, 11.0), Candle::new(11.0, 13.0, 10.0, 12.5)]);
340/// let area = Rect::new(0, 0, 40, 12);
341/// let mut buf = Buffer::empty(area);
342/// chart.render(area, &mut buf);
343/// ```
344#[derive(Debug, Clone)]
345pub struct CandlestickChart {
346    candles: Vec<Candle>,
347    style: CandleStyle,
348    colors: Option<(Color, Color)>,
349    hollow: bool,
350    theme: Option<Theme>,
351    base: Option<Style>,
352    candle_width: u16,
353    gap: u16,
354    show_volume: bool,
355    last_price_line: bool,
356    scroll: usize,
357    overlays: Vec<Overlay>,
358    bands: Vec<BandOverlay>,
359    panes: Vec<IndicatorPane>,
360    markers: Vec<TradeMarker>,
361    hlines: Vec<HLine>,
362    volume_profile: bool,
363    block: Option<Block<'static>>,
364    x_axis: Axis,
365    y_axis: Axis,
366}
367
368impl CandlestickChart {
369    /// Create a chart from candles.
370    pub fn new(candles: Vec<Candle>) -> Self {
371        Self {
372            candles,
373            style: CandleStyle::Candle,
374            colors: None,
375            hollow: false,
376            theme: None,
377            base: None,
378            candle_width: 1,
379            gap: 1,
380            show_volume: false,
381            last_price_line: true,
382            scroll: 0,
383            overlays: vec![],
384            bands: vec![],
385            panes: vec![],
386            markers: vec![],
387            hlines: vec![],
388            volume_profile: false,
389            block: None,
390            x_axis: Axis::new().ticks(6),
391            y_axis: Axis::new().grid(true),
392        }
393    }
394
395    setter!(
396        /// Bar style.
397        style: CandleStyle
398    );
399
400    /// Colors for bullish / bearish bars.
401    pub fn colors(mut self, up: Color, down: Color) -> Self {
402        self.colors = Some((up, down));
403        self
404    }
405
406    setter!(
407        /// Draw bullish candle bodies hollow (outlined) and bearish ones filled.
408        hollow: bool
409    );
410
411    /// Apply a [`Theme`]: bull/bear colors, axes, labels, background fill.
412    /// Colors set via [`CandlestickChart::colors`] still win.
413    #[cfg(feature = "theme")]
414    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
415        let t = theme.into();
416        self.x_axis.theme_in_place(&t);
417        self.y_axis.theme_in_place(&t);
418        self.theme = Some(t);
419        self
420    }
421
422    base_style_setter!(base);
423
424    fn up_color(&self) -> Color {
425        match (&self.colors, &self.theme) {
426            (Some((u, _)), _) => *u,
427            (None, Some(t)) => t.bull,
428            _ => Color::Green,
429        }
430    }
431
432    fn down_color(&self) -> Color {
433        match (&self.colors, &self.theme) {
434            (Some((_, d)), _) => *d,
435            (None, Some(t)) => t.bear,
436            _ => Color::Red,
437        }
438    }
439
440    fn dim_color(&self) -> Color {
441        self.theme.as_ref().map_or(Color::DarkGray, |t| t.axis)
442    }
443
444    fn label_color(&self) -> Color {
445        self.theme.as_ref().map_or(Color::Gray, |t| t.muted)
446    }
447
448    /// Body width in cells (ignored for OHLC bars; min 1).
449    pub fn candle_width(mut self, w: u16) -> Self {
450        self.candle_width = w.max(1);
451        self
452    }
453
454    setter!(
455        /// Empty cells between bars.
456        gap: u16
457    );
458
459    setter!(
460        /// Show a volume histogram under the price panel.
461        show_volume: bool
462    );
463
464    setter!(
465        /// Dashed horizontal line at the last visible close.
466        last_price_line: bool
467    );
468
469    setter!(
470        /// Hide the newest `n` candles (scroll back in time).
471        scroll: usize
472    );
473
474    /// Add an indicator overlay.
475    pub fn overlay(mut self, overlay: Overlay) -> Self {
476        self.overlays.push(overlay);
477        self
478    }
479
480    /// Add a shaded band (e.g. Bollinger) behind the candles.
481    pub fn band(mut self, band: BandOverlay) -> Self {
482        self.bands.push(band);
483        self
484    }
485
486    /// Add an indicator sub-pane below price/volume (dropped if there is no room).
487    pub fn pane(mut self, pane: IndicatorPane) -> Self {
488        self.panes.push(pane);
489        self
490    }
491
492    /// Add a buy/sell marker.
493    pub fn marker(mut self, marker: TradeMarker) -> Self {
494        self.markers.push(marker);
495        self
496    }
497
498    /// Add a horizontal reference line.
499    pub fn hline(mut self, line: HLine) -> Self {
500        self.hlines.push(line);
501        self
502    }
503
504    /// Support level (green dashed line labelled "S").
505    pub fn support(self, price: f64) -> Self {
506        self.hline(HLine::new(price, Color::Green).label(format!("S {price:.2}")))
507    }
508
509    /// Resistance level (red dashed line labelled "R").
510    pub fn resistance(self, price: f64) -> Self {
511        self.hline(HLine::new(price, Color::Red).label(format!("R {price:.2}")))
512    }
513
514    setter!(
515        /// Horizontal volume-by-price histogram along the right of the price panel.
516        volume_profile: bool
517    );
518
519    block_setter!(block, 'static);
520
521    /// X axis (title / label style; labels come from [`Candle::label`]).
522    pub fn x_axis(mut self, axis: Axis) -> Self {
523        self.x_axis = axis;
524        if let Some(t) = &self.theme {
525            self.x_axis.theme_in_place(t);
526        }
527        self
528    }
529
530    /// Y (price) axis.
531    pub fn y_axis(mut self, axis: Axis) -> Self {
532        self.y_axis = axis;
533        if let Some(t) = &self.theme {
534            self.y_axis.theme_in_place(t);
535        }
536        self
537    }
538
539    /// Cells per candle slot (body + gap). Braille packs bodies edge to edge.
540    fn slot_cells(&self) -> usize {
541        let gap = if self.style == CandleStyle::Braille {
542            self.gap.saturating_sub(1)
543        } else {
544            self.gap
545        };
546        (self.bar_width() + gap) as usize
547    }
548
549    fn bar_width(&self) -> u16 {
550        match self.style {
551            CandleStyle::Ohlc => 1,
552            _ => self.candle_width,
553        }
554    }
555
556    /// Index range `start..end` of candles visible in `slots` slots.
557    pub(crate) fn visible_range(&self, slots: usize) -> (usize, usize) {
558        let end = self.candles.len().saturating_sub(self.scroll);
559        (end.saturating_sub(slots), end)
560    }
561
562    fn color_of(&self, c: &Candle) -> Color {
563        if c.is_bullish() {
564            self.up_color()
565        } else {
566            self.down_color()
567        }
568    }
569
570    fn draw_profile(
571        &self,
572        buf: &mut Buffer,
573        price: Rect,
574        vis: &[&Candle],
575        sub: &dyn Fn(f64) -> i32,
576    ) {
577        let mut bins = vec![0.0f64; price.height as usize];
578        for c in vis.iter().filter(|c| c.is_valid() && c.volume.is_finite()) {
579            let (r0, r1) = ((sub(c.high) / 2) as usize, (sub(c.low) / 2) as usize);
580            let share = c.volume / (r1 - r0 + 1) as f64;
581            for b in bins.iter_mut().take(r1 + 1).skip(r0) {
582                *b += share;
583            }
584        }
585        let max = bins.iter().cloned().fold(0.0, f64::max);
586        if max <= 0.0 {
587            return;
588        }
589        let w = (price.width / 5).clamp(1, 20) as f64;
590        let st = Style::default().fg(self.dim_color());
591        for (r, v) in bins.iter().enumerate() {
592            let len = (v / max * w).round() as u16;
593            for dx in 0..len {
594                buf.set_string(price.right() - 1 - dx, price.y + r as u16, "▒", st);
595            }
596        }
597    }
598
599    #[allow(clippy::too_many_arguments)]
600    fn draw_pane(
601        &self,
602        buf: &mut Buffer,
603        r: Rect,
604        gutter: Rect,
605        pane: &IndicatorPane,
606        start: usize,
607        n_vis: usize,
608        slot: usize,
609        bw: u16,
610    ) {
611        if r.height == 0 || r.width == 0 {
612            return;
613        }
614        let dim = Style::default().fg(self.dim_color());
615        // (name, lines [(values,color)], hist, bounds, refs)
616        let (name, lines, hist, (lo, hi), refs): (String, Vec<_>, Option<Vec<_>>, _, Vec<f64>) =
617            match pane {
618                IndicatorPane::Rsi { period } => (
619                    format!("RSI {period}"),
620                    vec![(indicator::rsi(&self.candles, *period), Color::Cyan)],
621                    None,
622                    (0.0, 100.0),
623                    vec![70.0, 30.0],
624                ),
625                IndicatorPane::Macd { fast, slow, signal } => {
626                    let (m, s, h) = indicator::macd(&self.candles, *fast, *slow, *signal);
627                    let range = (start..start + n_vis)
628                        .flat_map(|i| [m.get(i), s.get(i), h.get(i)])
629                        .flatten()
630                        .flatten()
631                        .fold(0.0f64, |a, v| a.max(v.abs()));
632                    let range = if range > 0.0 { range } else { 1.0 };
633                    (
634                        format!("MACD {fast},{slow},{signal}"),
635                        vec![(m, Color::Cyan), (s, Color::Yellow)],
636                        Some(h),
637                        (-range, range),
638                        vec![0.0],
639                    )
640                }
641                IndicatorPane::Custom {
642                    name,
643                    values,
644                    color,
645                } => {
646                    let vals = || {
647                        (start..start + n_vis)
648                            .filter_map(|i| values.get(i).copied().flatten())
649                            .filter(|v| v.is_finite())
650                    };
651                    let lo = vals().fold(f64::INFINITY, f64::min);
652                    let hi = vals().fold(f64::NEG_INFINITY, f64::max);
653                    let b = if hi > lo { (lo, hi) } else { (0.0, 1.0) };
654                    (
655                        name.clone(),
656                        vec![(values.clone(), *color)],
657                        None,
658                        b,
659                        vec![],
660                    )
661                }
662            };
663        let h = r.height as f64;
664        let row = |v: f64| -> u16 {
665            ((hi - v) / (hi - lo) * (h - 1.0))
666                .round()
667                .clamp(0.0, h - 1.0) as u16
668        };
669        let mut ticks = vec![];
670        for rv in &refs {
671            let rr = row(*rv);
672            hline_row(buf, r, rr, '┄', dim);
673            ticks.push((rr, format!("{rv:.0}")));
674        }
675        layout::draw_y_labels(buf, gutter, &ticks, dim);
676        let xs = |i: usize| r.x + (i * slot) as u16;
677        if let Some(hs) = &hist {
678            let z = row(0.0);
679            for i in 0..n_vis {
680                let Some(Some(v)) = hs.get(start + i) else {
681                    continue;
682                };
683                if !v.is_finite() {
684                    continue;
685                }
686                let col = if *v >= 0.0 {
687                    self.up_color()
688                } else {
689                    self.down_color()
690                };
691                let rv = row(*v);
692                for dx in 0..bw {
693                    let x = xs(i) + dx;
694                    if x >= r.right() {
695                        break;
696                    }
697                    for y in z.min(rv)..=z.max(rv) {
698                        buf.set_string(x, r.y + y, "█", Style::default().fg(col));
699                    }
700                }
701            }
702        }
703        for (vals, col) in &lines {
704            for i in 0..n_vis {
705                let Some(Some(v)) = vals.get(start + i) else {
706                    continue;
707                };
708                let x = xs(i) + bw / 2;
709                if !v.is_finite() || x >= r.right() {
710                    continue;
711                }
712                buf.set_string(x, r.y + row(*v), "●", Style::default().fg(*col));
713            }
714        }
715        if text_width(&name) < r.width {
716            buf.set_string(r.x + 1, r.y, &name, dim);
717        }
718    }
719
720    fn render_inner(&self, area: Rect, buf: &mut Buffer) {
721        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
722        let src: Vec<Candle> = match self.style {
723            CandleStyle::HeikinAshi => heikin_ashi(&self.candles),
724            _ => self.candles.clone(),
725        };
726        let bw = self.bar_width();
727        let slot = self.slot_cells();
728        // provisional width to pick the visible window (label width impacts it slightly)
729        let (start, end) = self.visible_range((inner.width as usize).max(1) / slot);
730        let vis: Vec<&Candle> = src[start.min(src.len())..end.min(src.len())]
731            .iter()
732            .collect();
733        let valid: Vec<&&Candle> = vis.iter().filter(|c| c.is_valid()).collect();
734
735        let (lo, hi) = self.y_axis.bounds.unwrap_or_else(|| {
736            if valid.is_empty() {
737                (0.0, 1.0)
738            } else {
739                let lo = valid.iter().map(|c| c.low).fold(f64::INFINITY, f64::min);
740                let hi = valid
741                    .iter()
742                    .map(|c| c.high)
743                    .fold(f64::NEG_INFINITY, f64::max);
744                nice_bounds(lo, hi, self.y_axis.ticks)
745            }
746        });
747        if hi <= lo {
748            return;
749        }
750        let y_marks = self.y_axis.tick_marks((lo, hi));
751        let yw = y_marks
752            .iter()
753            .map(|(_, l)| text_width(l))
754            .max()
755            .unwrap_or(0);
756        let has_labels = vis.iter().any(|c| c.label.is_some());
757        let Some(a) = layout::compute(
758            inner,
759            yw,
760            has_labels,
761            self.x_axis.title.is_some(),
762            self.y_axis.title.is_some(),
763        ) else {
764            return;
765        };
766        let plot = a.plot;
767        // recompute window with the real plot width
768        let (start, end) =
769            self.visible_range((plot.width as usize + slot - bw as usize) / slot.max(1));
770        let vis: Vec<&Candle> = src[start.min(src.len())..end.min(src.len())]
771            .iter()
772            .collect();
773
774        let vol_h = if self.show_volume && plot.height >= 8 {
775            (plot.height / 4).max(2)
776        } else {
777            0
778        };
779        let pane_each = (plot.height / 6).max(3);
780        let mut panes_n = 0usize;
781        let mut panes_h = 0u16;
782        for _ in &self.panes {
783            let nh = panes_h + pane_each;
784            if plot.height.saturating_sub(nh + vol_h) < 5 {
785                break;
786            }
787            panes_n += 1;
788            panes_h = nh;
789        }
790        let vol_bottom = plot.bottom() - panes_h;
791        let price = Rect::new(plot.x, plot.y, plot.width, plot.height - vol_h - panes_h);
792        let sub_n = price.height as f64 * 2.0;
793        let sub = |p: f64| -> i32 {
794            ((hi - p) / (hi - lo) * (sub_n - 1.0))
795                .round()
796                .clamp(0.0, sub_n - 1.0) as i32
797        };
798
799        if crate::interact::recording() {
800            for (i, c) in vis.iter().enumerate().filter(|(_, c)| c.is_valid()) {
801                let x = price.x + (i * slot) as u16;
802                let (t, b) = ((sub(c.high) / 2) as u16, (sub(c.low) / 2) as u16);
803                let rect =
804                    Rect::new(x, price.y + t, bw.max(1), b.max(t) - t + 1).intersection(price);
805                crate::interact::record_point(rect, 0, start + i, || {
806                    let f = crate::util::format_compact;
807                    let mut lines = vec![
808                        format!("O {}  H {}", f(c.open), f(c.high)),
809                        format!("L {}  C {}", f(c.low), f(c.close)),
810                    ];
811                    if c.volume > 0.0 {
812                        lines.push(format!("vol {}", f(c.volume)));
813                    }
814                    (
815                        c.label.clone().unwrap_or_else(|| format!("#{}", start + i)),
816                        lines,
817                    )
818                });
819            }
820        }
821
822        // grid + y labels
823        let y_ticks: Vec<(u16, String)> = y_marks
824            .iter()
825            .map(|(f, l)| (layout::frac_row(*f, price.height, 2), l.clone()))
826            .collect();
827        if self.y_axis.grid {
828            let rows: Vec<u16> = y_ticks.iter().map(|t| t.0).collect();
829            layout::draw_grid(
830                buf,
831                price,
832                &[],
833                &rows,
834                self.y_axis.grid_style,
835                self.y_axis.grid_kind,
836            );
837        }
838
839        // volume profile + bands (behind candles)
840        if self.volume_profile && price.width >= 20 {
841            self.draw_profile(buf, price, &vis, &sub);
842        }
843        for band in &self.bands {
844            let st = Style::default().fg(band.color);
845            for i in 0..vis.len() {
846                let (Some(Some(u)), Some(Some(l))) =
847                    (band.upper.get(start + i), band.lower.get(start + i))
848                else {
849                    continue;
850                };
851                if !u.is_finite() || !l.is_finite() || (*u < lo && *l < lo) || (*u > hi && *l > hi)
852                {
853                    continue;
854                }
855                let x0 = price.x + (i * slot) as u16;
856                for dx in 0..slot.min(2).max(bw as usize) as u16 {
857                    let x = x0 + dx;
858                    if x >= price.right() {
859                        break;
860                    }
861                    for r in (sub(*u) / 2)..=(sub(*l) / 2) {
862                        if let Some(cell) = buf.cell_mut((x, price.y + r as u16)) {
863                            if cell.symbol() == " " || cell.symbol() == "·" {
864                                cell.set_char('░').set_style(st);
865                            }
866                        }
867                    }
868                }
869            }
870        }
871
872        // horizontal lines + last price line
873        for h in &self.hlines {
874            if h.price.is_finite() && h.price >= lo && h.price <= hi {
875                let row = (sub(h.price) / 2) as u16;
876                let label = h.label.clone().unwrap_or_else(|| format!("{:.2}", h.price));
877                hline_row(buf, price, row, '┄', Style::default().fg(h.color));
878                tag(buf, price, row, &label, Style::default().fg(h.color));
879            }
880        }
881        let last_tag = if self.last_price_line {
882            vis.iter().rev().find(|c| c.is_valid()).map(|c| {
883                let row = (sub(c.close) / 2) as u16;
884                hline_row(buf, price, row, '┈', Style::default().fg(self.color_of(c)));
885                (row, format!("{:.2}", c.close), self.color_of(c))
886            })
887        } else {
888            None
889        };
890
891        let max_vol = vis
892            .iter()
893            .map(|c| c.volume)
894            .filter(|v| v.is_finite())
895            .fold(0.0f64, f64::max);
896        let mut x_ticks: Vec<(u16, String)> = vec![];
897        let mut dots = (self.style == CandleStyle::Braille)
898            .then(|| Canvas::new(price.width, price.height, Marker::Braille));
899        let dot_n = price.height as f64 * 4.0;
900        let dsub = |p: f64| -> i32 {
901            ((hi - p) / (hi - lo) * (dot_n - 1.0))
902                .round()
903                .clamp(0.0, dot_n - 1.0) as i32
904        };
905        for (i, c) in vis.iter().enumerate() {
906            let x0 = price.x + (i * slot) as u16;
907            if x0 + bw > price.right() {
908                break;
909            }
910            let centre = x0 + bw / 2;
911            if let Some(l) = &c.label {
912                x_ticks.push((centre - plot.x, l.clone()));
913            }
914            if !c.is_valid() {
915                continue;
916            }
917            let color = self.color_of(c);
918            let st = Style::default().fg(color);
919            if let Some(cv) = dots.as_mut() {
920                let px0 = i32::from(x0 - price.x) * 2;
921                let pw = i32::from(bw) * 2;
922                let wick = px0 + (pw - 1) / 2;
923                let (w0, w1) = (dsub(c.high), dsub(c.low));
924                for py in w0..=w1 {
925                    cv.set(wick, py, color);
926                }
927                let (oa, ob) = (dsub(c.open), dsub(c.close));
928                let (b0, b1) = (oa.min(ob), oa.max(ob));
929                let hollow = self.hollow && c.is_bullish();
930                for py in b0..=b1 {
931                    for px in px0..px0 + pw {
932                        let edge = py == b0 || py == b1 || px == px0 || px == px0 + pw - 1;
933                        if !hollow || edge {
934                            cv.set(px, py, color);
935                        }
936                    }
937                }
938            } else if self.style == CandleStyle::Ohlc {
939                let (r_h, r_l) = ((sub(c.high) / 2) as u16, (sub(c.low) / 2) as u16);
940                let (r_o, r_c) = ((sub(c.open) / 2) as u16, (sub(c.close) / 2) as u16);
941                for r in r_h..=r_l {
942                    let ch = match (r == r_o, r == r_c) {
943                        (true, true) => '┼',
944                        (true, false) => '┤',
945                        (false, true) => '├',
946                        _ => '│',
947                    };
948                    buf.set_string(centre, price.y + r, ch.to_string(), st);
949                }
950            } else {
951                let (b0, b1) = {
952                    let (a_, b_) = (sub(c.open), sub(c.close));
953                    (a_.min(b_), a_.max(b_))
954                };
955                let (w0, w1) = (sub(c.high), sub(c.low));
956                for r in (w0 / 2)..=(w1 / 2) {
957                    let (t, b) = (2 * r, 2 * r + 1);
958                    let body_t = t >= b0 && t <= b1;
959                    let body_b = b >= b0 && b <= b1;
960                    let wick_t = t >= w0 && t <= w1;
961                    let wick_b = b >= w0 && b <= w1;
962                    let hollow = self.hollow && c.is_bullish();
963                    let body_ch = match (body_t, body_b) {
964                        (true, true) => Some('█'),
965                        (true, false) => Some('▀'),
966                        (false, true) => Some('▄'),
967                        _ => None,
968                    };
969                    let wick_ch = match (wick_t, wick_b) {
970                        (true, true) => Some('│'),
971                        (true, false) => Some('╵'),
972                        (false, true) => Some('╷'),
973                        _ => None,
974                    };
975                    for dx in 0..bw {
976                        let ch = if dx == bw / 2 {
977                            body_ch.or(wick_ch)
978                        } else {
979                            body_ch
980                        };
981                        let ch = match ch {
982                            Some('█') if hollow => {
983                                let (top_r, bot_r) = (b0 / 2, b1 / 2);
984                                if bw == 1 {
985                                    Some('┃')
986                                } else if dx == 0 {
987                                    Some('▌')
988                                } else if dx == bw - 1 {
989                                    Some('▐')
990                                } else if r == top_r {
991                                    Some('▔')
992                                } else if r == bot_r {
993                                    Some('▁')
994                                } else {
995                                    Some(' ')
996                                }
997                            }
998                            other => other,
999                        };
1000                        if let Some(ch) = ch {
1001                            buf.set_string(x0 + dx, price.y + r as u16, ch.to_string(), st);
1002                        }
1003                    }
1004                }
1005                // doji: make sure body is visible
1006                if b0 == b1 && bw > 1 {
1007                    // body already drawn with half block above
1008                }
1009            }
1010            // volume
1011            if vol_h > 0 && max_vol > 0.0 && c.volume.is_finite() && c.volume > 0.0 {
1012                let total = (c.volume / max_vol * vol_h as f64 * 8.0).round().max(1.0) as i32;
1013                for r in 0..vol_h as i32 {
1014                    let fill = (total - r * 8).clamp(0, 8) as usize;
1015                    if fill == 0 {
1016                        break;
1017                    }
1018                    let y = vol_bottom - 1 - r as u16;
1019                    for dx in 0..bw {
1020                        buf.set_string(x0 + dx, y, EIGHTHS[fill].to_string(), st);
1021                    }
1022                }
1023            }
1024        }
1025
1026        if let Some(cv) = &dots {
1027            cv.render(buf, price);
1028        }
1029
1030        // overlays on top of bars
1031        for ov in &self.overlays {
1032            for (i, _) in vis.iter().enumerate() {
1033                let Some(Some(v)) = ov.values.get(start + i) else {
1034                    continue;
1035                };
1036                if !v.is_finite() || *v < lo || *v > hi {
1037                    continue;
1038                }
1039                let x = price.x + (i * slot) as u16 + bw / 2;
1040                if x >= price.right() {
1041                    continue;
1042                }
1043                let row = (sub(*v) / 2) as u16;
1044                buf.set_string(x, price.y + row, "●", Style::default().fg(ov.color));
1045            }
1046        }
1047
1048        // trade markers
1049        for m in &self.markers {
1050            if m.index < start || m.index >= start + vis.len() || !m.price.is_finite() {
1051                continue;
1052            }
1053            if m.price < lo || m.price > hi {
1054                continue;
1055            }
1056            let i = m.index - start;
1057            let x = price.x + (i * slot) as u16 + bw / 2;
1058            if x >= price.right() {
1059                continue;
1060            }
1061            let row = (sub(m.price) / 2) as u16;
1062            let (g, col) = match m.side {
1063                TradeSide::Buy => ('▲', self.up_color()),
1064                TradeSide::Sell => ('▼', self.down_color()),
1065            };
1066            let st = Style::default().fg(col).add_modifier(Modifier::BOLD);
1067            buf.set_string(x, price.y + row, g.to_string(), st);
1068            if let Some(l) = &m.label {
1069                if x + 1 + text_width(l) < price.right() {
1070                    buf.set_string(x + 1, price.y + row, l, Style::default().fg(col));
1071                }
1072            }
1073        }
1074        if let Some((row, text, col)) = last_tag {
1075            let st = Style::default().fg(Color::Black).bg(col);
1076            tag(buf, price, row, &format!(" {text} "), st);
1077        }
1078
1079        // indicator panes
1080        for (k, pane) in self.panes.iter().take(panes_n).enumerate() {
1081            let r = Rect::new(
1082                plot.x,
1083                plot.bottom() - panes_h + k as u16 * pane_each,
1084                plot.width,
1085                pane_each,
1086            );
1087            let gutter = Rect::new(a.y_labels.x, r.y, a.y_labels.width, r.height);
1088            self.draw_pane(buf, r, gutter, pane, start, vis.len(), slot, bw);
1089        }
1090
1091        layout::draw_axes(buf, &a, self.x_axis.style, self.y_axis.style);
1092        layout::draw_y_labels(
1093            buf,
1094            Rect::new(a.y_labels.x, price.y, a.y_labels.width, price.height),
1095            &y_ticks,
1096            self.y_axis.label_style,
1097        );
1098        if vol_h > 0 {
1099            let top = Rect::new(a.y_labels.x, vol_bottom - vol_h, a.y_labels.width, vol_h);
1100            let label = format_compact(max_vol);
1101            layout::draw_y_labels(
1102                buf,
1103                top,
1104                &[(0, label)],
1105                Style::default().fg(self.dim_color()),
1106            );
1107        }
1108        layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.x_axis.label_style);
1109        layout::draw_titles(
1110            buf,
1111            inner,
1112            &a,
1113            self.x_axis
1114                .title
1115                .as_deref()
1116                .map(|t| (t, self.x_axis.label_style)),
1117            self.y_axis
1118                .title
1119                .as_deref()
1120                .map(|t| (t, self.y_axis.label_style)),
1121        );
1122        // overlay legend (top-left of plot)
1123        let mut x = plot.x + 1;
1124        for ov in &self.overlays {
1125            let w = text_width(&ov.name) + 3;
1126            if x + w > plot.right() {
1127                break;
1128            }
1129            buf.set_string(x, plot.y, "●", Style::default().fg(ov.color));
1130            buf.set_string(
1131                x + 2,
1132                plot.y,
1133                &ov.name,
1134                Style::default().fg(self.label_color()),
1135            );
1136            x += w + 1;
1137        }
1138    }
1139}
1140
1141impl CandlestickChart {
1142    fn render_into(&self, area: Rect, buf: &mut Buffer) {
1143        self.render_inner(area, buf);
1144    }
1145}
1146
1147widget_impls!(CandlestickChart);
1148
1149#[cfg(feature = "theme")]
1150impl tui_nuances::Themed for CandlestickChart {
1151    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
1152        self.theme(theme)
1153    }
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::*;
1159    use ratatui::widgets::Widget;
1160
1161    fn data(n: usize) -> Vec<Candle> {
1162        (0..n)
1163            .map(|i| {
1164                let b = 100.0 + (i as f64 * 0.7).sin() * 10.0;
1165                let up = i % 2 == 0;
1166                let (o, c) = if up { (b, b + 3.0) } else { (b + 3.0, b) };
1167                Candle::new(o, b + 5.0, b - 2.0, c)
1168                    .volume(100.0 + i as f64 * 10.0)
1169                    .label(format!("{i}"))
1170            })
1171            .collect()
1172    }
1173
1174    fn dump(buf: &Buffer, area: Rect) -> String {
1175        (area.y..area.bottom())
1176            .flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
1177            .map(|p| buf[p].symbol().to_string())
1178            .collect()
1179    }
1180
1181    #[test]
1182    fn candle_new_widens_range() {
1183        let c = Candle::new(10.0, 9.0, 11.0, 12.0);
1184        assert_eq!(c.high, 12.0);
1185        assert_eq!(c.low, 10.0);
1186        assert!(c.is_bullish());
1187        assert!(!Candle::new(5.0, 6.0, 1.0, 2.0).is_bullish());
1188    }
1189
1190    #[test]
1191    fn sma_values() {
1192        let c: Vec<Candle> = [1.0, 2.0, 3.0, 4.0]
1193            .iter()
1194            .map(|&p| Candle::new(p, p, p, p))
1195            .collect();
1196        let s = sma(&c, 2);
1197        assert_eq!(s, vec![None, Some(1.5), Some(2.5), Some(3.5)]);
1198        assert_eq!(sma(&c, 0).len(), 4);
1199    }
1200
1201    #[test]
1202    fn ema_values() {
1203        let c: Vec<Candle> = [1.0, 2.0, 3.0, 4.0]
1204            .iter()
1205            .map(|&p| Candle::new(p, p, p, p))
1206            .collect();
1207        let e = ema(&c, 2);
1208        assert_eq!(e[0], None);
1209        assert_eq!(e[1], Some(1.5));
1210        let k = 2.0 / 3.0;
1211        assert!((e[2].unwrap() - (3.0 * k + 1.5 * (1.0 - k))).abs() < 1e-12);
1212    }
1213
1214    #[test]
1215    fn heikin_ashi_first_bar() {
1216        let c = vec![Candle::new(10.0, 14.0, 8.0, 12.0)];
1217        let h = heikin_ashi(&c);
1218        assert_eq!(h[0].close, 11.0);
1219        assert_eq!(h[0].open, 11.0);
1220        assert_eq!(h.len(), 1);
1221    }
1222
1223    #[test]
1224    fn visible_range_scrolls() {
1225        let ch = CandlestickChart::new(data(20));
1226        assert_eq!(ch.visible_range(5), (15, 20));
1227        let ch = ch.scroll(3);
1228        assert_eq!(ch.visible_range(5), (12, 17));
1229        assert_eq!(CandlestickChart::new(data(3)).visible_range(10), (0, 3));
1230        assert_eq!(
1231            CandlestickChart::new(data(3)).scroll(10).visible_range(4),
1232            (0, 0)
1233        );
1234    }
1235
1236    #[test]
1237    fn renders_all_styles() {
1238        for style in [
1239            CandleStyle::Candle,
1240            CandleStyle::Ohlc,
1241            CandleStyle::HeikinAshi,
1242            CandleStyle::Braille,
1243        ] {
1244            let area = Rect::new(0, 0, 60, 20);
1245            let mut buf = Buffer::empty(area);
1246            let d = data(30);
1247            let s = sma(&d, 5);
1248            CandlestickChart::new(d)
1249                .style(style)
1250                .show_volume(true)
1251                .overlay(Overlay::new("SMA5", s, Color::Yellow))
1252                .block(Block::bordered())
1253                .render(area, &mut buf);
1254            let t = dump(&buf, area);
1255            assert!(t.contains('└'), "{style:?}");
1256            assert!(t.contains('●'), "{style:?}");
1257        }
1258    }
1259
1260    #[test]
1261    fn candle_glyphs_present() {
1262        let area = Rect::new(0, 0, 40, 16);
1263        let mut buf = Buffer::empty(area);
1264        CandlestickChart::new(data(10))
1265            .candle_width(3)
1266            .render(area, &mut buf);
1267        let t = dump(&buf, area);
1268        assert!(t.contains('█'));
1269        assert!(t.contains('│'));
1270    }
1271
1272    #[cfg(feature = "theme")]
1273    #[test]
1274    fn braille_candles_dense_and_colored() {
1275        let area = Rect::new(0, 0, 40, 16);
1276        let braille_cols = |style| {
1277            let mut buf = Buffer::empty(area);
1278            CandlestickChart::new(data(30))
1279                .style(style)
1280                .colors(Color::Green, Color::Red)
1281                .last_price_line(false)
1282                .render(area, &mut buf);
1283            let mut cols = std::collections::HashSet::new();
1284            let mut colors = std::collections::HashSet::new();
1285            for y in 0..16 {
1286                for x in 0..40 {
1287                    let c = &buf[(x, y)];
1288                    let ch = c.symbol().chars().next().unwrap();
1289                    if ('\u{2801}'..='\u{28FF}').contains(&ch) {
1290                        cols.insert(x);
1291                        colors.insert(c.fg);
1292                    }
1293                }
1294            }
1295            (cols.len(), colors)
1296        };
1297        let (n, colors) = braille_cols(CandleStyle::Braille);
1298        assert!(n >= 25, "{n}");
1299        assert!(colors.contains(&Color::Green) || colors.contains(&Color::Red));
1300        assert_eq!(braille_cols(CandleStyle::Candle).0, 0);
1301        // themed + hollow + gap + volume do not panic
1302        let mut buf = Buffer::empty(area);
1303        CandlestickChart::new(data(30))
1304            .style(CandleStyle::Braille)
1305            .theme(Theme::nord())
1306            .hollow(true)
1307            .gap(2)
1308            .candle_width(2)
1309            .show_volume(true)
1310            .render(area, &mut buf);
1311    }
1312
1313    #[test]
1314    fn ohlc_glyphs_present() {
1315        let area = Rect::new(0, 0, 40, 16);
1316        let mut buf = Buffer::empty(area);
1317        CandlestickChart::new(data(10))
1318            .style(CandleStyle::Ohlc)
1319            .render(area, &mut buf);
1320        let t = dump(&buf, area);
1321        assert!(t.contains('┤') || t.contains('┼'));
1322        assert!(t.contains('├') || t.contains('┼'));
1323    }
1324
1325    #[test]
1326    fn bullish_bearish_colors() {
1327        let area = Rect::new(0, 0, 20, 12);
1328        let mut buf = Buffer::empty(area);
1329        let c = vec![
1330            Candle::new(10.0, 20.0, 5.0, 18.0),
1331            Candle::new(18.0, 20.0, 5.0, 8.0),
1332        ];
1333        CandlestickChart::new(c)
1334            .colors(Color::Blue, Color::Magenta)
1335            .last_price_line(false)
1336            .render(area, &mut buf);
1337        let fgs: Vec<Color> = (0..20)
1338            .flat_map(|x| (0..12).map(move |y| (x, y)))
1339            .filter(|p| buf[*p].symbol() == "█")
1340            .map(|p| buf[p].fg)
1341            .collect();
1342        assert!(fgs.contains(&Color::Blue));
1343        assert!(fgs.contains(&Color::Magenta));
1344    }
1345
1346    #[test]
1347    fn volume_panel_draws_eighths() {
1348        let area = Rect::new(0, 0, 40, 20);
1349        let mut buf = Buffer::empty(area);
1350        CandlestickChart::new(data(10))
1351            .show_volume(true)
1352            .render(area, &mut buf);
1353        let t = dump(&buf, area);
1354        assert!(t.contains('▇') || t.contains('█'));
1355    }
1356
1357    #[test]
1358    fn handles_empty_and_invalid() {
1359        let area = Rect::new(0, 0, 30, 10);
1360        let mut buf = Buffer::empty(area);
1361        CandlestickChart::new(vec![]).render(area, &mut buf);
1362        CandlestickChart::new(vec![Candle {
1363            open: f64::NAN,
1364            high: 1.0,
1365            low: 0.0,
1366            close: 1.0,
1367            ..Default::default()
1368        }])
1369        .render(area, &mut buf);
1370    }
1371
1372    #[test]
1373    fn single_flat_candle() {
1374        let area = Rect::new(0, 0, 30, 10);
1375        let mut buf = Buffer::empty(area);
1376        CandlestickChart::new(vec![Candle::new(5.0, 5.0, 5.0, 5.0)]).render(area, &mut buf);
1377    }
1378
1379    #[test]
1380    fn tiny_areas_safe() {
1381        for (w, h) in [(0, 0), (3, 3), (8, 4), (12, 5)] {
1382            let area = Rect::new(0, 0, w, h);
1383            let mut buf = Buffer::empty(area);
1384            CandlestickChart::new(data(5))
1385                .show_volume(true)
1386                .render(area, &mut buf);
1387        }
1388    }
1389}