Skip to main content

weirdnet_chart/
series.rs

1//! The series model: time-ordered ring buffers of points or candles, live updates and downsampling.
2
3use std::collections::VecDeque;
4use std::fmt;
5
6use crate::time::Timestamp;
7
8/// A single value at a time, for line, area and bar series.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct Point {
11    /// When.
12    pub time: Timestamp,
13    /// The value.
14    pub value: f64,
15}
16
17impl Point {
18    /// A point at `time` with `value`.
19    pub const fn new(time: Timestamp, value: f64) -> Point {
20        Point { time, value }
21    }
22}
23
24/// An OHLC bar with volume. `time` is the start of the bar's interval.
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct Candle {
27    /// Start of the interval.
28    pub time: Timestamp,
29    /// First price.
30    pub open: f64,
31    /// Highest price.
32    pub high: f64,
33    /// Lowest price.
34    pub low: f64,
35    /// Last price.
36    pub close: f64,
37    /// Traded volume.
38    pub volume: f64,
39}
40
41impl Candle {
42    /// A candle from its parts.
43    pub const fn new(time: Timestamp, open: f64, high: f64, low: f64, close: f64, volume: f64) -> Candle {
44        Candle { time, open, high, low, close, volume }
45    }
46
47    /// A candle opened by a single trade.
48    pub const fn from_trade(time: Timestamp, price: f64, size: f64) -> Candle {
49        Candle { time, open: price, high: price, low: price, close: price, volume: size }
50    }
51
52    /// Whether the close is at or above the open.
53    pub fn is_up(&self) -> bool {
54        self.close >= self.open
55    }
56
57    /// Folds a later trade into this candle.
58    pub fn apply_trade(&mut self, price: f64, size: f64) {
59        self.high = self.high.max(price);
60        self.low = self.low.min(price);
61        self.close = price;
62        self.volume += size;
63    }
64
65    /// Folds a later candle into this one (used when aggregating).
66    pub fn merge(&mut self, later: &Candle) {
67        self.high = self.high.max(later.high);
68        self.low = self.low.min(later.low);
69        self.close = later.close;
70        self.volume += later.volume;
71    }
72}
73
74/// Anything a [`Series`] can hold: it has a time and a value extent.
75pub trait Sample: Copy {
76    /// When the sample happened.
77    fn time(&self) -> Timestamp;
78    /// The lowest and highest value it covers.
79    fn extent(&self) -> (f64, f64);
80}
81
82impl Sample for Point {
83    fn time(&self) -> Timestamp {
84        self.time
85    }
86    fn extent(&self) -> (f64, f64) {
87        (self.value, self.value)
88    }
89}
90
91impl Sample for Candle {
92    fn time(&self) -> Timestamp {
93        self.time
94    }
95    fn extent(&self) -> (f64, f64) {
96        (self.low, self.high)
97    }
98}
99
100/// What a push did.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub enum Change {
103    /// A new sample was appended.
104    Appended,
105    /// A new sample was appended and the oldest one dropped to stay within capacity.
106    AppendedEvicted,
107    /// The newest sample had the same time and was replaced (a live update).
108    Replaced,
109}
110
111/// A push older than the newest sample.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub struct OutOfOrder {
114    /// The rejected sample's time.
115    pub time: Timestamp,
116    /// The newest time already in the series.
117    pub latest: Timestamp,
118}
119
120impl fmt::Display for OutOfOrder {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(f, "sample at {} is older than the newest sample at {}", self.time, self.latest)
123    }
124}
125
126impl std::error::Error for OutOfOrder {}
127
128/// A bounded, time-ordered ring buffer of samples.
129///
130/// Appending is O(1), the oldest samples drop off once `capacity` is reached, and range
131/// lookups are binary searches. A push with the same time as the newest sample replaces it,
132/// which is how a live candle or price updates in place.
133#[derive(Clone, Debug)]
134pub struct Series<T> {
135    samples: VecDeque<T>,
136    capacity: usize,
137    revision: u64,
138}
139
140impl<T: Sample> Series<T> {
141    /// An empty series holding at most `capacity` samples (at least one).
142    pub fn with_capacity(capacity: usize) -> Series<T> {
143        let capacity = capacity.max(1);
144        Series { samples: VecDeque::with_capacity(capacity.min(4096)), capacity, revision: 0 }
145    }
146
147    /// The maximum number of samples kept.
148    pub fn capacity(&self) -> usize {
149        self.capacity
150    }
151
152    /// Changes the capacity, dropping the oldest samples if needed.
153    pub fn set_capacity(&mut self, capacity: usize) {
154        self.capacity = capacity.max(1);
155        while self.samples.len() > self.capacity {
156            self.samples.pop_front();
157        }
158        self.revision += 1;
159    }
160
161    /// The number of samples.
162    pub fn len(&self) -> usize {
163        self.samples.len()
164    }
165
166    /// Whether there are no samples.
167    pub fn is_empty(&self) -> bool {
168        self.samples.is_empty()
169    }
170
171    /// Bumped on every change; compare it to skip work when nothing changed.
172    pub fn revision(&self) -> u64 {
173        self.revision
174    }
175
176    /// Appends `sample`, or replaces the newest one if it has the same time.
177    pub fn push(&mut self, sample: T) -> Result<Change, OutOfOrder> {
178        let change = match self.samples.back_mut() {
179            Some(last) if last.time() == sample.time() => {
180                *last = sample;
181                Change::Replaced
182            }
183            Some(last) if last.time() > sample.time() => return Err(OutOfOrder { time: sample.time(), latest: last.time() }),
184            _ => {
185                let evicted = self.samples.len() >= self.capacity;
186                if evicted {
187                    self.samples.pop_front();
188                }
189                self.samples.push_back(sample);
190                if evicted { Change::AppendedEvicted } else { Change::Appended }
191            }
192        };
193        self.revision += 1;
194        Ok(change)
195    }
196
197    /// Pushes every sample in order, stopping at the first out-of-order one.
198    pub fn extend<I: IntoIterator<Item = T>>(&mut self, samples: I) -> Result<(), OutOfOrder> {
199        for s in samples {
200            self.push(s)?;
201        }
202        Ok(())
203    }
204
205    /// Replaces the contents with `samples`, which are sorted by time first (history loads).
206    /// Later duplicates of a time win.
207    pub fn replace_all(&mut self, samples: Vec<T>) {
208        let mut samples = samples;
209        samples.sort_by_key(|s| s.time());
210        self.samples.clear();
211        for s in samples {
212            match self.samples.back_mut() {
213                Some(last) if last.time() == s.time() => *last = s,
214                _ => self.samples.push_back(s),
215            }
216        }
217        while self.samples.len() > self.capacity {
218            self.samples.pop_front();
219        }
220        self.revision += 1;
221    }
222
223    /// Edits the newest sample in place (its time must not change).
224    pub fn update_last(&mut self, f: impl FnOnce(&mut T)) -> bool {
225        let Some(last) = self.samples.back_mut() else { return false };
226        let time = last.time();
227        f(last);
228        debug_assert_eq!(time, last.time(), "update_last must not change the time");
229        self.revision += 1;
230        true
231    }
232
233    /// Removes every sample.
234    pub fn clear(&mut self) {
235        self.samples.clear();
236        self.revision += 1;
237    }
238
239    /// The oldest sample.
240    pub fn first(&self) -> Option<&T> {
241        self.samples.front()
242    }
243
244    /// The newest sample.
245    pub fn last(&self) -> Option<&T> {
246        self.samples.back()
247    }
248
249    /// Every sample, oldest first.
250    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + ExactSizeIterator {
251        self.samples.iter()
252    }
253
254    /// The sample at `index` (0 is the oldest).
255    pub fn get(&self, index: usize) -> Option<&T> {
256        self.samples.get(index)
257    }
258
259    /// The index range of samples with `start <= time <= end`.
260    pub fn index_range(&self, start: Timestamp, end: Timestamp) -> std::ops::Range<usize> {
261        let a = self.samples.partition_point(|s| s.time() < start);
262        let b = self.samples.partition_point(|s| s.time() <= end);
263        a..b.max(a)
264    }
265
266    /// Samples with `start <= time <= end`, oldest first.
267    pub fn range(&self, start: Timestamp, end: Timestamp) -> impl DoubleEndedIterator<Item = &T> + ExactSizeIterator {
268        self.samples.range(self.index_range(start, end))
269    }
270
271    /// Like [`range`](Self::range) plus one sample on each side when there is one, so lines
272    /// run to the edges of a viewport.
273    pub fn range_padded(&self, start: Timestamp, end: Timestamp) -> impl DoubleEndedIterator<Item = &T> + ExactSizeIterator {
274        let r = self.index_range(start, end);
275        let a = r.start.saturating_sub(1);
276        let b = (r.end + 1).min(self.samples.len());
277        self.samples.range(a..b)
278    }
279
280    /// The lowest and highest value among samples in `[start, end]`, ignoring non-finite values.
281    pub fn extent(&self, start: Timestamp, end: Timestamp) -> Option<(f64, f64)> {
282        fold_extent(self.range(start, end).map(Sample::extent))
283    }
284
285    /// The typical spacing between samples: the median of the last (up to) 64 gaps.
286    pub fn interval(&self) -> Option<i64> {
287        let n = self.samples.len();
288        if n < 2 {
289            return None;
290        }
291        let from = n.saturating_sub(65);
292        let mut gaps: Vec<i64> = (from + 1..n).map(|i| self.samples[i].time() - self.samples[i - 1].time()).filter(|g| *g > 0).collect();
293        if gaps.is_empty() {
294            return None;
295        }
296        gaps.sort_unstable();
297        Some(gaps[gaps.len() / 2])
298    }
299}
300
301impl Series<Candle> {
302    /// Folds a trade into the candle for `interval_ms`-long bars starting at multiples of the
303    /// interval: it updates the open candle or starts the next one.
304    pub fn apply_trade(&mut self, time: Timestamp, price: f64, size: f64, interval_ms: i64) -> Result<Change, OutOfOrder> {
305        let interval_ms = interval_ms.max(1);
306        let bucket = time.div_euclid(interval_ms) * interval_ms;
307        match self.samples.back() {
308            Some(last) if last.time == bucket => {
309                self.update_last(|c| c.apply_trade(price, size));
310                Ok(Change::Replaced)
311            }
312            _ => self.push(Candle::from_trade(bucket, price, size)),
313        }
314    }
315}
316
317pub(crate) fn fold_extent(it: impl Iterator<Item = (f64, f64)>) -> Option<(f64, f64)> {
318    let mut out: Option<(f64, f64)> = None;
319    for (lo, hi) in it {
320        if !(lo.is_finite() && hi.is_finite()) {
321            continue;
322        }
323        out = Some(match out {
324            Some((a, b)) => (a.min(lo), b.max(hi)),
325            None => (lo, hi),
326        });
327    }
328    out
329}
330
331/// Reduces points to at most four per bucket (first, lowest, highest, last), keeping every
332/// spike and every gap (non-finite value), for drawing `buckets` columns of a range `[start, end]`.
333///
334/// Points must be in time order. When there are no more points than buckets they are
335/// returned unchanged.
336pub fn downsample_min_max<'a>(points: impl ExactSizeIterator<Item = &'a Point>, start: Timestamp, end: Timestamp, buckets: usize) -> Vec<Point> {
337    if points.len() <= buckets.max(1) * 4 || end <= start {
338        return points.copied().collect();
339    }
340    let buckets = buckets.max(1);
341    let width = (end - start) as f64 / buckets as f64;
342    let bucket_of = |t: Timestamp| (((t - start) as f64 / width).floor().clamp(-1.0, buckets as f64)) as i64;
343    let mut out = Vec::with_capacity(buckets * 4);
344    let mut current: Option<(i64, [Point; 4])> = None;
345    let flush = |out: &mut Vec<Point>, b: [Point; 4]| {
346        let [first, lo, hi, last] = b;
347        let mut mid = [lo, hi];
348        mid.sort_by_key(|p| p.time);
349        for p in [first, mid[0], mid[1], last] {
350            if out.last() != Some(&p) {
351                out.push(p);
352            }
353        }
354    };
355    for p in points {
356        if !p.value.is_finite() {
357            // Keep gaps: a non-finite value ends the bucket and is passed through.
358            if let Some((_, acc)) = current.take() {
359                flush(&mut out, acc);
360            }
361            out.push(*p);
362            continue;
363        }
364        let b = bucket_of(p.time);
365        match &mut current {
366            Some((cb, acc)) if *cb == b => {
367                if p.value < acc[1].value {
368                    acc[1] = *p;
369                }
370                if p.value > acc[2].value {
371                    acc[2] = *p;
372                }
373                acc[3] = *p;
374            }
375            _ => {
376                if let Some((_, acc)) = current.take() {
377                    flush(&mut out, acc);
378                }
379                current = Some((b, [*p; 4]));
380            }
381        }
382    }
383    if let Some((_, acc)) = current {
384        flush(&mut out, acc);
385    }
386    out
387}
388
389/// Merges candles into wider bars so that at most `buckets` remain across `[start, end]`.
390/// Each output bar starts at its first input candle's time. Candles must be in time order.
391pub fn aggregate_candles<'a>(candles: impl ExactSizeIterator<Item = &'a Candle>, start: Timestamp, end: Timestamp, buckets: usize) -> Vec<Candle> {
392    if candles.len() <= buckets.max(1) || end <= start {
393        return candles.copied().collect();
394    }
395    let width = (end - start) as f64 / buckets.max(1) as f64;
396    let mut out: Vec<Candle> = Vec::with_capacity(buckets + 2);
397    let mut current_bucket = i64::MIN;
398    for c in candles {
399        let b = ((c.time - start) as f64 / width).floor() as i64;
400        match out.last_mut() {
401            Some(last) if b == current_bucket => last.merge(c),
402            _ => {
403                out.push(*c);
404                current_bucket = b;
405            }
406        }
407    }
408    out
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414
415    #[test]
416    fn push_replace_evict_and_order() {
417        let mut s = Series::with_capacity(3);
418        assert_eq!(s.push(Point::new(1, 1.0)), Ok(Change::Appended));
419        assert_eq!(s.push(Point::new(1, 2.0)), Ok(Change::Replaced));
420        assert_eq!(s.last().unwrap().value, 2.0);
421        s.push(Point::new(2, 3.0)).unwrap();
422        s.push(Point::new(3, 4.0)).unwrap();
423        assert_eq!(s.push(Point::new(4, 5.0)), Ok(Change::AppendedEvicted));
424        assert_eq!(s.first().unwrap().time, 2);
425        assert_eq!(s.push(Point::new(3, 9.0)), Err(OutOfOrder { time: 3, latest: 4 }));
426        assert_eq!(s.len(), 3);
427        assert_eq!(s.revision(), 5);
428    }
429
430    #[test]
431    fn ranges_and_extent() {
432        let mut s = Series::with_capacity(100);
433        s.extend((0..10).map(|i| Point::new(i * 10, i as f64))).unwrap();
434        let r: Vec<_> = s.range(15, 45).map(|p| p.time).collect();
435        assert_eq!(r, [20, 30, 40]);
436        let p: Vec<_> = s.range_padded(15, 45).map(|p| p.time).collect();
437        assert_eq!(p, [10, 20, 30, 40, 50]);
438        assert_eq!(s.extent(15, 45), Some((2.0, 4.0)));
439        assert_eq!(s.extent(1000, 2000), None);
440        assert_eq!(s.interval(), Some(10));
441        s.push(Point::new(100, f64::NAN)).unwrap();
442        assert_eq!(s.extent(90, 100), Some((9.0, 9.0)));
443    }
444
445    #[test]
446    fn replace_all_sorts_and_dedups() {
447        let mut s = Series::with_capacity(2);
448        s.replace_all(vec![Point::new(3, 3.0), Point::new(1, 1.0), Point::new(3, 4.0), Point::new(2, 2.0)]);
449        let v: Vec<_> = s.iter().map(|p| (p.time, p.value)).collect();
450        assert_eq!(v, [(2, 2.0), (3, 4.0)]);
451    }
452
453    #[test]
454    fn trades_build_candles() {
455        let mut s: Series<Candle> = Series::with_capacity(10);
456        s.apply_trade(1_000, 10.0, 1.0, 60_000).unwrap();
457        s.apply_trade(30_000, 12.0, 2.0, 60_000).unwrap();
458        s.apply_trade(59_999, 9.0, 1.0, 60_000).unwrap();
459        assert_eq!(s.apply_trade(60_000, 11.0, 1.0, 60_000), Ok(Change::Appended));
460        assert_eq!(s.len(), 2);
461        assert_eq!(*s.first().unwrap(), Candle::new(0, 10.0, 12.0, 9.0, 9.0, 4.0));
462        assert!(!s.first().unwrap().is_up());
463    }
464
465    #[test]
466    fn min_max_keeps_spikes() {
467        let pts: Vec<Point> = (0..1000).map(|i| Point::new(i, if i == 517 { 100.0 } else { (i % 7) as f64 })).collect();
468        let out = downsample_min_max(pts.iter(), 0, 1000, 10);
469        assert!(out.len() <= 40);
470        assert!(out.iter().any(|p| p.value == 100.0));
471        assert_eq!(out.first().unwrap().time, 0);
472        assert_eq!(out.last().unwrap().time, 999);
473        assert!(out.windows(2).all(|w| w[0].time <= w[1].time));
474        let few: Vec<Point> = pts[..5].to_vec();
475        assert_eq!(downsample_min_max(few.iter(), 0, 1000, 10), few);
476    }
477
478    #[test]
479    fn candles_aggregate() {
480        let cs: Vec<Candle> = (0..100).map(|i| Candle::new(i * 60, i as f64, i as f64 + 2.0, i as f64 - 1.0, i as f64 + 1.0, 1.0)).collect();
481        let out = aggregate_candles(cs.iter(), 0, 6000, 10);
482        assert_eq!(out.len(), 10);
483        assert_eq!(out[0], Candle::new(0, 0.0, 11.0, -1.0, 10.0, 10.0));
484        let total: f64 = out.iter().map(|c| c.volume).sum();
485        assert_eq!(total, 100.0);
486    }
487}