1#![forbid(unsafe_code)]
39
40mod footprint;
41#[cfg(feature = "gpu")]
42mod gpu;
43mod grid;
44mod heatmap;
45mod levels;
46#[cfg(feature = "testing")]
47pub mod testing;
48mod tpo;
49mod trades;
50
51use core::ops::Range;
52
53use ferrochart_core::Chart;
54use ferrochart_core::data::{DataChange, OhlcColumns, SeriesId, Timestamp};
55use ferrochart_core::error::{Error, Result};
56use ferrochart_core::plugin::CustomSeries;
57
58pub use footprint::{
59 CELLS_MIN_SPACING, FOOTPRINT_KIND, Footprint, FootprintColors, FootprintMode, FootprintOptions,
60 NUMBERS_MIN_SPACING,
61};
62#[cfg(feature = "gpu")]
63pub use gpu::{HeatmapGpu, register_gpu, supports_native_heatmap};
64pub use grid::{Column, SparseGrid};
65pub use heatmap::{
66 ColorScale, DepthSnapshot, HEATMAP_KIND, Heatmap, HeatmapColors, HeatmapOptions, HeatmapRange,
67 HeatmapSource, MAX_LEVELS_PER_ROW,
68};
69pub use levels::PriceLevels;
70pub use tpo::{
71 SessionProfile, TPO_KIND, TPO_MIN_FONT, TPO_MIN_SPACING, Tpo, TpoColors, TpoOptions, tpo_letter,
72};
73pub use trades::{Side, TickColumns, TickRule};
74
75pub(crate) fn column_start(time: Timestamp, period: i64) -> Timestamp {
78 time.div_euclid(period).checked_mul(period).unwrap_or(time)
79}
80
81pub(crate) trait TradeSink: CustomSeries {
83 fn timeframe(&self) -> i64;
85 fn last_column(&self) -> Option<Timestamp>;
87 fn apply(&mut self, trades: &TickColumns, range: Range<usize>) -> Result<()>;
89}
90
91pub fn append_trades(chart: &mut Chart, id: SeriesId, trades: &TickColumns) -> Result<()> {
105 trades.check(None)?;
106 if chart.custom_series::<Footprint>(id).is_some() {
107 return append::<Footprint>(chart, id, trades);
108 }
109 if let Some(h) = chart.custom_series::<Heatmap>(id) {
110 if h.options().source != HeatmapSource::Trades {
111 return Err(Error::InvalidArgument("the heatmap takes depth snapshots"));
112 }
113 return append::<Heatmap>(chart, id, trades);
114 }
115 chart.series_kind(id).ok_or(Error::UnknownId)?;
116 Err(Error::InvalidArgument("the series takes no trades"))
117}
118
119pub fn append_depth(chart: &mut Chart, id: SeriesId, snapshot: &DepthSnapshot<'_>) -> Result<()> {
133 if chart.custom_series::<Heatmap>(id).is_none() {
134 chart.series_kind(id).ok_or(Error::UnknownId)?;
135 return Err(Error::InvalidArgument(
136 "the series takes no depth snapshots",
137 ));
138 }
139 let mut failed = None;
140 chart.update_custom(id, |h: &mut Heatmap| {
141 let (before, version) = (h.grid().columns(), h.version());
142 let result = h.push_depth(snapshot);
143 let change = match h.grid().columns() - before {
144 _ if h.version() == version => DataChange::Append { count: 0 },
145 0 => DataChange::UpdateLast,
146 count if result.is_ok() => DataChange::Append { count },
147 _ => DataChange::Replace,
148 };
149 failed = result.err();
150 change
151 })?;
152 failed.map_or(Ok(()), Err)
153}
154
155fn append<T: TradeSink>(chart: &mut Chart, id: SeriesId, trades: &TickColumns) -> Result<()> {
156 let s = chart.custom_series::<T>(id).ok_or(Error::UnknownId)?;
157 let (period, last) = (s.timeframe(), s.last_column());
158 let n = trades.len();
159 let split = match (last, trades.time.first()) {
161 (Some(last), Some(&t0)) if column_start(t0, period) < last => {
162 return Err(Error::TimeNotIncreasing { index: 0 });
163 }
164 (Some(last), _) => trades
165 .time
166 .partition_point(|&t| column_start(t, period) <= last),
167 (None, _) => 0,
168 };
169 let mut failed = None;
170 if split > 0 {
171 chart.update_custom(id, |s: &mut T| match s.apply(trades, 0..split) {
172 Ok(()) => DataChange::UpdateLast,
173 Err(e) => {
174 failed = Some(e);
175 DataChange::Replace
176 }
177 })?;
178 }
179 if failed.is_none() && split < n {
180 chart.update_custom(id, |s: &mut T| {
181 let before = s.times().len();
182 match s.apply(trades, split..n) {
183 Ok(()) => DataChange::Append {
184 count: s.times().len() - before,
185 },
186 Err(e) => {
187 failed = Some(e);
188 DataChange::Replace
189 }
190 }
191 })?;
192 }
193 failed.map_or(Ok(()), Err)
194}
195
196pub fn append_bars(chart: &mut Chart, id: SeriesId, bars: &OhlcColumns) -> Result<()> {
213 let Some(t) = chart.custom_series::<Tpo>(id) else {
214 chart.series_kind(id).ok_or(Error::UnknownId)?;
215 return Err(Error::InvalidArgument("the series takes no bars"));
216 };
217 tpo::check_bars(bars, t.price_levels())?;
218 let n = bars.time.len();
219 let split = match (t.last_session(), bars.time.first()) {
220 (Some(last), Some(&t0)) if t.session_start(t0) < last => {
221 return Err(Error::TimeNotIncreasing { index: 0 });
222 }
223 (Some(last), _) => bars.time.partition_point(|&x| t.session_start(x) <= last),
224 (None, _) => 0,
225 };
226 let apply = |t: &mut Tpo, range: Range<usize>| -> Result<()> {
227 let result = range.into_iter().try_for_each(|i| {
228 t.push_raw(bars.time[i], bars.high[i], bars.low[i])
229 .map(drop)
230 });
231 t.finish_last();
232 result
233 };
234 let mut failed = None;
235 if split > 0 {
236 chart.update_custom(id, |t: &mut Tpo| match apply(t, 0..split) {
237 Ok(()) => DataChange::UpdateLast,
238 Err(e) => {
239 failed = Some(e);
240 DataChange::Replace
241 }
242 })?;
243 }
244 if failed.is_none() && split < n {
245 chart.update_custom(id, |t: &mut Tpo| {
246 let before = t.sessions().len();
247 match apply(t, split..n) {
248 Ok(()) => DataChange::Append {
249 count: t.sessions().len() - before,
250 },
251 Err(e) => {
252 failed = Some(e);
253 DataChange::Replace
254 }
255 }
256 })?;
257 }
258 failed.map_or(Ok(()), Err)
259}