ferrochart-core 0.3.0

Platform-independent core of the FerroChart financial charting engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Custom series: a plugin that owns its data, gives
//! core its times and range extremes, and writes immediate primitives for the
//! visible points.

use core::any::Any;
use core::fmt;

use crate::data::{ChangeLog, SeriesMapping, TimeIndex, Timestamp};
use crate::drawing::{DrawingCtx, FrameBuilder, index_of_time, time_of_index};
use crate::error::{Error, Result};
use crate::frame::SeriesStyle;
use crate::geom::Px;

/// How a custom series is placed on the time axis.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AxisMode {
    /// Each point's time is a slot of the time axis, like the points of a
    /// built-in series (e.g. footprint columns sharing the candles' slots).
    Slots,
    /// Points are placed between the existing slots by interpolating their
    /// times and add no slots (e.g. 1 s heatmap columns on a 1 min chart).
    Overlay,
}

/// A series that owns its data.
///
/// Core asks it for its times and extremes and lets it draw the visible
/// points; the data is changed through [`crate::Chart::update_custom`], which
/// tells core what changed. Point `i` is element `i` of
/// [`times`](Self::times).
///
/// # Examples
///
/// ```
/// use ferrochart_core::data::{DataChange, Timestamp};
/// use ferrochart_core::drawing::FrameBuilder;
/// use ferrochart_core::geom::RectPx;
/// use ferrochart_core::plugin::{AxisMode, CustomSeries, MinMaxIndex, SeriesCtx};
/// use ferrochart_core::chart::SeriesOptions;
/// use ferrochart_core::testing::MonoMeasurer;
/// use ferrochart_core::{Chart, ChartOptions};
///
/// /// A vertical bar from `lo` to `hi` per point.
/// #[derive(Default)]
/// struct Ranges {
///     time: Vec<Timestamp>,
///     range: Vec<(f64, f64)>,
///     index: MinMaxIndex,
/// }
///
/// impl Ranges {
///     fn push(&mut self, t: Timestamp, lo: f64, hi: f64) -> DataChange {
///         self.time.push(t);
///         self.range.push((lo, hi));
///         let _ = self.index.push(lo, hi);
///         DataChange::Append { count: 1 }
///     }
/// }
///
/// impl CustomSeries for Ranges {
///     fn kind(&self) -> &'static str {
///         "example.ranges"
///     }
///     fn axis_mode(&self) -> AxisMode {
///         AxisMode::Slots
///     }
///     fn times(&self) -> &[Timestamp] {
///         &self.time
///     }
///     fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
///         self.index.query(from, to)
///     }
///     fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
///         let w = (ctx.bar_spacing().0 * 0.6).max(1.0);
///         for i in from..to {
///             let (lo, hi) = self.range[i];
///             let (Some(x), Some(y0), Some(y1)) =
///                 (ctx.x_of_point(i), ctx.coords().y_of(hi), ctx.coords().y_of(lo))
///             else {
///                 continue;
///             };
///             let rect = RectPx { x: x - w / 2.0, y: y0, w, h: (y1 - y0).max(1.0) };
///             out.rect(rect, ctx.style().up);
///         }
///     }
/// }
///
/// let mut chart = Chart::new(ChartOptions::default());
/// let id = chart.add_custom_series(
///     chart.main_pane(),
///     Box::new(Ranges::default()),
///     SeriesOptions::default(),
/// )?;
/// chart.update_custom(id, |r: &mut Ranges| r.push(60_000, 1.0, 2.0))?;
/// chart.update_custom(id, |r: &mut Ranges| r.push(120_000, 1.5, 3.0))?;
/// assert_eq!(chart.custom_series::<Ranges>(id).map(|r| r.time.len()), Some(2));
/// chart.build_frame(0.0, &MonoMeasurer);
/// # Ok::<(), ferrochart_core::Error>(())
/// ```
pub trait CustomSeries: Send + Any {
    /// Kind name, e.g. `"orderflow.heatmap"`; renderers that draw it natively
    /// declare this name.
    fn kind(&self) -> &'static str;
    /// How the points are placed on the time axis; read once, when added.
    fn axis_mode(&self) -> AxisMode;
    /// Times of the points, strictly increasing.
    fn times(&self) -> &[Timestamp];
    /// Price extremes of points `from..to`, for auto scaling. Called every
    /// frame, so it must be O(log n) (see [`crate::plugin::MinMaxIndex`]).
    fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)>;
    /// Portable path: writes the primitives of points `from..to` (the
    /// visible ones and one more on each side). Must not allocate once
    /// warmed up.
    fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>);
    /// Value of the last-value label; `None` hides it.
    fn last_value(&self) -> Option<f64> {
        None
    }
    /// Value of point `point` for the crosshair and magnet.
    fn crosshair_value(&self, point: usize) -> Option<f64> {
        let _ = point;
        None
    }
    /// Parameters of the native GPU path, e.g. a color-scale range.
    fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
        let _ = (ctx, params);
    }
}

/// What a [`CustomSeries`] knows about the chart while it draws.
pub struct SeriesCtx<'a> {
    pub(crate) coords: DrawingCtx<'a>,
    pub(crate) store: &'a CustomStore,
    /// `SeriesOptions::shift` in bars.
    pub(crate) shift: f64,
    pub(crate) visible: (usize, usize),
    pub(crate) style: SeriesStyle,
}

impl<'a> SeriesCtx<'a> {
    /// Time/price conversions of the pane, with this series' price map (on
    /// relative scales each series has its own), fonts and price
    /// formatting.
    pub fn coords(&self) -> &DrawingCtx<'a> {
        &self.coords
    }

    /// x of point `i` (the center of its slot); `None` if it has none.
    pub fn x_of_point(&self, i: usize) -> Option<f32> {
        let index = self.store.x_index(self.coords.index, i)? + self.shift;
        let x = f64::from(self.coords.plot.x) + self.coords.time_scale.index_to_x_f64(index);
        x.is_finite().then_some(x as f32)
    }

    /// The points being drawn, `from..to` (the visible ones and one more on
    /// each side).
    pub fn visible(&self) -> (usize, usize) {
        self.visible
    }

    /// Distance between two slots of the time axis.
    pub fn bar_spacing(&self) -> Px {
        Px(self.coords.time_scale.bar_spacing() as f32)
    }

    /// Colors and line settings resolved from the series options and the
    /// theme (`up`/`down` are `color`/`down_color` or the theme's).
    pub fn style(&self) -> &SeriesStyle {
        &self.style
    }
}

/// A custom series in the chart: the plugin and where its points are.
pub(crate) struct CustomStore {
    pub(crate) plugin: Box<dyn CustomSeries>,
    pub(crate) kind: &'static str,
    pub(crate) mode: AxisMode,
    /// `Slots`: logical index of each point (`Mapped` has `len` offsets).
    mapping: SeriesMapping,
    /// Points core has accepted (the plugin's data may be longer only
    /// between a change and its sync).
    len: usize,
    /// Times of the first and last accepted point.
    bounds: Option<(Timestamp, Timestamp)>,
    /// Changes by point number (`CustomDraw::points` is in point numbers).
    pub(crate) log: ChangeLog,
}

impl fmt::Debug for CustomStore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CustomStore")
            .field("kind", &self.kind)
            .field("mode", &self.mode)
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

/// How `Chart::update_custom` applies a change after checking it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CustomChange {
    /// Nothing to do.
    None,
    UpdateLast,
    Append,
    Prepend {
        count: usize,
    },
    Replace,
}

impl CustomStore {
    pub(crate) fn new(plugin: Box<dyn CustomSeries>) -> Self {
        Self {
            kind: plugin.kind(),
            mode: plugin.axis_mode(),
            plugin,
            mapping: SeriesMapping::Aligned { first: 0 },
            len: 0,
            bounds: None,
            log: ChangeLog::new(),
        }
    }

    pub(crate) fn len(&self) -> usize {
        self.len
    }

    /// The accepted times.
    pub(crate) fn times(&self) -> &[Timestamp] {
        let t = self.plugin.times();
        t.get(..self.len).unwrap_or(t)
    }

    pub(crate) fn heap_bytes(&self) -> usize {
        match &self.mapping {
            SeriesMapping::Aligned { .. } => 0,
            SeriesMapping::Mapped { offsets, .. } => offsets.capacity() * 4,
        }
    }

    /// Logical index of point `i` (`Slots`).
    fn logical(&self, i: usize) -> Option<i64> {
        if i >= self.len {
            return None;
        }
        self.mapping.logical_index(i)
    }

    /// Logical indices `first..end` the points cover (`Slots` only).
    pub(crate) fn span(&self) -> Option<(i64, i64)> {
        if self.mode != AxisMode::Slots || self.len == 0 {
            return None;
        }
        Some((self.logical(0)?, self.logical(self.len - 1)? + 1))
    }

    /// The point in slot `j` (`Slots` only).
    pub(crate) fn point_at(&self, j: i64) -> Option<usize> {
        if self.mode != AxisMode::Slots {
            return None;
        }
        match &self.mapping {
            SeriesMapping::Aligned { first } => {
                let p = usize::try_from(j.checked_sub(*first)?).ok()?;
                (p < self.len).then_some(p)
            }
            SeriesMapping::Mapped { first, offsets } => {
                let off = u32::try_from(j.checked_sub(*first)?).ok()?;
                offsets.get(..self.len)?.binary_search(&off).ok()
            }
        }
    }

    /// Fractional logical index of point `i`.
    pub(crate) fn x_index(&self, index: &TimeIndex, i: usize) -> Option<f64> {
        match self.mode {
            AxisMode::Slots => self.logical(i).map(|j| j as f64),
            AxisMode::Overlay => index_of_time(index, *self.times().get(i)?),
        }
    }

    /// Points in slots `from..to` (`Slots`).
    fn slot_points(&self, from: i64, to: i64) -> (usize, usize) {
        let n = self.len;
        let (a, b) = match &self.mapping {
            SeriesMapping::Aligned { first } => {
                let rel = |j: i64| {
                    usize::try_from(j.saturating_sub(*first).max(0))
                        .unwrap_or(n)
                        .min(n)
                };
                (rel(from), rel(to))
            }
            SeriesMapping::Mapped { first, offsets } => {
                let offsets = offsets.get(..n).unwrap_or(offsets);
                let (lo, hi) = (from.saturating_sub(*first), to.saturating_sub(*first));
                (
                    offsets.partition_point(|&o| i64::from(o) < lo),
                    offsets.partition_point(|&o| i64::from(o) < hi),
                )
            }
        };
        (a, b.max(a))
    }

    /// Points in time range `t0..=t1` (`Overlay`).
    fn time_points(&self, t0: Timestamp, t1: Timestamp) -> (usize, usize) {
        let times = self.times();
        let a = times.partition_point(|&t| t < t0);
        (a, times.partition_point(|&t| t <= t1).max(a))
    }

    /// Exact points positioned in logical range `from..=to`.
    fn points_between(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
        if self.len == 0 || from.partial_cmp(&to).is_none_or(core::cmp::Ordering::is_gt) {
            return (0, 0);
        }
        match self.mode {
            AxisMode::Slots => self.slot_points(from.ceil() as i64, to.floor() as i64 + 1),
            AxisMode::Overlay => match (time_of_index(index, from), time_of_index(index, to)) {
                (Some(t0), Some(t1)) => self.time_points(t0, t1),
                _ => (0, 0),
            },
        }
    }

    /// Points positioned in logical range `from..=to`, plus one on each side.
    pub(crate) fn points_in(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
        if self.len == 0 {
            return (0, 0);
        }
        let (a, b) = self.points_between(index, from, to);
        (a.saturating_sub(1), (b + 1).min(self.len))
    }

    /// Extremes of the points in logical range `from..to`.
    pub(crate) fn extremes(&self, index: &TimeIndex, from: i64, to: i64) -> Option<(f64, f64)> {
        let (a, b) = self.points_between(index, from as f64, (to - 1) as f64);
        if a >= b {
            return None;
        }
        self.plugin.extremes(a, b)
    }

    /// The crosshair value at slot `j`.
    pub(crate) fn value_at(&self, j: i64) -> Option<f64> {
        let v = self.plugin.crosshair_value(self.point_at(j)?)?;
        v.is_finite().then_some(v)
    }

    /// Checks the plugin's data after `change` and says how to apply it. A
    /// change that does not match the data (wrong count, the last time moved)
    /// is applied as a `Replace`.
    pub(crate) fn classify(&self, change: crate::data::DataChange) -> Result<CustomChange> {
        use crate::data::DataChange as D;
        let times = self.plugin.times();
        let (n, old) = (times.len(), self.len);
        let change = match (change, self.bounds) {
            (D::UpdateLast, Some((_, last))) if n == old && times.last() == Some(&last) => {
                CustomChange::UpdateLast
            }
            (D::Append { count: 0 } | D::Prepend { count: 0 }, _) if n == old => CustomChange::None,
            (D::Append { count }, Some((_, last))) if n == old + count => {
                if times.get(old - 1) == Some(&last) {
                    check_increasing(&times[old - 1..], old - 1)?;
                    CustomChange::Append
                } else {
                    CustomChange::Replace
                }
            }
            (D::Prepend { count }, Some((first, _))) if n == old + count => {
                if times.get(count) == Some(&first) {
                    check_increasing(&times[..=count], 0)?;
                    CustomChange::Prepend { count }
                } else {
                    CustomChange::Replace
                }
            }
            _ => CustomChange::Replace,
        };
        if change == CustomChange::Replace {
            check_increasing(times, 0)?;
        }
        Ok(change)
    }

    /// Accepts all of the plugin's points, with `mapping` (`Slots`).
    pub(crate) fn accept(&mut self, mapping: SeriesMapping) {
        self.mapping = mapping;
        self.take_all();
    }

    /// Accepts all of the plugin's points with the current mapping.
    fn take_all(&mut self) {
        let times = self.plugin.times();
        self.len = times.len();
        self.bounds = times.first().copied().zip(times.last().copied());
    }

    /// Maps all points onto `index` (`Slots`) and accepts them.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if a time is not a slot of `index`;
    /// [`Error::OutOfMemory`].
    pub(crate) fn map_onto(&mut self, index: &TimeIndex) -> Result<()> {
        let mapping = if self.mode == AxisMode::Slots {
            index
                .map_series(self.plugin.times())?
                .ok_or(Error::InvalidArgument(
                    "custom series times are not on the axis",
                ))?
        } else {
            SeriesMapping::Aligned { first: 0 }
        };
        self.accept(mapping);
        Ok(())
    }

    /// Maps the points after the accepted ones onto `index` (whose slots
    /// they already are) and accepts them.
    pub(crate) fn extend_onto(&mut self, index: &TimeIndex) -> Result<()> {
        if self.mode == AxisMode::Slots {
            let times = self.plugin.times();
            let new = times.get(self.len..).unwrap_or(&[]);
            for (p, &t) in (self.len..).zip(new) {
                let j = index.index_of(t).ok_or(Error::InvalidArgument(
                    "custom series times are not on the axis",
                ))?;
                match &mut self.mapping {
                    SeriesMapping::Aligned { first } if p == 0 => *first = j,
                    SeriesMapping::Aligned { first }
                        if Some(j) == first.checked_add(i64::try_from(p).unwrap_or(i64::MAX)) => {}
                    SeriesMapping::Aligned { first } => {
                        let first = *first;
                        let mut offsets = Vec::new();
                        offsets.try_reserve(p + 1).map_err(|_| Error::OutOfMemory)?;
                        offsets.extend((0..p).filter_map(|o| u32::try_from(o).ok()));
                        offsets.push(offset(first, j)?);
                        self.mapping = SeriesMapping::Mapped { first, offsets };
                    }
                    SeriesMapping::Mapped { first, offsets } => {
                        let o = offset(*first, j)?;
                        offsets.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
                        offsets.push(o);
                    }
                }
            }
        }
        self.take_all();
        Ok(())
    }

    /// Drops all points (after invalid data): nothing is drawn until the
    /// next valid change.
    pub(crate) fn clear(&mut self) {
        self.len = 0;
        self.bounds = None;
        self.mapping = SeriesMapping::Aligned { first: 0 };
        self.log.replace();
    }
}

fn offset(first: i64, j: i64) -> Result<u32> {
    j.checked_sub(first)
        .and_then(|o| u32::try_from(o).ok())
        .ok_or(Error::InvalidArgument(
            "mapped series spans more than u32::MAX slots",
        ))
}

/// `Err(TimeNotIncreasing)` with the index in the plugin's data (`times`
/// starts at point `base`).
fn check_increasing(times: &[Timestamp], base: usize) -> Result<()> {
    match times.windows(2).position(|w| w[1] <= w[0]) {
        Some(k) => Err(Error::TimeNotIncreasing {
            index: base + k + 1,
        }),
        None => Ok(()),
    }
}