1use crate::data::lod::{bucket_of, bucket_start};
12use core::any::Any;
13
14use crate::data::{
15 BandId, BarUpdate, ChangeLog, Column, DataChange, DataDelta, DrawingId, IdxSpan, IndicatorId,
16 LayerPluginId, LogicalIndex, OhlcLevelView, PaneId, PriceLineId, SeriesId, TimeIndex,
17 Timestamp, ValidationMode,
18};
19use crate::drawing::{DrawingCtx, DrawingManager, FrameBuilder};
20use crate::error::{Error, Result};
21use crate::format::NumberFormat;
22use crate::format::auto_decimals;
23use crate::frame::{
24 CustomDraw, DrawCmd, FontId, FontStyleRef, Frame, Invalidation, LabelBg, LayerId, LineDash,
25 LineInst, Reveal, SeriesDraw, SeriesKind, SeriesStyle, StrokeStyle, TextAlign, TextRun,
26 XTransform,
27};
28use crate::geom::{Css, PointCss, PointPx, Px, RectPx, Rgba, SizeCss, SizePx, Span};
29use crate::interaction::{CrosshairMode, Drag, Interaction};
30use crate::pane::{PRICE_MARGINS, Pane, PaneLayout, PaneOptions, SEPARATOR_PX, stack};
31use crate::plugin::{
32 AxisMode, CustomChange, CustomSeries, CustomStore, Indicator, IndicatorInput, IndicatorOutputs,
33 LayerCtx, LayerPlugin, LayerPosition, OutputKind, Placement, SeriesCtx, SeriesTransform,
34};
35use crate::price_scale::{Normalize, PriceScale, ScaleSide};
36use crate::series::{Op, Store, is_ohlc_kind, is_value_kind};
37use crate::sync::{SyncMessage, SyncState};
38use crate::text::{StackStr, TextMeasurer, text_width};
39use crate::theme::Theme;
40use crate::time_scale::{
41 TimeScale, TimeTick, TimeZoneProvider, Utc, collect_ticks, format_crosshair_time, format_tick,
42};
43use crate::transform::store::{TransformStore, input_columns};
44
45pub struct ChartOptions {
57 pub theme: Theme,
59 pub time_zone: Box<dyn TimeZoneProvider>,
61 pub ohlc_validation: ValidationMode,
63 pub bar_spacing: Css,
65 pub min_bar_spacing: Css,
67 pub max_bar_spacing: Css,
69 pub right_offset: f64,
71}
72
73impl Default for ChartOptions {
74 fn default() -> Self {
75 Self {
76 theme: Theme::light(),
77 time_zone: Box::new(Utc),
78 ohlc_validation: ValidationMode::Reject,
79 bar_spacing: Css(6.0),
80 min_bar_spacing: Css(0.5),
81 max_bar_spacing: Css(50.0),
82 right_offset: 3.0,
83 }
84 }
85}
86
87pub use crate::series::SeriesData;
88
89#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct SeriesOptions {
110 pub price_precision: Option<u8>,
114 pub source: Option<SeriesId>,
116 pub color: Option<Rgba>,
119 pub down_color: Option<Rgba>,
121 pub top_fill: Option<Rgba>,
123 pub bottom_fill: Option<Rgba>,
125 pub line_width: Css,
127 pub line_style: LineDash,
129 pub step: bool,
131 pub base_value: f64,
133 pub last_value_visible: bool,
136 pub price_line_visible: bool,
139 pub shift: i32,
143}
144
145impl Default for SeriesOptions {
146 fn default() -> Self {
147 Self {
148 price_precision: None,
149 source: None,
150 color: None,
151 down_color: None,
152 top_fill: None,
153 bottom_fill: None,
154 line_width: Css(2.0),
155 line_style: LineDash::Solid,
156 step: false,
157 base_value: 0.0,
158 last_value_visible: true,
159 price_line_visible: true,
160 shift: 0,
161 }
162 }
163}
164
165#[derive(Clone, Copy, Debug, Default, PartialEq)]
193pub struct BandOptions {
194 pub fill: Option<Rgba>,
197 pub fill_crossed: Option<Rgba>,
199}
200
201fn volume_like(e: &SeriesEntry) -> bool {
204 e.kind == SeriesKind::Volume || e.volume_scale
205}
206
207#[derive(Clone, Copy, Debug)]
209struct MarkerHit {
210 series: SeriesId,
211 index: usize,
212 pane: PaneId,
213 pos: PointPx,
214 radius: f32,
215}
216
217const HIT_TOLERANCE: f32 = 4.0;
219
220fn segment_distance(p: PointPx, a: PointPx, b: PointPx) -> f32 {
222 let (dx, dy) = (b.x - a.x, b.y - a.y);
223 let len2 = dx * dx + dy * dy;
224 let t = if len2 > 0.0 {
225 (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0)
226 } else {
227 0.0
228 };
229 (p.x - (a.x + dx * t)).hypot(p.y - (a.y + dy * t))
230}
231
232#[derive(Clone, Copy, Debug)]
234struct BandEntry {
235 id: BandId,
236 upper: SeriesId,
237 lower: SeriesId,
238 opts: BandOptions,
239}
240
241#[derive(Clone, Debug, PartialEq)]
262pub struct PriceLineOptions {
263 pub price: f64,
265 pub color: Option<Rgba>,
267 pub line_width: Css,
269 pub line_style: LineDash,
271 pub axis_label_visible: bool,
273 pub title: String,
275}
276
277impl Default for PriceLineOptions {
278 fn default() -> Self {
279 Self {
280 price: 0.0,
281 color: None,
282 line_width: Css(1.0),
283 line_style: LineDash::Dashed,
284 axis_label_visible: true,
285 title: String::new(),
286 }
287 }
288}
289
290#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
292pub enum MarkerPosition {
293 #[default]
295 AboveBar,
296 BelowBar,
298}
299
300#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
302pub enum MarkerShape {
303 #[default]
305 Circle,
306 Square,
308 ArrowUp,
310 ArrowDown,
312}
313
314impl MarkerShape {
315 fn icon(self) -> u16 {
316 use crate::transform_helpers::{ICON_ARROW_DOWN, ICON_ARROW_UP, ICON_CIRCLE, ICON_SQUARE};
317 match self {
318 Self::Circle => ICON_CIRCLE,
319 Self::Square => ICON_SQUARE,
320 Self::ArrowUp => ICON_ARROW_UP,
321 Self::ArrowDown => ICON_ARROW_DOWN,
322 }
323 }
324}
325
326#[derive(Clone, Debug, Default, PartialEq)]
350pub struct Marker {
351 pub time: Timestamp,
354 pub position: MarkerPosition,
356 pub shape: MarkerShape,
358 pub color: Option<Rgba>,
360 pub text: String,
362}
363
364const MARKER_SIZE: f32 = 10.0;
366const MARKER_GAP: f32 = 4.0;
367
368#[derive(Clone, Debug)]
369struct PriceLineEntry {
370 id: PriceLineId,
371 series: SeriesId,
372 opts: PriceLineOptions,
373}
374
375#[derive(Clone, Copy, Debug)]
377struct AxisLabel {
378 want: f32,
380 at: f32,
382 text: Span,
383 bg: Rgba,
384 fg: Rgba,
385}
386
387impl SeriesOptions {
388 pub fn volume_of(source: SeriesId) -> Self {
390 Self {
391 source: Some(source),
392 ..Self::default()
393 }
394 }
395}
396
397#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399#[non_exhaustive]
400pub enum WarningKind {
401 OhlcRepaired {
403 series: SeriesId,
405 bars: usize,
407 },
408 TimeAxisMerged {
412 series: SeriesId,
414 slots: usize,
416 },
417 DataDropped {
420 series: SeriesId,
422 },
423}
424
425#[derive(Clone, Copy, Debug, PartialEq)]
427pub struct BarValues {
428 pub open: f64,
430 pub high: f64,
432 pub low: f64,
434 pub close: f64,
436 pub volume: Option<f64>,
438}
439
440#[derive(Clone, Copy, Debug, PartialEq)]
442pub struct CrosshairPoint {
443 pub logical_index: i64,
445 pub time: Option<Timestamp>,
447 pub pane: PaneId,
449 pub price: f64,
451 pub bar: Option<BarValues>,
453}
454
455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457#[non_exhaustive]
458pub enum ClickTarget {
459 Drawing(DrawingId),
461 Marker {
464 series: SeriesId,
466 index: usize,
468 },
469 Series(SeriesId),
472}
473
474#[derive(Clone, Copy, Debug, PartialEq)]
480#[non_exhaustive]
481pub enum ChartEvent {
482 CrosshairMove {
484 point: Option<CrosshairPoint>,
486 },
487 Click {
490 pos: PointCss,
492 pane: PaneId,
494 logical_index: f64,
496 time: Option<Timestamp>,
498 price: f64,
500 target: Option<ClickTarget>,
502 },
503 VisibleRangeChanged {
505 from: LogicalIndex,
507 to: LogicalIndex,
509 },
510 NeedMoreHistory {
513 bars_before_start: i64,
516 },
517 DrawingCreated(DrawingId),
520 DrawingModified(DrawingId),
522 DrawingRemoved(DrawingId),
524 DrawingSelected(Option<DrawingId>),
526 Warning(WarningKind),
528 Sync(SyncMessage),
532 DrawingSync,
536}
537
538#[derive(Clone, Copy, Debug, Default, PartialEq)]
541pub struct Layout {
542 pub plot: RectPx,
544 pub price_axis: RectPx,
546 pub time_axis: RectPx,
548}
549
550#[derive(Debug)]
551struct SeriesEntry {
552 id: SeriesId,
553 pane: PaneId,
554 kind: SeriesKind,
555 opts: SeriesOptions,
556 store: Store,
557 norm: Option<Normalize>,
560 markers: Vec<Marker>,
562 derived: bool,
565 volume_scale: bool,
567 auto_decimals: u8,
569}
570
571enum Target<'a> {
573 Data(SeriesData),
574 Custom(&'a mut CustomStore),
576}
577
578impl Target<'_> {
579 fn times(&self) -> &[Timestamp] {
580 match self {
581 Self::Data(d) => d.times(),
582 Self::Custom(c) => c.plugin.times(),
583 }
584 }
585}
586
587const CIRCLE_SEGMENTS: u16 = 16;
589
590const NOT_CUSTOM: Error = Error::InvalidArgument("not a custom series");
591const NEXT_TO_TRANSFORM: Error =
592 Error::InvalidArgument("a transform series cannot share the chart with other series");
593
594struct LayerEntry {
596 id: LayerPluginId,
597 pane: Option<PaneId>,
599 position: LayerPosition,
600 plugin: Box<dyn LayerPlugin>,
601}
602
603struct IndicatorEntry {
605 id: IndicatorId,
606 source: SeriesId,
607 ind: Box<dyn Indicator>,
608 series: Vec<SeriesId>,
610 own_pane: Option<PaneId>,
612 bands: Vec<BandId>,
614}
615
616fn compute_indicator(
621 entry: &mut IndicatorEntry,
622 source: crate::series::Source<'_>,
623 index: &crate::data::TimeIndex,
624 change: DataChange,
625 out: &mut IndicatorOutputs,
626) -> (DataChange, usize) {
627 let input = IndicatorInput::new(source, index);
628 let len = input.len();
629 let change = match change {
630 DataChange::Append { count } if count <= len => change,
631 DataChange::UpdateLast if len > 0 => change,
632 _ => DataChange::Replace,
633 };
634 let start = match change {
635 DataChange::Append { count } => len - count,
636 DataChange::UpdateLast => len - 1,
637 _ => 0,
638 };
639 out.reset(entry.ind.outputs().len(), start, len);
640 entry.ind.update(&input, change, out);
641 (change, start)
642}
643
644const INDICATOR_PALETTE: [u32; 6] = [
646 0x0029_62FF,
647 0x00FF_9800,
648 0x009C_27B0,
649 0x0000_BCD4,
650 0x00E9_1E63,
651 0x0079_5548,
652];
653
654#[derive(Clone, Copy, Debug)]
656struct PlacedTick {
657 x: f32,
658 width: f32,
659 tick: TimeTick,
660}
661
662pub struct Chart {
687 theme: Theme,
688 tz: Box<dyn TimeZoneProvider>,
689 validation: ValidationMode,
690 default_right_offset: f64,
691 pub(crate) default_bar_spacing: Css,
692 size: SizeCss,
693 pub(crate) dpr: f32,
694 pub(crate) panes: Vec<Pane>,
695 next_pane: u32,
696 pub(crate) time_index: TimeIndex,
697 series: Vec<SeriesEntry>,
698 next_id: u32,
699 pub(crate) time_scale: TimeScale,
700 pub(crate) invalidation: Invalidation,
701 revisions: [u64; 3],
702 frame: Frame,
703 pub(crate) layout: Layout,
704 pub(crate) input: Interaction,
705 last_range: (f64, f64),
706 last_crosshair: Option<CrosshairPoint>,
707 history_requested: Option<i64>,
708 axis_width: f32,
709 events: Vec<ChartEvent>,
710 price_lines: Vec<PriceLineEntry>,
711 indicators: Vec<IndicatorEntry>,
712 next_indicator: u32,
713 palette_next: usize,
715 ind_out: IndicatorOutputs,
718 axis_rebuilt: bool,
720 next_price_line: u32,
721 axis_labels: Vec<AxisLabel>,
723 time_ticks: Vec<TimeTick>,
724 placed: Vec<PlacedTick>,
725 pub(crate) drawings: DrawingManager,
726 pub(crate) text_cache: CachedText,
728 pub(crate) handle_buf: core::cell::RefCell<Vec<PointPx>>,
731 pub(crate) sync: SyncState,
733 layer_plugins: Vec<LayerEntry>,
735 next_layer: u32,
736 native_kinds: Vec<&'static str>,
738 bands: Vec<BandEntry>,
740 next_band: u32,
741 marker_hits: Vec<MarkerHit>,
743 reveal: Option<Reveal>,
745}
746
747#[derive(Clone, Copy, Debug)]
751pub(crate) struct CachedText {
752 advances: [f32; 128],
753 subscripts: [f32; 10],
754 line: f32,
756}
757
758impl Default for CachedText {
759 fn default() -> Self {
760 Self {
761 advances: [0.6; 128],
762 subscripts: [0.6; 10],
763 line: 1.2,
764 }
765 }
766}
767
768impl TextMeasurer for CachedText {
769 fn ascii_advances(&self, _: FontStyleRef) -> &[f32; 128] {
770 &self.advances
771 }
772
773 fn subscript_advances(&self, _: FontStyleRef) -> Option<&[f32; 10]> {
774 Some(&self.subscripts)
775 }
776
777 fn measure(&self, text: &str, style: FontStyleRef) -> SizePx {
778 SizePx {
779 w: text.chars().count() as f32 * 0.6 * style.size,
780 h: self.line * style.size,
781 }
782 }
783
784 fn line_height(&self, style: FontStyleRef) -> f32 {
785 self.line * style.size
786 }
787}
788
789pub(crate) const HANDLE_CSS: f32 = 9.0;
791
792#[derive(Clone, Copy)]
794struct PoolMark {
795 lines: usize,
796 rects: usize,
797 points: usize,
798 runs: usize,
799}
800
801impl PoolMark {
802 fn of(frame: &Frame) -> Self {
803 let p = &frame.pools;
804 Self {
805 lines: p.lines.len(),
806 rects: p.rects.len(),
807 points: p.points.len(),
808 runs: p.text_runs.len(),
809 }
810 }
811
812 fn bounds(self, frame: &Frame, ctx: &DrawingCtx<'_>) -> RectPx {
814 let p = &frame.pools;
815 let (mut x0, mut y0, mut x1, mut y1) = (
816 f32::INFINITY,
817 f32::INFINITY,
818 f32::NEG_INFINITY,
819 f32::NEG_INFINITY,
820 );
821 let mut add = |x: f32, y: f32| {
822 x0 = x0.min(x);
823 y0 = y0.min(y);
824 x1 = x1.max(x);
825 y1 = y1.max(y);
826 };
827 for l in p.lines.get(self.lines..).unwrap_or(&[]) {
828 add(l.from.x, l.from.y);
829 add(l.to.x, l.to.y);
830 }
831 for r in p.rects.get(self.rects..).unwrap_or(&[]) {
832 add(r.rect.x, r.rect.y);
833 add(r.rect.right(), r.rect.bottom());
834 }
835 for q in p.points.get(self.points..).unwrap_or(&[]) {
836 add(q.x, q.y);
837 }
838 for run in p.text_runs.get(self.runs..).unwrap_or(&[]) {
839 let w = ctx.text_width(p.text_of(run.text), run.style);
840 let h = ctx.line_height(run.style) * 0.5 + run.bg.map_or(0.0, |b| b.padding.0);
841 let x = match run.align {
842 TextAlign::Left => run.pos.x,
843 TextAlign::Center => run.pos.x - w * 0.5,
844 TextAlign::Right => run.pos.x - w,
845 };
846 add(x - h, run.pos.y - h);
847 add(x + w + h, run.pos.y + h);
848 }
849 if x0 > x1 {
850 return RectPx::default();
851 }
852 RectPx {
853 x: x0,
854 y: y0,
855 w: x1 - x0,
856 h: y1 - y0,
857 }
858 }
859}
860
861const TICK_SAMPLE_PX: f64 = 8.0;
863
864impl Chart {
865 pub fn new(options: ChartOptions) -> Self {
867 let dpr = 1.0;
868 let mut frame = Frame::default();
869 frame.reserve();
870 Self {
871 theme: options.theme,
872 tz: options.time_zone,
873 validation: options.ohlc_validation,
874 default_right_offset: options.right_offset,
875 default_bar_spacing: options.bar_spacing,
876 size: SizeCss::default(),
877 dpr,
878 panes: vec![Pane::new(PaneId(0), 1.0)],
879 next_pane: 1,
880 time_index: TimeIndex::new(),
881 series: Vec::new(),
882 next_id: 0,
883 time_scale: TimeScale::new(
884 f64::from(options.bar_spacing.to_px(dpr).0),
885 options.right_offset,
886 f64::from(options.min_bar_spacing.to_px(dpr).0),
887 f64::from(options.max_bar_spacing.to_px(dpr).0),
888 ),
889 invalidation: Invalidation::Full,
890 revisions: [0; 3],
891 frame,
892 layout: Layout::default(),
893 input: Interaction::default(),
894 last_range: (f64::NAN, f64::NAN),
895 last_crosshair: None,
896 history_requested: None,
897 axis_width: 0.0,
898 events: Vec::with_capacity(64),
899 price_lines: Vec::new(),
900 indicators: Vec::new(),
901 next_indicator: 0,
902 palette_next: 0,
903 ind_out: IndicatorOutputs::default(),
904 axis_rebuilt: false,
905 next_price_line: 0,
906 axis_labels: Vec::with_capacity(64),
907 time_ticks: Vec::with_capacity(2048),
908 placed: Vec::with_capacity(256),
909 drawings: DrawingManager::new(PaneId(0)),
910 text_cache: CachedText::default(),
911 handle_buf: core::cell::RefCell::new(Vec::new()),
912 sync: SyncState::default(),
913 layer_plugins: Vec::new(),
914 next_layer: 0,
915 bands: Vec::new(),
916 next_band: 0,
917 marker_hits: Vec::new(),
918 reveal: None,
919 native_kinds: Vec::new(),
920 }
921 }
922
923 pub fn resize(&mut self, size: SizeCss, dpr: f32) {
927 let finite = size.w.is_finite() && size.h.is_finite() && dpr.is_finite();
928 if !finite || dpr <= 0.0 || size.w < 0.0 || size.h < 0.0 {
929 return;
930 }
931 if (dpr - self.dpr).abs() > f32::EPSILON {
932 self.time_scale.rescale(f64::from(dpr / self.dpr));
933 self.dpr = dpr;
934 }
935 self.size = size;
936 self.invalidation = Invalidation::Full;
937 }
938
939 pub fn main_pane(&self) -> PaneId {
941 self.panes.first().map_or(PaneId(0), |p| p.id)
942 }
943
944 pub fn add_pane(&mut self, opts: PaneOptions) -> PaneId {
972 let id = PaneId(self.next_pane);
973 self.next_pane = self.next_pane.wrapping_add(1);
974 self.panes.push(Pane::new(id, opts.stretch_factor));
975 self.drawings.pane_added(id);
976 self.invalidation = Invalidation::Full;
977 id
978 }
979
980 pub fn remove_pane(&mut self, id: PaneId) -> Result<()> {
988 let i = self.pane_index(id).ok_or(Error::UnknownId)?;
989 if self.panes.len() == 1 {
990 return Err(Error::InvalidArgument("a chart keeps at least one pane"));
991 }
992 while let Some(sid) = self.series.iter().find(|e| e.pane == id).map(|e| e.id) {
993 self.remove_series(sid)?;
994 }
995 self.panes.remove(i);
996 self.drawings.pane_removed(id);
997 self.layer_plugins.retain(|l| l.pane != Some(id));
998 if self.input.drag.involves(id) {
999 self.input.drag = Drag::Idle;
1000 }
1001 self.invalidation = Invalidation::Full;
1002 Ok(())
1003 }
1004
1005 pub fn panes(&self) -> impl Iterator<Item = PaneId> + '_ {
1007 self.panes.iter().map(|p| p.id)
1008 }
1009
1010 pub fn pane_layout(&self, id: PaneId) -> Option<PaneLayout> {
1012 let pane = self.panes.get(self.pane_index(id)?)?;
1013 Some(PaneLayout {
1014 plot: pane.plot,
1015 price_axis: RectPx {
1016 x: self.layout.price_axis.x,
1017 y: pane.plot.y,
1018 w: self.layout.price_axis.w,
1019 h: pane.plot.h,
1020 },
1021 })
1022 }
1023
1024 pub fn pane_stretch(&self, id: PaneId) -> Option<f32> {
1026 Some(self.panes.get(self.pane_index(id)?)?.stretch)
1027 }
1028
1029 pub fn set_pane_stretch(&mut self, id: PaneId, stretch: f32) -> Result<()> {
1037 let i = self.pane_index(id).ok_or(Error::UnknownId)?;
1038 if !(stretch.is_finite() && stretch > 0.0) {
1039 return Err(Error::InvalidArgument(
1040 "a stretch factor must be finite and positive",
1041 ));
1042 }
1043 if let Some(p) = self.panes.get_mut(i) {
1044 p.stretch = stretch;
1045 }
1046 self.invalidation = Invalidation::Full;
1047 Ok(())
1048 }
1049
1050 pub fn visible_price_range(&self, id: PaneId) -> Option<(f64, f64)> {
1074 let pane = self.panes.get(self.pane_index(id)?)?;
1075 let h = f64::from(pane.plot.h);
1076 if !(pane.has_content && h > 0.0) {
1077 return None;
1078 }
1079 let a = pane.price_scale.y_to_price(h, 0.0, h);
1080 let b = pane.price_scale.y_to_price(0.0, 0.0, h);
1081 (a.is_finite() && b.is_finite()).then_some((a.min(b), a.max(b)))
1082 }
1083
1084 pub(crate) fn pane_index(&self, id: PaneId) -> Option<usize> {
1085 self.panes.iter().position(|p| p.id == id)
1086 }
1087
1088 pub(crate) fn pane_mut(&mut self, id: PaneId) -> Option<&mut Pane> {
1089 self.panes.iter_mut().find(|p| p.id == id)
1090 }
1091
1092 fn entry(&self, id: SeriesId) -> Result<&SeriesEntry> {
1093 self.series
1094 .iter()
1095 .find(|e| e.id == id)
1096 .ok_or(Error::UnknownId)
1097 }
1098
1099 fn entry_index(&self, id: SeriesId) -> Result<usize> {
1100 self.series
1101 .iter()
1102 .position(|e| e.id == id)
1103 .ok_or(Error::UnknownId)
1104 }
1105
1106 pub fn add_candlestick(&mut self) -> Result<SeriesId> {
1126 self.add_series(
1127 self.main_pane(),
1128 SeriesKind::Candlestick,
1129 SeriesOptions::default(),
1130 )
1131 }
1132
1133 pub fn add_volume(&mut self, source: SeriesId) -> Result<SeriesId> {
1141 self.add_series(
1142 self.main_pane(),
1143 SeriesKind::Volume,
1144 SeriesOptions::volume_of(source),
1145 )
1146 }
1147
1148 pub fn add_series(
1181 &mut self,
1182 pane: PaneId,
1183 kind: SeriesKind,
1184 opts: SeriesOptions,
1185 ) -> Result<SeriesId> {
1186 if self.transform_entry().is_some() && kind != SeriesKind::Volume {
1187 return Err(NEXT_TO_TRANSFORM);
1188 }
1189 self.insert_series(pane, kind, opts)
1190 }
1191
1192 fn insert_series(
1194 &mut self,
1195 pane: PaneId,
1196 kind: SeriesKind,
1197 opts: SeriesOptions,
1198 ) -> Result<SeriesId> {
1199 if self.pane_index(pane).is_none() {
1200 return Err(Error::UnknownId);
1201 }
1202 if kind == SeriesKind::Custom {
1203 return Err(Error::InvalidArgument(
1204 "custom series are added with add_custom_series",
1205 ));
1206 }
1207 if matches!(kind, SeriesKind::Kagi | SeriesKind::PointFigure) {
1208 return Err(Error::InvalidArgument(
1209 "Kagi and Point & Figure series are added with add_transform_series",
1210 ));
1211 }
1212 if kind == SeriesKind::Band {
1213 return Err(Error::InvalidArgument("bands are added with add_band"));
1214 }
1215 if kind == SeriesKind::Volume {
1216 let source_ok = opts
1217 .source
1218 .and_then(|s| self.entry(s).ok())
1219 .is_some_and(|e| is_ohlc_kind(e.kind) || e.store.transform().is_some());
1220 if !source_ok {
1221 return Err(Error::InvalidArgument(
1222 "a volume series needs an OHLC series of this chart as its source",
1223 ));
1224 }
1225 if !self.series.iter().any(|e| e.pane == pane)
1226 && let Some(p) = self.pane_mut(pane)
1227 {
1228 let _ = p.price_scale.set_margins(PRICE_MARGINS.0, 0.0);
1230 }
1231 }
1232 let id = SeriesId(self.next_id);
1233 self.next_id = self.next_id.checked_add(1).ok_or(Error::OutOfMemory)?;
1234 self.series.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
1235 self.series.push(SeriesEntry {
1236 id,
1237 pane,
1238 kind,
1239 opts,
1240 store: Store::for_kind(kind),
1241 norm: None,
1242 markers: Vec::new(),
1243 derived: false,
1244 volume_scale: false,
1245 auto_decimals: 2,
1246 });
1247 self.invalidation = Invalidation::Full;
1248 Ok(id)
1249 }
1250
1251 pub fn series_options(&self, id: SeriesId) -> Option<&SeriesOptions> {
1253 self.entry(id).ok().map(|e| &e.opts)
1254 }
1255
1256 pub fn series_kind(&self, id: SeriesId) -> Option<SeriesKind> {
1258 self.entry(id).ok().map(|e| e.kind)
1259 }
1260
1261 pub fn series_pane(&self, id: SeriesId) -> Option<PaneId> {
1263 self.entry(id).ok().map(|e| e.pane)
1264 }
1265
1266 pub fn set_series_options(&mut self, id: SeriesId, opts: SeriesOptions) -> Result<()> {
1293 let k = self.entry_index(id)?;
1294 if opts.source != self.series[k].opts.source {
1295 return Err(Error::InvalidArgument(
1296 "the source of a series cannot change",
1297 ));
1298 }
1299 self.series[k].opts = opts;
1300 self.invalidation = Invalidation::Full;
1301 Ok(())
1302 }
1303
1304 pub fn remove_series(&mut self, id: SeriesId) -> Result<()> {
1311 if self.entry(id)?.derived {
1312 return Err(Error::InvalidArgument(
1313 "an indicator output; remove the indicator instead",
1314 ));
1315 }
1316 self.drop_indicators_of(id);
1317 self.series
1318 .retain(|e| e.id != id && e.opts.source != Some(id));
1319 self.price_lines
1320 .retain(|l| self.series.iter().any(|e| e.id == l.series));
1321 self.prune_bands();
1322 if self.series.iter().all(|e| e.store.is_empty()) {
1324 self.time_index = TimeIndex::new();
1325 self.time_scale.set_extent(0, 0);
1326 }
1327 self.invalidation = Invalidation::Full;
1328 Ok(())
1329 }
1330
1331 fn after_change(&mut self, id: SeriesId, repaired: usize) {
1332 self.time_scale
1333 .set_extent(self.time_index.first_index(), self.time_index.end_index());
1334 self.invalidation = self.invalidation.max(Invalidation::Data);
1335 if repaired > 0 {
1336 self.events
1337 .push(ChartEvent::Warning(WarningKind::OhlcRepaired {
1338 series: id,
1339 bars: repaired,
1340 }));
1341 }
1342 }
1343
1344 fn data_entry(&self, id: SeriesId) -> Result<usize> {
1346 let k = self.entry_index(id)?;
1347 if self.series[k].store.takes_data() {
1348 Ok(k)
1349 } else if self.series[k].kind == SeriesKind::Custom {
1350 Err(Error::InvalidArgument(
1351 "a custom series owns its data; use update_custom",
1352 ))
1353 } else {
1354 Err(Error::InvalidArgument(
1355 "this series has no data of its own; use its source series",
1356 ))
1357 }
1358 }
1359
1360 fn run_op<T>(
1363 &mut self,
1364 k: usize,
1365 added: (usize, usize),
1366 f: impl FnOnce(&Op<'_>, &mut Store) -> Result<T>,
1367 ) -> Result<T> {
1368 let entry = &mut self.series[k];
1369 let op = Op {
1370 kind: entry.kind,
1371 index: &self.time_index,
1372 mode: self.validation,
1373 };
1374 let out = f(&op, &mut entry.store);
1375 if out.is_err() {
1376 self.time_index.truncate_ends(added.0, added.1);
1377 }
1378 out
1379 }
1380
1381 fn cover(&mut self, times: &[Timestamp]) -> Result<Option<(usize, usize)>> {
1386 let index = &mut self.time_index;
1387 let (Some(&t0), Some(&tn)) = (times.first(), times.last()) else {
1388 return Ok(Some((0, 0)));
1389 };
1390 let (Some(&first), Some(&last)) = (index.times().first(), index.times().last()) else {
1391 index.append(times)?;
1392 return Ok(Some((0, times.len())));
1393 };
1394 if t0 > last {
1395 index.append(times)?;
1396 return Ok(Some((0, times.len())));
1397 }
1398 if tn < first {
1399 index.prepend(times)?;
1400 return Ok(Some((times.len(), 0)));
1401 }
1402 if let [t] = times {
1403 return Ok(index.index_of(*t).map(|_| (0, 0)));
1405 }
1406 let head = times.partition_point(|&t| t < first);
1407 let body_end = times.partition_point(|&t| t <= last).max(head);
1408 if index.map_series(×[head..body_end])?.is_none() {
1409 return Ok(None);
1410 }
1411 index.prepend(×[..head])?;
1412 if let Err(e) = index.append(×[body_end..]) {
1413 index.truncate_ends(head, 0);
1414 return Err(e);
1415 }
1416 Ok(Some((head, times.len() - body_end)))
1417 }
1418
1419 fn other_spans(&self, k: usize) -> Vec<(i64, i64)> {
1422 let mut spans: Vec<(i64, i64)> = self
1423 .series
1424 .iter()
1425 .enumerate()
1426 .filter(|&(j, e)| j != k && !e.derived)
1427 .filter_map(|(_, e)| e.store.span())
1428 .collect();
1429 spans.sort_unstable();
1430 let mut merged: Vec<(i64, i64)> = Vec::with_capacity(spans.len());
1431 for (a, b) in spans {
1432 match merged.last_mut() {
1433 Some(last) if a <= last.1 => last.1 = last.1.max(b),
1434 _ => merged.push((a, b)),
1435 }
1436 }
1437 merged
1438 }
1439
1440 fn has_orphans(&self, others: &[(i64, i64)], times: &[Timestamp]) -> bool {
1444 let index = &self.time_index;
1445 let end = index.end_index();
1446 let mut at = index.first_index();
1447 for &(a, b) in others.iter().chain(core::iter::once(&(end, end))) {
1448 if at < a {
1449 let (Some(ta), Some(tb)) = (index.time_at(at), index.time_at(a - 1)) else {
1450 return true;
1451 };
1452 let lo = times.partition_point(|&t| t < ta);
1453 let hi = times.partition_point(|&t| t <= tb);
1454 if i64::try_from(hi - lo).ok() != Some(a - at) {
1455 return true;
1456 }
1457 }
1458 at = at.max(b);
1459 }
1460 false
1461 }
1462
1463 fn rebuild(&mut self, k: usize, target: Target<'_>, others: &[(i64, i64)]) -> Result<usize> {
1470 let old = &self.time_index;
1471 let mut kept = Vec::new();
1472 for &(a, b) in others {
1473 let from = usize::try_from(a - old.first_index()).unwrap_or(0);
1474 let to = usize::try_from(b - old.first_index()).unwrap_or(0);
1475 kept.extend_from_slice(old.times().get(from..to).unwrap_or(&[]));
1476 }
1477 let mut index = TimeIndex::from_times(kept)?;
1478 index.merge(target.times())?;
1479 let inserted = match (old.times().first(), old.times().last()) {
1480 (Some(&first), Some(&last)) => target
1481 .times()
1482 .iter()
1483 .filter(|&&t| t > first && t < last && old.index_of(t).is_none())
1484 .count(),
1485 _ => 0,
1486 };
1487 let shared = index
1488 .times()
1489 .iter()
1490 .enumerate()
1491 .find_map(|(p, &t)| Some((old.index_of(t)?, p)));
1492 if let Some((j, p)) = shared
1493 && let Some(first) = j.checked_sub(i64::try_from(p).unwrap_or(i64::MAX))
1494 {
1495 index.rebase(first);
1496 }
1497 let snapshots: Vec<(usize, SeriesData)> = self
1498 .series
1499 .iter()
1500 .enumerate()
1501 .filter(|&(j, e)| j != k && !e.store.is_empty() && !e.derived)
1502 .filter_map(|(j, e)| Some((j, e.store.snapshot(old)?)))
1503 .collect();
1504 let entry = &mut self.series[k];
1506 let repaired = match target {
1507 Target::Data(data) => Op {
1508 kind: entry.kind,
1509 index: &index,
1510 mode: self.validation,
1511 }
1512 .set(&mut entry.store, data)?,
1513 Target::Custom(c) => {
1514 c.map_onto(&index)?;
1515 c.log.replace();
1516 0
1517 }
1518 };
1519 let id = entry.id;
1520 for (j, snap) in snapshots {
1521 let entry = &mut self.series[j];
1522 let op = Op {
1523 kind: entry.kind,
1524 index: &index,
1525 mode: ValidationMode::Repair,
1526 };
1527 if op.set(&mut entry.store, snap).is_err() {
1529 entry.store = Store::for_kind(entry.kind);
1530 self.events
1531 .push(ChartEvent::Warning(WarningKind::DataDropped {
1532 series: entry.id,
1533 }));
1534 }
1535 }
1536 for e in &mut self.series {
1538 if let Store::Custom(c) = &mut e.store
1539 && c.mode == AxisMode::Slots
1540 && c.len() > 0
1541 {
1542 c.log.replace();
1543 if c.map_onto(&index).is_err() {
1544 c.clear();
1545 self.events
1546 .push(ChartEvent::Warning(WarningKind::DataDropped {
1547 series: e.id,
1548 }));
1549 }
1550 }
1551 }
1552 for e in self.series.iter_mut().filter(|e| e.derived) {
1554 e.store = Store::for_kind(e.kind);
1555 }
1556 self.axis_rebuilt = true;
1557 self.time_index = index;
1558 self.time_index.shrink_to_fit();
1559 if inserted > 0 {
1560 self.events
1561 .push(ChartEvent::Warning(WarningKind::TimeAxisMerged {
1562 series: id,
1563 slots: inserted,
1564 }));
1565 }
1566 Ok(repaired)
1567 }
1568
1569 fn combined(&self, k: usize, new: SeriesData, prepend: bool) -> Result<SeriesData> {
1572 let store = &self.series[k].store;
1573 let Some(old) = store
1574 .snapshot(&self.time_index)
1575 .filter(|_| !store.is_empty())
1576 else {
1577 return Ok(new);
1578 };
1579 let (Some(&new_first), Some(&new_last)) = (new.times().first(), new.times().last()) else {
1580 return Ok(old);
1581 };
1582 let (Some(&old_first), Some(&old_last)) = (old.times().first(), old.times().last()) else {
1583 return Ok(new);
1584 };
1585 if prepend {
1586 if new_last >= old_first {
1587 return Err(Error::TimeNotIncreasing {
1588 index: new.times().len() - 1,
1589 });
1590 }
1591 new.concat(old)
1592 } else {
1593 if new_first <= old_last {
1594 return Err(Error::TimeNotIncreasing { index: 0 });
1595 }
1596 old.concat(new)
1597 }
1598 }
1599
1600 pub fn set_data(&mut self, id: SeriesId, data: impl Into<SeriesData>) -> Result<()> {
1615 self.set_data_data(id, data.into())
1616 }
1617
1618 fn set_data_data(&mut self, id: SeriesId, data: SeriesData) -> Result<()> {
1619 let k = self.data_entry(id)?;
1620 if self.series[k].store.transform().is_some() {
1621 let (input, repaired) = input_columns(data, self.validation)?;
1622 self.run_transform(k, repaired, |t, index| {
1623 t.set(index, input).map(|()| Some(DataChange::Replace))
1624 })?;
1625 return Ok(());
1626 }
1627 let others = self.other_spans(k);
1628 let repaired = if others.is_empty() {
1629 let (times, data) = data.take_times()?;
1631 let index = TimeIndex::from_times(times)?;
1632 let entry = &mut self.series[k];
1633 let repaired = Op {
1634 kind: entry.kind,
1635 index: &index,
1636 mode: self.validation,
1637 }
1638 .set_aligned(&mut entry.store, index.first_index(), data)?;
1639 self.time_index = index;
1640 self.time_index.shrink_to_fit();
1641 self.axis_rebuilt = true;
1643 repaired
1644 } else if self.time_index.map_series(data.times())?.is_some()
1645 && !self.has_orphans(&others, data.times())
1646 {
1647 self.run_op(k, (0, 0), |op, store| op.set(store, data))?
1648 } else {
1649 self.rebuild(k, Target::Data(data), &others)?
1650 };
1651 self.after_change(id, repaired);
1652 self.after_data(id, DataChange::Replace);
1653 Ok(())
1654 }
1655
1656 pub fn append(&mut self, id: SeriesId, data: impl Into<SeriesData>) -> Result<()> {
1664 self.append_data(id, data.into())
1665 }
1666
1667 fn append_data(&mut self, id: SeriesId, data: SeriesData) -> Result<()> {
1668 let k = self.data_entry(id)?;
1669 if self.series[k].store.transform().is_some() {
1670 let (input, repaired) = input_columns(data, self.validation)?;
1671 self.run_transform(k, repaired, |t, index| t.append(index, input))?;
1672 return Ok(());
1673 }
1674 let old_end = self.series[k].store.span().map(|(_, e)| e);
1675 let repaired = if let Some(added) = self.cover(data.times())? {
1676 self.run_op(k, added, |op, store| op.append(store, data))?
1677 } else {
1678 let all = self.combined(k, data, false)?;
1679 let others = self.other_spans(k);
1680 self.rebuild(k, Target::Data(all), &others)?
1681 };
1682 self.after_change(id, repaired);
1683 let change = match (old_end, self.series[k].store.span()) {
1684 (Some(old), Some((_, end))) => DataChange::Append {
1685 count: usize::try_from(end - old).unwrap_or(0),
1686 },
1687 _ => DataChange::Replace,
1688 };
1689 self.after_data(id, change);
1690 Ok(())
1691 }
1692
1693 pub fn prepend(&mut self, id: SeriesId, data: impl Into<SeriesData>) -> Result<()> {
1701 self.prepend_data(id, data.into())
1702 }
1703
1704 fn prepend_data(&mut self, id: SeriesId, data: SeriesData) -> Result<()> {
1705 let k = self.data_entry(id)?;
1706 if self.series[k].store.transform().is_some() {
1707 let (input, repaired) = input_columns(data, self.validation)?;
1708 self.run_transform(k, repaired, |t, index| {
1709 t.prepend(index, input).map(|()| Some(DataChange::Replace))
1710 })?;
1711 return Ok(());
1712 }
1713 let repaired = if let Some(added) = self.cover(data.times())? {
1714 self.run_op(k, added, |op, store| op.prepend(store, data))?
1715 } else {
1716 let all = self.combined(k, data, true)?;
1717 let others = self.other_spans(k);
1718 self.rebuild(k, Target::Data(all), &others)?
1719 };
1720 self.after_change(id, repaired);
1721 self.after_data(id, DataChange::Replace);
1722 Ok(())
1723 }
1724
1725 pub fn update_last(&mut self, id: SeriesId, bar: BarUpdate) -> Result<DataChange> {
1739 let k = self.data_entry(id)?;
1740 if self.series[k].store.transform().is_some() {
1741 let (bar, repaired) = crate::data::ohlc::OhlcStore::check_one(bar, self.validation)?;
1742 return self.run_transform(k, repaired, |t, index| t.update_last(index, bar));
1743 }
1744 let (change, repaired) = if let Some(added) = self.cover(&[bar.time])? {
1745 self.run_op(k, added, |op, store| op.update_last(store, bar))?
1746 } else {
1747 let point = SeriesData::point(self.series[k].kind, bar);
1748 let all = self.combined(k, point, false)?;
1749 let others = self.other_spans(k);
1750 (
1751 DataChange::Append { count: 1 },
1752 self.rebuild(k, Target::Data(all), &others)?,
1753 )
1754 };
1755 if change == DataChange::UpdateLast {
1756 self.invalidation = self.invalidation.max(Invalidation::Data);
1757 if repaired > 0 {
1758 self.after_change(id, repaired);
1759 }
1760 } else {
1761 self.after_change(id, repaired);
1762 }
1763 self.after_data(id, change);
1764 Ok(change)
1765 }
1766
1767 pub fn add_transform_series(
1813 &mut self,
1814 pane: PaneId,
1815 t: Box<dyn SeriesTransform>,
1816 opts: SeriesOptions,
1817 ) -> Result<SeriesId> {
1818 if self.pane_index(pane).is_none() {
1819 return Err(Error::UnknownId);
1820 }
1821 if self
1822 .series
1823 .iter()
1824 .any(|e| !e.derived && e.kind != SeriesKind::Volume)
1825 {
1826 return Err(NEXT_TO_TRANSFORM);
1827 }
1828 let kind = t.output_kind();
1829 if !matches!(
1830 kind,
1831 SeriesKind::Candlestick
1832 | SeriesKind::OhlcBar
1833 | SeriesKind::Kagi
1834 | SeriesKind::PointFigure
1835 ) {
1836 return Err(Error::InvalidArgument(
1837 "a transform is drawn as candlesticks, OHLC bars, Kagi or Point & Figure",
1838 ));
1839 }
1840 if kind == SeriesKind::PointFigure
1841 && !t.box_size().is_some_and(|b| b.is_finite() && b > 0.0)
1842 {
1843 return Err(Error::InvalidArgument(
1844 "a Point & Figure transform needs a positive box size",
1845 ));
1846 }
1847 let id = SeriesId(self.next_id);
1848 self.next_id = self.next_id.checked_add(1).ok_or(Error::OutOfMemory)?;
1849 self.series.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
1850 self.series.push(SeriesEntry {
1851 id,
1852 pane,
1853 kind,
1854 opts,
1855 store: Store::Transform(Box::new(TransformStore::new(t))),
1856 norm: None,
1857 markers: Vec::new(),
1858 derived: false,
1859 volume_scale: false,
1860 auto_decimals: 2,
1861 });
1862 self.invalidation = Invalidation::Full;
1863 Ok(id)
1864 }
1865
1866 fn transform_entry(&self) -> Option<usize> {
1868 self.series
1869 .iter()
1870 .position(|e| e.store.transform().is_some())
1871 }
1872
1873 fn run_transform(
1876 &mut self,
1877 k: usize,
1878 repaired: usize,
1879 f: impl FnOnce(&mut TransformStore, &mut TimeIndex) -> Result<Option<DataChange>>,
1880 ) -> Result<DataChange> {
1881 let Store::Transform(t) = &mut self.series[k].store else {
1882 return Err(Error::InvalidArgument("not a transform series"));
1883 };
1884 let out = f(t, &mut self.time_index);
1885 let id = self.series[k].id;
1886 let change = match out {
1887 Ok(c) => c,
1888 Err(e) => {
1889 self.after_change(id, 0);
1891 self.after_data(id, DataChange::Replace);
1892 return Err(e);
1893 }
1894 };
1895 match change {
1896 None => {
1897 if repaired > 0 {
1898 self.after_change(id, repaired);
1899 }
1900 Ok(DataChange::Append { count: 0 })
1901 }
1902 Some(DataChange::UpdateLast) => {
1903 self.invalidation = self.invalidation.max(Invalidation::Data);
1904 if repaired > 0 {
1905 self.after_change(id, repaired);
1906 }
1907 self.after_data(id, DataChange::UpdateLast);
1908 Ok(DataChange::UpdateLast)
1909 }
1910 Some(change) => {
1911 self.after_change(id, repaired);
1912 self.after_data(id, change);
1913 Ok(change)
1914 }
1915 }
1916 }
1917
1918 pub fn add_custom_series(
1929 &mut self,
1930 pane: PaneId,
1931 series: Box<dyn CustomSeries>,
1932 opts: SeriesOptions,
1933 ) -> Result<SeriesId> {
1934 if self.pane_index(pane).is_none() {
1935 return Err(Error::UnknownId);
1936 }
1937 if self.transform_entry().is_some() {
1938 return Err(NEXT_TO_TRANSFORM);
1939 }
1940 let id = SeriesId(self.next_id);
1941 let next = self.next_id.checked_add(1).ok_or(Error::OutOfMemory)?;
1942 self.series.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
1943 let has_data = !series.times().is_empty();
1944 self.series.push(SeriesEntry {
1945 id,
1946 pane,
1947 kind: SeriesKind::Custom,
1948 opts,
1949 store: Store::Custom(Box::new(CustomStore::new(series))),
1950 norm: None,
1951 markers: Vec::new(),
1952 derived: false,
1953 volume_scale: false,
1954 auto_decimals: 2,
1955 });
1956 self.next_id = next;
1957 self.invalidation = Invalidation::Full;
1958 if has_data && let Err(e) = self.change_custom(id, |_| Ok(DataChange::Replace)) {
1959 self.series.pop();
1960 return Err(e);
1961 }
1962 Ok(id)
1963 }
1964
1965 pub fn custom_series<T: CustomSeries>(&self, id: SeriesId) -> Option<&T> {
1968 let any: &dyn Any = self.entry(id).ok()?.store.custom()?.plugin.as_ref();
1969 any.downcast_ref::<T>()
1970 }
1971
1972 pub fn update_custom<T: CustomSeries>(
1987 &mut self,
1988 id: SeriesId,
1989 f: impl FnOnce(&mut T) -> DataChange,
1990 ) -> Result<()> {
1991 self.change_custom(id, |c| {
1992 let any: &mut dyn Any = c.plugin.as_mut();
1993 let t = any.downcast_mut::<T>().ok_or(Error::InvalidArgument(
1994 "the custom series is of another type",
1995 ))?;
1996 Ok(f(t))
1997 })
1998 }
1999
2000 fn change_custom(
2003 &mut self,
2004 id: SeriesId,
2005 modify: impl FnOnce(&mut CustomStore) -> Result<DataChange>,
2006 ) -> Result<()> {
2007 let k = self.entry_index(id)?;
2008 let store = core::mem::replace(&mut self.series[k].store, Store::None);
2009 let Store::Custom(mut c) = store else {
2010 self.series[k].store = store;
2011 return Err(NOT_CUSTOM);
2012 };
2013 let out = modify(&mut c).and_then(|change| {
2014 let applied = c
2015 .classify(change)
2016 .and_then(|kind| self.apply_custom(k, &mut c, kind));
2017 if applied.is_err() {
2018 c.clear();
2019 self.invalidation = Invalidation::Full;
2020 }
2021 applied
2022 });
2023 self.series[k].store = Store::Custom(c);
2024 match out? {
2025 None => {}
2026 Some(DataChange::UpdateLast) => {
2027 self.invalidation = self.invalidation.max(Invalidation::Data);
2028 self.after_data(id, DataChange::UpdateLast);
2029 }
2030 Some(change) => {
2031 self.after_change(id, 0);
2032 self.after_data(id, change);
2033 }
2034 }
2035 Ok(())
2036 }
2037
2038 fn apply_custom(
2041 &mut self,
2042 k: usize,
2043 c: &mut CustomStore,
2044 kind: CustomChange,
2045 ) -> Result<Option<DataChange>> {
2046 let old = c.len();
2047 let n = c.plugin.times().len();
2048 let span = |a: usize, b: usize| IdxSpan {
2049 start: i64::try_from(a).unwrap_or(i64::MAX),
2050 end: i64::try_from(b).unwrap_or(i64::MAX),
2051 };
2052 let change = match kind {
2053 CustomChange::None => return Ok(None),
2054 CustomChange::UpdateLast => {
2055 c.log.record(span(old.saturating_sub(1), old));
2057 return Ok(Some(DataChange::UpdateLast));
2058 }
2059 CustomChange::Append => DataChange::Append { count: n - old },
2060 CustomChange::Prepend { count } => DataChange::Prepend { count },
2061 CustomChange::Replace => DataChange::Replace,
2062 };
2063 if c.mode == AxisMode::Overlay {
2064 c.map_onto(&self.time_index)?;
2065 if kind == CustomChange::Append {
2066 c.log.record(span(old, n));
2067 } else {
2068 c.log.replace();
2069 }
2070 return Ok(Some(change));
2071 }
2072 match kind {
2073 CustomChange::Append | CustomChange::Prepend { .. } => {
2074 let times = c.plugin.times();
2075 let new = match kind {
2076 CustomChange::Prepend { count } => times.get(..count),
2077 _ => times.get(old..),
2078 };
2079 if let Some(added) = self.cover(new.unwrap_or(&[]))? {
2080 let mapped = if kind == CustomChange::Append {
2081 c.extend_onto(&self.time_index)
2082 } else {
2083 c.map_onto(&self.time_index)
2084 };
2085 if let Err(e) = mapped {
2086 self.time_index.truncate_ends(added.0, added.1);
2087 return Err(e);
2088 }
2089 if kind == CustomChange::Append {
2090 c.log.record(span(old, n));
2091 } else {
2092 c.log.replace();
2094 }
2095 } else {
2096 let others = self.other_spans(k);
2097 self.rebuild(k, Target::Custom(c), &others)?;
2098 }
2099 }
2100 _ => {
2101 let others = self.other_spans(k);
2102 let times = c.plugin.times();
2103 if others.is_empty() {
2104 let mut own = Vec::new();
2106 own.try_reserve_exact(times.len())
2107 .map_err(|_| Error::OutOfMemory)?;
2108 own.extend_from_slice(times);
2109 let index = TimeIndex::from_times(own)?;
2110 c.map_onto(&index)?;
2111 self.time_index = index;
2112 self.axis_rebuilt = true;
2113 } else if let Some(m) = self.time_index.map_series(times)?
2114 && !self.has_orphans(&others, times)
2115 {
2116 c.accept(m);
2117 } else {
2118 self.rebuild(k, Target::Custom(c), &others)?;
2119 }
2120 c.log.replace();
2121 }
2122 }
2123 Ok(Some(change))
2124 }
2125
2126 pub fn create_price_line(
2139 &mut self,
2140 series: SeriesId,
2141 opts: PriceLineOptions,
2142 ) -> Result<PriceLineId> {
2143 let e = self.entry(series)?;
2144 if e.kind == SeriesKind::Volume {
2145 return Err(Error::InvalidArgument("volume series have no price lines"));
2146 }
2147 if !opts.price.is_finite() {
2148 return Err(Error::InvalidArgument("the price must be finite"));
2149 }
2150 let id = PriceLineId(self.next_price_line);
2151 self.next_price_line += 1;
2152 self.price_lines.push(PriceLineEntry { id, series, opts });
2153 self.invalidation = self.invalidation.max(Invalidation::Data);
2154 Ok(id)
2155 }
2156
2157 pub fn update_price_line(&mut self, id: PriceLineId, opts: PriceLineOptions) -> Result<()> {
2179 if !opts.price.is_finite() {
2180 return Err(Error::InvalidArgument("the price must be finite"));
2181 }
2182 let line = self
2183 .price_lines
2184 .iter_mut()
2185 .find(|l| l.id == id)
2186 .ok_or(Error::UnknownId)?;
2187 line.opts = opts;
2188 self.invalidation = self.invalidation.max(Invalidation::Data);
2189 Ok(())
2190 }
2191
2192 pub fn price_line(&self, id: PriceLineId) -> Option<&PriceLineOptions> {
2194 self.price_lines
2195 .iter()
2196 .find(|l| l.id == id)
2197 .map(|l| &l.opts)
2198 }
2199
2200 pub fn remove_price_line(&mut self, id: PriceLineId) -> Result<()> {
2206 let n = self.price_lines.len();
2207 self.price_lines.retain(|l| l.id != id);
2208 if self.price_lines.len() == n {
2209 return Err(Error::UnknownId);
2210 }
2211 self.invalidation = self.invalidation.max(Invalidation::Data);
2212 Ok(())
2213 }
2214
2215 pub fn add_indicator(
2269 &mut self,
2270 source: SeriesId,
2271 ind: Box<dyn Indicator>,
2272 placement: Placement,
2273 ) -> Result<IndicatorId> {
2274 let src = self.entry(source)?;
2275 if src.kind == SeriesKind::Volume {
2276 return Err(Error::InvalidArgument(
2277 "volume series have no data of their own; use the source series",
2278 ));
2279 }
2280 if src.kind == SeriesKind::Custom {
2281 return Err(Error::InvalidArgument(
2282 "indicators take built-in series as their source",
2283 ));
2284 }
2285 if ind.outputs().is_empty() {
2286 return Err(Error::InvalidArgument("the indicator has no outputs"));
2287 }
2288 let n_out = ind.outputs().len();
2289 if ind
2290 .outputs()
2291 .iter()
2292 .enumerate()
2293 .any(|(i, o)| o.fill_to.is_some_and(|(to, _)| to >= n_out || to == i))
2294 {
2295 return Err(Error::InvalidArgument(
2296 "fill_to must name another output of the indicator",
2297 ));
2298 }
2299 let has_data = !src.store.is_empty();
2300 if ind.needs_volume() && (is_value_kind(src.kind) || has_data && !src.store.has_volume()) {
2301 return Err(Error::InvalidArgument("the indicator needs volume"));
2302 }
2303 let src_pane = src.pane;
2304 let volume_pane = self
2305 .series
2306 .iter()
2307 .find(|e| e.kind == SeriesKind::Volume && e.opts.source == Some(source))
2308 .map(|e| e.pane);
2309 let on_volume = placement == Placement::Volume && volume_pane.is_some();
2310 let (pane, own_pane) = match (placement, volume_pane) {
2311 (Placement::Volume, Some(p)) => (p, None),
2312 (Placement::Overlay, _) => (src_pane, None),
2313 (Placement::Pane(p), _) => {
2314 if !self.panes.iter().any(|x| x.id == p) {
2315 return Err(Error::UnknownId);
2316 }
2317 (p, None)
2318 }
2319 (Placement::NewPane | Placement::Volume, _) => {
2320 let p = self.add_pane(PaneOptions::default());
2321 (p, Some(p))
2322 }
2323 };
2324 let mut series = Vec::with_capacity(ind.outputs().len());
2325 for spec in ind.outputs() {
2326 let color = spec.color.unwrap_or_else(|| {
2327 let c = INDICATOR_PALETTE[self.palette_next % INDICATOR_PALETTE.len()];
2328 self.palette_next += 1;
2329 Rgba::hex(c)
2330 });
2331 let kind = match spec.kind {
2332 OutputKind::Line => SeriesKind::Line,
2333 OutputKind::Histogram => SeriesKind::Histogram,
2334 OutputKind::Points => SeriesKind::Points,
2335 };
2336 let opts = SeriesOptions {
2337 color: Some(color),
2338 line_width: Css(if kind == SeriesKind::Points { 3.0 } else { 1.0 }),
2340 price_line_visible: false,
2341 shift: spec.shift,
2342 ..SeriesOptions::default()
2343 };
2344 let id = self.insert_series(pane, kind, opts)?;
2345 if let Some(e) = self.series.iter_mut().find(|e| e.id == id) {
2346 e.derived = true;
2347 e.volume_scale = on_volume;
2348 }
2349 series.push(id);
2350 }
2351 let mut bands = Vec::new();
2352 for (i, spec) in ind.outputs().iter().enumerate() {
2353 if let Some((to, opts)) = spec.fill_to
2354 && let (Some(&upper), Some(&lower)) = (series.get(i), series.get(to))
2355 {
2356 bands.push(self.add_band(upper, lower, opts)?);
2357 }
2358 }
2359 let id = IndicatorId(self.next_indicator);
2360 self.next_indicator += 1;
2361 self.indicators.push(IndicatorEntry {
2362 id,
2363 source,
2364 ind,
2365 series,
2366 own_pane,
2367 bands,
2368 });
2369 self.update_indicator(self.indicators.len() - 1, DataChange::Replace);
2370 self.invalidation = Invalidation::Full;
2371 Ok(id)
2372 }
2373
2374 pub fn remove_indicator(&mut self, id: IndicatorId) -> Result<()> {
2381 let n = self
2382 .indicators
2383 .iter()
2384 .position(|x| x.id == id)
2385 .ok_or(Error::UnknownId)?;
2386 self.drop_indicator(n);
2387 self.invalidation = Invalidation::Full;
2388 Ok(())
2389 }
2390
2391 pub fn indicator_series(&self, id: IndicatorId) -> Option<&[SeriesId]> {
2394 self.indicators
2395 .iter()
2396 .find(|x| x.id == id)
2397 .map(|x| x.series.as_slice())
2398 }
2399
2400 pub fn indicator_bands(&self, id: IndicatorId) -> Option<&[BandId]> {
2444 self.indicators
2445 .iter()
2446 .find(|x| x.id == id)
2447 .map(|x| x.bands.as_slice())
2448 }
2449
2450 fn drop_indicator(&mut self, n: usize) {
2451 if n >= self.indicators.len() {
2452 return;
2453 }
2454 let entry = self.indicators.remove(n);
2455 for &out in &entry.series {
2456 self.drop_indicators_of(out);
2457 }
2458 self.series.retain(|e| !entry.series.contains(&e.id));
2459 self.price_lines
2460 .retain(|l| self.series.iter().any(|e| e.id == l.series));
2461 self.prune_bands();
2462 if let Some(p) = entry.own_pane
2463 && self.panes.len() > 1
2464 && !self.series.iter().any(|e| e.pane == p)
2465 {
2466 let _ = self.remove_pane(p);
2467 }
2468 }
2469
2470 fn drop_indicators_of(&mut self, series: SeriesId) {
2472 while let Some(n) = self.indicators.iter().position(|x| x.source == series) {
2473 self.drop_indicator(n);
2474 }
2475 }
2476
2477 fn after_data(&mut self, id: SeriesId, change: DataChange) {
2479 if core::mem::take(&mut self.axis_rebuilt) {
2480 let roots = (0..self.indicators.len())
2482 .filter(|&n| {
2483 let src = self.indicators[n].source;
2484 !self.indicators.iter().any(|x| x.series.contains(&src))
2485 })
2486 .collect();
2487 self.recompute_levels(roots);
2488 } else {
2489 self.run_indicators(id, change);
2490 }
2491 }
2492
2493 fn run_indicators(&mut self, source: SeriesId, change: DataChange) {
2495 if !matches!(change, DataChange::Append { .. } | DataChange::UpdateLast) {
2496 let roots = (0..self.indicators.len())
2497 .filter(|&n| self.indicators[n].source == source)
2498 .collect();
2499 self.recompute_levels(roots);
2500 return;
2501 }
2502 for n in 0..self.indicators.len() {
2503 if self.indicators[n].source == source {
2504 self.update_indicator(n, change);
2505 for o in 0..self.indicators[n].series.len() {
2506 let out = self.indicators[n].series[o];
2507 self.run_indicators(out, change);
2508 }
2509 }
2510 }
2511 }
2512
2513 fn recompute_levels(&mut self, mut level: Vec<usize>) {
2518 while !level.is_empty() {
2519 self.recompute_level(&level);
2520 let outs: Vec<SeriesId> = level
2521 .iter()
2522 .flat_map(|&n| self.indicators[n].series.iter().copied())
2523 .collect();
2524 level = (0..self.indicators.len())
2525 .filter(|&n| outs.contains(&self.indicators[n].source))
2526 .collect();
2527 }
2528 }
2529
2530 fn recompute_level(&mut self, level: &[usize]) {
2531 #[cfg(feature = "rayon")]
2532 if level.len() > 1 {
2533 use rayon::prelude::*;
2534 let index = &self.time_index;
2535 let sources: Vec<Option<crate::series::PlainSource<'_>>> = (0..self.indicators.len())
2538 .map(|n| {
2539 let src = self.indicators[n].source;
2540 level
2541 .contains(&n)
2542 .then(|| self.series.iter().find(|e| e.id == src))
2543 .flatten()
2544 .and_then(|e| match e.store.source() {
2545 crate::series::Source::Plain(p) => Some(p),
2546 crate::series::Source::Custom(_) => None,
2547 })
2548 })
2549 .collect();
2550 let results: Vec<_> = self
2551 .indicators
2552 .par_iter_mut()
2553 .zip(sources.par_iter())
2554 .enumerate()
2555 .filter_map(|(n, (entry, source))| {
2556 let mut out = IndicatorOutputs::default();
2557 let source = crate::series::Source::Plain((*source)?);
2558 let done =
2559 compute_indicator(entry, source, index, DataChange::Replace, &mut out);
2560 Some((n, done, out))
2561 })
2562 .collect();
2563 let done: Vec<usize> = results.iter().map(|r| r.0).collect();
2564 for (n, (change, start), out) in results {
2565 self.write_indicator(n, change, start, &out);
2566 }
2567 for &n in level.iter().filter(|n| !done.contains(n)) {
2568 self.update_indicator(n, DataChange::Replace);
2569 }
2570 return;
2571 }
2572 for &n in level {
2573 self.update_indicator(n, DataChange::Replace);
2574 }
2575 }
2576
2577 fn update_indicator(&mut self, n: usize, change: DataChange) {
2579 let Some(entry) = self.indicators.get_mut(n) else {
2580 return;
2581 };
2582 let Some(source) = self.series.iter().find(|e| e.id == entry.source) else {
2583 return;
2584 };
2585 let mut out = core::mem::take(&mut self.ind_out);
2586 let (change, start) = compute_indicator(
2587 entry,
2588 source.store.source(),
2589 &self.time_index,
2590 change,
2591 &mut out,
2592 );
2593 self.write_indicator(n, change, start, &out);
2594 if change == DataChange::Replace {
2595 out.shrink();
2596 }
2597 self.ind_out = out;
2598 }
2599
2600 fn write_indicator(
2603 &mut self,
2604 n: usize,
2605 change: DataChange,
2606 start: usize,
2607 out: &IndicatorOutputs,
2608 ) {
2609 let Some(entry) = self.indicators.get(n) else {
2610 return;
2611 };
2612 let Some(k) = self.series.iter().position(|e| e.id == entry.source) else {
2613 return;
2614 };
2615 let input = IndicatorInput::new(self.series[k].store.source(), &self.time_index);
2616 let len = input.len();
2617 let first = input.first();
2618 let outputs = out.columns().len();
2619 for o in 0..outputs.min(entry.series.len()) {
2620 let id = entry.series[o];
2621 let Some(ko) = self.series.iter().position(|e| e.id == id) else {
2622 continue;
2623 };
2624 let col = out.columns().get(o).map_or(&[][..], Vec::as_slice);
2625 let src = &self.series[k].store;
2626 let index = &self.time_index;
2627 if change == DataChange::UpdateLast {
2630 let j = first + i64::try_from(start).unwrap_or(0);
2631 let (Some(time), Some(&v)) = (index.time_at(j), col.first()) else {
2632 continue;
2633 };
2634 if src.bar_at(j).is_none() {
2635 continue;
2636 }
2637 let bar = BarUpdate {
2638 time,
2639 open: v,
2640 high: v,
2641 low: v,
2642 close: v,
2643 volume: None,
2644 };
2645 let entry = &mut self.series[ko];
2646 let op = Op {
2647 kind: entry.kind,
2648 index,
2649 mode: ValidationMode::Repair,
2650 };
2651 let _ = op.update_last(&mut entry.store, bar);
2652 continue;
2653 }
2654 let mut time = Vec::new();
2655 let mut value = Vec::new();
2656 for (i, &v) in col.iter().enumerate() {
2657 let j = first + i64::try_from(start + i).unwrap_or(0);
2658 if src.bar_at(j).is_some()
2659 && let Some(t) = index.time_at(j)
2660 {
2661 time.push(t);
2662 value.push(v);
2663 }
2664 }
2665 if time.is_empty() && change != DataChange::Replace {
2666 continue;
2667 }
2668 let data = SeriesData::Value(crate::data::ValueColumns {
2669 time,
2670 value,
2671 color: None,
2672 });
2673 let entry = &mut self.series[ko];
2674 let op = Op {
2675 kind: entry.kind,
2676 index,
2677 mode: ValidationMode::Repair,
2678 };
2679 let done = if change == DataChange::Replace {
2680 if len == 0 {
2681 entry.store = Store::for_kind(entry.kind);
2682 Ok(0)
2683 } else {
2684 op.set(&mut entry.store, data)
2685 }
2686 } else {
2687 op.append(&mut entry.store, data)
2688 };
2689 if done.is_err() {
2690 entry.store = Store::for_kind(entry.kind);
2692 }
2693 }
2694 }
2695
2696 pub fn set_markers(&mut self, series: SeriesId, mut markers: Vec<Marker>) -> Result<()> {
2708 let k = self.entry_index(series)?;
2709 if self.series[k].kind == SeriesKind::Volume {
2710 return Err(Error::InvalidArgument("volume series have no markers"));
2711 }
2712 markers.sort_by_key(|m| m.time);
2713 self.series[k].markers = markers;
2714 self.invalidation = self.invalidation.max(Invalidation::Data);
2715 Ok(())
2716 }
2717
2718 pub fn markers(&self, series: SeriesId) -> Option<&[Marker]> {
2720 self.entry(series).ok().map(|e| e.markers.as_slice())
2721 }
2722
2723 pub fn time_scale(&mut self) -> &mut TimeScale {
2725 &mut self.time_scale
2726 }
2727
2728 pub fn price_scale(&mut self, pane: PaneId, side: ScaleSide) -> Option<&mut PriceScale> {
2731 if side != ScaleSide::Right {
2732 return None;
2733 }
2734 self.pane_mut(pane).map(|p| &mut p.price_scale)
2735 }
2736
2737 pub fn fit_content(&mut self) {
2739 self.time_scale.fit_content();
2740 }
2741
2742 pub fn scroll_to_realtime(&mut self) {
2745 self.time_scale.set_right_offset(self.default_right_offset);
2746 }
2747
2748 pub fn needs_redraw(&self) -> Invalidation {
2751 let mut inv = self.invalidation;
2752 if self.time_scale.changed
2753 || self.drawings.dirty
2754 || self.input.kinetic.is_some()
2755 || self.panes.iter().any(|p| p.price_scale.changed)
2756 {
2757 inv = inv.max(Invalidation::Light);
2758 }
2759 inv.max(self.sync_pending())
2760 }
2761
2762 pub fn frame(&self) -> &Frame {
2764 &self.frame
2765 }
2766
2767 pub fn data_view(&self) -> ChartDataView<'_> {
2769 ChartDataView {
2770 series: &self.series,
2771 time_index: &self.time_index,
2772 }
2773 }
2774
2775 pub fn layout(&self) -> Layout {
2777 self.layout
2778 }
2779
2780 pub fn set_reveal(&mut self, reveal: Option<Reveal>) {
2798 if self.reveal != reveal {
2799 self.reveal = reveal;
2800 self.invalidation = self.invalidation.max(Invalidation::Light);
2801 }
2802 }
2803
2804 pub fn reveal(&self) -> Option<Reveal> {
2806 self.reveal
2807 }
2808
2809 fn data_clip(&self, plot: RectPx) -> RectPx {
2811 self.reveal.map_or(plot, |r| r.clip(plot))
2812 }
2813
2814 fn revealing(&self) -> bool {
2817 self.reveal.is_some_and(|r| !r.is_done())
2818 }
2819
2820 pub fn heap_bytes(&self) -> usize {
2823 self.series
2824 .iter()
2825 .map(|e| e.store.heap_bytes())
2826 .sum::<usize>()
2827 + self.time_index.len() * core::mem::size_of::<i64>()
2828 }
2829
2830 pub fn drain_events(&mut self) -> impl Iterator<Item = ChartEvent> + '_ {
2832 self.events.append(&mut self.drawings.events);
2833 self.events.drain(..)
2834 }
2835
2836 fn style_of(&self, e: &SeriesEntry) -> SeriesStyle {
2838 let t = &self.theme;
2839 let o = &e.opts;
2840 let mut st = SeriesStyle {
2841 line_width: Px(o.line_width.to_px(self.dpr).0.round().max(1.0)),
2842 line_dash: o.line_style,
2843 step: o.step,
2844 base_value: o.base_value,
2845 ..SeriesStyle::default()
2846 };
2847 let (up, down) = match e.kind {
2848 SeriesKind::Line | SeriesKind::Area | SeriesKind::Histogram | SeriesKind::Points => {
2849 let c = o.color.unwrap_or(if e.kind == SeriesKind::Histogram {
2850 t.up
2851 } else {
2852 t.line
2853 });
2854 (c, c)
2855 }
2856 SeriesKind::Volume => (t.volume_up, t.volume_down),
2857 _ => (o.color.unwrap_or(t.up), o.down_color.unwrap_or(t.down)),
2858 };
2859 st.up = up;
2860 st.down = down;
2861 st.up_border = up;
2862 st.down_border = down;
2863 let themed_wicks = o.color.is_none() && o.down_color.is_none();
2864 st.up_wick = if themed_wicks { t.up_wick } else { up };
2865 st.down_wick = if themed_wicks { t.down_wick } else { down };
2866 let (top, bottom) = match e.kind {
2867 SeriesKind::Area => (up.with_alpha(0x66), up.with_alpha(0x05)),
2868 _ => (up.with_alpha(0x33), down.with_alpha(0x33)),
2869 };
2870 st.fill_top = o.top_fill.unwrap_or(top);
2871 st.fill_bottom = o.bottom_fill.unwrap_or(bottom);
2872 st
2873 }
2874
2875 fn autoscale(&mut self) {
2878 let (from, to) = self.time_scale.visible_range();
2879 let (a, b) = (from.floor() as i64, to.ceil() as i64 + 1);
2880 let spacing = self.time_scale.bar_spacing();
2881 for i in 0..self.panes.len() {
2882 let id = self.panes[i].id;
2883 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
2884 let mut precision = None;
2885 let mut any_price = false;
2886 let mut max_volume: Option<f64> = None;
2887 for k in 0..self.series.len() {
2888 if self.series[k].pane != id {
2889 continue;
2890 }
2891 if self.series[k].kind == SeriesKind::Volume {
2892 let source = self.series[k]
2893 .opts
2894 .source
2895 .and_then(|s| self.series.iter().find(|e| e.id == s));
2896 if let Some(src) = source
2897 && src.store.has_volume()
2898 {
2899 let level = lod_level(src.store.lod(), spacing);
2900 if let Some(view) = src.store.level_view(level) {
2901 let span = visible_span(&view, from, to);
2902 let m = max_volume_in(&view, span);
2903 max_volume = Some(max_volume.unwrap_or(0.0).max(m));
2904 }
2905 }
2906 continue;
2907 }
2908 if self.series[k].volume_scale {
2909 let e = &mut self.series[k];
2911 e.norm = Some(Normalize::IDENTITY);
2912 let s = i64::from(e.opts.shift);
2913 if let Some((_, h)) = e.store.extremes(a - s, b - s) {
2914 max_volume = Some(max_volume.unwrap_or(0.0).max(h));
2915 }
2916 continue;
2917 }
2918 let mode = self.panes[i].price_scale.mode();
2919 let e = &mut self.series[k];
2920 precision.get_or_insert(e.opts.price_precision);
2921 if e.store.is_empty() {
2922 e.norm = None;
2923 continue;
2924 }
2925 any_price = true;
2926 let s = i64::from(e.opts.shift);
2927 let (a, b) = (a - s, b - s);
2928 let base = mode
2929 .is_relative()
2930 .then(|| first_value(&e.store, a, b))
2931 .flatten();
2932 e.norm = Normalize::new(mode, base);
2933 let Some(norm) = e.norm else { continue };
2934 let extremes = match e.store.custom() {
2935 Some(c) => c.extremes(&self.time_index, a, b),
2936 None => e.store.extremes(a, b),
2937 };
2938 if let Some((l, h)) = extremes {
2939 e.auto_decimals = auto_decimals(l.abs().max(h.abs()));
2940 lo = lo.min(norm.apply(l));
2942 hi = hi.max(norm.apply(h));
2943 if e.kind == SeriesKind::Histogram {
2944 let base = norm.apply(e.opts.base_value);
2945 lo = lo.min(base);
2946 hi = hi.max(base);
2947 }
2948 }
2949 }
2950 let pane = &mut self.panes[i];
2951 pane.has_content = any_price || max_volume.is_some();
2952 pane.labels = match pane.price_scale.mode() {
2953 _ if !any_price && max_volume.is_some() => NumberFormat::Compact,
2954 crate::price_scale::PriceScaleMode::Percentage => NumberFormat::Percent(2),
2955 crate::price_scale::PriceScaleMode::IndexedTo100 => NumberFormat::Fixed(2),
2956 _ => match precision.flatten() {
2957 Some(p) => NumberFormat::Fixed(p),
2958 None if lo <= hi => NumberFormat::Auto(auto_decimals(lo.abs().max(hi.abs()))),
2959 None => NumberFormat::Auto(2),
2960 },
2961 };
2962 if any_price && lo <= hi {
2963 pane.price_scale.fit(lo, hi);
2964 }
2965 if let Some(m) = max_volume {
2966 if any_price {
2967 pane.volume_scale.fit(0.0, m);
2968 } else {
2969 pane.price_scale.fit(0.0, m);
2970 }
2971 }
2972 }
2973 }
2974
2975 fn pane_has_content(&self, i: usize) -> bool {
2977 self.panes.get(i).is_some_and(|p| p.has_content)
2978 }
2979
2980 pub fn build_frame(&mut self, now_ms: f64, text: &dyn TextMeasurer) {
2991 self.step_kinetic(now_ms);
2992 self.pull_sync();
2993 let inv = self.needs_redraw();
2994 if inv >= Invalidation::Light {
2995 self.revisions[LayerId::Background as usize] += 1;
2996 self.revisions[LayerId::Main as usize] += 1;
2997 }
2998 if inv >= Invalidation::Cursor {
2999 self.revisions[LayerId::Overlay as usize] += 1;
3000 }
3001 let w = (self.size.w * self.dpr).round();
3002 let h = (self.size.h * self.dpr).round();
3003 self.frame
3004 .begin(SizePx { w, h }, self.theme.background, inv);
3005 for (layer, rev) in self.frame.layers.iter_mut().zip(self.revisions) {
3006 layer.revision = rev;
3007 }
3008 self.invalidation = Invalidation::None;
3009 self.time_scale.changed = false;
3010 self.drawings.dirty = false;
3011 for pane in &mut self.panes {
3012 pane.price_scale.changed = false;
3013 }
3014 if w < 1.0 || h < 1.0 {
3015 return;
3016 }
3017
3018 let font = FontStyleRef {
3019 font: FontId(0),
3020 size: self.theme.font_size.to_px(self.dpr).0,
3021 };
3022 let line_h = text.line_height(font);
3023 if font.size > 0.0 {
3024 self.text_cache = CachedText {
3025 advances: *text.ascii_advances(font),
3026 subscripts: text.subscript_advances(font).copied().unwrap_or([0.6; 10]),
3027 line: line_h / font.size,
3028 };
3029 }
3030 let pad = self.theme.axis_padding.to_px(self.dpr).0.round();
3031 let time_h = (line_h + 2.0 * pad).ceil().min(h);
3032 let panes_h = (h - time_h).max(0.0);
3033
3034 for _ in 0..2 {
3038 let plot_w = (w - self.axis_width).max(0.0);
3039 self.time_scale.set_width(f64::from(plot_w));
3040 stack(&mut self.panes, 0.0, panes_h, plot_w);
3041 self.autoscale();
3042 let mut widest: f32 = 0.0;
3043 for i in 0..self.panes.len() {
3044 let has_content = self.pane_has_content(i);
3045 let pane = &mut self.panes[i];
3046 if has_content {
3047 pane.price_scale.ticks(
3048 f64::from(pane.plot.h),
3049 f64::from(line_h) * 2.5,
3050 &mut pane.ticks,
3051 );
3052 } else {
3053 pane.ticks.clear();
3054 }
3055 let labels = pane.labels.for_ticks(&pane.ticks);
3056 for &p in &pane.ticks {
3057 let mut s = StackStr::<64>::new();
3058 write_label(&mut s, p, labels);
3059 widest = widest.max(text_width(text, s.as_str(), font));
3060 }
3061 }
3062 let required = (widest + 2.0 * pad).ceil().min(w);
3063 if required > self.axis_width || required < self.axis_width * 0.75 {
3064 self.axis_width = required;
3065 } else {
3066 break;
3067 }
3068 }
3069 let plot_w = (w - self.axis_width).max(0.0);
3070 self.time_scale.set_width(f64::from(plot_w));
3071 self.time_scale.settle();
3072 stack(&mut self.panes, 0.0, panes_h, plot_w);
3073 self.layout = Layout {
3074 plot: self.panes.first().map_or(RectPx::default(), |p| p.plot),
3075 price_axis: RectPx {
3076 x: plot_w,
3077 y: 0.0,
3078 w: w - plot_w,
3079 h: panes_h,
3080 },
3081 time_axis: RectPx {
3082 x: 0.0,
3083 y: panes_h,
3084 w,
3085 h: h - panes_h,
3086 },
3087 };
3088
3089 self.place_time_ticks(text, font);
3090 self.emit_layers(None, LayerPosition::BelowSeries, text);
3091 self.marker_hits.clear();
3092 for i in 0..self.panes.len() {
3093 self.emit_grid(i);
3094 self.emit_layers(Some(i), LayerPosition::Background, text);
3095 self.emit_layers(Some(i), LayerPosition::BelowSeries, text);
3096 self.emit_series(i, text);
3097 self.emit_markers(i, line_h, font);
3098 self.emit_layers(Some(i), LayerPosition::AboveSeries, text);
3099 self.emit_drawings(i, text);
3100 self.emit_marks(i, line_h, pad, font);
3101 self.emit_price_labels(i, line_h, pad, font);
3102 }
3103 self.emit_layers(None, LayerPosition::Background, text);
3104 self.emit_layers(None, LayerPosition::AboveSeries, text);
3105 self.emit_axes(time_h, font);
3106 for i in 0..self.panes.len() {
3107 self.emit_layers(Some(i), LayerPosition::Overlay, text);
3108 }
3109 self.emit_layers(None, LayerPosition::Overlay, text);
3110 if let Some(r) = self.reveal {
3111 for pane in &self.panes {
3112 r.push_pen(&mut self.frame, LayerId::Overlay, pane.plot, self.dpr);
3113 }
3114 }
3115 let local_crosshair = self.emit_crosshair(time_h, pad, font);
3116 self.emit_view_events();
3117 self.push_sync(local_crosshair.map(|i| i as f64));
3118 }
3119
3120 pub fn drawings(&mut self) -> &mut DrawingManager {
3122 &mut self.drawings
3123 }
3124
3125 pub fn add_band(
3138 &mut self,
3139 upper: SeriesId,
3140 lower: SeriesId,
3141 opts: BandOptions,
3142 ) -> Result<BandId> {
3143 let (u, l) = (self.entry(upper)?, self.entry(lower)?);
3144 if !is_value_kind(u.kind) || !is_value_kind(l.kind) {
3145 return Err(Error::InvalidArgument(
3146 "a band is between two single-value series",
3147 ));
3148 }
3149 if u.pane != l.pane || upper == lower {
3150 return Err(Error::InvalidArgument(
3151 "a band is between two different series of the same pane",
3152 ));
3153 }
3154 let id = BandId(self.next_band);
3155 self.next_band += 1;
3156 self.bands.push(BandEntry {
3157 id,
3158 upper,
3159 lower,
3160 opts,
3161 });
3162 self.invalidation = Invalidation::Full;
3163 Ok(id)
3164 }
3165
3166 pub fn set_band_options(&mut self, id: BandId, opts: BandOptions) -> Result<()> {
3172 let b = self
3173 .bands
3174 .iter_mut()
3175 .find(|b| b.id == id)
3176 .ok_or(Error::UnknownId)?;
3177 b.opts = opts;
3178 self.invalidation = Invalidation::Full;
3179 Ok(())
3180 }
3181
3182 pub fn band_options(&self, id: BandId) -> Option<&BandOptions> {
3184 self.bands.iter().find(|b| b.id == id).map(|b| &b.opts)
3185 }
3186
3187 pub fn remove_band(&mut self, id: BandId) -> Result<()> {
3193 let n = self
3194 .bands
3195 .iter()
3196 .position(|b| b.id == id)
3197 .ok_or(Error::UnknownId)?;
3198 self.bands.remove(n);
3199 self.invalidation = Invalidation::Full;
3200 Ok(())
3201 }
3202
3203 pub(crate) fn emit_click(&mut self, pane: PaneId, p: PointPx, drawing: Option<DrawingId>) {
3206 let Some(pn) = self.pane_index(pane).and_then(|i| self.panes.get(i)) else {
3207 return;
3208 };
3209 let plot = pn.plot;
3210 let logical_index = self.time_scale.x_to_index(Px(p.x - plot.x));
3211 let price = pn
3212 .price_scale
3213 .y_to_price(f64::from(p.y), f64::from(plot.y), f64::from(plot.h));
3214 let time = self.time_index.time_at(logical_index.round() as i64);
3215 let target = drawing
3216 .or_else(|| self.hit_drawing(pane, p).map(|(d, _)| d))
3217 .map(ClickTarget::Drawing)
3218 .or_else(|| self.hit_marker(pane, p))
3219 .or_else(|| self.hit_series(pane, p).map(ClickTarget::Series));
3220 self.events.push(ChartEvent::Click {
3221 pos: PointCss {
3222 x: p.x / self.dpr,
3223 y: p.y / self.dpr,
3224 },
3225 pane,
3226 logical_index,
3227 time,
3228 price,
3229 target,
3230 });
3231 }
3232
3233 fn hit_marker(&self, pane: PaneId, p: PointPx) -> Option<ClickTarget> {
3235 let tol = HIT_TOLERANCE * 0.5 * self.dpr;
3236 self.marker_hits
3237 .iter()
3238 .rev()
3239 .find(|m| m.pane == pane && (p.x - m.pos.x).hypot(p.y - m.pos.y) <= m.radius + tol)
3240 .map(|m| ClickTarget::Marker {
3241 series: m.series,
3242 index: m.index,
3243 })
3244 }
3245
3246 fn hit_series(&self, pane: PaneId, p: PointPx) -> Option<SeriesId> {
3249 let pn = self.panes.get(self.pane_index(pane)?)?;
3250 let plot = pn.plot;
3251 let (top, height) = (f64::from(plot.y), f64::from(plot.h));
3252 let has_price = self
3253 .series
3254 .iter()
3255 .any(|e| e.pane == pane && !volume_like(e) && !e.store.is_empty());
3256 let tol = HIT_TOLERANCE * self.dpr;
3257 let m = crate::transform_helpers::bar_metrics(self.time_scale.bar_spacing() as f32);
3258 let half_bar = (m.body * 0.5).max(tol * 0.5);
3259 let center = self.time_scale.x_to_index(Px(p.x - plot.x)).round() as i64;
3260 let within = |a: f32, b: f32| p.y >= a.min(b) - 1.0 && p.y <= a.max(b) + 1.0;
3261 for e in self.series.iter().rev().filter(|e| e.pane == pane) {
3262 let (store, shift) = if e.kind == SeriesKind::Volume {
3263 let src = e
3264 .opts
3265 .source
3266 .and_then(|s| self.series.iter().find(|x| x.id == s));
3267 let Some(src) = src else { continue };
3268 (&src.store, 0)
3269 } else {
3270 (&e.store, i64::from(e.opts.shift))
3271 };
3272 let x_of = |j: i64| plot.x + self.time_scale.index_to_x((j + shift) as f64).0;
3273 let y_of = |v: f64| -> Option<f32> {
3274 let y = if volume_like(e) {
3275 let scale = if has_price {
3276 &pn.volume_scale
3277 } else {
3278 &pn.price_scale
3279 };
3280 scale.price_to_y(v, top, height)
3281 } else {
3282 pn.price_scale.price_to_y(e.norm?.apply(v), top, height)
3283 };
3284 y.is_finite().then_some(y as f32)
3285 };
3286 let point = |j: i64| -> Option<PointPx> {
3287 let v = store.bar_at(j)?[3];
3288 Some(PointPx {
3289 x: x_of(j),
3290 y: y_of(v)?,
3291 })
3292 };
3293 let j = center - shift;
3294 let hit = match e.kind {
3295 k if is_ohlc_kind(k) => (|| {
3296 let [o, h, l, c] = store.bar_at(j)?;
3297 let dx = (p.x - x_of(j)).abs();
3298 let (yo, yh, yl, yc) = (y_of(o)?, y_of(h)?, y_of(l)?, y_of(c)?);
3299 Some(
3300 (dx <= tol * 0.5 && within(yh, yl))
3301 || (dx <= m.body * 0.5 && within(yo, yc)),
3302 )
3303 })(),
3304 SeriesKind::Volume | SeriesKind::Histogram => (|| {
3305 let (v, base) = if e.kind == SeriesKind::Volume {
3306 (store.volume_at(j)?, 0.0)
3307 } else {
3308 (store.bar_at(j)?[3], e.opts.base_value)
3309 };
3310 let dx = (p.x - x_of(j)).abs();
3311 Some(dx <= half_bar && within(y_of(v)?, y_of(base)?))
3312 })(),
3313 SeriesKind::Points => point(j).map(|c| {
3314 let r = e.opts.line_width.to_px(self.dpr).0 * 0.5;
3315 (p.x - c.x).hypot(p.y - c.y) <= r + tol * 0.5
3316 }),
3317 SeriesKind::Line | SeriesKind::Area | SeriesKind::Baseline => point(j).map(|c| {
3318 [point(j - 1), point(j + 1)]
3319 .into_iter()
3320 .map(|n| {
3321 n.map_or_else(
3322 || (p.x - c.x).hypot(p.y - c.y),
3323 |n| segment_distance(p, c, n),
3324 )
3325 })
3326 .fold(f32::INFINITY, f32::min)
3327 <= tol
3328 }),
3329 _ => None,
3330 };
3331 if hit == Some(true) {
3332 return Some(e.id);
3333 }
3334 }
3335 None
3336 }
3337
3338 fn prune_bands(&mut self) {
3340 let series = &self.series;
3341 self.bands.retain(|b| {
3342 series.iter().any(|e| e.id == b.upper) && series.iter().any(|e| e.id == b.lower)
3343 });
3344 }
3345
3346 pub fn add_layer(
3355 &mut self,
3356 pane: Option<PaneId>,
3357 plugin: Box<dyn LayerPlugin>,
3358 ) -> Result<LayerPluginId> {
3359 if pane.is_some_and(|p| self.pane_index(p).is_none()) {
3360 return Err(Error::UnknownId);
3361 }
3362 let id = LayerPluginId(self.next_layer);
3363 self.next_layer = self.next_layer.checked_add(1).ok_or(Error::OutOfMemory)?;
3364 self.layer_plugins
3365 .try_reserve(1)
3366 .map_err(|_| Error::OutOfMemory)?;
3367 self.layer_plugins.push(LayerEntry {
3368 id,
3369 pane,
3370 position: plugin.position(),
3371 plugin,
3372 });
3373 self.invalidation = self.invalidation.max(Invalidation::Light);
3374 Ok(id)
3375 }
3376
3377 pub fn remove_layer(&mut self, id: LayerPluginId) -> Result<()> {
3384 let n = self
3385 .layer_plugins
3386 .iter()
3387 .position(|l| l.id == id)
3388 .ok_or(Error::UnknownId)?;
3389 self.layer_plugins.remove(n);
3390 self.invalidation = self.invalidation.max(Invalidation::Light);
3391 Ok(())
3392 }
3393
3394 pub fn invalidate_layer(&mut self, id: LayerPluginId) -> Result<()> {
3400 if !self.layer_plugins.iter().any(|l| l.id == id) {
3401 return Err(Error::UnknownId);
3402 }
3403 self.invalidation = self.invalidation.max(Invalidation::Light);
3404 Ok(())
3405 }
3406
3407 fn emit_layers(
3409 &mut self,
3410 pane: Option<usize>,
3411 position: LayerPosition,
3412 text: &dyn TextMeasurer,
3413 ) {
3414 let pane_id = match pane {
3415 Some(i) => match self.panes.get(i) {
3416 Some(p) => Some(p.id),
3417 None => return,
3418 },
3419 None => None,
3420 };
3421 if !self
3422 .layer_plugins
3423 .iter()
3424 .any(|l| l.pane == pane_id && l.position == position)
3425 {
3426 return;
3427 }
3428 let norm = pane.and_then(|i| self.drawing_norm(i));
3429 let (rect, coords) = match pane {
3430 Some(i) => {
3431 let p = &self.panes[i];
3432 let coords = (!self.time_index.is_empty() && p.has_content)
3433 .then_some(norm)
3434 .flatten()
3435 .map(|norm| DrawingCtx {
3436 index: &self.time_index,
3437 time_scale: &self.time_scale,
3438 price_scale: &p.price_scale,
3439 norm,
3440 plot: p.plot,
3441 dpr: self.dpr,
3442 labels: p.labels,
3443 text,
3444 });
3445 (p.plot, coords)
3446 }
3447 None => (
3448 RectPx {
3449 x: 0.0,
3450 y: 0.0,
3451 w: self.layout.price_axis.x,
3452 h: self.layout.price_axis.h,
3453 },
3454 None,
3455 ),
3456 };
3457 let ctx = LayerCtx {
3458 rect,
3459 dpr: self.dpr,
3460 text,
3461 coords,
3462 };
3463 let layer = match position {
3464 LayerPosition::Background => LayerId::Background,
3465 LayerPosition::BelowSeries | LayerPosition::AboveSeries => LayerId::Main,
3466 LayerPosition::Overlay => LayerId::Overlay,
3467 };
3468 let clip = match (pane, position) {
3470 (Some(_), LayerPosition::BelowSeries | LayerPosition::AboveSeries) => {
3471 self.data_clip(rect)
3472 }
3473 _ => rect,
3474 };
3475 let frame = &mut self.frame;
3476 frame.push_cmd(layer, DrawCmd::PushClip(clip));
3477 for l in &self.layer_plugins {
3478 if l.pane == pane_id && l.position == position {
3479 l.plugin.build(
3480 &ctx,
3481 &mut FrameBuilder {
3482 frame: &mut *frame,
3483 layer,
3484 },
3485 );
3486 }
3487 }
3488 frame.push_cmd(layer, DrawCmd::PopClip);
3489 }
3490
3491 pub(crate) fn drawing_norm(&self, i: usize) -> Option<Normalize> {
3494 let pane = self.panes.get(i)?;
3495 if !pane.price_scale.mode().is_relative() {
3496 return Some(Normalize::IDENTITY);
3497 }
3498 self.series
3499 .iter()
3500 .find(|e| e.pane == pane.id && !e.derived && e.kind != SeriesKind::Volume)
3501 .and_then(|e| e.norm)
3502 }
3503
3504 pub(crate) fn drawing_ctx<'a>(
3506 &'a self,
3507 i: usize,
3508 text: &'a dyn TextMeasurer,
3509 ) -> Option<DrawingCtx<'a>> {
3510 let pane = self.panes.get(i)?;
3511 if self.time_index.is_empty() || !pane.has_content {
3512 return None;
3513 }
3514 Some(DrawingCtx {
3515 index: &self.time_index,
3516 time_scale: &self.time_scale,
3517 price_scale: &pane.price_scale,
3518 norm: self.drawing_norm(i)?,
3519 plot: pane.plot,
3520 dpr: self.dpr,
3521 labels: pane.labels,
3522 text,
3523 })
3524 }
3525
3526 fn emit_drawings(&mut self, i: usize, text: &dyn TextMeasurer) {
3529 let Some(pane) = self.panes.get(i) else {
3530 return;
3531 };
3532 let (id, plot) = (pane.id, pane.plot);
3533 if !self.drawings.entries.iter().any(|e| e.pane == id) {
3534 return;
3535 }
3536 let Some(norm) = self.drawing_norm(i) else {
3537 return;
3538 };
3539 if self.time_index.is_empty() || !pane.has_content {
3540 return;
3541 }
3542 let ctx = DrawingCtx {
3543 index: &self.time_index,
3544 time_scale: &self.time_scale,
3545 price_scale: &pane.price_scale,
3546 norm,
3547 plot,
3548 dpr: self.dpr,
3549 labels: pane.labels,
3550 text,
3551 };
3552 let clip = self.data_clip(plot);
3553 let frame = &mut self.frame;
3554 frame.push_cmd(LayerId::Main, DrawCmd::PushClip(clip));
3555 let selected = self.drawings.selected();
3556 let mut handles = self.handle_buf.borrow_mut();
3557 handles.clear();
3558 for e in &mut self.drawings.entries {
3559 if e.pane != id {
3560 continue;
3561 }
3562 let mark = PoolMark::of(frame);
3563 if e.visible {
3564 e.tool.build(
3565 &ctx,
3566 &mut FrameBuilder {
3567 frame: &mut *frame,
3568 layer: LayerId::Main,
3569 },
3570 );
3571 }
3572 e.bbox = mark.bounds(frame, &ctx);
3573 if e.visible && selected == Some(e.id) {
3574 e.tool.handles(&ctx, &mut handles);
3575 }
3576 }
3577 let outer = (HANDLE_CSS * self.dpr).round();
3579 let inner = (outer - 2.0 * (1.5 * self.dpr).round()).max(2.0);
3580 let color = selected
3581 .and_then(|s| self.drawings.entry(s))
3582 .map_or(self.theme.line, |e| e.tool.style().line);
3583 for p in handles.iter() {
3584 let pos = PointPx {
3585 x: p.x.round(),
3586 y: p.y.round(),
3587 };
3588 for (size, c) in [(outer, color), (inner, self.theme.background)] {
3589 frame.push_icon(
3590 LayerId::Main,
3591 crate::frame::IconInst {
3592 pos,
3593 size: Px(size),
3594 icon: crate::transform_helpers::ICON_CIRCLE,
3595 color: c,
3596 },
3597 );
3598 }
3599 }
3600 frame.push_cmd(LayerId::Main, DrawCmd::PopClip);
3601 }
3602
3603 pub(crate) fn push_event(&mut self, event: ChartEvent) {
3606 let coalesce = matches!(
3607 event,
3608 ChartEvent::CrosshairMove { .. }
3609 | ChartEvent::VisibleRangeChanged { .. }
3610 | ChartEvent::Sync(_)
3611 );
3612 let same_kind = |e: &ChartEvent| match (e, &event) {
3613 (ChartEvent::Sync(a), ChartEvent::Sync(b)) => {
3614 core::mem::discriminant(a) == core::mem::discriminant(b)
3615 }
3616 _ => core::mem::discriminant(e) == core::mem::discriminant(&event),
3617 };
3618 if coalesce && let Some(e) = self.events.iter_mut().find(|e| same_kind(e)) {
3619 *e = event;
3620 return;
3621 }
3622 self.events.push(event);
3623 }
3624
3625 fn emit_view_events(&mut self) {
3626 if self.time_index.is_empty() {
3627 return;
3628 }
3629 let (from, to) = self.time_scale.visible_range();
3630 if (from, to) != self.last_range {
3631 self.last_range = (from, to);
3632 self.push_event(ChartEvent::VisibleRangeChanged { from, to });
3633 }
3634 let first = self.time_index.first_index();
3635 let before = from.floor() as i64 - first;
3636 if (before as f64) < to - from && self.history_requested != Some(first) {
3637 self.history_requested = Some(first);
3638 self.push_event(ChartEvent::NeedMoreHistory {
3639 bars_before_start: before,
3640 });
3641 }
3642 }
3643
3644 fn bar_at(&self, j: i64) -> Option<BarValues> {
3647 let (e, [open, high, low, close]) = self
3648 .series
3649 .iter()
3650 .filter(|e| is_ohlc_kind(e.kind))
3651 .find_map(|e| Some((e, e.store.bar_at(j)?)))?;
3652 Some(BarValues {
3653 open,
3654 high,
3655 low,
3656 close,
3657 volume: e.store.volume_at(j),
3658 })
3659 }
3660
3661 pub(crate) fn magnet_bar(&self, pane: PaneId, j: i64) -> Option<[f64; 4]> {
3664 self.series
3665 .iter()
3666 .find(|e| e.pane == pane && !volume_like(e) && !e.store.is_empty())
3667 .and_then(|e| e.store.bar_at(j - i64::from(e.opts.shift)))
3668 }
3669
3670 pub(crate) fn pane_at(&self, p: PointPx) -> Option<usize> {
3672 self.panes.iter().position(|pane| pane.plot.contains(p))
3673 }
3674
3675 fn emit_crosshair(&mut self, time_h: f32, pad: f32, font: FontStyleRef) -> Option<i64> {
3682 let hovered = self
3683 .input
3684 .pointer
3685 .filter(|_| self.input.crosshair != CrosshairMode::Hidden && !self.revealing())
3686 .and_then(|p| Some((p, self.pane_at(p)?)));
3687 let local = hovered.and_then(|(p, i)| {
3688 let pane = self.panes.get(i)?;
3689 let plot = pane.plot;
3690 let idx = self.time_scale.x_to_index(Px(p.x - plot.x)).round() as i64;
3691 let x = plot.x + self.time_scale.index_to_x_f64(idx as f64) as f32;
3692 let bar = self.bar_at(idx);
3693 let (top, height) = (f64::from(plot.y), f64::from(plot.h));
3694 let mut y = p.y;
3695 let magnet = self
3696 .series
3697 .iter()
3698 .find(|e| e.pane == pane.id && !volume_like(e) && !e.store.is_empty())
3699 .and_then(|e| Some((e.store.bar_at(idx - i64::from(e.opts.shift))?, e.norm?)));
3700 if self.input.crosshair == CrosshairMode::Magnet
3701 && let Some((b, norm)) = magnet
3702 {
3703 let mut best = f32::INFINITY;
3704 for v in b {
3705 let vy = pane.price_scale.price_to_y(norm.apply(v), top, height) as f32;
3706 if (vy - p.y).abs() < (best - p.y).abs() {
3707 best = vy;
3708 }
3709 }
3710 if best.is_finite() {
3711 y = best.clamp(plot.y, plot.bottom() - 1.0);
3712 }
3713 }
3714 let price = pane.price_scale.y_to_price(f64::from(y), top, height);
3715 Some((
3716 Some((i, y)),
3717 x,
3718 CrosshairPoint {
3719 logical_index: idx,
3720 time: self.time_index.time_at(idx),
3721 pane: pane.id,
3722 price,
3723 bar,
3724 },
3725 ))
3726 });
3727 let local_index = local.map(|(_, _, c)| c.logical_index);
3728 let point = local.or_else(|| {
3729 if self.input.crosshair == CrosshairMode::Hidden {
3730 return None;
3731 }
3732 let idx = self.remote_crosshair_index()?;
3733 let plot = self.panes.first()?.plot;
3734 let x = plot.x + self.time_scale.index_to_x_f64(idx as f64) as f32;
3735 Some((
3736 None,
3737 x,
3738 CrosshairPoint {
3739 logical_index: idx,
3740 time: self.time_index.time_at(idx),
3741 pane: self.main_pane(),
3742 price: f64::NAN,
3743 bar: self.bar_at(idx),
3744 },
3745 ))
3746 });
3747 let event_point = point.map(|(_, _, c)| c);
3748 if !same_crosshair(event_point.as_ref(), self.last_crosshair.as_ref()) {
3749 self.last_crosshair = event_point;
3750 self.push_event(ChartEvent::CrosshairMove { point: event_point });
3751 }
3752 let (row, x, info) = point?;
3753 let plot0 = self.panes.first().map_or(RectPx::default(), |p| p.plot);
3754 if row.is_none() && !(x >= plot0.x && x < plot0.right()) {
3755 return local_index;
3756 }
3757 let stroke = StrokeStyle {
3758 width: Px(1.0),
3759 color: self.theme.crosshair,
3760 dash: LineDash::Dashed,
3761 };
3762 let cx = x.floor() + 0.5;
3763 for k in 0..self.panes.len() {
3764 let plot = self.panes[k].plot;
3765 let (from, to) = (
3766 PointPx { x: cx, y: plot.y },
3767 PointPx {
3768 x: cx,
3769 y: plot.bottom(),
3770 },
3771 );
3772 self.frame
3773 .push_line(LayerId::Overlay, LineInst { from, to, stroke });
3774 }
3775 let bg = Some(LabelBg {
3776 color: self.theme.crosshair_label_bg,
3777 padding: Px((pad * 0.5).round()),
3778 });
3779 let color = self.theme.crosshair_label_text;
3780 if let Some((i, y)) = row
3781 && let Some(pane) = self.panes.get(i)
3782 {
3783 let (plot, labels) = (pane.plot, pane.labels);
3784 let cy = y.floor() + 0.5;
3785 let (from, to) = (
3786 PointPx { x: plot.x, y: cy },
3787 PointPx {
3788 x: plot.right(),
3789 y: cy,
3790 },
3791 );
3792 self.frame
3793 .push_line(LayerId::Overlay, LineInst { from, to, stroke });
3794 let start = self.frame.pools.text.len();
3795 write_label(&mut self.frame.pools.text, info.price, labels);
3796 let span = Span {
3797 start: u32::try_from(start).unwrap_or(0),
3798 len: u32::try_from(self.frame.pools.text.len() - start).unwrap_or(0),
3799 };
3800 self.frame.push_text(
3801 LayerId::Overlay,
3802 TextRun {
3803 pos: PointPx {
3804 x: plot.right() + pad,
3805 y: y.round(),
3806 },
3807 text: span,
3808 style: font,
3809 color,
3810 align: TextAlign::Left,
3811 bg,
3812 },
3813 );
3814 }
3815 if let Some(t) = info.time {
3816 let mut s = StackStr::<32>::new();
3817 if format_crosshair_time(t + self.tz.offset_ms(t), &mut s).is_ok() {
3818 let span = self.frame.push_str(s.as_str());
3819 self.frame.push_text(
3820 LayerId::Overlay,
3821 TextRun {
3822 pos: PointPx {
3823 x: x.round(),
3824 y: (self.layout.time_axis.y + time_h * 0.5).round(),
3825 },
3826 text: span,
3827 style: font,
3828 color,
3829 align: TextAlign::Center,
3830 bg,
3831 },
3832 );
3833 }
3834 }
3835 local_index
3836 }
3837
3838 fn place_time_ticks(&mut self, text: &dyn TextMeasurer, font: FontStyleRef) {
3841 self.placed.clear();
3842 if self.time_index.is_empty() {
3843 return;
3844 }
3845 let spacing = self.time_scale.bar_spacing();
3846 let mut shift = 0;
3847 while ((1_u64 << shift) as f64) * spacing < TICK_SAMPLE_PX && shift < 40 {
3848 shift += 1;
3849 }
3850 let (from, to) = self.time_scale.visible_range();
3851 collect_ticks(
3852 &self.time_index,
3853 self.tz.as_ref(),
3854 from.floor() as i64,
3855 to.ceil() as i64,
3856 shift,
3857 &mut self.time_ticks,
3858 );
3859 self.time_ticks
3860 .sort_unstable_by(|a, b| b.weight.cmp(&a.weight).then(a.index.cmp(&b.index)));
3861 let plot_w = self.layout.plot.w;
3862 for &tick in &self.time_ticks {
3863 let x = self.time_scale.index_to_x_f64(tick.index as f64) as f32;
3864 let Some(label) = self.tick_label(tick) else {
3865 continue;
3866 };
3867 let width = text_width(text, label.as_str(), font);
3868 if x - width * 0.5 < 0.0 || x + width * 0.5 > plot_w {
3869 continue;
3870 }
3871 let free = self
3872 .placed
3873 .iter()
3874 .all(|p| (p.x - x).abs() >= 1.5 * p.width.max(width));
3875 if free && self.placed.len() < self.placed.capacity() {
3876 self.placed.push(PlacedTick { x, width, tick });
3877 }
3878 }
3879 }
3880
3881 fn tick_label(&self, tick: TimeTick) -> Option<StackStr<32>> {
3882 let t = self.time_index.time_at(tick.index)?;
3883 let mut s = StackStr::<32>::new();
3884 format_tick(t + self.tz.offset_ms(t), tick.weight, &mut s).ok()?;
3885 Some(s)
3886 }
3887
3888 fn line(from: PointPx, to: PointPx, color: crate::geom::Rgba) -> LineInst {
3889 LineInst {
3890 from,
3891 to,
3892 stroke: StrokeStyle {
3893 width: Px(1.0),
3894 color,
3895 dash: LineDash::Solid,
3896 },
3897 }
3898 }
3899
3900 fn emit_grid(&mut self, i: usize) {
3901 let grid = self.theme.grid;
3902 let Some(plot) = self.panes.get(i).map(|p| p.plot) else {
3903 return;
3904 };
3905 for k in 0..self.panes[i].ticks.len() {
3906 let pane = &self.panes[i];
3907 let y = pane
3908 .price_scale
3909 .price_to_y(pane.ticks[k], f64::from(plot.y), f64::from(plot.h))
3910 as f32;
3911 let y = y.floor() + 0.5;
3912 if y > plot.y && y < plot.bottom() {
3913 let l = Self::line(
3914 PointPx { x: plot.x, y },
3915 PointPx { x: plot.right(), y },
3916 grid,
3917 );
3918 self.frame.push_line(LayerId::Background, l);
3919 }
3920 }
3921 for k in 0..self.placed.len() {
3922 let x = self.placed[k].x.floor() + 0.5 + plot.x;
3923 let l = Self::line(
3924 PointPx { x, y: plot.y },
3925 PointPx {
3926 x,
3927 y: plot.bottom(),
3928 },
3929 grid,
3930 );
3931 self.frame.push_line(LayerId::Background, l);
3932 }
3933 }
3934
3935 fn draw_range(
3938 &self,
3939 view: &OhlcLevelView<'_>,
3940 plot: RectPx,
3941 shift: i32,
3942 ) -> (crate::data::IdxSpan, XTransform) {
3943 let (from, to) = self.time_scale.visible_range();
3944 let shift = f64::from(shift);
3945 let span = visible_span(view, from - shift, to - shift);
3946 let k = u32::from(view.level);
3947 let size = (1_i64 << k) as f64;
3948 let center = if k == 0 {
3949 span.start as f64
3950 } else {
3951 bucket_start(span.start, k) as f64 + (size - 1.0) * 0.5
3952 };
3953 let xt = XTransform {
3954 base: span.start,
3955 step: (self.time_scale.bar_spacing() * size) as f32,
3956 offset: (f64::from(plot.x) + self.time_scale.index_to_x_f64(center + shift)) as f32,
3957 };
3958 (span, xt)
3959 }
3960
3961 fn emit_series(&mut self, i: usize, text: &dyn TextMeasurer) {
3964 let Some(pane) = self.panes.get(i) else {
3965 return;
3966 };
3967 let (id, plot) = (pane.id, pane.plot);
3968 let clip = self.data_clip(plot);
3969 self.frame.push_cmd(LayerId::Main, DrawCmd::PushClip(clip));
3970 let has_price = self
3971 .series
3972 .iter()
3973 .any(|e| e.pane == id && !volume_like(e) && !e.store.is_empty());
3974 for volumes in [true, false] {
3975 if !volumes {
3976 for b in 0..self.bands.len() {
3977 self.emit_band(i, b);
3978 }
3979 }
3980 for k in 0..self.series.len() {
3981 let e = &self.series[k];
3982 if e.pane == id && (e.kind == SeriesKind::Volume) == volumes {
3983 match e.kind {
3984 SeriesKind::Custom => self.emit_custom(i, k, text),
3985 SeriesKind::Kagi | SeriesKind::PointFigure => self.emit_figure(i, k),
3986 _ => self.emit_one(i, k, has_price),
3987 }
3988 }
3989 }
3990 }
3991 self.frame.push_cmd(LayerId::Main, DrawCmd::PopClip);
3992 }
3993
3994 fn emit_one(&mut self, i: usize, k: usize, has_price: bool) {
3996 let (Some(pane), Some(e)) = (self.panes.get(i), self.series.get(k)) else {
3997 return;
3998 };
3999 let plot = pane.plot;
4000 let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4001 let (data_id, store) = if e.kind == SeriesKind::Volume {
4002 let Some(src) = e
4003 .opts
4004 .source
4005 .and_then(|s| self.series.iter().find(|x| x.id == s))
4006 else {
4007 return;
4008 };
4009 if !src.store.has_volume() {
4010 return;
4011 }
4012 (src.id, &src.store)
4013 } else {
4014 (e.id, &e.store)
4015 };
4016 let Some(log) = store.log() else { return };
4017 if store.is_empty() {
4018 return;
4019 }
4020 let level = lod_level(store.lod(), self.time_scale.bar_spacing());
4021 let Some(view) = store.level_view(level) else {
4022 return;
4023 };
4024 let shift = if e.kind == SeriesKind::Volume {
4025 0
4026 } else {
4027 e.opts.shift
4028 };
4029 let (span, xt) = self.draw_range(&view, plot, shift);
4030 let yt = if volume_like(e) {
4031 if has_price {
4032 pane.volume_scale.transform(top, height)
4033 } else {
4034 pane.price_scale.transform(top, height)
4035 }
4036 } else {
4037 let Some(norm) = e.norm else { return };
4039 pane.price_scale.series_transform(top, height, norm)
4040 };
4041 let generation = log.generation();
4042 let (kind, style) = (e.kind, self.style_of(e));
4043 let style = self.frame.push_style(style);
4044 self.frame.push_cmd(
4045 LayerId::Main,
4046 DrawCmd::Series(SeriesDraw {
4047 series: data_id,
4048 generation,
4049 style,
4050 kind,
4051 lod_level: level,
4052 index_range: span,
4053 x_transform: xt,
4054 y_transform: yt,
4055 clip: plot,
4056 pair: None,
4057 }),
4058 );
4059 }
4060
4061 fn emit_band(&mut self, i: usize, b: usize) {
4065 let (Some(pane), Some(band)) = (self.panes.get(i), self.bands.get(b)) else {
4066 return;
4067 };
4068 let find = |id: SeriesId| self.series.iter().find(|e| e.id == id);
4069 let (Some(u), Some(l)) = (find(band.upper), find(band.lower)) else {
4070 return;
4071 };
4072 if u.pane != pane.id || u.store.is_empty() || l.store.is_empty() {
4073 return;
4074 }
4075 let (Some(norm), Some(lower_norm)) = (u.norm, l.norm) else {
4076 return;
4077 };
4078 if norm != lower_norm || u.opts.shift != l.opts.shift {
4079 return;
4080 }
4081 let (Some(ul), Some(ll)) = (u.store.log(), l.store.log()) else {
4082 return;
4083 };
4084 let level = lod_level(u.store.lod(), self.time_scale.bar_spacing());
4085 let (Some(view), Some(_)) = (u.store.level_view(level), l.store.level_view(level)) else {
4086 return;
4087 };
4088 let plot = pane.plot;
4089 let (span, xt) = self.draw_range(&view, plot, u.opts.shift);
4090 let yt = pane
4091 .price_scale
4092 .series_transform(f64::from(plot.y), f64::from(plot.h), norm);
4093 let generation = ul
4094 .generation()
4095 .wrapping_add(ll.generation().rotate_left(32));
4096 let fill = band
4097 .opts
4098 .fill
4099 .unwrap_or_else(|| self.style_of(u).up.with_alpha(0x26));
4100 let style = SeriesStyle {
4101 fill_top: fill,
4102 fill_bottom: band.opts.fill_crossed.unwrap_or(fill),
4103 ..SeriesStyle::default()
4104 };
4105 let (upper, lower) = (band.upper, band.lower);
4106 let style = self.frame.push_style(style);
4107 self.frame.push_cmd(
4108 LayerId::Main,
4109 DrawCmd::Series(SeriesDraw {
4110 series: upper,
4111 generation,
4112 style,
4113 kind: SeriesKind::Band,
4114 lod_level: level,
4115 index_range: span,
4116 x_transform: xt,
4117 y_transform: yt,
4118 clip: plot,
4119 pair: Some(lower),
4120 }),
4121 );
4122 }
4123
4124 fn emit_custom(&mut self, i: usize, k: usize, text: &dyn TextMeasurer) {
4126 let (Some(pane), Some(e)) = (self.panes.get(i), self.series.get(k)) else {
4127 return;
4128 };
4129 let (Some(c), Some(norm)) = (e.store.custom(), e.norm) else {
4130 return;
4131 };
4132 let shift = f64::from(e.opts.shift);
4133 let (from, to) = self.time_scale.visible_range();
4134 let visible = c.points_in(&self.time_index, from - shift, to - shift);
4135 if visible.0 >= visible.1 {
4136 return;
4137 }
4138 let ctx = SeriesCtx {
4139 coords: DrawingCtx {
4140 index: &self.time_index,
4141 time_scale: &self.time_scale,
4142 price_scale: &pane.price_scale,
4143 norm,
4144 plot: pane.plot,
4145 dpr: self.dpr,
4146 labels: pane.labels,
4147 text,
4148 },
4149 store: c,
4150 shift,
4151 visible,
4152 style: self.style_of(e),
4153 };
4154 if !self.native_kinds.contains(&c.kind) {
4155 c.plugin.build(
4156 &ctx,
4157 visible.0,
4158 visible.1,
4159 &mut FrameBuilder {
4160 frame: &mut self.frame,
4161 layer: LayerId::Main,
4162 },
4163 );
4164 return;
4165 }
4166 let mut params = [0.0; 8];
4167 c.plugin.native_params(&ctx, &mut params);
4168 let plot = pane.plot;
4169 let base = from.floor() as i64;
4170 let x_transform = XTransform {
4171 base,
4172 step: self.time_scale.bar_spacing() as f32,
4173 offset: (f64::from(plot.x) + self.time_scale.index_to_x_f64(base as f64 + shift))
4174 as f32,
4175 };
4176 let y_transform =
4177 pane.price_scale
4178 .series_transform(f64::from(plot.y), f64::from(plot.h), norm);
4179 let (series, generation, kind) = (e.id, c.log.generation(), c.kind);
4180 let style = self.frame.push_style(ctx.style);
4181 let points = IdxSpan {
4182 start: i64::try_from(visible.0).unwrap_or(i64::MAX),
4183 end: i64::try_from(visible.1).unwrap_or(i64::MAX),
4184 };
4185 self.frame.push_cmd(
4186 LayerId::Main,
4187 DrawCmd::Custom(CustomDraw {
4188 series,
4189 generation,
4190 kind,
4191 points,
4192 x_transform,
4193 y_transform,
4194 style,
4195 params,
4196 clip: plot,
4197 }),
4198 );
4199 }
4200
4201 fn emit_figure(&mut self, i: usize, k: usize) {
4206 let (Some(pane), Some(e)) = (self.panes.get(i), self.series.get(k)) else {
4207 return;
4208 };
4209 let (Some(t), Some(norm)) = (e.store.transform(), e.norm) else {
4210 return;
4211 };
4212 let style = self.style_of(e);
4213 let out = &t.out;
4214 if out.len() == 0 {
4215 return;
4216 }
4217 let plot = pane.plot;
4218 let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4219 let scale = &pane.price_scale;
4220 let ts = &self.time_scale;
4221 let y = |p: f64| -> Option<f32> {
4222 let y = scale.price_to_y(norm.apply(p), top, height);
4223 y.is_finite().then(|| y.clamp(-1e7, 1e7) as f32)
4224 };
4225 let shift = f64::from(e.opts.shift);
4226 let x = |j: f64| (f64::from(plot.x) + ts.index_to_x_f64(j + shift)) as f32;
4227 let spacing = ts.bar_spacing();
4228 let (from, to) = ts.visible_range();
4229 let mut b = FrameBuilder {
4230 frame: &mut self.frame,
4231 layer: LayerId::Main,
4232 };
4233 let thin = Px((style.line_width.0 / 2.0).max(1.0));
4234 let stroke = |flag: u8| StrokeStyle {
4235 width: if flag == 1 { style.line_width } else { thin },
4236 color: if flag == 1 { style.up } else { style.down },
4237 dash: LineDash::Solid,
4238 };
4239 if spacing < 1.0 {
4240 let level = lod_level(Some(out.lod()), spacing);
4241 let Some(view) = out.level_view(level) else {
4242 return;
4243 };
4244 let span = visible_span(&view, from - shift, to - shift);
4245 let lvl = u32::from(level);
4246 let size = (1_i64 << lvl) as f64;
4247 let one = StrokeStyle {
4248 width: Px(1.0),
4249 color: style.up,
4250 dash: LineDash::Solid,
4251 };
4252 let mut col: Option<(f32, f32, f32)> = None;
4254 let flush = |b: &mut FrameBuilder<'_>, c: (f32, f32, f32)| {
4255 let x = c.0 + 0.5;
4256 b.line(
4257 PointPx { x, y: c.1 },
4258 PointPx {
4259 x,
4260 y: c.2.max(c.1 + 1.0),
4261 },
4262 one,
4263 );
4264 };
4265 for j in span.start..span.end {
4266 let center = if lvl == 0 {
4267 j as f64
4268 } else {
4269 bucket_start(j, lvl) as f64 + (size - 1.0) * 0.5
4270 };
4271 let (Some(hi), Some(lo)) =
4272 (view.high.at(view.first, j), view.low.at(view.first, j))
4273 else {
4274 continue;
4275 };
4276 let (Some(y0), Some(y1)) = (y(hi), y(lo)) else {
4277 continue;
4278 };
4279 let px = x(center).floor();
4280 col = match col {
4281 Some(c) if (c.0 - px).abs() < 0.5 => Some((px, c.1.min(y0), c.2.max(y1))),
4283 Some(c) => {
4284 flush(&mut b, c);
4285 Some((px, y0, y1))
4286 }
4287 None => Some((px, y0, y1)),
4288 };
4289 }
4290 if let Some(c) = col {
4291 flush(&mut b, c);
4292 }
4293 return;
4294 }
4295 let first = out.first();
4296 let a = ((from - shift).floor() as i64 - 1).max(first);
4297 let end = ((to - shift).ceil() as i64 + 2).min(out.end());
4298 let flag_at = |j: i64| {
4299 usize::try_from(j - first)
4300 .ok()
4301 .and_then(|p| t.flags.get(p).copied())
4302 .unwrap_or(0)
4303 };
4304 if e.kind == SeriesKind::Kagi {
4305 for j in a..end {
4306 let Some([open, _, _, close]) = out.bar_at(j) else {
4307 continue;
4308 };
4309 let (Some(yo), Some(yc)) = (y(open), y(close)) else {
4310 continue;
4311 };
4312 let xj = x(j as f64);
4313 let flag = flag_at(j);
4314 let prev = out.bar_at(j - 1);
4315 let start = if prev.is_some() { flag_at(j - 1) } else { flag };
4316 if prev.is_some() {
4317 let from = PointPx {
4319 x: x((j - 1) as f64),
4320 y: yo,
4321 };
4322 b.line(from, PointPx { x: xj, y: yo }, stroke(start));
4323 }
4324 match prev.and_then(|p| y(p[0])) {
4325 Some(ys) if start != flag => {
4327 b.line(
4328 PointPx { x: xj, y: yo },
4329 PointPx { x: xj, y: ys },
4330 stroke(start),
4331 );
4332 b.line(
4333 PointPx { x: xj, y: ys },
4334 PointPx { x: xj, y: yc },
4335 stroke(flag),
4336 );
4337 }
4338 _ => b.line(
4339 PointPx { x: xj, y: yo },
4340 PointPx { x: xj, y: yc },
4341 stroke(flag),
4342 ),
4343 }
4344 }
4345 return;
4346 }
4347 let Some(size) = t.plugin.box_size().filter(|s| s.is_finite() && *s > 0.0) else {
4349 return;
4350 };
4351 let w = (spacing * 0.8) as f32;
4352 let mark = Px((style.line_width.0 * 0.75).max(1.0));
4353 for j in a..end {
4354 let Some([_, high, low, _]) = out.bar_at(j) else {
4355 continue;
4356 };
4357 let (Some(y_hi), Some(y_lo)) = (y(high), y(low)) else {
4358 continue;
4359 };
4360 let flag = flag_at(j);
4361 let color = if flag == 1 { style.up } else { style.down };
4362 let xc = x(j as f64);
4363 let boxes = ((high - low) / size).round();
4364 let box_px = (y_lo - y_hi).abs() / boxes.max(1.0) as f32;
4365 if spacing < 4.0 || box_px < 4.0 || boxes > 10_000.0 {
4366 let r = RectPx {
4367 x: xc - w / 2.0,
4368 y: y_hi.min(y_lo),
4369 w: w.max(1.0),
4370 h: (y_lo - y_hi).abs().max(1.0),
4371 };
4372 b.rect(r, color);
4373 continue;
4374 }
4375 let pen = StrokeStyle {
4376 width: mark,
4377 color,
4378 dash: LineDash::Solid,
4379 };
4380 let (l, r) = (xc - w / 2.0, xc + w / 2.0);
4381 for m in 0..boxes as i64 {
4382 let (Some(y0), Some(y1)) =
4383 (y(low + m as f64 * size), y(low + (m + 1) as f64 * size))
4384 else {
4385 continue;
4386 };
4387 let inset = (y0 - y1).abs() * 0.1;
4389 let (yb, yt) = (y0.max(y1) - inset, y0.min(y1) + inset);
4390 if flag == 1 {
4391 b.line(PointPx { x: l, y: yt }, PointPx { x: r, y: yb }, pen);
4392 b.line(PointPx { x: l, y: yb }, PointPx { x: r, y: yt }, pen);
4393 } else {
4394 let (cy, rx, ry) = (f32::midpoint(yb, yt), w / 2.0, (yb - yt) / 2.0);
4395 b.polyline(
4396 (0..=CIRCLE_SEGMENTS).map(|s| {
4397 let a =
4398 f32::from(s) * core::f32::consts::TAU / f32::from(CIRCLE_SEGMENTS);
4399 PointPx {
4400 x: xc + rx * a.cos(),
4401 y: cy + ry * a.sin(),
4402 }
4403 }),
4404 pen,
4405 );
4406 }
4407 }
4408 }
4409 }
4410
4411 pub fn set_native_kinds(&mut self, kinds: &[&'static str]) {
4417 if self.native_kinds.as_slice() == kinds {
4418 return;
4419 }
4420 self.native_kinds.clear();
4421 self.native_kinds.extend_from_slice(kinds);
4422 self.invalidation = Invalidation::Full;
4423 }
4424
4425 fn push_label(&mut self, pos: PointPx, align: TextAlign, font: FontStyleRef, span: Span) {
4426 self.frame.push_text(
4427 LayerId::Main,
4428 TextRun {
4429 pos,
4430 text: span,
4431 style: font,
4432 color: self.theme.text,
4433 align,
4434 bg: None,
4435 },
4436 );
4437 }
4438
4439 fn emit_price_labels(&mut self, i: usize, line_h: f32, pad: f32, font: FontStyleRef) {
4441 let Some(pane) = self.panes.get(i) else {
4442 return;
4443 };
4444 let (plot, labels) = (pane.plot, pane.labels.for_ticks(&pane.ticks));
4445 for k in 0..self.panes[i].ticks.len() {
4446 let pane = &self.panes[i];
4447 let p = pane.ticks[k];
4448 let y = pane
4449 .price_scale
4450 .price_to_y(p, f64::from(plot.y), f64::from(plot.h)) as f32;
4451 if y < plot.y + line_h * 0.5 || y > plot.bottom() - line_h * 0.5 {
4452 continue;
4453 }
4454 let label_h = line_h + pad;
4456 if self.axis_labels.iter().any(|l| (l.at - y).abs() < label_h) {
4457 continue;
4458 }
4459 let start = self.frame.pools.text.len();
4460 write_label(&mut self.frame.pools.text, p, labels);
4461 let span = Span {
4462 start: u32::try_from(start).unwrap_or(0),
4463 len: u32::try_from(self.frame.pools.text.len() - start).unwrap_or(0),
4464 };
4465 self.push_label(
4466 PointPx {
4467 x: plot.right() + pad,
4468 y: y.round(),
4469 },
4470 TextAlign::Left,
4471 font,
4472 span,
4473 );
4474 }
4475 let label_h = (line_h + pad).round();
4477 let axis_right = self.frame.size_px.w;
4478 for n in 0..self.axis_labels.len() {
4479 let l = self.axis_labels[n];
4480 let y = l.at.round();
4481 self.frame.push_rect(
4482 LayerId::Main,
4483 crate::frame::RectInst {
4484 rect: RectPx {
4485 x: plot.right() + 1.0,
4486 y: (y - label_h * 0.5).round(),
4487 w: (axis_right - plot.right() - 1.0).max(0.0),
4488 h: label_h,
4489 },
4490 color: l.bg,
4491 },
4492 );
4493 self.frame.push_text(
4494 LayerId::Main,
4495 TextRun {
4496 pos: PointPx {
4497 x: plot.right() + pad,
4498 y,
4499 },
4500 text: l.text,
4501 style: font,
4502 color: l.fg,
4503 align: TextAlign::Left,
4504 bg: None,
4505 },
4506 );
4507 }
4508 }
4509
4510 fn last_value(&self, k: usize) -> Option<(f64, Rgba)> {
4513 let e = self.series.get(k)?;
4514 if let Some(c) = e.store.custom() {
4515 let v = c.plugin.last_value().filter(|v| v.is_finite())?;
4516 return Some((v, self.style_of(e).up));
4517 }
4518 let (first, end) = e.store.span()?;
4519 let [open, _, _, close] = (first..end).rev().find_map(|j| e.store.bar_at(j))?;
4520 let style = self.style_of(e);
4521 let up = match e.kind {
4522 SeriesKind::Baseline => close >= e.opts.base_value,
4523 k if is_ohlc_kind(k) || matches!(k, SeriesKind::Kagi | SeriesKind::PointFigure) => {
4524 close >= open
4525 }
4526 _ => true,
4527 };
4528 Some((close, if up { style.up } else { style.down }))
4529 }
4530
4531 fn emit_markers(&mut self, i: usize, line_h: f32, font: FontStyleRef) {
4534 let Some(pane) = self.panes.get(i) else {
4535 return;
4536 };
4537 let (id, plot) = (pane.id, pane.plot);
4538 let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4539 if self.time_index.is_empty()
4540 || !self
4541 .series
4542 .iter()
4543 .any(|e| e.pane == id && !e.markers.is_empty())
4544 {
4545 return;
4546 }
4547 let (first, end) = (self.time_index.first_index(), self.time_index.end_index());
4548 let (a, b) = self.time_scale.visible_range();
4549 let ja = (a.floor() as i64).clamp(first, end - 1);
4550 let jb = (b.ceil() as i64).clamp(first, end - 1);
4551 let Some(t_hi) = self.time_index.time_at(jb) else {
4552 return;
4553 };
4554 let t_skip = self.time_index.time_at(ja - 1).unwrap_or(i64::MIN);
4557 let size = (MARKER_SIZE * self.dpr).round().max(4.0);
4558 let gap = (MARKER_GAP * self.dpr).round();
4559 let clip = self.data_clip(plot);
4560 self.frame.push_cmd(LayerId::Main, DrawCmd::PushClip(clip));
4561 for k in 0..self.series.len() {
4562 let e = &self.series[k];
4563 let Some(norm) = e.norm.filter(|_| e.pane == id && !e.markers.is_empty()) else {
4564 continue;
4565 };
4566 let main = self.style_of(e).up;
4567 let start = e.markers.partition_point(|m| m.time <= t_skip);
4568 let mut stack = (i64::MIN, 0.0_f32, 0.0_f32);
4570 for n in start..e.markers.len() {
4571 let m = &e.markers[n];
4572 if m.time > t_hi && jb < end - 1 {
4573 break;
4574 }
4575 let j = self.time_index.lower_bound(m.time).min(end - 1);
4576 let Some([_, high, low, _]) = e.store.bar_at(j) else {
4577 continue;
4578 };
4579 if j != stack.0 {
4580 stack = (j, 0.0, 0.0);
4581 }
4582 let above = m.position == MarkerPosition::AboveBar;
4583 let price = if above { high } else { low };
4584 let y_bar = self.panes[i]
4585 .price_scale
4586 .price_to_y(norm.apply(price), top, height) as f32;
4587 let text_h = if m.text.is_empty() { 0.0 } else { line_h };
4588 let (cy, ty) = if above {
4589 let cy = y_bar - gap - stack.1 - size * 0.5;
4590 stack.1 += gap + size + text_h;
4591 (cy, cy - size * 0.5 - text_h * 0.5)
4592 } else {
4593 let cy = y_bar + gap + stack.2 + size * 0.5;
4594 stack.2 += gap + size + text_h;
4595 (cy, cy + size * 0.5 + text_h * 0.5)
4596 };
4597 let shown = j + i64::from(e.opts.shift);
4598 let x = (plot.x + self.time_scale.index_to_x(shown as f64).0).round();
4599 let color = m.color.unwrap_or(main);
4600 self.marker_hits.push(MarkerHit {
4601 series: e.id,
4602 index: n,
4603 pane: id,
4604 pos: PointPx { x, y: cy.round() },
4605 radius: size * 0.5,
4606 });
4607 self.frame.push_icon(
4608 LayerId::Main,
4609 crate::frame::IconInst {
4610 pos: PointPx { x, y: cy.round() },
4611 size: Px(size),
4612 icon: m.shape.icon(),
4613 color,
4614 },
4615 );
4616 if text_h > 0.0 {
4617 let span = self.frame.push_str(&e.markers[n].text);
4618 self.frame.push_text(
4619 LayerId::Main,
4620 TextRun {
4621 pos: PointPx { x, y: ty.round() },
4622 text: span,
4623 style: font,
4624 color,
4625 align: TextAlign::Center,
4626 bg: None,
4627 },
4628 );
4629 }
4630 }
4631 }
4632 self.frame.push_cmd(LayerId::Main, DrawCmd::PopClip);
4633 }
4634
4635 fn emit_marks(&mut self, i: usize, line_h: f32, pad: f32, font: FontStyleRef) {
4641 self.axis_labels.clear();
4642 if self.revealing() {
4643 return; }
4645 let Some(pane) = self.panes.get(i) else {
4646 return;
4647 };
4648 let (id, plot, labels) = (pane.id, pane.plot, pane.labels);
4649 let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4650 let inside = |y: f32| y >= plot.y && y < plot.bottom();
4651 let format = |e: &SeriesEntry| match labels {
4652 NumberFormat::Fixed(_) | NumberFormat::Auto(_) => match e.opts.price_precision {
4653 Some(p) => NumberFormat::Fixed(p),
4654 None => NumberFormat::Auto(e.auto_decimals),
4655 },
4656 other => other,
4657 };
4658 for k in 0..self.series.len() {
4659 let e = &self.series[k];
4660 if e.pane != id || volume_like(e) {
4661 continue;
4662 }
4663 let (Some(norm), Some((value, color))) = (e.norm, self.last_value(k)) else {
4664 continue;
4665 };
4666 let (show_line, show_label, fmt) = (
4667 e.opts.price_line_visible,
4668 e.opts.last_value_visible,
4669 format(e),
4670 );
4671 let d = norm.apply(value);
4672 let y = self.panes[i].price_scale.price_to_y(d, top, height) as f32;
4673 if !inside(y) {
4674 continue;
4675 }
4676 if show_line {
4677 let yl = y.floor() + 0.5;
4678 self.frame.push_line(
4679 LayerId::Main,
4680 LineInst {
4681 from: PointPx { x: plot.x, y: yl },
4682 to: PointPx {
4683 x: plot.right(),
4684 y: yl,
4685 },
4686 stroke: StrokeStyle {
4687 width: Px(1.0),
4688 color,
4689 dash: LineDash::Dotted,
4690 },
4691 },
4692 );
4693 }
4694 if show_label {
4695 self.push_axis_label(y, d, fmt, color);
4696 }
4697 }
4698 for n in 0..self.price_lines.len() {
4699 let line = &self.price_lines[n];
4700 let Some(k) = self.series.iter().position(|e| e.id == line.series) else {
4701 continue;
4702 };
4703 let e = &self.series[k];
4704 let Some(norm) = e.norm.filter(|_| e.pane == id) else {
4705 continue;
4706 };
4707 let color = line.opts.color.unwrap_or_else(|| self.style_of(e).up);
4708 let fmt = format(e);
4709 let d = norm.apply(line.opts.price);
4710 let y = self.panes[i].price_scale.price_to_y(d, top, height) as f32;
4711 if !inside(y) {
4712 continue;
4713 }
4714 let width = line.opts.line_width.to_px(self.dpr).0.round().max(1.0);
4715 let yl = if width as i32 % 2 == 1 {
4716 y.floor() + 0.5
4717 } else {
4718 y.round()
4719 };
4720 self.frame.push_line(
4721 LayerId::Main,
4722 LineInst {
4723 from: PointPx { x: plot.x, y: yl },
4724 to: PointPx {
4725 x: plot.right(),
4726 y: yl,
4727 },
4728 stroke: StrokeStyle {
4729 width: Px(width),
4730 color,
4731 dash: line.opts.line_style,
4732 },
4733 },
4734 );
4735 let show_label = line.opts.axis_label_visible;
4736 if !line.opts.title.is_empty() {
4737 let span = self.frame.push_str(&self.price_lines[n].opts.title);
4738 self.frame.push_text(
4739 LayerId::Main,
4740 TextRun {
4741 pos: PointPx {
4742 x: plot.right() - pad,
4743 y: (y - line_h * 0.5 - 2.0).round(),
4744 },
4745 text: span,
4746 style: font,
4747 color,
4748 align: TextAlign::Right,
4749 bg: None,
4750 },
4751 );
4752 }
4753 if show_label {
4754 self.push_axis_label(y, d, fmt, color);
4755 }
4756 }
4757 let h = line_h + pad;
4760 let (lo, hi) = (plot.y + h * 0.5, plot.bottom() - h * 0.5);
4761 for n in 0..self.axis_labels.len() {
4762 let want = self.axis_labels[n].want.clamp(lo, hi.max(lo));
4763 let placed = &self.axis_labels[..n];
4764 let free = |c: f32| {
4765 c >= lo - 0.01
4766 && c <= hi + 0.01
4767 && placed.iter().all(|p| (p.at - c).abs() >= h - 0.01)
4768 };
4769 let mut best = want;
4770 if !free(want) {
4771 let mut dist = f32::INFINITY;
4772 for p in placed {
4773 for c in [p.at - h, p.at + h] {
4774 if free(c) && (c - want).abs() < dist {
4775 dist = (c - want).abs();
4776 best = c;
4777 }
4778 }
4779 }
4780 }
4781 self.axis_labels[n].at = best;
4782 }
4783 }
4784
4785 fn push_axis_label(&mut self, want: f32, value: f64, format: NumberFormat, bg: Rgba) {
4787 let start = self.frame.pools.text.len();
4788 write_label(&mut self.frame.pools.text, value, format);
4789 let text = Span {
4790 start: u32::try_from(start).unwrap_or(0),
4791 len: u32::try_from(self.frame.pools.text.len() - start).unwrap_or(0),
4792 };
4793 if self.axis_labels.len() < self.axis_labels.capacity() {
4794 self.axis_labels.push(AxisLabel {
4795 want,
4796 at: want,
4797 text,
4798 bg,
4799 fg: contrast(bg),
4800 });
4801 }
4802 }
4803
4804 fn emit_axes(&mut self, time_h: f32, font: FontStyleRef) {
4806 let axis = self.theme.axis_line;
4807 let (w, h) = (self.frame.size_px.w, self.frame.size_px.h);
4808 let layout = self.layout;
4809 let x = layout.price_axis.x + 0.5;
4810 let l = Self::line(
4811 PointPx { x, y: 0.0 },
4812 PointPx {
4813 x,
4814 y: layout.price_axis.bottom(),
4815 },
4816 axis,
4817 );
4818 self.frame.push_line(LayerId::Main, l);
4819 for k in 1..self.panes.len() {
4821 let y = self.panes[k].plot.y - SEPARATOR_PX + 0.5;
4822 let l = Self::line(PointPx { x: 0.0, y }, PointPx { x: w, y }, axis);
4823 self.frame.push_line(LayerId::Main, l);
4824 }
4825 let y = layout.time_axis.y + 0.5;
4826 if y < h {
4827 let l = Self::line(PointPx { x: 0.0, y }, PointPx { x: w, y }, axis);
4828 self.frame.push_line(LayerId::Main, l);
4829 }
4830
4831 let y = (layout.time_axis.y + time_h * 0.5).round();
4832 for k in 0..self.placed.len() {
4833 let placed = self.placed[k];
4834 let Some(label) = self.tick_label(placed.tick) else {
4835 continue;
4836 };
4837 let span = self.frame.push_str(label.as_str());
4838 self.push_label(
4839 PointPx {
4840 x: layout.plot.x + placed.x.round(),
4841 y,
4842 },
4843 TextAlign::Center,
4844 font,
4845 span,
4846 );
4847 }
4848 }
4849}
4850
4851#[derive(Clone, Copy)]
4874pub struct ChartDataView<'a> {
4875 series: &'a [SeriesEntry],
4876 time_index: &'a TimeIndex,
4877}
4878
4879static EMPTY_TIME_INDEX: TimeIndex = TimeIndex::new();
4881
4882impl<'a> ChartDataView<'a> {
4883 pub fn empty() -> ChartDataView<'static> {
4895 ChartDataView {
4896 series: &[],
4897 time_index: &EMPTY_TIME_INDEX,
4898 }
4899 }
4900
4901 fn store(self, id: SeriesId) -> Option<&'a Store> {
4903 let series = self.series;
4904 let e = series.iter().find(|e| e.id == id)?;
4905 match e.kind {
4906 SeriesKind::Volume => {
4907 let src = e.opts.source?;
4908 series.iter().find(|x| x.id == src).map(|x| &x.store)
4909 }
4910 _ => Some(&e.store),
4911 }
4912 }
4913
4914 pub fn generation(&self, id: SeriesId) -> Option<u64> {
4916 self.store(id)?.log().map(ChangeLog::generation)
4917 }
4918
4919 pub fn changes_since(&self, id: SeriesId, since_gen: u64) -> DataDelta {
4922 self.store(id)
4923 .and_then(Store::log)
4924 .map_or(DataDelta::Full, |log| log.changes_since(since_gen))
4925 }
4926
4927 pub fn ohlc(&self, id: SeriesId, level: u8) -> Option<OhlcLevelView<'a>> {
4931 self.store(id)?.level_view(level)
4932 }
4933
4934 pub fn point_colors(&self, id: SeriesId) -> Option<(i64, &'a [u32])> {
4937 self.store(id)?.colors()
4938 }
4939
4940 pub fn custom(&self, id: SeriesId) -> Option<&'a dyn CustomSeries> {
4943 let e = self.series.iter().find(|e| e.id == id)?;
4944 e.store.custom().map(|c| c.plugin.as_ref())
4945 }
4946
4947 pub fn custom_index(&self, id: SeriesId, point: usize) -> Option<f64> {
4951 let e = self.series.iter().find(|e| e.id == id)?;
4952 e.store.custom()?.x_index(self.time_index, point)
4953 }
4954
4955 pub fn time_index(&self) -> &'a TimeIndex {
4957 self.time_index
4958 }
4959}
4960
4961fn lod_level(lod: Option<&crate::data::lod::Lod>, bar_spacing: f64) -> u8 {
4963 let bars_per_px = 1.0 / bar_spacing;
4964 if bars_per_px < 4.0 {
4965 return 0;
4966 }
4967 let Some(max) = lod.and_then(crate::data::lod::Lod::max_level) else {
4968 return 0;
4969 };
4970 let want = bars_per_px.log2().ceil().max(2.0).min(f64::from(max));
4971 want as u8
4972}
4973
4974fn visible_span(view: &OhlcLevelView<'_>, from: f64, to: f64) -> crate::data::IdxSpan {
4977 let (i0, i1) = (from.floor() as i64 - 1, to.ceil() as i64 + 1);
4978 let k = u32::from(view.level);
4979 let (start, end) = if k == 0 {
4980 (i0, i1 + 1)
4981 } else {
4982 (bucket_of(i0, k), bucket_of(i1, k) + 1)
4983 };
4984 crate::data::IdxSpan {
4985 start: start.max(view.first),
4986 end: end.min(view.end()),
4987 }
4988}
4989
4990fn max_volume_in(view: &OhlcLevelView<'_>, span: crate::data::IdxSpan) -> f64 {
4992 let mut max_volume: f64 = 0.0;
4993 if let Some(col) = view.volume {
4994 for j in span.start..span.end {
4995 let p = usize::try_from(j - view.first).unwrap_or(usize::MAX);
4996 max_volume = max_volume.max(col.get(p).unwrap_or(0.0));
4997 }
4998 }
4999 max_volume
5000}
5001
5002fn write_label(out: &mut impl core::fmt::Write, v: f64, format: NumberFormat) {
5004 format.write(out, v);
5005}
5006
5007fn contrast(bg: Rgba) -> Rgba {
5009 let l = 0.299 * f32::from(bg.r) + 0.587 * f32::from(bg.g) + 0.114 * f32::from(bg.b);
5010 if l > 160.0 {
5011 Rgba::hex(0x0013_1722)
5012 } else {
5013 Rgba::hex(0x00FF_FFFF)
5014 }
5015}
5016
5017fn first_value(store: &Store, from: i64, to: i64) -> Option<f64> {
5020 let (first, end) = store.span()?;
5021 (from.max(first)..to.min(end)).find_map(|j| store.bar_at(j).map(|b| b[3]))
5022}
5023
5024impl Column<'_> {
5025 pub fn at(&self, first: i64, j: i64) -> Option<f64> {
5027 self.get(usize::try_from(j - first).ok()?)
5028 }
5029}
5030
5031fn same_crosshair(a: Option<&CrosshairPoint>, b: Option<&CrosshairPoint>) -> bool {
5034 match (a, b) {
5035 (None, None) => true,
5036 (Some(a), Some(b)) => {
5037 let bits = |v: Option<BarValues>| {
5038 v.map(|v| {
5039 [v.open, v.high, v.low, v.close, v.volume.unwrap_or(f64::NAN)].map(f64::to_bits)
5040 })
5041 };
5042 a.logical_index == b.logical_index
5043 && a.time == b.time
5044 && a.pane == b.pane
5045 && a.price.to_bits() == b.price.to_bits()
5046 && bits(a.bar) == bits(b.bar)
5047 && a.bar.map(|v| v.volume.is_some()) == b.bar.map(|v| v.volume.is_some())
5048 }
5049 _ => false,
5050 }
5051}
5052
5053#[cfg(test)]
5054mod tests {
5055 use super::*;
5056 use crate::data::{OhlcColumns, ValueColumns};
5057
5058 fn ohlc(times: &[i64], close: f64) -> SeriesData {
5059 let n = times.len();
5060 SeriesData::Ohlc(OhlcColumns {
5061 time: times.to_vec(),
5062 open: vec![close; n],
5063 high: vec![close + 1.0; n],
5064 low: vec![close - 1.0; n],
5065 close: vec![close; n],
5066 volume: Some(vec![10.0; n]),
5067 })
5068 }
5069
5070 fn values(times: &[i64], v: &[f64]) -> SeriesData {
5071 SeriesData::Value(ValueColumns {
5072 time: times.to_vec(),
5073 value: v.to_vec(),
5074 color: None,
5075 })
5076 }
5077
5078 fn two_series(a: SeriesKind, b: SeriesKind) -> (Chart, SeriesId, SeriesId) {
5079 let mut chart = Chart::new(ChartOptions::default());
5080 let pane = chart.main_pane();
5081 let x = chart.add_series(pane, a, SeriesOptions::default()).unwrap();
5082 let y = chart.add_series(pane, b, SeriesOptions::default()).unwrap();
5083 (chart, x, y)
5084 }
5085
5086 fn at(chart: &Chart, id: SeriesId, t: i64) -> Option<f64> {
5088 let j = chart.time_index.index_of(t)?;
5089 let e = chart.series.iter().find(|e| e.id == id)?;
5090 e.store.bar_at(j).map(|b| b[3])
5091 }
5092
5093 fn merged_warnings(chart: &mut Chart) -> usize {
5094 chart
5095 .drain_events()
5096 .filter(|e| matches!(e, ChartEvent::Warning(WarningKind::TimeAxisMerged { .. })))
5097 .count()
5098 }
5099
5100 #[test]
5103 fn time_axis_is_the_union_of_all_series() {
5104 let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Line);
5105 chart
5106 .set_data(candles, ohlc(&[10, 20, 30, 40], 5.0))
5107 .unwrap();
5108 chart.drain_events().for_each(drop);
5109 chart
5111 .set_data(line, values(&[30, 40, 50, 60], &[1.0, 2.0, 3.0, 4.0]))
5112 .unwrap();
5113 assert_eq!(chart.time_index.times(), &[10, 20, 30, 40, 50, 60]);
5114 assert_eq!(chart.time_index.index_of(10), Some(0));
5115 assert_eq!(merged_warnings(&mut chart), 0);
5116 chart
5118 .set_data(line, values(&[15, 30, 60], &[1.0, 2.0, 4.0]))
5119 .unwrap();
5120 assert_eq!(chart.time_index.times(), &[10, 15, 20, 30, 40, 60]);
5121 assert_eq!(merged_warnings(&mut chart), 1);
5122 assert_eq!(chart.time_index.index_of(10), Some(0)); for t in [10, 20, 30, 40] {
5124 assert_eq!(at(&chart, candles, t), Some(5.0), "t = {t}");
5125 }
5126 assert_eq!(at(&chart, candles, 15), None); assert_eq!(at(&chart, line, 15), Some(1.0));
5128 assert_eq!(at(&chart, line, 20), Some(1.5)); chart.append(candles, ohlc(&[50], 6.0)).unwrap();
5131 assert_eq!(chart.time_index.times(), &[10, 15, 20, 30, 40, 50, 60]);
5132 assert_eq!(merged_warnings(&mut chart), 1);
5133 assert_eq!(at(&chart, candles, 50), Some(6.0));
5134 assert_eq!(at(&chart, line, 60), Some(4.0));
5135 let bar = BarUpdate {
5137 time: 70,
5138 open: 7.0,
5139 high: 8.0,
5140 low: 6.0,
5141 close: 7.0,
5142 volume: Some(1.0),
5143 };
5144 assert_eq!(
5145 chart.update_last(candles, bar),
5146 Ok(DataChange::Append { count: 2 })
5147 );
5148 assert_eq!(at(&chart, candles, 60), None);
5149 assert_eq!(at(&chart, candles, 70), Some(7.0));
5150 assert_eq!(merged_warnings(&mut chart), 0);
5151 }
5152
5153 #[test]
5155 fn replaced_data_leaves_no_stale_bars() {
5156 let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Area);
5157 chart.set_data(candles, ohlc(&[1, 2, 3], 5.0)).unwrap();
5158 chart.set_data(line, values(&[1, 2, 3], &[1.0; 3])).unwrap();
5159 chart
5160 .set_data(candles, ohlc(&[101, 102, 103], 9.0))
5161 .unwrap();
5162 assert_eq!(chart.time_index.len(), 6);
5164 chart
5165 .set_data(line, values(&[101, 102, 103], &[2.0; 3]))
5166 .unwrap();
5167 assert_eq!(chart.time_index.times(), &[101, 102, 103]);
5168 assert_eq!(at(&chart, candles, 102), Some(9.0));
5169 assert_eq!(at(&chart, line, 103), Some(2.0));
5170 }
5171
5172 #[test]
5175 fn relative_scales_normalize_each_series() {
5176 use crate::price_scale::PriceScaleMode;
5177 use crate::testing::MonoMeasurer;
5178 use crate::transform_helpers::y_of_price;
5179
5180 let (mut chart, a, b) = two_series(SeriesKind::Line, SeriesKind::Line);
5181 chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5182 let times: Vec<i64> = (0..50).collect();
5183 let va: Vec<f64> = (0..50).map(|i| 10.0 + f64::from(i) * 0.1).collect();
5184 let vb: Vec<f64> = (0..50).map(|i| 1000.0 - f64::from(i)).collect();
5185 chart.set_data(a, values(×, &va)).unwrap();
5186 chart.set_data(b, values(×, &vb)).unwrap();
5187 chart.fit_content();
5188 let pane = chart.main_pane();
5189 for (mode, start) in [
5190 (PriceScaleMode::Percentage, 0.0),
5191 (PriceScaleMode::IndexedTo100, 100.0),
5192 ] {
5193 chart
5194 .price_scale(pane, ScaleSide::Right)
5195 .unwrap()
5196 .set_mode(mode)
5197 .unwrap();
5198 chart.build_frame(0.0, &MonoMeasurer);
5199 let draws: Vec<SeriesDraw> = chart.frame().layers[LayerId::Main as usize]
5200 .cmds
5201 .iter()
5202 .filter_map(|c| match c {
5203 DrawCmd::Series(s) => Some(*s),
5204 _ => None,
5205 })
5206 .collect();
5207 assert_eq!(draws.len(), 2);
5208 let j0 = chart.time_scale.visible_range().0.floor().max(0.0) as usize;
5210 let ya = y_of_price(&draws[0].y_transform, va[j0]);
5211 let yb = y_of_price(&draws[1].y_transform, vb[j0]);
5212 assert!((ya - yb).abs() < 0.01, "{mode:?}: {ya} vs {yb}");
5213 let p = &chart.panes[0];
5215 let y0 = p
5216 .price_scale
5217 .price_to_y(start, f64::from(p.plot.y), f64::from(p.plot.h));
5218 assert!((y0 as f32 - ya).abs() < 0.01, "{mode:?}");
5219 let (ea, eb) = (
5221 y_of_price(&draws[0].y_transform, va[49]),
5222 y_of_price(&draws[1].y_transform, vb[49]),
5223 );
5224 assert!(ea < ya && eb > yb, "{mode:?}");
5225 }
5226 let text = &chart.frame().pools.text;
5228 assert!(!text.contains('%'), "indexed labels have no %");
5229 chart
5230 .price_scale(pane, ScaleSide::Right)
5231 .unwrap()
5232 .set_mode(PriceScaleMode::Percentage)
5233 .unwrap();
5234 chart.build_frame(0.0, &MonoMeasurer);
5235 assert!(chart.frame().pools.text.contains('%'));
5236 }
5237
5238 #[test]
5240 fn failed_operations_leave_the_axis_unchanged() {
5241 let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Line);
5242 chart.set_data(candles, ohlc(&[10, 20, 30], 5.0)).unwrap();
5243 chart
5244 .set_data(line, values(&[10, 20, 30], &[1.0; 3]))
5245 .unwrap();
5246 let before = chart.time_index.clone();
5247 let mut bad = ohlc(&[40, 50], 5.0);
5248 if let SeriesData::Ohlc(c) = &mut bad {
5249 c.high[1] = f64::INFINITY;
5250 }
5251 assert!(chart.append(candles, bad.clone()).is_err()); assert!(matches!(
5253 chart.append(line, ohlc(&[40], 1.0)),
5254 Err(Error::InvalidArgument(_))
5255 )); assert_eq!(chart.time_index, before);
5257 if let SeriesData::Ohlc(c) = &mut bad {
5258 c.time = vec![15, 25];
5259 }
5260 assert!(chart.set_data(candles, bad).is_err()); assert_eq!(chart.time_index, before);
5262 assert_eq!(at(&chart, candles, 20), Some(5.0));
5263 assert_eq!(
5264 chart.append(line, values(&[20], &[3.0])),
5265 Err(Error::TimeNotIncreasing { index: 0 })
5266 );
5267 }
5268
5269 #[test]
5270 fn chart_is_send() {
5271 fn assert_send<T: Send>() {}
5272 assert_send::<Chart>();
5273 }
5274
5275 #[test]
5276 fn invalid_ids_are_errors() {
5277 let mut chart = Chart::new(ChartOptions::default());
5278 let pane = chart.main_pane();
5279 assert_eq!(
5280 chart.add_series(PaneId(9), SeriesKind::Candlestick, SeriesOptions::default()),
5281 Err(Error::UnknownId)
5282 );
5283 assert_eq!(chart.remove_series(SeriesId(3)), Err(Error::UnknownId));
5284 let line = chart
5285 .add_series(pane, SeriesKind::Line, SeriesOptions::default())
5286 .unwrap();
5287 assert!(matches!(
5289 chart.add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(line)),
5290 Err(Error::InvalidArgument(_))
5291 ));
5292 assert!(matches!(
5293 chart.add_series(
5294 pane,
5295 SeriesKind::Volume,
5296 SeriesOptions::volume_of(SeriesId(0))
5297 ),
5298 Err(Error::InvalidArgument(_))
5299 ));
5300 assert!(chart.price_scale(pane, ScaleSide::Left).is_none());
5301 assert_eq!(
5302 chart.set_series_options(SeriesId(9), SeriesOptions::default()),
5303 Err(Error::UnknownId)
5304 );
5305 assert!(chart.series_options(SeriesId(9)).is_none());
5306 assert!(matches!(
5308 chart.set_series_options(line, SeriesOptions::volume_of(line)),
5309 Err(Error::InvalidArgument(_))
5310 ));
5311 assert_eq!(chart.series_kind(line), Some(SeriesKind::Line));
5312 assert_eq!(chart.series_pane(line), Some(pane));
5313 assert_eq!(chart.series_pane(SeriesId(9)), None);
5314 }
5315
5316 fn loaded(n: usize, options: ChartOptions) -> (Chart, SeriesId) {
5317 let mut chart = Chart::new(options);
5318 chart.resize(SizeCss { w: 800.0, h: 400.0 }, 1.0);
5319 let pane = chart.main_pane();
5320 let id = chart
5321 .add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())
5322 .unwrap();
5323 chart
5324 .add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(id))
5325 .unwrap();
5326 let data = crate::testing::random_walk(9, n, 0, 60_000).unwrap();
5327 chart.set_data(id, SeriesData::Ohlc(data)).unwrap();
5328 (chart, id)
5329 }
5330
5331 #[test]
5332 fn redraw_only_when_something_changed() {
5333 let (mut chart, _) = loaded(1000, ChartOptions::default());
5334 assert_eq!(chart.needs_redraw(), Invalidation::Full);
5335 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5336 assert_eq!(chart.needs_redraw(), Invalidation::None);
5337 chart.time_scale().scroll_by(Px(10.0));
5338 assert_eq!(chart.needs_redraw(), Invalidation::Light);
5339 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5340 assert_eq!(chart.needs_redraw(), Invalidation::None);
5341 }
5342
5343 #[test]
5344 fn prepend_keeps_the_view() {
5345 let (mut chart, id) = loaded(1000, ChartOptions::default());
5346 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5347 let before = chart.time_scale().visible_range();
5348 let older = crate::testing::random_walk(10, 500, -500 * 60_000, 60_000).unwrap();
5349 chart.prepend(id, SeriesData::Ohlc(older)).unwrap();
5350 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5351 assert_eq!(chart.time_scale().visible_range(), before);
5352 assert_eq!(chart.data_view().time_index().first_index(), -500);
5353 }
5354
5355 #[test]
5356 fn repaired_bars_produce_a_warning() {
5357 let (mut chart, id) = loaded(
5358 10,
5359 ChartOptions {
5360 ohlc_validation: ValidationMode::Repair,
5361 ..ChartOptions::default()
5362 },
5363 );
5364 let mut bad = crate::testing::random_walk(1, 2, 10 * 60_000, 60_000).unwrap();
5365 bad.high[1] = bad.low[1] - 1.0;
5366 chart.append(id, SeriesData::Ohlc(bad)).unwrap();
5367 let events: Vec<_> = chart.drain_events().collect();
5368 assert_eq!(
5369 events,
5370 [ChartEvent::Warning(WarningKind::OhlcRepaired {
5371 series: id,
5372 bars: 1
5373 })]
5374 );
5375 }
5376
5377 #[test]
5378 fn removing_candles_removes_their_volume() {
5379 let (mut chart, id) = loaded(100, ChartOptions::default());
5380 let volume = SeriesId(1);
5381 assert!(chart.data_view().ohlc(volume, 0).is_some());
5382 chart.remove_series(id).unwrap();
5383 assert_eq!(chart.remove_series(volume), Err(Error::UnknownId));
5384 assert!(chart.data_view().ohlc(id, 0).is_none());
5385 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5387 }
5388
5389 #[test]
5390 fn volume_series_has_no_data_of_its_own() {
5391 let (mut chart, _) = loaded(10, ChartOptions::default());
5392 let data = crate::testing::random_walk(1, 10, 0, 60_000).unwrap();
5393 assert!(matches!(
5394 chart.set_data(SeriesId(1), SeriesData::Ohlc(data)),
5395 Err(Error::InvalidArgument(_))
5396 ));
5397 }
5398
5399 fn main_texts(chart: &Chart) -> Vec<(String, f32)> {
5401 let f = chart.frame();
5402 f.layers[LayerId::Main as usize]
5403 .cmds
5404 .iter()
5405 .filter_map(|c| match c {
5406 DrawCmd::Text(s) => Some(*s),
5407 _ => None,
5408 })
5409 .flat_map(|s| f.pools.text_runs[s.start as usize..(s.start + s.len) as usize].to_vec())
5410 .map(|r| (f.pools.text_of(r.text).to_owned(), r.pos.y))
5411 .collect()
5412 }
5413
5414 #[test]
5416 fn price_lines_follow_their_series() {
5417 let mut chart = Chart::new(ChartOptions::default());
5418 let pane = chart.main_pane();
5419 let line = chart
5420 .add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())
5421 .unwrap();
5422 let vol = chart
5423 .add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(line))
5424 .unwrap();
5425 let opts = |price| PriceLineOptions {
5426 price,
5427 ..PriceLineOptions::default()
5428 };
5429 assert_eq!(
5430 chart.create_price_line(vol, opts(1.0)),
5431 Err(Error::InvalidArgument("volume series have no price lines"))
5432 );
5433 assert!(chart.create_price_line(line, opts(f64::NAN)).is_err());
5434 assert_eq!(
5435 chart.create_price_line(SeriesId(99), opts(1.0)),
5436 Err(Error::UnknownId)
5437 );
5438 let a = chart.create_price_line(line, opts(1.0)).unwrap();
5439 let b = chart.create_price_line(line, opts(2.0)).unwrap();
5440 assert_ne!(a, b);
5441 chart.update_price_line(a, opts(3.0)).unwrap();
5442 assert_eq!(chart.price_line(a).map(|o| o.price), Some(3.0));
5443 chart.remove_price_line(b).unwrap();
5444 assert_eq!(chart.remove_price_line(b), Err(Error::UnknownId));
5445 chart.remove_series(line).unwrap();
5446 assert!(chart.price_line(a).is_none());
5447 assert_eq!(chart.update_price_line(a, opts(1.0)), Err(Error::UnknownId));
5448 }
5449
5450 #[test]
5453 fn automatic_precision_reaches_tiny_prices() {
5454 use crate::testing::MonoMeasurer;
5455
5456 let (mut chart, a, _) = two_series(SeriesKind::Line, SeriesKind::Line);
5457 chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5458 let times: Vec<i64> = (0..20).collect();
5459 let v: Vec<f64> = (0..20)
5460 .map(|i| 0.000_012_34 + f64::from(i) * 1e-9)
5461 .collect();
5462 chart.set_data(a, values(×, &v)).unwrap();
5463 chart.fit_content();
5464 chart.build_frame(0.0, &MonoMeasurer);
5465 let texts: Vec<String> = main_texts(&chart).into_iter().map(|(t, _)| t).collect();
5466 assert!(texts.iter().any(|t| t == "0.0₄1236"), "{texts:?}");
5469 let ticks = texts.iter().filter(|t| t.starts_with("0.0₄123")).count();
5470 assert!(ticks >= 3, "{texts:?}");
5471
5472 let k = chart.series.iter().position(|e| e.id == a).unwrap();
5473 chart.series[k].opts.price_precision = Some(2);
5474 chart.invalidation = Invalidation::Full;
5475 chart.build_frame(0.0, &MonoMeasurer);
5476 let texts: Vec<String> = main_texts(&chart).into_iter().map(|(t, _)| t).collect();
5477 assert!(texts.iter().any(|t| t == "0.00"), "{texts:?}");
5478 assert!(!texts.iter().any(|t| t.contains('₄')), "{texts:?}");
5479 }
5480
5481 #[test]
5484 fn fine_ticks_are_not_rounded_together() {
5485 use crate::testing::MonoMeasurer;
5486
5487 let (mut chart, a, _) = two_series(SeriesKind::Line, SeriesKind::Line);
5488 chart.resize(SizeCss { w: 400.0, h: 600.0 }, 1.0);
5489 let times: Vec<i64> = (0..20).collect();
5490 let v: Vec<f64> = (0..20).map(|i| 1.0 + f64::from(i) * 0.0002).collect();
5491 chart.set_data(a, values(×, &v)).unwrap();
5492 chart.fit_content();
5493 chart.build_frame(0.0, &MonoMeasurer);
5494 let ticks: Vec<String> = main_texts(&chart)
5495 .into_iter()
5496 .map(|(t, _)| t)
5497 .filter(|t| t.parse::<f64>().is_ok() && t.len() > "1.00".len())
5498 .collect();
5499 assert!(ticks.len() >= 3, "{ticks:?}");
5500 let mut unique = ticks.clone();
5501 unique.dedup();
5502 assert_eq!(unique, ticks);
5503 }
5504
5505 #[test]
5508 fn axis_labels_do_not_overlap() {
5509 use crate::testing::MonoMeasurer;
5510
5511 let (mut chart, a, b) = two_series(SeriesKind::Line, SeriesKind::Line);
5512 chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5513 let times: Vec<i64> = (0..20).collect();
5514 let va: Vec<f64> = (0..20).map(f64::from).collect();
5515 let mut vb = va.clone();
5516 vb[19] = 19.01;
5517 chart.set_data(a, values(×, &va)).unwrap();
5518 chart.set_data(b, values(×, &vb)).unwrap();
5519 for price in [19.02, 18.99] {
5520 chart
5521 .create_price_line(
5522 a,
5523 PriceLineOptions {
5524 price,
5525 title: "t".into(),
5526 ..PriceLineOptions::default()
5527 },
5528 )
5529 .unwrap();
5530 }
5531 chart.fit_content();
5532 chart.build_frame(0.0, &MonoMeasurer);
5533 assert_eq!(chart.axis_labels.len(), 4);
5534 let plot = chart.panes[0].plot;
5535 let mut ys: Vec<f32> = chart.axis_labels.iter().map(|l| l.at).collect();
5536 assert!((ys[0] - chart.axis_labels[0].want).abs() < 0.01);
5538 ys.sort_by(f32::total_cmp);
5539 let texts = main_texts(&chart);
5540 let gap = ys
5541 .windows(2)
5542 .map(|w| w[1] - w[0])
5543 .fold(f32::INFINITY, f32::min);
5544 assert!(gap >= 10.0, "labels overlap: {ys:?}");
5545 assert!(ys.iter().all(|&y| y > plot.y && y < plot.bottom()));
5546 assert_eq!(texts.iter().filter(|(t, _)| t == "t").count(), 2);
5548 for v in ["19.00", "19.01", "19.02", "18.99"] {
5549 assert!(texts.iter().any(|(t, _)| t == v), "missing {v}: {texts:?}");
5550 }
5551 let k = chart.series.iter().position(|e| e.id == b).unwrap();
5553 chart.series[k].opts.last_value_visible = false;
5554 chart.invalidation = Invalidation::Full;
5555 chart.build_frame(0.0, &MonoMeasurer);
5556 assert_eq!(chart.axis_labels.len(), 3);
5557 }
5558
5559 #[test]
5562 fn markers_stack_and_snap() {
5563 use crate::testing::MonoMeasurer;
5564 use MarkerPosition::{AboveBar, BelowBar};
5565
5566 let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Line);
5567 chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5568 chart
5569 .set_data(candles, ohlc(&[10, 20, 30, 40], 5.0))
5570 .unwrap();
5571 chart
5573 .set_data(line, values(&[10, 25, 40], &[5.0, 5.0, 5.0]))
5574 .unwrap();
5575 let m = |time, position, text: &str| Marker {
5576 time,
5577 position,
5578 text: text.into(),
5579 ..Marker::default()
5580 };
5581 chart
5582 .set_markers(
5583 candles,
5584 vec![
5585 m(40, AboveBar, ""),
5586 m(19, AboveBar, "a"), m(20, AboveBar, ""),
5588 m(20, BelowBar, ""),
5589 m(25, AboveBar, ""), ],
5591 )
5592 .unwrap();
5593 assert_eq!(
5594 chart
5595 .markers(candles)
5596 .unwrap()
5597 .iter()
5598 .map(|m| m.time)
5599 .collect::<Vec<_>>(),
5600 [19, 20, 20, 25, 40]
5601 );
5602 chart.fit_content();
5603 chart.build_frame(0.0, &MonoMeasurer);
5604 let icons = chart.frame().pools.icons.clone();
5605 assert_eq!(icons.len(), 4);
5606 let x20 = chart.panes[0].plot.x + chart.time_scale.index_to_x(1.0).0;
5607 let at20: Vec<_> = icons
5608 .iter()
5609 .filter(|i| (i.pos.x - x20.round()).abs() < 0.5)
5610 .collect();
5611 assert_eq!(at20.len(), 3);
5612 let (y_text, y1, y2, y_below) = (
5614 main_texts(&chart).iter().find(|(t, _)| t == "a").unwrap().1,
5615 at20[0].pos.y,
5616 at20[1].pos.y,
5617 at20[2].pos.y,
5618 );
5619 assert!(y2 < y_text && y_text < y1, "{y2} < {y_text} < {y1}");
5620 assert!(y_below > y1);
5621 assert_eq!(
5623 chart.set_markers(SeriesId(99), vec![]),
5624 Err(Error::UnknownId)
5625 );
5626 let vol = chart
5627 .add_series(
5628 chart.main_pane(),
5629 SeriesKind::Volume,
5630 SeriesOptions::volume_of(candles),
5631 )
5632 .unwrap();
5633 assert!(chart.set_markers(vol, vec![]).is_err());
5634 assert!(chart.markers(SeriesId(99)).is_none());
5635 }
5636
5637 struct Fill(crate::plugin::LayerPosition, Rgba);
5640
5641 impl LayerPlugin for Fill {
5642 fn position(&self) -> LayerPosition {
5643 self.0
5644 }
5645 fn build(&self, ctx: &LayerCtx<'_>, out: &mut FrameBuilder<'_>) {
5646 let mut r = ctx.rect();
5647 if ctx.coords().is_some() {
5648 r.h /= 2.0;
5649 }
5650 out.rect(r, self.1);
5651 }
5652 }
5653
5654 fn rects_of(chart: &Chart, layer: LayerId) -> Vec<(Rgba, RectPx)> {
5655 let f = chart.frame();
5656 f.layers[layer as usize]
5657 .cmds
5658 .iter()
5659 .filter_map(|c| match c {
5660 DrawCmd::Rects(span) => Some(*span),
5661 _ => None,
5662 })
5663 .flat_map(|span| {
5664 let a = span.start as usize;
5665 f.pools.rects[a..a + span.len as usize]
5666 .iter()
5667 .map(|r| (r.color, r.rect))
5668 })
5669 .collect()
5670 }
5671
5672 #[test]
5673 fn layer_plugins_draw_in_their_layer() {
5674 let (mut chart, _) = loaded(200, ChartOptions::default());
5675 let red = Rgba::hex(0xFF_0000);
5676 let blue = Rgba::hex(0x00_00FF);
5677 let green = Rgba::hex(0x00_FF00);
5678 let pane = chart.add_pane(PaneOptions::default());
5679 let wide = chart
5680 .add_layer(None, Box::new(Fill(LayerPosition::Background, red)))
5681 .unwrap();
5682 chart
5683 .add_layer(
5684 Some(chart.main_pane()),
5685 Box::new(Fill(LayerPosition::AboveSeries, blue)),
5686 )
5687 .unwrap();
5688 chart
5689 .add_layer(Some(pane), Box::new(Fill(LayerPosition::Overlay, green)))
5690 .unwrap();
5691 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5692 let bg = rects_of(&chart, LayerId::Background);
5693 let main = rects_of(&chart, LayerId::Main);
5694 let overlay = rects_of(&chart, LayerId::Overlay);
5695 let plot = chart.layout().plot;
5696 assert!(
5698 bg.iter()
5699 .any(|&(c, r)| c == red && r.y == 0.0 && r.h > plot.h)
5700 );
5701 assert!(main.iter().any(|&(c, r)| c == blue
5703 && r == RectPx {
5704 h: plot.h / 2.0,
5705 ..plot
5706 }));
5707 let lower = chart.pane_layout(pane).unwrap().plot;
5709 assert!(overlay.iter().any(|&(c, r)| c == green && r == lower));
5710
5711 chart.remove_pane(pane).unwrap();
5712 chart.remove_layer(wide).unwrap();
5713 assert_eq!(chart.remove_layer(wide), Err(Error::UnknownId));
5714 assert_eq!(chart.invalidate_layer(wide), Err(Error::UnknownId));
5715 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5716 assert!(
5717 !rects_of(&chart, LayerId::Background)
5718 .iter()
5719 .any(|&(c, _)| c == red)
5720 );
5721 assert!(
5722 !rects_of(&chart, LayerId::Overlay)
5723 .iter()
5724 .any(|&(c, _)| c == green)
5725 );
5726 assert!(
5727 rects_of(&chart, LayerId::Main)
5728 .iter()
5729 .any(|&(c, _)| c == blue)
5730 );
5731 assert!(
5732 chart
5733 .add_layer(Some(pane), Box::new(Fill(LayerPosition::Overlay, green)))
5734 .is_err()
5735 );
5736 }
5737
5738 #[derive(Default)]
5740 struct Ranges {
5741 mode: Option<AxisMode>,
5742 time: Vec<i64>,
5743 range: Vec<(f64, f64)>,
5744 }
5745
5746 impl Ranges {
5747 fn overlay() -> Self {
5748 Self {
5749 mode: Some(AxisMode::Overlay),
5750 ..Self::default()
5751 }
5752 }
5753
5754 fn push(&mut self, t: i64, lo: f64, hi: f64) -> DataChange {
5755 self.time.push(t);
5756 self.range.push((lo, hi));
5757 DataChange::Append { count: 1 }
5758 }
5759 }
5760
5761 impl CustomSeries for Ranges {
5762 fn kind(&self) -> &'static str {
5763 "test.ranges"
5764 }
5765 fn axis_mode(&self) -> AxisMode {
5766 self.mode.unwrap_or(AxisMode::Slots)
5767 }
5768 fn times(&self) -> &[Timestamp] {
5769 &self.time
5770 }
5771 fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
5772 self.range[from..to]
5774 .iter()
5775 .fold(None, |acc, &(l, h)| match acc {
5776 None => Some((l, h)),
5777 Some((a, b)) => Some((l.min(a), h.max(b))),
5778 })
5779 }
5780 fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
5781 for i in from..to {
5782 let (lo, hi) = self.range[i];
5783 let (Some(x), Some(y0), Some(y1)) = (
5784 ctx.x_of_point(i),
5785 ctx.coords().y_of(hi),
5786 ctx.coords().y_of(lo),
5787 ) else {
5788 continue;
5789 };
5790 let rect = RectPx {
5791 x: x - 1.0,
5792 y: y0,
5793 w: 2.0,
5794 h: y1 - y0,
5795 };
5796 out.rect(rect, ctx.style().up);
5797 }
5798 }
5799 fn last_value(&self) -> Option<f64> {
5800 self.range.last().map(|r| r.1)
5801 }
5802 fn crosshair_value(&self, point: usize) -> Option<f64> {
5803 self.range.get(point).map(|r| r.1)
5804 }
5805 fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
5806 params[0] = ctx.visible().1 as f32;
5807 }
5808 }
5809
5810 const RED: u32 = 0x00FF_0000;
5811
5812 struct Probe;
5814
5815 impl CustomSeries for Probe {
5816 fn kind(&self) -> &'static str {
5817 "test.probe"
5818 }
5819 fn axis_mode(&self) -> AxisMode {
5820 AxisMode::Slots
5821 }
5822 fn times(&self) -> &[Timestamp] {
5823 &[]
5824 }
5825 fn extremes(&self, _: usize, _: usize) -> Option<(f64, f64)> {
5826 None
5827 }
5828 fn build(&self, _: &SeriesCtx<'_>, _: usize, _: usize, _: &mut FrameBuilder<'_>) {}
5829 }
5830
5831 struct Nothing;
5833
5834 impl Indicator for Nothing {
5835 fn name(&self) -> &'static str {
5836 "nothing"
5837 }
5838 fn outputs(&self) -> &[crate::plugin::OutputSpec] {
5839 const OUT: [crate::plugin::OutputSpec; 1] = [crate::plugin::OutputSpec::line("x")];
5840 &OUT
5841 }
5842 fn default_placement(&self) -> Placement {
5843 Placement::Overlay
5844 }
5845 fn warmup(&self) -> usize {
5846 0
5847 }
5848 fn update(&mut self, _: &IndicatorInput<'_>, _: DataChange, _: &mut IndicatorOutputs) {}
5849 }
5850
5851 fn custom_chart(r: Ranges) -> (Chart, SeriesId) {
5852 let mut chart = Chart::new(ChartOptions::default());
5853 chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5854 let opts = SeriesOptions {
5855 color: Some(Rgba::hex(RED)),
5856 ..SeriesOptions::default()
5857 };
5858 let id = chart
5859 .add_custom_series(chart.main_pane(), Box::new(r), opts)
5860 .unwrap();
5861 (chart, id)
5862 }
5863
5864 fn red_rects(chart: &mut Chart) -> Vec<RectPx> {
5865 chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5866 let right = chart.layout().plot.right();
5868 rects_of(chart, LayerId::Main)
5869 .into_iter()
5870 .filter(|(c, r)| *c == Rgba::hex(RED) && r.x < right)
5871 .map(|(_, r)| r)
5872 .collect()
5873 }
5874
5875 #[test]
5876 fn custom_series_take_slots_and_draw() {
5877 let mut r = Ranges::default();
5878 for (n, t) in [60_000, 120_000, 180_000].into_iter().enumerate() {
5879 r.push(t, n as f64, n as f64 + 1.0);
5880 }
5881 let (mut chart, id) = custom_chart(r);
5882 assert_eq!(chart.series_kind(id), Some(SeriesKind::Custom));
5883 assert_eq!(chart.time_index.times(), &[60_000, 120_000, 180_000]);
5884 chart.fit_content();
5885 let rects = red_rects(&mut chart);
5886 assert_eq!(rects.len(), 3);
5887 assert!(rects[0].x < rects[1].x && rects[1].x < rects[2].x);
5888 let plot = chart.layout().plot;
5890 assert!(rects[0].bottom() > plot.y + plot.h * 0.7);
5891 assert!(rects[2].y < plot.y + plot.h * 0.3);
5892
5893 let view = chart.data_view();
5894 let g = view.generation(id).unwrap();
5895 let any: &dyn Any = view.custom(id).unwrap();
5896 assert_eq!(any.downcast_ref::<Ranges>().unwrap().time.len(), 3);
5897
5898 chart
5900 .update_custom(id, |r: &mut Ranges| {
5901 r.range[2].1 = 9.0;
5902 DataChange::UpdateLast
5903 })
5904 .unwrap();
5905 assert_eq!(
5906 chart.data_view().changes_since(id, g),
5907 DataDelta::Range(IdxSpan { start: 2, end: 3 })
5908 );
5909 chart
5910 .update_custom(id, |r: &mut Ranges| r.push(240_000, 1.0, 2.0))
5911 .unwrap();
5912 assert_eq!(chart.time_index.len(), 4);
5913 assert_eq!(chart.custom_series::<Ranges>(id).unwrap().time.len(), 4);
5914 assert_eq!(chart.entry(id).unwrap().store.bar_at(2), Some([9.0; 4]));
5915 assert_eq!(chart.last_value(0).map(|v| v.0), Some(2.0));
5916 chart.fit_content();
5917 assert_eq!(red_rects(&mut chart).len(), 4);
5918 }
5919
5920 #[test]
5921 fn custom_series_share_the_axis() {
5922 let mut chart = Chart::new(ChartOptions::default());
5923 chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5924 let pane = chart.main_pane();
5925 let candles = chart
5926 .add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())
5927 .unwrap();
5928 chart.set_data(candles, ohlc(&[0, 20, 40], 10.0)).unwrap();
5929 let mut r = Ranges::default();
5930 r.push(20, 1.0, 2.0);
5931 r.push(40, 1.0, 2.0);
5932 let id = chart
5933 .add_custom_series(pane, Box::new(r), SeriesOptions::default())
5934 .unwrap();
5935 assert_eq!(chart.time_index.times(), &[0, 20, 40]);
5937 let c = |chart: &Chart| chart.entry(id).unwrap().store.span();
5938 assert_eq!(c(&chart), Some((1, 3)));
5939
5940 chart
5942 .update_custom(id, |r: &mut Ranges| {
5943 r.time.insert(1, 30);
5944 r.range.insert(1, (0.0, 1.0));
5945 DataChange::Replace
5946 })
5947 .unwrap();
5948 assert_eq!(chart.time_index.times(), &[0, 20, 30, 40]);
5949 assert_eq!(at(&chart, candles, 40), Some(10.0));
5950 assert_eq!(merged_warnings(&mut chart), 1);
5951 assert_eq!(
5952 chart.entry(id).unwrap().store.custom().unwrap().point_at(3),
5953 Some(2)
5954 );
5955
5956 chart
5958 .set_data(candles, ohlc(&[0, 10, 20, 40], 10.0))
5959 .unwrap();
5960 assert_eq!(chart.time_index.times(), &[0, 10, 20, 30, 40]);
5961 let cs = chart.entry(id).unwrap().store.custom().unwrap();
5962 assert_eq!(
5963 (cs.point_at(2), cs.point_at(3), cs.point_at(4)),
5964 (Some(0), Some(1), Some(2))
5965 );
5966
5967 chart.remove_series(candles).unwrap();
5969 assert!(chart.time_index.len() >= 3);
5970 assert_eq!(c(&chart).map(|(a, b)| b - a), Some(3));
5971 assert!(
5972 chart
5973 .add_indicator(id, Box::new(Nothing), Placement::Overlay)
5974 .is_err()
5975 );
5976 assert!(chart.set_data(id, values(&[0], &[1.0])).is_err());
5977 assert!(
5978 chart
5979 .add_series(pane, SeriesKind::Custom, SeriesOptions::default())
5980 .is_err()
5981 );
5982 }
5983
5984 #[test]
5985 fn overlay_custom_series_add_no_slots() {
5986 let (mut chart, id) = custom_chart(Ranges::overlay());
5987 let line = chart
5988 .add_series(
5989 chart.main_pane(),
5990 SeriesKind::Line,
5991 SeriesOptions::default(),
5992 )
5993 .unwrap();
5994 chart
5995 .set_data(line, values(&[0, 60, 120], &[0.0, 0.0, 0.0]))
5996 .unwrap();
5997 chart
5998 .update_custom(id, |r: &mut Ranges| {
5999 for t in [10, 30, 90] {
6000 r.push(t, 1.0, 2.0);
6001 }
6002 DataChange::Replace
6003 })
6004 .unwrap();
6005 assert_eq!(chart.time_index.len(), 3);
6006 chart.fit_content();
6007 let rects = red_rects(&mut chart);
6008 assert_eq!(rects.len(), 3);
6009 let x = |i: f64| chart.layout().plot.x + chart.time_scale.index_to_x_f64(i) as f32 - 1.0;
6011 for (r, i) in rects.iter().zip([1.0 / 6.0, 0.5, 1.5]) {
6012 assert!((r.x - x(i)).abs() < 0.01, "{} {}", r.x, x(i));
6013 }
6014 }
6015
6016 #[test]
6017 fn invalid_custom_data_is_an_error() {
6018 let (mut chart, id) = custom_chart(Ranges::default());
6019 chart
6020 .update_custom(id, |r: &mut Ranges| r.push(60, 1.0, 2.0))
6021 .unwrap();
6022 chart
6023 .update_custom(id, |r: &mut Ranges| r.push(120, 1.0, 2.0))
6024 .unwrap();
6025 assert_eq!(
6027 chart.update_custom(id, |r: &mut Ranges| r.push(90, 1.0, 2.0)),
6028 Err(Error::TimeNotIncreasing { index: 2 })
6029 );
6030 assert!(red_rects(&mut chart).is_empty());
6031 assert!(
6033 chart
6034 .update_custom(id, |_: &mut Probe| unreachable!())
6035 .is_err()
6036 );
6037 assert!(chart.custom_series::<Probe>(id).is_none());
6038 chart
6040 .update_custom(id, |r: &mut Ranges| {
6041 r.time[2] = 180;
6042 DataChange::Replace
6043 })
6044 .unwrap();
6045 chart.fit_content();
6046 assert_eq!(red_rects(&mut chart).len(), 3);
6047 let mut dup = Ranges::default();
6049 dup.push(1, 0.0, 1.0);
6050 dup.push(1, 0.0, 1.0);
6051 let pane = chart.main_pane();
6052 assert!(
6053 chart
6054 .add_custom_series(pane, Box::new(dup), SeriesOptions::default())
6055 .is_err()
6056 );
6057 assert_eq!(chart.series.len(), 1);
6058 chart.remove_series(id).unwrap();
6059 assert!(chart.custom_series::<Ranges>(id).is_none());
6060 }
6061
6062 #[test]
6063 fn native_kinds_get_a_custom_draw() {
6064 let mut r = Ranges::default();
6065 for (n, t) in [60_000, 120_000, 180_000].into_iter().enumerate() {
6066 r.push(t, n as f64, n as f64 + 1.0);
6067 }
6068 let (mut chart, id) = custom_chart(r);
6069 chart.fit_content();
6070 let portable = red_rects(&mut chart);
6071 assert_eq!(portable.len(), 3);
6072
6073 chart.set_native_kinds(&["test.ranges"]);
6074 assert_eq!(chart.needs_redraw(), Invalidation::Full);
6075 assert!(red_rects(&mut chart).is_empty());
6076 let draws: Vec<CustomDraw> = chart.frame().layers[LayerId::Main as usize]
6077 .cmds
6078 .iter()
6079 .filter_map(|c| match c {
6080 DrawCmd::Custom(d) => Some(*d),
6081 _ => None,
6082 })
6083 .collect();
6084 assert_eq!(draws.len(), 1);
6085 let d = draws[0];
6086 assert_eq!((d.series, d.kind), (id, "test.ranges"));
6087 assert_eq!(d.points, IdxSpan { start: 0, end: 3 });
6088 assert_eq!(d.clip, chart.layout().plot);
6089 assert!((d.params[0] - 3.0).abs() < f32::EPSILON);
6090 assert_eq!(Some(d.generation), chart.data_view().generation(id));
6091 assert_eq!(chart.frame().styles[d.style.0 as usize].up, Rgba::hex(RED));
6092 let view = chart.data_view();
6094 for (i, r) in portable.iter().enumerate() {
6095 let idx = view.custom_index(id, i).unwrap();
6096 let x = ((idx - d.x_transform.base as f64) as f32) * d.x_transform.step
6097 + d.x_transform.offset;
6098 assert!((x - (r.x + 1.0)).abs() < 1e-3, "{x} {}", r.x + 1.0);
6099 }
6100 chart.set_native_kinds(&["test.ranges"]);
6102 assert_eq!(chart.needs_redraw(), Invalidation::None);
6103 chart.set_native_kinds(&[]);
6104 assert_eq!(red_rects(&mut chart).len(), 3);
6105 }
6106
6107 use crate::testing::{MonoMeasurer as Mono, random_walk};
6108
6109 fn main_lines(chart: &Chart) -> Vec<LineInst> {
6111 let f = chart.frame();
6112 f.layers[LayerId::Main as usize]
6113 .cmds
6114 .iter()
6115 .filter_map(|c| match c {
6116 DrawCmd::Lines(s) => f.pools.lines.get(s.range()),
6117 _ => None,
6118 })
6119 .flatten()
6120 .copied()
6121 .collect()
6122 }
6123
6124 fn transform_chart(t: Box<dyn SeriesTransform>, bars: usize) -> (Chart, SeriesId) {
6125 let mut chart = Chart::new(ChartOptions {
6126 min_bar_spacing: Css(0.01),
6127 ..ChartOptions::default()
6128 });
6129 chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
6130 let id = chart
6131 .add_transform_series(chart.main_pane(), t, SeriesOptions::default())
6132 .unwrap();
6133 let data = random_walk(5, bars, 0, 60_000).unwrap();
6134 chart.set_data(id, SeriesData::Ohlc(data)).unwrap();
6135 chart.fit_content();
6136 (chart, id)
6137 }
6138
6139 #[test]
6140 fn a_transform_series_owns_the_axis() {
6141 use crate::transform::{Kagi, Renko, Reversal};
6142 let (mut chart, renko) = transform_chart(Box::new(Renko::fixed(1.0).unwrap()), 2_000);
6143 let pane = chart.main_pane();
6144 let n = chart.time_index.len();
6145 assert!(n > 10 && n < 2_000, "{n} bricks");
6146 let times = chart.time_index.times();
6148 assert!(times.windows(2).all(|w| w[0] < w[1]));
6149 assert!(times[0] >= 0 && times[n - 1] <= 2_000 * 60_000);
6150 let opts = SeriesOptions::default;
6151 assert!(chart.add_series(pane, SeriesKind::Line, opts()).is_err());
6152 assert!(chart.add_series(pane, SeriesKind::Kagi, opts()).is_err());
6153 assert!(
6154 chart
6155 .add_transform_series(
6156 pane,
6157 Box::new(Kagi::new(Reversal::Fixed(1.0)).unwrap()),
6158 opts()
6159 )
6160 .is_err()
6161 );
6162 assert!(
6163 chart
6164 .add_custom_series(pane, Box::new(Ranges::default()), opts())
6165 .is_err()
6166 );
6167 chart
6169 .add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(renko))
6170 .unwrap();
6171 chart.build_frame(0.0, &Mono);
6172 let kinds: Vec<SeriesKind> = chart.frame().layers[LayerId::Main as usize]
6173 .cmds
6174 .iter()
6175 .filter_map(|c| match c {
6176 DrawCmd::Series(d) => Some(d.kind),
6177 _ => None,
6178 })
6179 .collect();
6180 assert_eq!(kinds, [SeriesKind::Volume, SeriesKind::Candlestick]);
6181 chart.remove_series(renko).unwrap();
6184 chart.add_series(pane, SeriesKind::Line, opts()).unwrap();
6185 assert!(
6186 chart
6187 .add_transform_series(pane, Box::new(Renko::fixed(1.0).unwrap()), opts())
6188 .is_err()
6189 );
6190 }
6191
6192 #[test]
6193 fn indicators_follow_a_transform_series() {
6194 use crate::transform::{Kagi, Reversal};
6195 struct Double;
6197 impl Indicator for Double {
6198 fn name(&self) -> &'static str {
6199 "double"
6200 }
6201 fn outputs(&self) -> &[crate::plugin::OutputSpec] {
6202 const OUT: [crate::plugin::OutputSpec; 1] = [crate::plugin::OutputSpec::line("d")];
6203 &OUT
6204 }
6205 fn default_placement(&self) -> Placement {
6206 Placement::Overlay
6207 }
6208 fn warmup(&self) -> usize {
6209 0
6210 }
6211 fn update(
6212 &mut self,
6213 input: &IndicatorInput<'_>,
6214 _: DataChange,
6215 out: &mut IndicatorOutputs,
6216 ) {
6217 let start = out.start();
6218 for (i, v) in out.column(0).iter_mut().enumerate() {
6219 if let Some(b) = input.bar(start + i) {
6220 *v = 2.0 * b.close;
6221 }
6222 }
6223 }
6224 }
6225 let kagi = || Box::new(Kagi::new(Reversal::Fixed(1.5)).unwrap());
6226 let (mut chart, id) = transform_chart(kagi(), 300);
6227 let ind = chart
6228 .add_indicator(id, Box::new(Double), Placement::Overlay)
6229 .unwrap();
6230 let mut all = random_walk(5, 300, 0, 60_000).unwrap();
6231 let mut bar = BarUpdate {
6232 time: *all.time.last().unwrap(),
6233 open: *all.open.last().unwrap(),
6234 high: *all.high.last().unwrap(),
6235 low: *all.low.last().unwrap(),
6236 close: *all.close.last().unwrap(),
6237 volume: all.volume.as_ref().and_then(|v| v.last().copied()),
6238 };
6239 let mut x = 7_u64;
6240 for i in 0..400 {
6241 x = x.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
6242 let mv = ((x >> 33) as f64 / f64::from(1_u32 << 31) - 0.5) * 2.0;
6243 if i % 9 == 0 {
6244 bar = BarUpdate {
6245 time: bar.time + 60_000,
6246 open: bar.close,
6247 high: bar.close,
6248 low: bar.close,
6249 close: bar.close,
6250 volume: Some(0.0),
6251 };
6252 all.time.push(bar.time);
6253 all.open.push(bar.open);
6254 all.high.push(bar.high);
6255 all.low.push(bar.low);
6256 all.close.push(bar.close);
6257 all.volume.as_mut().unwrap().push(0.0);
6258 }
6259 bar.close += mv;
6260 bar.high = bar.high.max(bar.close);
6261 bar.low = bar.low.min(bar.close);
6262 bar.volume = bar.volume.map(|v| v + 1.0);
6263 let p = all.time.len() - 1;
6264 all.close[p] = bar.close;
6265 all.high[p] = bar.high;
6266 all.low[p] = bar.low;
6267 all.volume.as_mut().unwrap()[p] = bar.volume.unwrap();
6268 chart.update_last(id, bar).unwrap();
6269 }
6270 let (mut fresh, fid) = transform_chart(kagi(), 1);
6271 fresh.set_data(fid, SeriesData::Ohlc(all)).unwrap();
6272 let find = fresh
6273 .add_indicator(fid, Box::new(Double), Placement::Overlay)
6274 .unwrap();
6275 assert_eq!(chart.time_index.times(), fresh.time_index.times());
6276 let values = |c: &Chart, ind: IndicatorId| -> Vec<u64> {
6277 let s = c.indicator_series(ind).unwrap()[0];
6278 let view = c.data_view().ohlc(s, 0).unwrap();
6279 (0..view.close.len())
6280 .map(|i| view.close.get(i).unwrap().to_bits())
6281 .collect()
6282 };
6283 assert_eq!(values(&chart, ind), values(&fresh, find));
6284 assert_eq!(values(&chart, ind).len(), chart.time_index.len());
6285 }
6286
6287 #[test]
6288 fn kagi_and_point_figure_are_primitives() {
6289 use crate::transform::{Kagi, PointFigure, Reversal};
6290 let theme = Theme::light();
6291 let (mut chart, _) =
6293 transform_chart(Box::new(Kagi::new(Reversal::Fixed(2.0)).unwrap()), 3_000);
6294 chart.time_scale().set_bar_spacing(8.0);
6295 chart.build_frame(0.0, &Mono);
6296 let lines: Vec<LineInst> = main_lines(&chart)
6298 .into_iter()
6299 .filter(|l| l.stroke.dash == LineDash::Solid)
6300 .collect();
6301 let thick = lines.iter().filter(|l| l.stroke.color == theme.up).count();
6302 let thin = lines
6303 .iter()
6304 .filter(|l| l.stroke.color == theme.down)
6305 .count();
6306 assert!(thick > 10 && thin > 10, "{thick} thick, {thin} thin");
6307 assert!(
6308 lines
6309 .iter()
6310 .filter(|l| l.stroke.color == theme.up)
6311 .all(|l| l.stroke.width == Px(2.0))
6312 );
6313 assert!(
6314 lines
6315 .iter()
6316 .filter(|l| l.stroke.color == theme.down)
6317 .all(|l| l.stroke.width == Px(1.0))
6318 );
6319 chart.time_scale().set_bar_spacing(0.05);
6321 chart.build_frame(0.0, &Mono);
6322 let n = main_lines(&chart).len();
6323 assert!(n > 10 && n <= 800, "{n} lines");
6324 let (mut chart, _) = transform_chart(Box::new(PointFigure::new(0.5, 3).unwrap()), 3_000);
6326 chart.time_scale().set_bar_spacing(12.0);
6327 chart.build_frame(0.0, &Mono);
6328 let xs = main_lines(&chart)
6329 .iter()
6330 .filter(|l| l.stroke.color == theme.up && l.stroke.dash == LineDash::Solid)
6331 .count();
6332 let os = chart.frame().layers[LayerId::Main as usize]
6333 .cmds
6334 .iter()
6335 .filter(|c| matches!(c, DrawCmd::Polyline { style, .. } if style.color == theme.down))
6336 .count();
6337 assert!(xs > 10 && xs % 2 == 0 && os > 5, "{xs} X lines, {os} Os");
6338 chart.time_scale().set_bar_spacing(2.0);
6340 chart.build_frame(0.0, &Mono);
6341 let rects = rects_of(&chart, LayerId::Main)
6342 .iter()
6343 .filter(|(c, _)| *c == theme.up || *c == theme.down)
6344 .count();
6345 assert!(rects > 10, "{rects} columns");
6346 }
6347
6348 fn series_draws(chart: &Chart) -> Vec<SeriesDraw> {
6349 chart.frame().layers[LayerId::Main as usize]
6350 .cmds
6351 .iter()
6352 .filter_map(|c| match c {
6353 DrawCmd::Series(s) => Some(*s),
6354 _ => None,
6355 })
6356 .collect()
6357 }
6358
6359 #[test]
6362 fn bands_follow_their_series() {
6363 use crate::testing::MonoMeasurer;
6364 let (mut chart, a, b) = two_series(SeriesKind::Line, SeriesKind::Line);
6365 chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
6366 let t = [0, 60_000, 120_000];
6367 chart.set_data(a, values(&t, &[2.0, 3.0, 1.0])).unwrap();
6368 chart.set_data(b, values(&t, &[1.0, 1.0, 2.0])).unwrap();
6369 let candles = chart
6370 .add_series(
6371 chart.main_pane(),
6372 SeriesKind::Candlestick,
6373 SeriesOptions::default(),
6374 )
6375 .unwrap();
6376 assert!(chart.add_band(a, candles, BandOptions::default()).is_err());
6377 assert!(chart.add_band(a, a, BandOptions::default()).is_err());
6378 assert_eq!(
6379 chart.add_band(a, SeriesId(99), BandOptions::default()),
6380 Err(Error::UnknownId)
6381 );
6382 assert!(
6383 chart
6384 .add_series(
6385 chart.main_pane(),
6386 SeriesKind::Band,
6387 SeriesOptions::default()
6388 )
6389 .is_err()
6390 );
6391 let other = chart.add_pane(PaneOptions::default());
6392 let c = chart
6393 .add_series(other, SeriesKind::Line, SeriesOptions::default())
6394 .unwrap();
6395 assert!(chart.add_band(a, c, BandOptions::default()).is_err());
6396
6397 let fill = Rgba::hex(0x0011_2233);
6398 let band = chart
6399 .add_band(
6400 a,
6401 b,
6402 BandOptions {
6403 fill: Some(fill),
6404 fill_crossed: None,
6405 },
6406 )
6407 .unwrap();
6408 chart.build_frame(0.0, &MonoMeasurer);
6409 let draws = series_draws(&chart);
6410 let kinds: Vec<_> = draws.iter().map(|d| d.kind).collect();
6411 assert_eq!(kinds[0], SeriesKind::Band, "{kinds:?}");
6412 assert_eq!((draws[0].series, draws[0].pair), (a, Some(b)));
6413 let style = chart.frame().styles[draws[0].style.0 as usize];
6414 assert_eq!((style.fill_top, style.fill_bottom), (fill, fill));
6416 assert!(draws[1..].iter().all(|d| d.pair.is_none()));
6417
6418 let opts = SeriesOptions {
6420 shift: 2,
6421 ..*chart.series_options(b).unwrap()
6422 };
6423 chart.set_series_options(b, opts).unwrap();
6424 chart.build_frame(0.0, &MonoMeasurer);
6425 assert!(
6426 series_draws(&chart)
6427 .iter()
6428 .all(|d| d.kind != SeriesKind::Band)
6429 );
6430 let opts = SeriesOptions { shift: 0, ..opts };
6431 chart.set_series_options(b, opts).unwrap();
6432
6433 chart
6434 .set_band_options(band, BandOptions::default())
6435 .unwrap();
6436 assert_eq!(chart.band_options(band), Some(&BandOptions::default()));
6437 chart.remove_series(b).unwrap();
6438 assert_eq!(chart.band_options(band), None);
6439 assert_eq!(chart.remove_band(band), Err(Error::UnknownId));
6440 chart.build_frame(0.0, &MonoMeasurer);
6441 assert!(
6442 series_draws(&chart)
6443 .iter()
6444 .all(|d| d.kind != SeriesKind::Band)
6445 );
6446 }
6447
6448 #[test]
6450 fn fill_to_is_checked() {
6451 use crate::plugin::{IndicatorInput, IndicatorOutputs, OutputSpec};
6452 struct Bad([OutputSpec; 2]);
6453 impl Indicator for Bad {
6454 fn name(&self) -> &'static str {
6455 "bad"
6456 }
6457 fn outputs(&self) -> &[OutputSpec] {
6458 &self.0
6459 }
6460 fn default_placement(&self) -> Placement {
6461 Placement::Overlay
6462 }
6463 fn warmup(&self) -> usize {
6464 0
6465 }
6466 fn update(&mut self, _: &IndicatorInput<'_>, _: DataChange, _: &mut IndicatorOutputs) {}
6467 }
6468 let mut chart = Chart::new(ChartOptions::default());
6469 let src = chart
6470 .add_series(
6471 chart.main_pane(),
6472 SeriesKind::Line,
6473 SeriesOptions::default(),
6474 )
6475 .unwrap();
6476 for to in [0, 2] {
6477 let a = OutputSpec {
6478 fill_to: Some((to, BandOptions::default())),
6479 ..OutputSpec::line("a")
6480 };
6481 let bad = Bad([a, OutputSpec::line("b")]);
6482 assert!(
6483 chart
6484 .add_indicator(src, Box::new(bad), Placement::Overlay)
6485 .is_err()
6486 );
6487 }
6488 assert_eq!(chart.series.len(), 1, "nothing was added");
6489 }
6490}