use crate::data::OhlcLevelView;
use crate::data::lod::{f32_down, f32_up};
use crate::frame::{LineDash, PriceMapping, XTransform, YTransform};
use crate::geom::{PointPx, Px, RectPx};
pub const CHUNK_SHIFT: u32 = 12;
pub const CHUNK_LEN: i64 = 1 << CHUNK_SHIFT;
pub fn chunk_of(level: u8, e: i64) -> i64 {
let from_anchor = if level == 0 {
e - crate::data::ANCHOR
} else {
e
};
from_anchor >> CHUNK_SHIFT
}
pub fn chunk_start(level: u8, c: i64) -> i64 {
let from_anchor = c << CHUNK_SHIFT;
if level == 0 {
from_anchor + crate::data::ANCHOR
} else {
from_anchor
}
}
pub fn initial_chunk_ref(view: &OhlcLevelView<'_>, c: i64) -> Option<f64> {
let start = chunk_start(view.level, c).max(view.first);
let end = (chunk_start(view.level, c) + CHUNK_LEN).min(view.end());
let opens = || (start..end).filter_map(|j| view.open.at(view.first, j));
opens()
.find(|p| p.is_finite() && *p > 0.0)
.or_else(|| opens().find(|p| p.is_finite()))
.or_else(|| {
(start..end)
.filter_map(|j| view.high.at(view.first, j))
.find(|p| p.is_finite())
})
}
pub fn ohlc_rel(yt: &YTransform, ohlc: [f64; 4], chunk_ref: f64) -> [f32; 4] {
let r = map(yt.mapping, chunk_ref);
let [o, h, l, c] = ohlc.map(|v| map(yt.mapping, v) - r);
[o as f32, f32_up(h), f32_down(l), c as f32].map(gap_or)
}
pub const GAP: f32 = 3.0e38;
fn gap_or(v: f32) -> f32 {
if v.is_finite() { v } else { GAP }
}
pub fn is_gap(v_rel: f32) -> bool {
v_rel.abs() >= 1.0e38 || v_rel.is_nan()
}
pub fn is_up_rel(open_rel: f32, close_rel: f32) -> bool {
close_rel >= open_rel
}
pub fn snap(v: f32) -> f32 {
(v + 0.5).floor()
}
pub fn x_shift(xt: &XTransform) -> f32 {
if xt.step == 0.0 {
return 0.0;
}
(f64::from(xt.offset) / f64::from(xt.step)) as f32
}
pub fn x_center(xt: &XTransform, j: i64) -> f32 {
let d = (j - xt.base) as f32;
let shifted = d + x_shift(xt);
shifted * xt.step
}
fn map(mapping: PriceMapping, v: f64) -> f64 {
match mapping {
PriceMapping::Linear => v,
PriceMapping::Log => v.ln(),
}
}
pub fn v_rel(yt: &YTransform, value: f64, chunk_ref: f64) -> f32 {
(map(yt.mapping, value) - map(yt.mapping, chunk_ref)) as f32
}
pub fn y_bias(yt: &YTransform, chunk_ref: f64) -> f32 {
if yt.a == 0.0 {
return 0.0;
}
let delta = map(yt.mapping, chunk_ref) - map(yt.mapping, yt.view_ref);
(delta + f64::from(yt.b) / f64::from(yt.a)) as f32
}
pub fn y(yt: &YTransform, v_rel: f32, bias: f32) -> f32 {
let t = v_rel + bias;
t * yt.a
}
pub fn y_of_price(yt: &YTransform, price: f64) -> f32 {
y(yt, v_rel(yt, price, yt.view_ref), y_bias(yt, yt.view_ref))
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BarMetrics {
pub body: f32,
pub show_body: bool,
pub show_border: bool,
}
pub fn bar_metrics(step: f32) -> BarMetrics {
let mut body = (step * 0.8).floor().max(1.0);
if body % 2.0 == 0.0 {
body -= 1.0;
}
BarMetrics {
body,
show_body: step >= 1.5,
show_border: step >= 3.0,
}
}
pub fn is_up(open: f64, close: f64) -> bool {
close >= open
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CandleGeom {
pub wick: RectPx,
pub body: Option<RectPx>,
}
fn v_span(y0: f32, y1: f32) -> (f32, f32) {
let top = snap(y0.min(y1));
let bottom = snap(y0.max(y1));
(top, (bottom - top).max(1.0))
}
pub fn candle(xc: f32, m: BarMetrics, ys: [f32; 4]) -> CandleGeom {
let [y_open, y_high, y_low, y_close] = ys;
let column = xc.floor();
let (wy, wh) = v_span(y_high, y_low);
let wick = RectPx {
x: column,
y: wy,
w: 1.0,
h: wh,
};
let body = m.show_body.then(|| {
let (by, bh) = v_span(y_open, y_close);
RectPx {
x: column - (m.body - 1.0) * 0.5,
y: by,
w: m.body,
h: bh,
}
});
CandleGeom { wick, body }
}
pub fn histogram(xc: f32, m: BarMetrics, y_value: f32, y_base: f32) -> RectPx {
let column = xc.floor();
let width = if m.show_body { m.body } else { 1.0 };
let (y, h) = v_span(y_value, y_base);
RectPx {
x: column - (width - 1.0) * 0.5,
y,
w: width,
h,
}
}
pub fn ohlc_bar(xc: f32, m: BarMetrics, ys: [f32; 4]) -> [Option<RectPx>; 3] {
let [y_open, y_high, y_low, y_close] = ys;
let column = xc.floor();
let (wy, wh) = v_span(y_high, y_low);
let wick = RectPx {
x: column,
y: wy,
w: 1.0,
h: wh,
};
let half = (m.body - 1.0) * 0.5;
if !m.show_body || half < 1.0 {
return [Some(wick), None, None];
}
let (oy, _) = v_span(y_open, y_open);
let (cy, _) = v_span(y_close, y_close);
let open = RectPx {
x: column - half,
y: oy,
w: half,
h: 1.0,
};
let close = RectPx {
x: column + 1.0,
y: cy,
w: half,
h: 1.0,
};
[Some(wick), Some(open), Some(close)]
}
pub fn coverage_8(coverage: f32) -> u8 {
(coverage * 255.0 + 0.5).floor().clamp(0.0, 255.0) as u8
}
pub fn segment_coverage(p: PointPx, a: PointPx, b: PointPx, half_width: Px) -> f32 {
let pax = p.x - a.x;
let pay = p.y - a.y;
let bax = b.x - a.x;
let bay = b.y - a.y;
let len2 = bax * bax + bay * bay;
let mut h = 0.0;
if len2 > 0.0 {
h = ((pax * bax + pay * bay) / len2).clamp(0.0, 1.0);
}
let dx = pax - bax * h;
let dy = pay - bay * h;
let d = (dx * dx + dy * dy).sqrt();
(half_width.0 + 0.5 - d).clamp(0.0, 1.0)
}
pub fn line_axis(a: PointPx, b: PointPx) -> (PointPx, f32) {
let dx = b.x - a.x;
let dy = b.y - a.y;
let len = (dx * dx + dy * dy).sqrt().max(1e-4);
(
PointPx {
x: dx / len,
y: dy / len,
},
len,
)
}
pub fn line_coverage(along: f32, across: f32, len: f32, width: Px, dash: LineDash) -> f32 {
let half = width.0 * 0.5;
let cov_across = (half + 0.5 - across.abs()).clamp(0.0, 1.0);
let cov_along = (along.min(len - along) + 0.5).clamp(0.0, 1.0);
let on = match dash {
LineDash::Solid => true,
LineDash::Dashed => {
let t = along / (8.0 * width.0);
t - t.floor() < 0.5
}
LineDash::Dotted => {
let t = along / (3.0 * width.0);
t - t.floor() < 1.0 / 3.0
}
};
if on { cov_across * cov_along } else { 0.0 }
}
pub const ICON_CIRCLE: u16 = 0;
pub const ICON_SQUARE: u16 = 1;
pub const ICON_ARROW_UP: u16 = 2;
pub const ICON_ARROW_DOWN: u16 = 3;
pub fn icon_coverage(icon: u16, dx: f32, dy: f32, size: f32) -> f32 {
let h = size * 0.5;
let ax = dx.abs();
let d = match icon {
ICON_CIRCLE => (dx * dx + dy * dy).sqrt() - h,
ICON_SQUARE => {
let s = h * 0.8;
(ax - s).max(dy.abs() - s)
}
ICON_ARROW_UP | ICON_ARROW_DOWN => {
let ty = if icon == ICON_ARROW_UP { dy } else { -dy };
let head = ty.max((ax - ty - h) * 0.707_106_77);
let q = h * 0.5;
let shaft = (ax - h * 0.35).max((ty - q).abs() - q);
head.min(shaft)
}
_ => return 0.0,
};
(0.5 - d).clamp(0.0, 1.0)
}
pub fn dash_on(x: Px, width: Px, dash: LineDash) -> bool {
let period = match dash {
LineDash::Solid => return true,
LineDash::Dashed => 4.0 * width.0,
LineDash::Dotted => width.0,
};
let k = (x.0 / period).floor();
k - 2.0 * (k * 0.5).floor() < 0.5
}
pub fn fill_coverage(p: PointPx, a: PointPx, b: PointPx, base_y: Px) -> f32 {
if !(p.x >= a.x && p.x < b.x) {
return 0.0;
}
let t = (p.x - a.x) / (b.x - a.x);
let edge = a.y + (b.y - a.y) * t;
let lo = edge.min(base_y.0);
let hi = edge.max(base_y.0);
((p.y - lo).min(hi - p.y) + 0.5).clamp(0.0, 1.0)
}
pub fn band_coverage(
p: PointPx,
a: PointPx,
b: PointPx,
lower_a: f32,
lower_b: f32,
scale: f32,
) -> (f32, bool) {
if !(p.x >= a.x && p.x < b.x) {
return (0.0, false);
}
let t = (p.x - a.x) / (b.x - a.x);
let upper = a.y + (b.y - a.y) * t;
let lower = lower_a + (lower_b - lower_a) * t;
let lo = upper.min(lower);
let hi = upper.max(lower);
let coverage = ((p.y - lo).min(hi - p.y) + 0.5).clamp(0.0, 1.0);
(coverage, (lower - upper) * scale > 0.0)
}
pub fn line_segments(
yt: &YTransform,
bias: f32,
xj: f32,
xn: f32,
cur: [f32; 4],
next: [f32; 4],
step: bool,
) -> [Option<(PointPx, PointPx)>; 3] {
let [_, hi, lo, last] = cur;
let first_n = next[0];
let p = |x: f32, v: f32| PointPx {
x,
y: y(yt, v, bias),
};
let mut out = [None; 3];
if !is_gap(hi) && !is_gap(lo) && hi.to_bits() != lo.to_bits() {
out[0] = Some((p(xj, hi), p(xj, lo)));
}
if !is_gap(last) && !is_gap(first_n) {
if step {
out[1] = Some((p(xj, last), p(xn, last)));
out[2] = Some((p(xn, last), p(xn, first_n)));
} else {
out[1] = Some((p(xj, last), p(xn, first_n)));
}
}
out
}
pub fn fill_edge(
yt: &YTransform,
bias: f32,
xj: f32,
xn: f32,
cur: [f32; 4],
next: [f32; 4],
step: bool,
) -> Option<(PointPx, PointPx)> {
let (last, first_n) = (cur[3], next[0]);
if is_gap(last) || is_gap(first_n) {
return None;
}
let y0 = y(yt, last, bias);
let y1 = if step { y0 } else { y(yt, first_n, bias) };
Some((PointPx { x: xj, y: y0 }, PointPx { x: xn, y: y1 }))
}
pub fn histogram_value_y(yt: &YTransform, bias: f32, cur: [f32; 4], base_y: f32) -> Option<f32> {
let (hi, lo) = (cur[1], cur[2]);
if is_gap(hi) || is_gap(lo) {
return None;
}
let (y_hi, y_lo) = (y(yt, hi, bias), y(yt, lo, bias));
Some(if (y_hi - base_y).abs() >= (y_lo - base_y).abs() {
y_hi
} else {
y_lo
})
}
pub fn gradient_t(y: Px, top: Px, bottom: Px) -> f32 {
let h = bottom.0 - top.0;
if h <= 0.0 {
return 0.0;
}
((y.0 - top.0) / h).clamp(0.0, 1.0)
}
#[cfg(test)]
#[allow(clippy::float_cmp)] mod tests {
use super::*;
#[test]
fn body_is_odd_and_fits_in_step() {
for i in 1..2000 {
let step = i as f32 * 0.05;
let m = bar_metrics(step);
assert!(m.body >= 1.0);
assert_eq!(m.body % 2.0, 1.0, "step {step}");
assert!(m.body <= step.max(1.0), "step {step}");
}
}
#[test]
fn log_mapping_is_relative() {
let yt = YTransform {
a: -100.0,
b: 0.0,
view_ref: 10.0,
mapping: PriceMapping::Log,
};
assert!((y_of_price(&yt, 10.0 * core::f64::consts::E) + 100.0).abs() < 1e-3);
}
}