Skip to main content

ferrochart_orderflow/
tpo.rs

1//! TPO / market profile (rules in `docs/book/src/orderflow.md`):
2//! one slot per trading session; each period of the session marks the price
3//! levels it traded at with its letter.
4
5use core::cell::RefCell;
6
7use ferrochart_core::data::{OhlcColumns, Timestamp};
8use ferrochart_core::drawing::{FrameBuilder, Label};
9use ferrochart_core::error::{Error, Result};
10use ferrochart_core::frame::TextAlign;
11use ferrochart_core::geom::{Css, PointPx, RectPx, Rgba};
12use ferrochart_core::plugin::{AxisMode, CustomSeries, MinMaxIndex, SeriesCtx};
13use ferrochart_core::theme::Theme;
14
15use crate::levels::PriceLevels;
16
17const DAY: i64 = 86_400_000;
18
19/// The kind name of TPO series.
20pub const TPO_KIND: &str = "orderflow.tpo";
21
22/// Below this slot width (CSS px) nothing is drawn.
23pub const TPO_MIN_SPACING: f32 = 4.0;
24
25/// Smallest letter size (CSS px); with smaller rows the profile is drawn
26/// as a histogram.
27pub const TPO_MIN_FONT: f32 = 7.0;
28
29/// The letter of period `k` of a session: A–Z, then a–z, repeating.
30///
31/// # Examples
32///
33/// ```
34/// use ferrochart_orderflow::tpo_letter;
35///
36/// assert_eq!((tpo_letter(0), tpo_letter(25), tpo_letter(26), tpo_letter(52)), ('A', 'Z', 'a', 'A'));
37/// ```
38pub fn tpo_letter(k: u16) -> char {
39    let k = (k % 52) as u8;
40    char::from(if k < 26 { b'A' + k } else { b'a' + k - 26 })
41}
42
43/// Colors of a TPO profile.
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub struct TpoColors {
46    /// Letters (dimmed outside the value area).
47    pub letters: Rgba,
48    /// Histogram bars (dimmed outside the value area).
49    pub profile: Rgba,
50    /// Point of control: background of its letters, or its bar.
51    pub poc: Rgba,
52    /// The initial balance bar on the profile's left edge.
53    pub initial_balance: Rgba,
54}
55
56impl TpoColors {
57    /// Colors matching `theme`.
58    pub fn from_theme(theme: &Theme) -> Self {
59        Self {
60            letters: theme.text,
61            profile: theme.line,
62            poc: theme.down,
63            initial_balance: theme.up,
64        }
65    }
66}
67
68/// Options of a [`Tpo`].
69#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct TpoOptions {
71    /// Minimum price increment.
72    pub tick_size: f64,
73    /// Ticks per row.
74    pub row_size: u32,
75    /// Period length, ms (one letter each).
76    pub period_ms: i64,
77    /// Session length, ms (at most a day). A session starts every UTC day
78    /// at `session_offset_ms`; bars outside the sessions are skipped.
79    pub session_ms: i64,
80    /// Start of the sessions after UTC midnight, e.g. 14 h 30 min for
81    /// 9:30–16:00 New York (winter time).
82    pub session_offset_ms: i64,
83    /// Share of the TPOs in the value area, in (0, 1].
84    pub value_area: f64,
85    /// Colors.
86    pub colors: TpoColors,
87}
88
89impl TpoOptions {
90    /// One tick per row, 30 min periods, UTC days, a 70% value area,
91    /// colors from `theme`.
92    pub fn new(tick_size: f64, theme: &Theme) -> Self {
93        Self {
94            tick_size,
95            row_size: 1,
96            period_ms: 30 * 60_000,
97            session_ms: 24 * 3_600_000,
98            session_offset_ms: 0,
99            value_area: 0.7,
100            colors: TpoColors::from_theme(theme),
101        }
102    }
103}
104
105/// The profile of one session, in levels (see [`PriceLevels`]).
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
107pub struct SessionProfile {
108    /// Lowest and highest level traded.
109    pub low: i32,
110    /// Highest level traded.
111    pub high: i32,
112    /// Point of control: the level with the most TPOs.
113    pub poc: i32,
114    /// TPOs at the point of control (the most at any level).
115    pub max_count: u32,
116    /// TPOs of the session.
117    pub tpos: u32,
118    /// Value area, lowest and highest level.
119    pub value_area: (i32, i32),
120    /// Range of the first two periods; `None` if neither traded.
121    pub initial_balance: Option<(i32, i32)>,
122}
123
124/// A TPO series: add it with
125/// [`Chart::add_custom_series`](ferrochart_core::Chart::add_custom_series)
126/// and feed it with [`crate::append_bars`].
127///
128/// Each session takes one slot (`AxisMode::Slots`, at the session start).
129/// A profile needs a wide slot: raise `ChartOptions::max_bar_spacing` (50
130/// CSS px by default). When the letters of the drawn sessions do not all
131/// fit, the profiles are drawn as histograms of TPO counts.
132///
133/// # Examples
134///
135/// ```
136/// use ferrochart_core::chart::SeriesOptions;
137/// use ferrochart_core::data::OhlcColumns;
138/// use ferrochart_core::theme::Theme;
139/// use ferrochart_core::{Chart, ChartOptions};
140/// use ferrochart_orderflow::{Tpo, TpoOptions, append_bars};
141///
142/// let mut chart = Chart::new(ChartOptions::default());
143/// let tpo = Tpo::new(TpoOptions::new(1.0, &Theme::light()))?;
144/// let id = chart.add_custom_series(chart.main_pane(), Box::new(tpo), SeriesOptions::default())?;
145/// // Three 30 min bars: periods A, B and C of the first UTC day.
146/// let bars = OhlcColumns {
147///     time: vec![0, 1_800_000, 3_600_000],
148///     open: vec![10.0, 12.0, 11.0],
149///     high: vec![12.0, 13.0, 12.0],
150///     low: vec![10.0, 11.0, 11.0],
151///     close: vec![12.0, 11.0, 12.0],
152///     volume: None,
153/// };
154/// append_bars(&mut chart, id, &bars)?;
155/// let p = chart.custom_series::<Tpo>(id).unwrap().profile(0).unwrap();
156/// // 11 and 12 have 3 TPOs each, equally near the middle: the lower wins.
157/// assert_eq!((p.low, p.high, p.poc, p.max_count, p.tpos), (10, 13, 11, 3, 8));
158/// assert_eq!(p.initial_balance, Some((10, 13)));
159/// # Ok::<(), ferrochart_core::Error>(())
160/// ```
161#[derive(Debug)]
162pub struct Tpo {
163    opts: TpoOptions,
164    levels: PriceLevels,
165    /// Session start times.
166    sessions: Vec<Timestamp>,
167    /// Offset of each session's first period in `period`/`lo`/`hi`.
168    sess_start: Vec<u32>,
169    /// Period number within its session, ascending per session.
170    period: Vec<u16>,
171    lo: Vec<i32>,
172    hi: Vec<i32>,
173    profiles: Vec<SessionProfile>,
174    extremes: MinMaxIndex,
175    /// Difference array for the profile of the last session.
176    counts: Vec<i32>,
177    /// Per-level letter counters while drawing.
178    scratch: RefCell<Vec<u32>>,
179}
180
181fn reserve<T>(v: &mut Vec<T>) -> Result<()> {
182    v.try_reserve(1).map_err(|_| Error::OutOfMemory)
183}
184
185impl Tpo {
186    /// An empty TPO series.
187    ///
188    /// # Errors
189    ///
190    /// [`Error::InvalidArgument`] for a bad price grid, a non-positive
191    /// period, a session shorter than a period, longer than a day or than
192    /// 65 535 periods, or a value area outside (0, 1].
193    pub fn new(opts: TpoOptions) -> Result<Self> {
194        let levels = PriceLevels::new(opts.tick_size, opts.row_size)?;
195        if opts.period_ms <= 0
196            || opts.session_ms < opts.period_ms
197            || opts.session_ms > DAY
198            || opts.session_ms / opts.period_ms > i64::from(u16::MAX)
199        {
200            return Err(Error::InvalidArgument(
201                "period_ms must be positive and session_ms one period to one day",
202            ));
203        }
204        if !(opts.value_area > 0.0 && opts.value_area <= 1.0) {
205            return Err(Error::InvalidArgument("value_area must be in (0, 1]"));
206        }
207        Ok(Self {
208            opts,
209            levels,
210            sessions: Vec::new(),
211            sess_start: Vec::new(),
212            period: Vec::new(),
213            lo: Vec::new(),
214            hi: Vec::new(),
215            profiles: Vec::new(),
216            extremes: MinMaxIndex::new(),
217            counts: Vec::new(),
218            scratch: RefCell::new(Vec::new()),
219        })
220    }
221
222    /// The options.
223    pub fn options(&self) -> &TpoOptions {
224        &self.opts
225    }
226
227    /// Changes the colors.
228    pub fn set_colors(&mut self, colors: TpoColors) {
229        self.opts.colors = colors;
230    }
231
232    /// The price grid.
233    pub fn price_levels(&self) -> PriceLevels {
234        self.levels
235    }
236
237    /// Session start times.
238    pub fn sessions(&self) -> &[Timestamp] {
239        &self.sessions
240    }
241
242    /// The profile of session `i`.
243    pub fn profile(&self, i: usize) -> Option<SessionProfile> {
244        self.profiles.get(i).copied()
245    }
246
247    fn bounds(&self, i: usize) -> (usize, usize) {
248        let s = self.sess_start[i] as usize;
249        let e = self
250            .sess_start
251            .get(i + 1)
252            .map_or(self.period.len(), |&x| x as usize);
253        (s, e)
254    }
255
256    /// The traded periods of session `i`: period numbers (ascending) and
257    /// their lowest and highest levels.
258    pub fn periods(&self, i: usize) -> Option<(&[u16], &[i32], &[i32])> {
259        if i >= self.sessions.len() {
260            return None;
261        }
262        let (s, e) = self.bounds(i);
263        Some((&self.period[s..e], &self.lo[s..e], &self.hi[s..e]))
264    }
265
266    /// Start of the last session starting at or before `time` (it contains
267    /// `time` if [`Self::in_session`]).
268    pub fn session_start(&self, time: Timestamp) -> Timestamp {
269        let o = self.opts.session_offset_ms;
270        crate::column_start(time.saturating_sub(o), DAY).saturating_add(o)
271    }
272
273    /// Whether `time` falls in a session.
274    pub fn in_session(&self, time: Timestamp) -> bool {
275        time - self.session_start(time) < self.opts.session_ms
276    }
277
278    /// The session of the last bar, if any.
279    pub(crate) fn last_session(&self) -> Option<Timestamp> {
280        self.sessions.last().copied()
281    }
282
283    /// Adds a bar (its period is the one containing `time`; bars must be no
284    /// longer than a period); returns whether it opened a session. A bar
285    /// again at a time already seen (an update of a live bar) widens its
286    /// period's range. A bar outside the sessions is skipped.
287    ///
288    /// # Errors
289    ///
290    /// [`Error::InvalidArgument`] for non-finite prices, `high < low` or
291    /// prices outside the level range; [`Error::TimeNotIncreasing`] if its
292    /// session is before the last one; [`Error::OutOfMemory`].
293    pub fn push_bar(&mut self, time: Timestamp, high: f64, low: f64) -> Result<bool> {
294        let opened = self.push_raw(time, high, low)?;
295        self.finish_last();
296        Ok(opened)
297    }
298
299    /// [`Self::push_bar`] without updating the last session's profile
300    /// (batches call [`Self::finish_last`] once at the end).
301    pub(crate) fn push_raw(&mut self, time: Timestamp, high: f64, low: f64) -> Result<bool> {
302        let (Some(l), Some(h)) = (self.levels.level(low), self.levels.level(high)) else {
303            return Err(Error::InvalidArgument(
304                "bar prices must be finite and in range",
305            ));
306        };
307        if high < low {
308            return Err(Error::InvalidArgument("bar high must not be below low"));
309        }
310        let sess = self.session_start(time);
311        if !self.in_session(time) {
312            return match self.sessions.last() {
313                Some(&last) if sess < last => Err(Error::TimeNotIncreasing {
314                    index: self.sessions.len(),
315                }),
316                _ => Ok(false),
317            };
318        }
319        let opened = match self.sessions.last() {
320            Some(&last) if sess < last => {
321                return Err(Error::TimeNotIncreasing {
322                    index: self.sessions.len(),
323                });
324            }
325            Some(&last) if sess == last => false,
326            _ => true,
327        };
328        let k = u16::try_from((time - sess) / self.opts.period_ms).unwrap_or(u16::MAX);
329        if opened {
330            let start = u32::try_from(self.period.len()).map_err(|_| Error::OutOfMemory)?;
331            reserve(&mut self.sessions)?;
332            reserve(&mut self.sess_start)?;
333            reserve(&mut self.profiles)?;
334            reserve(&mut self.period)?;
335            reserve(&mut self.lo)?;
336            reserve(&mut self.hi)?;
337            if !self.sessions.is_empty() {
338                self.finish_last();
339            }
340            let (lo, hi) = (self.levels.edges(l).0, self.levels.edges(h).1);
341            self.extremes.push(lo, hi)?;
342            self.sessions.push(sess);
343            self.sess_start.push(start);
344            self.profiles.push(SessionProfile::default());
345            self.period.push(k);
346            self.lo.push(l);
347            self.hi.push(h);
348            return Ok(true);
349        }
350        let (s, e) = self.bounds(self.sessions.len() - 1);
351        match self.period[s..e].binary_search(&k) {
352            Ok(j) => {
353                let j = s + j;
354                self.lo[j] = self.lo[j].min(l);
355                self.hi[j] = self.hi[j].max(h);
356            }
357            Err(j) => {
358                reserve(&mut self.period)?;
359                reserve(&mut self.lo)?;
360                reserve(&mut self.hi)?;
361                self.period.insert(s + j, k);
362                self.lo.insert(s + j, l);
363                self.hi.insert(s + j, h);
364            }
365        }
366        Ok(false)
367    }
368
369    /// Recomputes the last session's profile and range.
370    pub(crate) fn finish_last(&mut self) {
371        let Some(i) = self.sessions.len().checked_sub(1) else {
372            return;
373        };
374        let (s, e) = self.bounds(i);
375        let (lo, hi) = (&self.lo[s..e], &self.hi[s..e]);
376        let (Some(&low), Some(&high)) = (lo.iter().min(), hi.iter().max()) else {
377            return;
378        };
379        let n = (i64::from(high) - i64::from(low) + 1) as usize;
380        // TPO counts per level by a difference array: O(periods + levels).
381        self.counts.clear();
382        if self.counts.try_reserve(n + 1).is_err() {
383            return;
384        }
385        self.counts.resize(n + 1, 0);
386        for (&a, &b) in lo.iter().zip(hi) {
387            self.counts[(a - low) as usize] += 1;
388            self.counts[(b - low) as usize + 1] -= 1;
389        }
390        let mut run = 0;
391        for c in &mut self.counts[..n] {
392            run += *c;
393            *c = run;
394        }
395        let counts = &self.counts[..n];
396        let tpos: u32 = counts.iter().map(|&c| c as u32).sum();
397        // POC: most TPOs; ties: nearest the middle of the range, then lower.
398        let mid2 = i64::from(low) + i64::from(high);
399        let mut poc = 0;
400        for (j, &c) in counts.iter().enumerate() {
401            let dist = |k: usize| (2 * (i64::from(low) + k as i64) - mid2).abs();
402            if c > counts[poc] || (c == counts[poc] && dist(j) < dist(poc)) {
403                poc = j;
404            }
405        }
406        // Value area (CBOT): from the POC, add the two rows above or the two
407        // below, whichever have more TPOs (above on a tie), until it holds
408        // `value_area` of the TPOs.
409        let target = (self.opts.value_area * f64::from(tpos)).ceil() as u32;
410        let (mut va_lo, mut va_hi) = (poc, poc);
411        let mut acc = counts[poc] as u32;
412        while acc < target {
413            let up: Vec2 = (1..=2)
414                .filter_map(|d| counts.get(va_hi + d).copied())
415                .fold((0, 0), add);
416            let down: Vec2 = (1..=2)
417                .filter_map(|d| va_lo.checked_sub(d).map(|k| counts[k]))
418                .fold((0, 0), add);
419            match (up.1, down.1) {
420                (0, 0) => break,
421                (u, d) if u > 0 && (d == 0 || up.0 >= down.0) => {
422                    va_hi += u;
423                    acc += up.0 as u32;
424                }
425                (_, d) => {
426                    va_lo -= d;
427                    acc += down.0 as u32;
428                }
429            }
430        }
431        let periods = &self.period[s..e];
432        let ib = periods
433            .iter()
434            .zip(lo.iter().zip(hi))
435            .filter(|(k, _)| **k < 2)
436            .fold(None, |acc: Option<(i32, i32)>, (_, (&a, &b))| {
437                Some(acc.map_or((a, b), |(x, y)| (x.min(a), y.max(b))))
438            });
439        let at = |k: usize| low + k as i32;
440        self.profiles[i] = SessionProfile {
441            low,
442            high,
443            poc: at(poc),
444            max_count: counts[poc] as u32,
445            tpos,
446            value_area: (at(va_lo), at(va_hi)),
447            initial_balance: ib,
448        };
449        self.extremes
450            .set_last(self.levels.edges(low).0, self.levels.edges(high).1);
451    }
452}
453
454/// (TPOs, rows).
455type Vec2 = (i32, usize);
456
457fn add(a: Vec2, c: i32) -> Vec2 {
458    (a.0 + c, a.1 + 1)
459}
460
461/// Checks bar columns for [`crate::append_bars`].
462pub(crate) fn check_bars(bars: &OhlcColumns, levels: PriceLevels) -> Result<()> {
463    let n = bars.time.len();
464    if bars.high.len() != n || bars.low.len() != n {
465        return Err(Error::InvalidArgument(
466            "bar time, high and low must have the same length",
467        ));
468    }
469    if let Some(i) = bars.time.windows(2).position(|w| w[1] < w[0]) {
470        return Err(Error::TimeNotIncreasing { index: i + 1 });
471    }
472    let bad = |p: f64| levels.level(p).is_none();
473    if bars
474        .high
475        .iter()
476        .zip(&bars.low)
477        .any(|(&h, &l)| bad(h) || bad(l) || h < l)
478    {
479        return Err(Error::InvalidArgument(
480            "bar prices must be finite, in range and high >= low",
481        ));
482    }
483    Ok(())
484}
485
486impl CustomSeries for Tpo {
487    fn kind(&self) -> &'static str {
488        TPO_KIND
489    }
490
491    fn axis_mode(&self) -> AxisMode {
492        AxisMode::Slots
493    }
494
495    fn times(&self) -> &[Timestamp] {
496        &self.sessions
497    }
498
499    fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
500        self.extremes.query(from, to)
501    }
502
503    fn crosshair_value(&self, point: usize) -> Option<f64> {
504        self.profiles.get(point).map(|p| self.levels.price(p.poc))
505    }
506
507    #[allow(clippy::too_many_lines)]
508    fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
509        let c = ctx.coords();
510        let dpr = c.dpr();
511        let spacing = ctx.bar_spacing().0;
512        if spacing < TPO_MIN_SPACING * dpr {
513            return;
514        }
515        let Ok(mut scratch) = self.scratch.try_borrow_mut() else {
516            return;
517        };
518        let o = &self.opts;
519        let w = (spacing * 0.9).round().max(1.0);
520        let ibw = (2.0 * dpr).round().max(1.0);
521        let gap = (2.0 * dpr).round();
522        let avail = w - ibw - gap;
523        if avail < 1.0 {
524            return;
525        }
526        let plot = c.plot();
527        let (pa, pb) = (c.price_at(plot.y), c.price_at(plot.y + plot.h));
528        let (Some(vis_lo), Some(vis_hi)) =
529            (self.levels.level(pa.min(pb)), self.levels.level(pa.max(pb)))
530        else {
531            return;
532        };
533        let (vis_lo, vis_hi) = (vis_lo.saturating_sub(1), vis_hi.saturating_add(1));
534        // Rows of a level: its rounded edges.
535        let rows = |l: i32| {
536            let (a, b) = self.levels.edges(l);
537            let (y1, y2) = (c.y_of(b)?, c.y_of(a)?);
538            let (top, bottom) = (y1.min(y2).round(), y1.max(y2).round());
539            Some((top, bottom - top))
540        };
541        let dim = |color: Rgba, k: f32| color.with_alpha((f32::from(color.a) * k).round() as u8);
542        // Letters or histograms for the whole frame: letters when the most
543        // TPOs at any level of the drawn sessions fit in a slot at a
544        // readable size (rows are as high as the first POC's).
545        let drawn = || self.profiles.get(from..to).unwrap_or(&[]).iter();
546        let max_count = drawn().map(|p| p.max_count).max().unwrap_or(0);
547        let row_h = drawn()
548            .find(|p| p.max_count > 0)
549            .and_then(|p| rows(p.poc))
550            .map_or(0.0, |(_, h)| h);
551        let font_css = 11.0_f32.min(row_h / dpr * 0.85);
552        let font = c.font(Css(font_css));
553        let cell = c.text_width("M", font).round().max(1.0);
554        let letters = font_css >= TPO_MIN_FONT && max_count as f32 * cell <= avail;
555        for i in from..to {
556            let (Some(p), Some(xc)) = (self.profiles.get(i).copied(), ctx.x_of_point(i)) else {
557                continue;
558            };
559            let (lo, hi) = (p.low.max(vis_lo), p.high.min(vis_hi));
560            if lo > hi || p.max_count == 0 {
561                continue;
562            }
563            let x0 = (xc - w / 2.0).round();
564            let cx = x0 + ibw + gap;
565            if let Some((a, b)) = p.initial_balance
566                && let (Some((top, _)), Some((t2, h2))) = (rows(b.min(vis_hi)), rows(a.max(vis_lo)))
567                && a.max(vis_lo) <= b.min(vis_hi)
568            {
569                let rect = RectPx {
570                    x: x0,
571                    y: top,
572                    w: ibw,
573                    h: t2 + h2 - top,
574                };
575                out.rect(rect, o.colors.initial_balance);
576            }
577            // Per-level TPO counters (visible levels only: a letter's place
578            // depends on the earlier periods at its level).
579            scratch.clear();
580            scratch.resize((hi - lo + 1) as usize, 0);
581            let Some((ks, plo, phi)) = self.periods(i) else {
582                continue;
583            };
584            if letters {
585                if p.poc >= lo
586                    && p.poc <= hi
587                    && let Some((top, h)) = rows(p.poc)
588                {
589                    let rect = RectPx {
590                        x: cx,
591                        y: top,
592                        w: p.max_count as f32 * cell,
593                        h,
594                    };
595                    out.rect(rect, dim(o.colors.poc, 0.35));
596                }
597                for ((&k, &a), &b) in ks.iter().zip(plo).zip(phi) {
598                    for l in a.max(lo)..=b.min(hi) {
599                        let n = &mut scratch[(l - lo) as usize];
600                        let x = cx + *n as f32 * cell;
601                        *n += 1;
602                        let Some((top, h)) = rows(l) else {
603                            continue;
604                        };
605                        if h < 1.0 {
606                            continue;
607                        }
608                        let in_va = l >= p.value_area.0 && l <= p.value_area.1;
609                        let color = if in_va {
610                            o.colors.letters
611                        } else {
612                            dim(o.colors.letters, 0.45)
613                        };
614                        out.text_fmt(
615                            PointPx {
616                                x,
617                                y: top + h / 2.0,
618                            },
619                            format_args!("{}", tpo_letter(k)),
620                            Label {
621                                font,
622                                color,
623                                align: TextAlign::Left,
624                                bg: None,
625                            },
626                        );
627                    }
628                }
629            } else {
630                for (&a, &b) in plo.iter().zip(phi) {
631                    for l in a.max(lo)..=b.min(hi) {
632                        scratch[(l - lo) as usize] += 1;
633                    }
634                }
635                let px1 = dpr.round().max(1.0);
636                for l in lo..=hi {
637                    let n = scratch[(l - lo) as usize];
638                    let Some((top, h)) = rows(l) else {
639                        continue;
640                    };
641                    if n == 0 || h < 1.0 {
642                        continue;
643                    }
644                    let bh = if h >= 4.0 { h - px1 } else { h };
645                    let bw = (n as f32 / p.max_count as f32 * avail).round().max(1.0);
646                    let color = if l == p.poc {
647                        o.colors.poc
648                    } else if l >= p.value_area.0 && l <= p.value_area.1 {
649                        dim(o.colors.profile, 0.7)
650                    } else {
651                        dim(o.colors.profile, 0.3)
652                    };
653                    out.rect(
654                        RectPx {
655                            x: cx,
656                            y: top,
657                            w: bw,
658                            h: bh,
659                        },
660                        color,
661                    );
662                }
663            }
664        }
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    #![allow(clippy::unwrap_used)]
671
672    use super::*;
673
674    fn tpo() -> Tpo {
675        Tpo::new(TpoOptions::new(1.0, &Theme::dark())).unwrap()
676    }
677
678    const P: i64 = 1_800_000;
679
680    #[test]
681    fn profile_value_area_and_initial_balance() {
682        let mut t = tpo();
683        // Periods: A 10–14, B 12–13, C 11–12, D 12–12, E 20–20.
684        for (k, lo, hi) in [
685            (0, 10.0, 14.0),
686            (1, 12.0, 13.0),
687            (2, 11.0, 12.0),
688            (3, 12.0, 12.0),
689            (4, 20.0, 20.0),
690        ] {
691            t.push_bar(k * P, hi, lo).unwrap();
692        }
693        let p = t.profile(0).unwrap();
694        // Counts: 10:1 11:2 12:4 13:2 14:1 20:1; total 11, target 8.
695        assert_eq!(
696            (p.low, p.high, p.poc, p.max_count, p.tpos),
697            (10, 20, 12, 4, 11)
698        );
699        // From 12 (4): above 13+14 = 3, below 11+10 = 3: above → 7; then
700        // above 15+16 = 0 < below 3 → 10–14.
701        assert_eq!(p.value_area, (10, 14));
702        assert_eq!(p.initial_balance, Some((10, 14)));
703        // A live update widens its period; a new day opens a session.
704        assert!(!t.push_bar(4 * P + 60_000, 21.0, 20.0).unwrap());
705        assert_eq!(t.periods(0).unwrap().2[4], 21);
706        assert!(t.push_bar(48 * P, 5.0, 5.0).unwrap());
707        assert_eq!(t.sessions(), &[0, 86_400_000]);
708        assert_eq!(t.profile(1).unwrap().initial_balance, Some((5, 5)));
709        assert!(matches!(
710            t.push_bar(0, 1.0, 1.0),
711            Err(Error::TimeNotIncreasing { .. })
712        ));
713        assert!(t.push_bar(48 * P, 1.0, 2.0).is_err());
714        assert!(t.push_bar(48 * P, f64::NAN, 2.0).is_err());
715    }
716
717    #[test]
718    fn poc_ties_go_to_the_middle() {
719        let mut t = tpo();
720        // Counts 1: 10, 11, 12 (and 13 by B): 10–13 → middle 11.5; 11 and 12
721        // are equally near; the lower wins.
722        t.push_bar(0, 12.0, 10.0).unwrap();
723        t.push_bar(P, 13.0, 13.0).unwrap();
724        assert_eq!(t.profile(0).unwrap().poc, 11);
725        // No initial balance when the first two periods did not trade.
726        let mut u = tpo();
727        u.push_bar(3 * P, 2.0, 1.0).unwrap();
728        assert_eq!(u.profile(0).unwrap().initial_balance, None);
729    }
730
731    #[test]
732    fn options_and_sessions() {
733        let theme = Theme::dark();
734        let mut o = TpoOptions::new(1.0, &theme);
735        o.session_ms = o.period_ms - 1;
736        assert!(Tpo::new(o).is_err());
737        o.session_ms = DAY + 1;
738        assert!(Tpo::new(o).is_err());
739        o.session_ms = 6 * 3_600_000 + 1_800_000;
740        o.value_area = 0.0;
741        assert!(Tpo::new(o).is_err());
742        o.value_area = 1.0;
743        o.session_offset_ms = 14 * 3_600_000 + 1_800_000;
744        let mut t = Tpo::new(o).unwrap();
745        let open = o.session_offset_ms;
746        assert_eq!(t.session_start(open + 5), open);
747        assert_eq!(t.session_start(0), open - DAY);
748        assert!(t.in_session(open) && !t.in_session(open + o.session_ms) && !t.in_session(0));
749        // Bars outside the session are skipped; periods count from the open.
750        assert!(!t.push_bar(open - 60_000, 2.0, 1.0).unwrap());
751        assert!(t.sessions().is_empty());
752        assert!(t.push_bar(open + P + 5, 2.0, 1.0).unwrap());
753        assert!(!t.push_bar(open + o.session_ms, 9.0, 1.0).unwrap());
754        assert_eq!(t.periods(0).unwrap(), (&[1_u16][..], &[1][..], &[2][..]));
755        assert_eq!(tpo_letter(51), 'z');
756    }
757}