Add xframe-indicators: 250 technical indicators as pure f64 functions

Port of src/indicators.h (lightgui eb0b5fc): 265 functions transpiled
from C++ (generator/transpile.py) + 5 hand-ported (f_frama, f_stc,
f_cyber_cycle, f_pivots, hilbert), de-duplicated helpers, NaN warm-up
semantics preserved, 250-def catalog cross-checked against
data/indicators.json (all match). Plot geometry (line_points/bar_rects/
markers) ported without cairo. Tests: 8/8 pass, warning-free.
This commit is contained in:
cnmcdee committed 2026-11-29 06:33:31 +00:00
1 parent 2347508363
commit a04bb568a0
10 files changed
+8759

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
[package]
name = "xframe-indicators"
version = "0.1.0"
edition = "2021"
description = "Technical indicators: 250 modules as pure Vec<f64> -> Vec<f64> functions with NaN warm-up semantics. Port of src/indicators.h (lightgui eb0b5fc)."
license = "MIT"
[dependencies]
File diff suppressed because it is too large. Load diff
+260
View File
@@ -0,0 +1,260 @@
// Generated by tools/transpile.py from the defs_* tables in
// src/indicators.h (lightgui eb0b5fc). DO NOT EDIT BY HAND.
use crate::generated::*;
use crate::hand::*;
use crate::{Def, PlotKind, Style};
/// The 250-indicator registry, in C++ registration order.
pub(crate) static DEFS: &[Def] = &[
Def { name: "SMA", kind: PlotKind::Overlay, style: Style::Lines, color: 0, defaults: "20", func: f_sma },
Def { name: "EMA", kind: PlotKind::Overlay, style: Style::Lines, color: 1, defaults: "20", func: f_ema },
Def { name: "WMA", kind: PlotKind::Overlay, style: Style::Lines, color: 2, defaults: "20", func: f_wma },
Def { name: "SMMA", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "20", func: f_smma },
Def { name: "DEMA", kind: PlotKind::Overlay, style: Style::Lines, color: 4, defaults: "20", func: f_dema },
Def { name: "TEMA", kind: PlotKind::Overlay, style: Style::Lines, color: 5, defaults: "20", func: f_tema },
Def { name: "TRIMA", kind: PlotKind::Overlay, style: Style::Lines, color: 6, defaults: "20", func: f_trima },
Def { name: "KAMA", kind: PlotKind::Overlay, style: Style::Lines, color: 7, defaults: "10", func: f_kama },
Def { name: "T3", kind: PlotKind::Overlay, style: Style::Lines, color: 8, defaults: "10,0.7", func: f_t3 },
Def { name: "HMA", kind: PlotKind::Overlay, style: Style::Lines, color: 9, defaults: "20", func: f_hma },
Def { name: "ZLEMA", kind: PlotKind::Overlay, style: Style::Lines, color: 10, defaults: "20", func: f_zlema },
Def { name: "VWMA", kind: PlotKind::Overlay, style: Style::Lines, color: 11, defaults: "20", func: f_vwma },
Def { name: "LSMA", kind: PlotKind::Overlay, style: Style::Lines, color: 12, defaults: "25", func: f_lsma },
Def { name: "ALMA", kind: PlotKind::Overlay, style: Style::Lines, color: 13, defaults: "9,0.85,6", func: f_alma },
Def { name: "McGinley Dynamic", kind: PlotKind::Overlay, style: Style::Lines, color: 0, defaults: "14", func: f_mcginley },
Def { name: "Geometric MA", kind: PlotKind::Overlay, style: Style::Lines, color: 1, defaults: "20", func: f_gma },
Def { name: "Median Price", kind: PlotKind::Overlay, style: Style::Lines, color: 2, defaults: "", func: f_median_price },
Def { name: "Typical Price", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "", func: f_typical_price },
Def { name: "Weighted Close", kind: PlotKind::Overlay, style: Style::Lines, color: 4, defaults: "", func: f_weighted_close },
Def { name: "Midprice", kind: PlotKind::Overlay, style: Style::Lines, color: 5, defaults: "14", func: f_midprice },
Def { name: "Midpoint", kind: PlotKind::Overlay, style: Style::Lines, color: 6, defaults: "14", func: f_midpoint },
Def { name: "VWAP", kind: PlotKind::Overlay, style: Style::Lines, color: 7, defaults: "", func: f_vwap },
Def { name: "Heikin Ashi Close", kind: PlotKind::Overlay, style: Style::Lines, color: 8, defaults: "", func: f_heikin_ashi },
Def { name: "Super Smoother", kind: PlotKind::Overlay, style: Style::Lines, color: 9, defaults: "14", func: f_super_smoother },
Def { name: "Decycler", kind: PlotKind::Overlay, style: Style::Lines, color: 10, defaults: "30", func: f_decycler },
Def { name: "Gaussian Filter", kind: PlotKind::Overlay, style: Style::Lines, color: 11, defaults: "14", func: f_gaussian },
Def { name: "Butterworth Filter", kind: PlotKind::Overlay, style: Style::Lines, color: 12, defaults: "14", func: f_butterworth },
Def { name: "Laguerre Filter", kind: PlotKind::Overlay, style: Style::Lines, color: 13, defaults: "0.8", func: f_laguerre },
Def { name: "VIDYA", kind: PlotKind::Overlay, style: Style::Lines, color: 0, defaults: "14", func: f_vidya },
Def { name: "FRAMA", kind: PlotKind::Overlay, style: Style::Lines, color: 1, defaults: "16", func: f_frama },
Def { name: "Variable MA", kind: PlotKind::Overlay, style: Style::Lines, color: 2, defaults: "14", func: f_vma },
Def { name: "Jurik MA", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "14,0", func: f_jma },
Def { name: "Bollinger Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 0, defaults: "20,2", func: f_bollinger },
Def { name: "Bollinger %B", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "20,2", func: f_bollinger_pb },
Def { name: "Bollinger Bandwidth", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "20,2", func: f_bollinger_bw },
Def { name: "Keltner Channels", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "20,2,10", func: f_keltner },
Def { name: "Donchian Channels", kind: PlotKind::Overlay, style: Style::Lines, color: 4, defaults: "20", func: f_donchian },
Def { name: "STARC Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 6, defaults: "15,2,15", func: f_starc },
Def { name: "MA Envelope", kind: PlotKind::Overlay, style: Style::Lines, color: 7, defaults: "20,2.5", func: f_envelope },
Def { name: "Ichimoku", kind: PlotKind::Overlay, style: Style::Lines, color: 8, defaults: "9,26,52", func: f_ichimoku },
Def { name: "Supertrend", kind: PlotKind::Overlay, style: Style::Lines, color: 9, defaults: "10,3", func: f_supertrend },
Def { name: "Parabolic SAR", kind: PlotKind::Overlay, style: Style::Lines, color: 10, defaults: "0.02,0.2", func: f_sar },
Def { name: "Pivot Points Standard", kind: PlotKind::Overlay, style: Style::Lines, color: 11, defaults: "0", func: f_pivots },
Def { name: "Pivot Points Woodie", kind: PlotKind::Overlay, style: Style::Lines, color: 12, defaults: "1", func: f_pivots },
Def { name: "Pivot Points Camarilla", kind: PlotKind::Overlay, style: Style::Lines, color: 13, defaults: "2", func: f_pivots },
Def { name: "Pivot Points Fibonacci", kind: PlotKind::Overlay, style: Style::Lines, color: 0, defaults: "3", func: f_pivots },
Def { name: "Pivot Points DeMark", kind: PlotKind::Overlay, style: Style::Lines, color: 1, defaults: "4", func: f_pivots },
Def { name: "Linear Regression Channel", kind: PlotKind::Overlay, style: Style::Lines, color: 2, defaults: "20,2", func: f_lr_channel },
Def { name: "Projection Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "14", func: f_projection_bands },
Def { name: "ATR Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 4, defaults: "14,2", func: f_atr_bands },
Def { name: "High-Low Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 5, defaults: "21", func: f_hilo_bands },
Def { name: "Fractal Chaos Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 6, defaults: "21", func: f_fractal_bands },
Def { name: "Chandelier Exit", kind: PlotKind::Overlay, style: Style::Lines, color: 7, defaults: "22,3", func: f_chandelier },
Def { name: "Alligator", kind: PlotKind::Overlay, style: Style::Lines, color: 8, defaults: "", func: f_alligator },
Def { name: "Guppy MMA", kind: PlotKind::Overlay, style: Style::Lines, color: 9, defaults: "", func: f_guppy },
Def { name: "Rainbow MA", kind: PlotKind::Overlay, style: Style::Lines, color: 10, defaults: "", func: f_rainbow },
Def { name: "VWAP Bands", kind: PlotKind::Overlay, style: Style::Lines, color: 11, defaults: "1", func: f_vwap_bands },
Def { name: "ZigZag", kind: PlotKind::Overlay, style: Style::Lines, color: 12, defaults: "5", func: f_zigzag },
Def { name: "Williams Fractals", kind: PlotKind::Markers, style: Style::Lines, color: 13, defaults: "", func: f_fractals },
Def { name: "Elder Impulse", kind: PlotKind::Markers, style: Style::Lines, color: 0, defaults: "13", func: f_impulse },
Def { name: "RSI", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "14", func: f_rsi },
Def { name: "Laguerre RSI", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "0.5", func: f_laguerre_rsi },
Def { name: "Connors RSI", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "", func: f_connors_rsi },
Def { name: "Inverse Fisher RSI", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "14", func: f_inv_fisher_rsi },
Def { name: "Stochastic Fast", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "14", func: f_stoch_fast },
Def { name: "Stochastic Slow", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "14", func: f_stoch_slow },
Def { name: "Stochastic Full", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "14,3,3", func: f_stoch_full },
Def { name: "Stochastic RSI", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "14", func: f_stoch_rsi },
Def { name: "SMI", kind: PlotKind::Pane, style: Style::Lines, color: 8, defaults: "14", func: f_smi },
Def { name: "Williams %R", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "14", func: f_williams_r },
Def { name: "CCI", kind: PlotKind::Pane, style: Style::Lines, color: 10, defaults: "20", func: f_cci },
Def { name: "CMO", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "14", func: f_cmo },
Def { name: "ROC", kind: PlotKind::Pane, style: Style::Lines, color: 12, defaults: "12", func: f_roc },
Def { name: "Momentum", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "10", func: f_momentum },
Def { name: "MACD", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "12,26,9", func: f_macd },
Def { name: "MACD Histogram", kind: PlotKind::Pane, style: Style::Bars, color: 1, defaults: "12,26,9", func: f_macd_hist },
Def { name: "PPO", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "12,26,9", func: f_ppo },
Def { name: "APO", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "12,26", func: f_apo },
Def { name: "TRIX", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "15", func: f_trix },
Def { name: "TSI", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "25,13", func: f_tsi },
Def { name: "RMI", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "14,5", func: f_rmi },
Def { name: "Ultimate Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "", func: f_ultimate },
Def { name: "Awesome Oscillator", kind: PlotKind::Pane, style: Style::Bars, color: 8, defaults: "", func: f_awesome },
Def { name: "Accelerator Oscillator", kind: PlotKind::Pane, style: Style::Bars, color: 9, defaults: "", func: f_accelerator },
Def { name: "Fisher Transform", kind: PlotKind::Pane, style: Style::Lines, color: 10, defaults: "10", func: f_fisher },
Def { name: "Schaff Trend Cycle", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "", func: f_stc },
Def { name: "Coppock Curve", kind: PlotKind::Pane, style: Style::Lines, color: 12, defaults: "", func: f_coppock },
Def { name: "KST", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "", func: f_kst },
Def { name: "Relative Vigor Index", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "10", func: f_rvi_vigor },
Def { name: "DeMarker", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "14", func: f_demarker },
Def { name: "Balance of Power", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "14", func: f_bop },
Def { name: "Bull Power", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "13", func: f_bull_power },
Def { name: "Bear Power", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "13", func: f_bear_power },
Def { name: "Force Index", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "13", func: f_force },
Def { name: "Ease of Movement", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "14", func: f_eom },
Def { name: "Mass Index", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "25", func: f_mass_index },
Def { name: "Vortex Indicator", kind: PlotKind::Pane, style: Style::Lines, color: 8, defaults: "14", func: f_vortex },
Def { name: "Aroon", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "25", func: f_aroon },
Def { name: "Aroon Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 10, defaults: "25", func: f_aroon_osc },
Def { name: "ADX", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "14", func: f_adx },
Def { name: "Plus DI", kind: PlotKind::Pane, style: Style::Lines, color: 12, defaults: "14", func: f_plus_di },
Def { name: "Minus DI", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "14", func: f_minus_di },
Def { name: "DX", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "14", func: f_dx },
Def { name: "ADXR", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "14", func: f_adxr },
Def { name: "DPO", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "20", func: f_dpo },
Def { name: "Qstick", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "14", func: f_qstick },
Def { name: "IMI", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "14", func: f_imi },
Def { name: "Random Walk Index", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "14", func: f_rwi },
Def { name: "Swing Index", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "", func: f_swing },
Def { name: "Accumulative Swing Index", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "", func: f_aswing },
Def { name: "Gator Oscillator", kind: PlotKind::Pane, style: Style::Bars, color: 8, defaults: "", func: f_gator },
Def { name: "Projection Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "14", func: f_projection_osc },
Def { name: "Volume", kind: PlotKind::Pane, style: Style::Bars, color: 10, defaults: "", func: f_volume },
Def { name: "Volume MA", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "20", func: f_volume_ma },
Def { name: "OBV", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "", func: f_obv },
Def { name: "Price Volume Trend", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "", func: f_pvt },
Def { name: "A/D Line", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "", func: f_ad_line },
Def { name: "Chaikin Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "3,10", func: f_adosc },
Def { name: "Chaikin Money Flow", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "20", func: f_cmf },
Def { name: "MFI", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "14", func: f_mfi },
Def { name: "Volume Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "5,34", func: f_vol_osc },
Def { name: "PVO", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "12,26", func: f_pvo },
Def { name: "Volume ROC", kind: PlotKind::Pane, style: Style::Lines, color: 8, defaults: "12", func: f_vol_roc },
Def { name: "NVI", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "", func: f_nvi },
Def { name: "PVI", kind: PlotKind::Pane, style: Style::Lines, color: 10, defaults: "", func: f_pvi },
Def { name: "Klinger Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "", func: f_klinger },
Def { name: "Twiggs Money Flow", kind: PlotKind::Pane, style: Style::Lines, color: 12, defaults: "21", func: f_twiggs },
Def { name: "Williams A/D", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "", func: f_williams_ad },
Def { name: "Intraday Intensity", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "21", func: f_intensity },
Def { name: "Accumulation Percent", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "", func: f_ad_percent },
Def { name: "Demand Index", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "20", func: f_demand },
Def { name: "Trade Volume Index", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "", func: f_tvi },
Def { name: "ATR", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "14", func: f_atr },
Def { name: "NATR", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "14", func: f_natr },
Def { name: "True Range", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "", func: f_tr },
Def { name: "Standard Deviation", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "20", func: f_stddev },
Def { name: "Variance", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "20", func: f_variance },
Def { name: "Historical Volatility", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "20", func: f_hist_vol },
Def { name: "Chaikin Volatility", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "10,10", func: f_chaikin_vol },
Def { name: "Ulcer Index", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "14", func: f_ulcer },
Def { name: "Choppiness Index", kind: PlotKind::Pane, style: Style::Lines, color: 8, defaults: "14", func: f_choppiness },
Def { name: "Relative Volatility Index", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "10", func: f_rvol_idx },
Def { name: "Parkinson Volatility", kind: PlotKind::Pane, style: Style::Lines, color: 10, defaults: "20", func: f_parkinson },
Def { name: "Garman-Klass Volatility", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "20", func: f_garman_klass },
Def { name: "Rogers-Satchell Volatility", kind: PlotKind::Pane, style: Style::Lines, color: 12, defaults: "20", func: f_rogers_satchell },
Def { name: "Yang-Zhang Volatility", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "20", func: f_yang_zhang },
Def { name: "Market Thermometer", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "22", func: f_thermometer },
Def { name: "Standard Error", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "20", func: f_std_error },
Def { name: "Mean Deviation", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "20", func: f_mean_dev },
Def { name: "Skewness", kind: PlotKind::Pane, style: Style::Lines, color: 3, defaults: "20", func: f_skewness },
Def { name: "Kurtosis", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "20", func: f_kurtosis },
Def { name: "Z-Score", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "20", func: f_zscore },
Def { name: "Linear Regression Slope", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "20", func: f_lr_slope },
Def { name: "Linear Regression Intercept", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "20", func: f_lr_intercept },
Def { name: "Linear Regression Angle", kind: PlotKind::Pane, style: Style::Lines, color: 8, defaults: "20", func: f_lr_angle },
Def { name: "R-Squared", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "20", func: f_r_squared },
Def { name: "TSF", kind: PlotKind::Overlay, style: Style::Lines, color: 10, defaults: "20", func: f_tsf },
Def { name: "Forecast Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "20", func: f_forecast_osc },
Def { name: "HT DC Period", kind: PlotKind::Pane, style: Style::Lines, color: 12, defaults: "", func: f_ht_period },
Def { name: "HT DC Phase", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "", func: f_ht_phase },
Def { name: "HT Phasor", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "", func: f_ht_phasor },
Def { name: "HT Sine", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "", func: f_ht_sine },
Def { name: "HT Trend Mode", kind: PlotKind::Pane, style: Style::Lines, color: 2, defaults: "", func: f_ht_trendmode },
Def { name: "HT Trendline", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "", func: f_ht_trendline },
Def { name: "MAMA", kind: PlotKind::Overlay, style: Style::Lines, color: 4, defaults: "0.5,0.05", func: f_mama_line },
Def { name: "FAMA", kind: PlotKind::Overlay, style: Style::Lines, color: 5, defaults: "0.5,0.05", func: f_fama_line },
Def { name: "Cyber Cycle", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "0.07", func: f_cyber_cycle },
Def { name: "CG Oscillator", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "10", func: f_cg },
Def { name: "Ehlers Stochastic", kind: PlotKind::Pane, style: Style::Lines, color: 8, defaults: "14", func: f_ehlers_stoch },
Def { name: "Roofing Filter", kind: PlotKind::Pane, style: Style::Lines, color: 9, defaults: "", func: f_roofing },
Def { name: "Band-Pass Filter", kind: PlotKind::Pane, style: Style::Lines, color: 10, defaults: "20,0.3", func: f_bandpass },
Def { name: "High-Pass Filter", kind: PlotKind::Pane, style: Style::Lines, color: 11, defaults: "48", func: f_highpass },
Def { name: "Squeeze Momentum", kind: PlotKind::Pane, style: Style::Bars, color: 12, defaults: "20", func: f_squeeze },
Def { name: "WaveTrend", kind: PlotKind::Pane, style: Style::Lines, color: 13, defaults: "", func: f_wavetrend },
Def { name: "PMO", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "", func: f_pmo },
Def { name: "Doji", kind: PlotKind::Markers, style: Style::Lines, color: 0, defaults: "", func: pat_doji },
Def { name: "Dragonfly Doji", kind: PlotKind::Markers, style: Style::Lines, color: 1, defaults: "", func: pat_dragonfly },
Def { name: "Gravestone Doji", kind: PlotKind::Markers, style: Style::Lines, color: 2, defaults: "", func: pat_gravestone },
Def { name: "Long Legged Doji", kind: PlotKind::Markers, style: Style::Lines, color: 3, defaults: "", func: pat_longlegged },
Def { name: "Rickshaw Man", kind: PlotKind::Markers, style: Style::Lines, color: 4, defaults: "", func: pat_rickshaw },
Def { name: "High Wave", kind: PlotKind::Markers, style: Style::Lines, color: 5, defaults: "", func: pat_highwave },
Def { name: "Spinning Top", kind: PlotKind::Markers, style: Style::Lines, color: 6, defaults: "", func: pat_spinningtop },
Def { name: "Hammer", kind: PlotKind::Markers, style: Style::Lines, color: 7, defaults: "", func: pat_hammer },
Def { name: "Takuri", kind: PlotKind::Markers, style: Style::Lines, color: 8, defaults: "", func: pat_takuri },
Def { name: "Inverted Hammer", kind: PlotKind::Markers, style: Style::Lines, color: 9, defaults: "", func: pat_inv_hammer },
Def { name: "Shooting Star", kind: PlotKind::Markers, style: Style::Lines, color: 10, defaults: "", func: pat_shooting_star },
Def { name: "Hanging Man", kind: PlotKind::Markers, style: Style::Lines, color: 11, defaults: "", func: pat_hanging_man },
Def { name: "Engulfing", kind: PlotKind::Markers, style: Style::Lines, color: 12, defaults: "", func: pat_engulfing },
Def { name: "Harami", kind: PlotKind::Markers, style: Style::Lines, color: 13, defaults: "", func: pat_harami },
Def { name: "Harami Cross", kind: PlotKind::Markers, style: Style::Lines, color: 0, defaults: "", func: pat_harami_cross },
Def { name: "Homing Pigeon", kind: PlotKind::Markers, style: Style::Lines, color: 1, defaults: "", func: pat_homing_pigeon },
Def { name: "Piercing Line", kind: PlotKind::Markers, style: Style::Lines, color: 2, defaults: "", func: pat_piercing },
Def { name: "Dark Cloud Cover", kind: PlotKind::Markers, style: Style::Lines, color: 3, defaults: "", func: pat_dark_cloud },
Def { name: "Thrusting", kind: PlotKind::Markers, style: Style::Lines, color: 4, defaults: "", func: pat_thrusting },
Def { name: "In-Neck", kind: PlotKind::Markers, style: Style::Lines, color: 5, defaults: "", func: pat_in_neck },
Def { name: "On-Neck", kind: PlotKind::Markers, style: Style::Lines, color: 6, defaults: "", func: pat_on_neck },
Def { name: "Counterattack", kind: PlotKind::Markers, style: Style::Lines, color: 7, defaults: "", func: pat_counterattack },
Def { name: "Separating Lines", kind: PlotKind::Markers, style: Style::Lines, color: 8, defaults: "", func: pat_separating },
Def { name: "Matching Low", kind: PlotKind::Markers, style: Style::Lines, color: 9, defaults: "", func: pat_matching_low },
Def { name: "Belt Hold", kind: PlotKind::Markers, style: Style::Lines, color: 10, defaults: "", func: pat_belt_hold },
Def { name: "Marubozu", kind: PlotKind::Markers, style: Style::Lines, color: 11, defaults: "", func: pat_marubozu },
Def { name: "Closing Marubozu", kind: PlotKind::Markers, style: Style::Lines, color: 12, defaults: "", func: pat_closing_marubozu },
Def { name: "Long Line", kind: PlotKind::Markers, style: Style::Lines, color: 13, defaults: "", func: pat_long_line },
Def { name: "Short Line", kind: PlotKind::Markers, style: Style::Lines, color: 0, defaults: "", func: pat_short_line },
Def { name: "Doji Star", kind: PlotKind::Markers, style: Style::Lines, color: 1, defaults: "", func: pat_doji_star },
Def { name: "Morning Star", kind: PlotKind::Markers, style: Style::Lines, color: 2, defaults: "", func: pat_morning_star_w },
Def { name: "Morning Doji Star", kind: PlotKind::Markers, style: Style::Lines, color: 3, defaults: "", func: pat_morning_doji_star_w },
Def { name: "Evening Star", kind: PlotKind::Markers, style: Style::Lines, color: 4, defaults: "", func: pat_evening_star_w },
Def { name: "Evening Doji Star", kind: PlotKind::Markers, style: Style::Lines, color: 5, defaults: "", func: pat_evening_doji_star_w },
Def { name: "Abandoned Baby", kind: PlotKind::Markers, style: Style::Lines, color: 6, defaults: "", func: pat_abandoned_baby },
Def { name: "Three White Soldiers", kind: PlotKind::Markers, style: Style::Lines, color: 7, defaults: "", func: pat_soldiers },
Def { name: "Three Black Crows", kind: PlotKind::Markers, style: Style::Lines, color: 8, defaults: "", func: pat_crows },
Def { name: "Identical Three Crows", kind: PlotKind::Markers, style: Style::Lines, color: 9, defaults: "", func: pat_identical_crows },
Def { name: "Two Crows", kind: PlotKind::Markers, style: Style::Lines, color: 10, defaults: "", func: pat_two_crows },
Def { name: "Upside Gap Two Crows", kind: PlotKind::Markers, style: Style::Lines, color: 11, defaults: "", func: pat_upside_gap_crows },
Def { name: "Advance Block", kind: PlotKind::Markers, style: Style::Lines, color: 12, defaults: "", func: pat_advance_block },
Def { name: "Stalled Pattern", kind: PlotKind::Markers, style: Style::Lines, color: 13, defaults: "", func: pat_stalled },
Def { name: "Three Inside", kind: PlotKind::Markers, style: Style::Lines, color: 0, defaults: "", func: pat_three_inside },
Def { name: "Three Outside", kind: PlotKind::Markers, style: Style::Lines, color: 1, defaults: "", func: pat_three_outside },
Def { name: "Three Line Strike", kind: PlotKind::Markers, style: Style::Lines, color: 2, defaults: "", func: pat_line_strike },
Def { name: "Three Stars In The South", kind: PlotKind::Markers, style: Style::Lines, color: 3, defaults: "", func: pat_stars_south },
Def { name: "Concealing Baby Swallow", kind: PlotKind::Markers, style: Style::Lines, color: 4, defaults: "", func: pat_concealing_swallow },
Def { name: "Ladder Bottom", kind: PlotKind::Markers, style: Style::Lines, color: 5, defaults: "", func: pat_ladder_bottom },
Def { name: "Breakaway", kind: PlotKind::Markers, style: Style::Lines, color: 6, defaults: "", func: pat_breakaway },
Def { name: "Mat Hold", kind: PlotKind::Markers, style: Style::Lines, color: 7, defaults: "", func: pat_mat_hold },
Def { name: "Rising/Falling Three Methods", kind: PlotKind::Markers, style: Style::Lines, color: 8, defaults: "", func: pat_risefall_methods },
Def { name: "Kicking", kind: PlotKind::Markers, style: Style::Lines, color: 9, defaults: "", func: pat_kicking },
Def { name: "Kicking By Length", kind: PlotKind::Markers, style: Style::Lines, color: 10, defaults: "", func: pat_kicking_length },
Def { name: "Tasuki Gap", kind: PlotKind::Markers, style: Style::Lines, color: 11, defaults: "", func: pat_tasuki_gap },
Def { name: "Gap Side Side White", kind: PlotKind::Markers, style: Style::Lines, color: 12, defaults: "", func: pat_gap_side_white },
Def { name: "X Side Gap Three Methods", kind: PlotKind::Markers, style: Style::Lines, color: 13, defaults: "", func: pat_xside_gap_methods },
Def { name: "Hikkake", kind: PlotKind::Markers, style: Style::Lines, color: 0, defaults: "", func: pat_hikkake },
Def { name: "Hikkake Modified", kind: PlotKind::Markers, style: Style::Lines, color: 1, defaults: "", func: pat_hikkake_mod },
Def { name: "Tristar", kind: PlotKind::Markers, style: Style::Lines, color: 2, defaults: "", func: pat_tristar },
Def { name: "Unique Three River", kind: PlotKind::Markers, style: Style::Lines, color: 3, defaults: "", func: pat_unique_river },
Def { name: "Stick Sandwich", kind: PlotKind::Markers, style: Style::Lines, color: 4, defaults: "", func: pat_stick_sandwich },
Def { name: "Inside Bar", kind: PlotKind::Markers, style: Style::Lines, color: 5, defaults: "", func: pat_inside_bar },
Def { name: "Outside Bar", kind: PlotKind::Markers, style: Style::Lines, color: 6, defaults: "", func: pat_outside_bar },
Def { name: "Pin Bar", kind: PlotKind::Markers, style: Style::Lines, color: 7, defaults: "", func: pat_pin_bar },
Def { name: "NR7", kind: PlotKind::Markers, style: Style::Lines, color: 8, defaults: "", func: pat_nr7 },
Def { name: "Gap", kind: PlotKind::Markers, style: Style::Lines, color: 9, defaults: "", func: pat_gap },
Def { name: "VHF", kind: PlotKind::Pane, style: Style::Lines, color: 0, defaults: "28", func: f_vhf },
Def { name: "Disparity Index", kind: PlotKind::Pane, style: Style::Lines, color: 1, defaults: "14", func: f_disparity },
Def { name: "ATR Trailing Stop", kind: PlotKind::Overlay, style: Style::Lines, color: 3, defaults: "14,3", func: f_atr_trail },
Def { name: "Polarized Fractal Efficiency", kind: PlotKind::Pane, style: Style::Lines, color: 4, defaults: "14", func: f_pfe },
Def { name: "Efficiency Ratio", kind: PlotKind::Pane, style: Style::Lines, color: 5, defaults: "10", func: f_efficiency },
Def { name: "Trend Intensity Index", kind: PlotKind::Pane, style: Style::Lines, color: 6, defaults: "30", func: f_tii },
Def { name: "Rolling Sum", kind: PlotKind::Pane, style: Style::Lines, color: 7, defaults: "14", func: f_rolling_sum },
Def { name: "Highest High", kind: PlotKind::Overlay, style: Style::Lines, color: 8, defaults: "20", func: f_highest_high },
Def { name: "Lowest Low", kind: PlotKind::Overlay, style: Style::Lines, color: 9, defaults: "20", func: f_lowest_low },
];
File diff suppressed because it is too large. Load diff
+307
View File
@@ -0,0 +1,307 @@
//! Hand-ported indicator functions — the five `static Lines` functions
//! the transpiler (`generator/transpile.py`) cannot handle: `f_frama`,
//! `f_stc` and `f_cyber_cycle` use C++ lambdas, `f_pivots` uses a
//! `switch`, and `hilbert` (a `Series` helper) uses a lambda.
//!
//! Each is a direct line-for-line port of the C++ original in
//! `src/indicators.h` (lightgui `eb0b5fc`); lambdas become Rust closures
//! or small local `fn`s, the `switch` becomes a `match`.
use crate::generated::*;
use crate::helpers::*;
use crate::{Bar, HilbertData, Lines, Series};
pub(crate) fn f_frama(b: &[Bar], p: &[f64]) -> Lines {
let mut n = pi(p, 0, 16);
if n % 2 == 1 {
n += 1;
}
let c = closes(b);
let mut out = vec![f64::NAN; c.len()];
let hh = highs(b);
let ll = lows(b);
// C++ size_t arithmetic wraps: at i == 2n-1, `i - 2n + 1` wraps
// through usize::MAX back to 0. Use wrapping ops so Rust debug
// mode does not panic (the wrapped `from > to` range is empty,
// exactly as the C++ loop that never runs).
for i in (2 * n).wrapping_sub(1)..c.len() {
// C++ lambda: range of (high-low) over [from, to].
let range = |from: usize, to: usize| -> f64 {
let mut mx = -1e300f64;
let mut mn = 1e300f64;
for k in from..=to {
mx = mx.max(hh[k]);
mn = mn.min(ll[k]);
}
mx - mn
};
let n1 = range(i.wrapping_sub(2 * n).wrapping_add(1), i.wrapping_sub(n)) / n as f64;
let n2 = range(i.wrapping_sub(n).wrapping_add(1), i) / n as f64;
let n3 = range(i.wrapping_sub(2 * n).wrapping_add(1), i) / (2.0 * n as f64);
if n1 <= 0.0 || n2 <= 0.0 || n3 <= 0.0 {
continue;
}
let dim = ((n1 + n2).ln() - n3.ln()) / 2.0f64.ln();
let mut alpha = (-4.6 * (dim - 1.0)).exp();
alpha = 1.0f64.min(0.01f64.max(alpha));
out[i] = if out[i - 1].is_finite() {
alpha * c[i] + (1.0 - alpha) * out[i - 1]
} else {
c[i]
};
}
vec![out]
}
pub(crate) fn f_stc(b: &[Bar], _p: &[f64]) -> Lines {
let m = macd_line(b, 23, 50);
// C++ lambda: stochastic of a series, as a 0..1 ratio.
let stoch_of = |s: &Series, n: usize| -> Series {
let mx = rolling_max(s, n);
let mn = rolling_min(s, n);
let mut out = vec![f64::NAN; s.len()];
for i in 0..s.len() {
if mx[i].is_finite() && mn[i].is_finite() && mx[i] > mn[i] {
out[i] = (s[i] - mn[i]) / (mx[i] - mn[i]);
}
}
out
};
let s1 = stoch_of(&m, 10);
let sm1 = ema_s(&s1, 3);
let s2 = stoch_of(&sm1, 10);
vec![scale_s(&ema_s(&s2, 3), 100.0)]
}
pub(crate) fn f_cyber_cycle(b: &[Bar], p: &[f64]) -> Lines {
let a = pd(p, 0, 0.07);
let c = closes(b);
let mut cyc = vec![f64::NAN; c.len()];
for i in 0..c.len() {
// C++ lambda: smoothed price k bars back, clamped at bar 0.
let sm = |k: i64| -> f64 {
let i0 = i as i64 - k;
let at = |j: i64| -> f64 { c[0i64.max(j) as usize] };
let v0 = at(i0);
let v1 = at(i0 - 1);
let v2 = at(i0 - 2);
let v3 = at(i0 - 3);
(v0 + 2.0 * v1 + 2.0 * v2 + v3) / 6.0
};
let s0 = sm(0);
let s1 = sm(1);
let s2 = sm(2);
let c1 = if i > 0 && cyc[i - 1].is_finite() { cyc[i - 1] } else { 0.0 };
let c2 = if i > 1 && cyc[i - 2].is_finite() { cyc[i - 2] } else { 0.0 };
let k = 1.0 - 0.5 * a;
cyc[i] = k * k * (s0 - 2.0 * s1 + s2) + 2.0 * (1.0 - a) * c1
- (1.0 - a) * (1.0 - a) * c2;
}
vec![cyc.clone(), shift_s(&cyc, 1)]
}
pub(crate) fn f_pivots(b: &[Bar], p: &[f64]) -> Lines {
let mode = pi(p, 0, 0); // 0 standard 1 woodie 2 camarilla 3 fib 4 demark
const NL: usize = 8;
let mut out: Lines = vec![vec![f64::NAN; b.len()]; NL];
let (mut h, mut l, mut c_prev, mut o) = (0.0, 0.0, 0.0, 0.0);
let mut have_prev = false;
let mut in_day = false;
let mut day: i64 = -1;
let (mut dh, mut dl, mut dc, mut d_o) = (0.0, 0.0, 0.0, 0.0);
for i in 0..b.len() {
let d = b[i].time / 86_400_000_000_000i64;
if !in_day || d != day {
if in_day {
h = dh;
l = dl;
c_prev = dc;
o = d_o;
have_prev = true;
}
day = d;
in_day = true;
dh = b[i].high;
dl = b[i].low;
d_o = b[i].open;
}
dh = dh.max(b[i].high);
dl = dl.min(b[i].low);
dc = b[i].close;
if !have_prev {
continue;
}
// pv/r1/s1 are assigned in every match arm (once per path, so
// that assignment is their initialization — no `mut`, no init).
// r2/s2/r3/s3 are NOT assigned by the DeMark arm (4), so they
// keep a 0.0 init that the mode-4 path reads.
let (pv, r1, s1): (f64, f64, f64);
let (mut r2, mut s2, mut r3, mut s3) = (0.0, 0.0, 0.0, 0.0);
let (mut r4, mut s4) = (0.0, 0.0);
let range = h - l;
match mode {
1 => {
// Woodie
pv = (h + l + 2.0 * c_prev) / 4.0;
r1 = 2.0 * pv - l;
s1 = 2.0 * pv - h;
r2 = pv + range;
s2 = pv - range;
r3 = h + 2.0 * (pv - l);
s3 = l - 2.0 * (h - pv);
}
2 => {
// Camarilla
pv = (h + l + c_prev) / 3.0;
r1 = c_prev + range * 1.1 / 12.0;
s1 = c_prev - range * 1.1 / 12.0;
r2 = c_prev + range * 1.1 / 6.0;
s2 = c_prev - range * 1.1 / 6.0;
r3 = c_prev + range * 1.1 / 4.0;
s3 = c_prev - range * 1.1 / 4.0;
r4 = c_prev + range * 1.1 / 2.0;
s4 = c_prev - range * 1.1 / 2.0;
}
3 => {
// Fibonacci
pv = (h + l + c_prev) / 3.0;
r1 = pv + 0.382 * range;
s1 = pv - 0.382 * range;
r2 = pv + 0.618 * range;
s2 = pv - 0.618 * range;
r3 = pv + range;
s3 = pv - range;
}
4 => {
// DeMark
let x = if c_prev < o {
h + 2.0 * l + c_prev
} else if c_prev > o {
2.0 * h + l + c_prev
} else {
h + l + 2.0 * c_prev
};
pv = x / 4.0;
r1 = x / 2.0 - l;
s1 = x / 2.0 - h;
}
_ => {
// Standard (floor)
pv = (h + l + c_prev) / 3.0;
r1 = 2.0 * pv - l;
s1 = 2.0 * pv - h;
r2 = pv + range;
s2 = pv - range;
r3 = h + 2.0 * (pv - l);
s3 = l - 2.0 * (h - pv);
}
}
let vals = [
pv,
r1,
s1,
r2,
s2,
r3,
s3,
if mode == 2 { r4 } else { f64::NAN },
];
let _ = s4;
for j in 0..NL {
out[j][i] = vals[j];
}
if mode == 2 {
out[7][i] = r4;
out[6][i] = s3; // keep R4 visible
}
}
out
}
/// Hilbert transform — port of the `static HilbertData hilbert(...)`
/// helper in indicators.h. The C++ `at` lambda clamps out-of-range
/// indices to the first/last value.
pub(crate) fn hilbert(price: &Series) -> HilbertData {
let n = price.len();
let mut r = HilbertData {
period: vec![f64::NAN; n],
phase: vec![f64::NAN; n],
inphase: vec![f64::NAN; n],
quadrature: vec![f64::NAN; n],
};
let mut smooth = vec![0.0; n];
let mut detr = vec![0.0; n];
let mut q1 = vec![0.0; n];
let mut i1 = vec![0.0; n];
let mut ji = vec![0.0; n];
let mut jq = vec![0.0; n];
let mut re = vec![0.0; n];
let mut im = vec![0.0; n];
let at = |v: &Series, i: i64| -> f64 {
if i < 0 {
v.first().copied().unwrap_or(0.0)
} else if i as usize >= v.len() {
v.last().copied().unwrap_or(0.0)
} else {
v[i as usize]
}
};
let mut period = 20.0;
let mut phase = 0.0;
for i in 0..n {
let ii = i as i64;
smooth[i] = (4.0 * price[i]
+ 3.0 * at(price, ii - 1)
+ 2.0 * at(price, ii - 2)
+ at(price, ii - 3))
/ 10.0;
let adj = 0.075 * period + 0.54;
detr[i] = (0.0962 * smooth[i] + 0.5769 * at(&smooth, ii - 2)
- 0.5769 * at(&smooth, ii - 4)
- 0.0962 * at(&smooth, ii - 6))
* adj;
q1[i] = (0.0962 * detr[i] + 0.5769 * at(&detr, ii - 2)
- 0.5769 * at(&detr, ii - 4)
- 0.0962 * at(&detr, ii - 6))
* adj;
i1[i] = at(&detr, ii - 3);
ji[i] = (0.0962 * i1[i] + 0.5769 * at(&i1, ii - 2)
- 0.5769 * at(&i1, ii - 4)
- 0.0962 * at(&i1, ii - 6))
* adj;
jq[i] = (0.0962 * q1[i] + 0.5769 * at(&q1, ii - 2)
- 0.5769 * at(&q1, ii - 4)
- 0.0962 * at(&q1, ii - 6))
* adj;
let re_raw = i1[i] * ji[i] + q1[i] * jq[i];
let im_raw = i1[i] * jq[i] - q1[i] * ji[i];
re[i] = 0.2 * re_raw + 0.8 * at(&re, ii - 1);
im[i] = 0.2 * im_raw + 0.8 * at(&im, ii - 1);
if im[i] != 0.0 && re[i] != 0.0 {
let mut p = 2.0 * std::f64::consts::PI / (im[i] / re[i]).atan();
p = p.min(1.5 * period);
p = p.max(0.67 * period);
p = 50.0f64.min(6.0f64.max(p));
period = 0.2 * p + 0.8 * period;
}
if i > 6 {
r.period[i] = period;
r.inphase[i] = i1[i];
r.quadrature[i] = q1[i];
let dp = if i1[i] != 0.0 {
(q1[i] / i1[i]).atan() * 180.0 / std::f64::consts::PI
} else {
0.0
};
phase += dp;
while phase >= 360.0 {
phase -= 360.0;
}
while phase < 0.0 {
phase += 360.0;
}
r.phase[i] = phase;
}
}
r
}
+467
View File
@@ -0,0 +1,467 @@
//! Shared math primitives — port of the `inline Series` helpers at the top
//! of `src/indicators.h` (lightgui `eb0b5fc`), plus `pi` / `pd`.
//!
//! The C++ header copy-pastes these into each indicator module; here they
//! live once. NaN warm-up semantics are preserved exactly: every rolling
//! helper emits `f64::NAN` until its window is full, and non-finite inputs
//! are skipped (never averaged in) unless the C++ code says otherwise.
use crate::{Bar, Series};
/// `fdi::nanv()` — quiet NaN.
pub fn nanv() -> f64 {
f64::NAN
}
/// `fdi::fin(v)` — `std::isfinite`.
pub fn fin(v: f64) -> bool {
v.is_finite()
}
/// Parameter helpers, mirroring the `static` `pi` / `pd` in indicators.h:
/// `pi` takes the i-th parameter when present and positive, else the
/// default; `pd` takes it when present, else the default.
pub fn pi(p: &[f64], i: usize, dflt: usize) -> usize {
if i < p.len() && p[i] > 0.0 {
p[i] as usize
} else {
dflt
}
}
pub fn pd(p: &[f64], i: usize, dflt: f64) -> f64 {
if i < p.len() {
p[i]
} else {
dflt
}
}
// ------------------------------------------------------------- fields
pub fn closes(b: &[Bar]) -> Series {
b.iter().map(|x| x.close).collect()
}
pub fn highs(b: &[Bar]) -> Series {
b.iter().map(|x| x.high).collect()
}
pub fn lows(b: &[Bar]) -> Series {
b.iter().map(|x| x.low).collect()
}
pub fn opens(b: &[Bar]) -> Series {
b.iter().map(|x| x.open).collect()
}
pub fn vols(b: &[Bar]) -> Series {
b.iter().map(|x| x.volume).collect()
}
pub fn hl2(b: &[Bar]) -> Series {
b.iter().map(|x| (x.high + x.low) / 2.0).collect()
}
pub fn hlc3(b: &[Bar]) -> Series {
b.iter().map(|x| (x.high + x.low + x.close) / 3.0).collect()
}
pub fn ohlc4(b: &[Bar]) -> Series {
b.iter()
.map(|x| (x.open + x.high + x.low + x.close) / 4.0)
.collect()
}
pub fn true_range(b: &[Bar]) -> Series {
let mut s = vec![f64::NAN; b.len()];
for i in 0..b.len() {
let mut tr = b[i].high - b[i].low;
if i > 0 {
tr = tr.max((b[i].high - b[i - 1].close).abs());
tr = tr.max((b[i].low - b[i - 1].close).abs());
}
s[i] = tr;
}
s
}
// ------------------------------------------------------------- rolling
pub fn sma_s(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
if n < 1 {
return out;
}
let mut sum = 0.0;
let mut cnt = 0usize;
for i in 0..input.len() {
if input[i].is_finite() {
sum += input[i];
cnt += 1;
}
if i >= n && input[i - n].is_finite() {
sum -= input[i - n];
cnt -= 1;
}
if cnt == n {
out[i] = sum / n as f64;
}
}
out
}
pub fn ema_s(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
if n < 1 {
return out;
}
let k = 2.0 / (n as f64 + 1.0);
let mut e = 0.0;
let mut started = false;
for i in 0..input.len() {
if !input[i].is_finite() {
continue;
}
if !started {
e = input[i];
started = true;
} else {
e = input[i] * k + e * (1.0 - k);
}
if i >= n - 1 {
out[i] = e;
}
}
out
}
/// Wilder's smoothing (SMMA / RMA).
pub fn smma_s(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
if n < 1 {
return out;
}
let mut e = 0.0;
let mut started = false;
for i in 0..input.len() {
if !input[i].is_finite() {
continue;
}
if !started {
e = input[i];
started = true;
} else {
e = (e * (n as f64 - 1.0) + input[i]) / n as f64;
}
if i >= n - 1 {
out[i] = e;
}
}
out
}
pub fn wma_s(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
if n < 1 {
return out;
}
let denom = n as f64 * (n as f64 + 1.0) / 2.0;
for i in (n - 1)..input.len() {
let mut sum = 0.0;
let mut ok = true;
for j in 0..n {
let v = input[i - j];
if !v.is_finite() {
ok = false;
break;
}
sum += v * (n - j) as f64;
}
if ok {
out[i] = sum / denom;
}
}
out
}
pub fn rolling_max(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
for i in 0..input.len() {
if i + 1 < n {
continue;
}
let mut m = -1e300f64;
let mut ok = true;
for j in 0..n {
if !input[i - j].is_finite() {
ok = false;
}
m = m.max(input[i - j]);
}
if ok {
out[i] = m;
}
}
out
}
pub fn rolling_min(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
for i in 0..input.len() {
if i + 1 < n {
continue;
}
let mut m = 1e300f64;
let mut ok = true;
for j in 0..n {
if !input[i - j].is_finite() {
ok = false;
}
m = m.min(input[i - j]);
}
if ok {
out[i] = m;
}
}
out
}
pub fn rolling_sum(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
let mut sum = 0.0;
let mut cnt = 0usize;
for i in 0..input.len() {
if input[i].is_finite() {
sum += input[i];
cnt += 1;
}
if i >= n && input[i - n].is_finite() {
sum -= input[i - n];
cnt -= 1;
}
if cnt == n {
out[i] = sum;
}
}
out
}
pub fn stdev_s(input: &Series, n: usize, sample: bool) -> Series {
let mut out = vec![f64::NAN; input.len()];
let mean = sma_s(input, n);
for i in 0..input.len() {
if !mean[i].is_finite() {
continue;
}
let mut ss = 0.0;
for j in 0..n {
let d = input[i - j] - mean[i];
ss += d * d;
}
let div = if sample { n - 1 } else { n } as f64;
out[i] = (ss / div).sqrt();
}
out
}
pub fn atr_s(b: &[Bar], n: usize) -> Series {
smma_s(&true_range(b), n)
}
/// RSI on a price series (Wilder).
pub fn rsi_s(input: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; input.len()];
if n < 1 || input.len() < 2 {
return out;
}
let mut gain = 0.0;
let mut loss = 0.0;
for i in 1..input.len() {
let d = input[i] - input[i - 1];
let g = if d > 0.0 { d } else { 0.0 };
let l = if d < 0.0 { -d } else { 0.0 };
if i == 1 {
gain = g;
loss = l;
} else {
gain = (gain * (n as f64 - 1.0) + g) / n as f64;
loss = (loss * (n as f64 - 1.0) + l) / n as f64;
}
if i >= n {
if loss == 0.0 {
out[i] = 100.0;
} else {
let rs = gain / loss;
out[i] = 100.0 - 100.0 / (1.0 + rs);
}
}
}
out
}
// ------------------------------------------------------------- element-wise
pub fn combine(a: &Series, b: &Series, op: char) -> Series {
let mut out = vec![f64::NAN; a.len()];
for i in 0..a.len().min(b.len()) {
if !a[i].is_finite() || !b[i].is_finite() {
continue;
}
out[i] = match op {
'+' => a[i] + b[i],
'-' => a[i] - b[i],
'*' => a[i] * b[i],
'/' => {
if b[i] != 0.0 {
a[i] / b[i]
} else {
f64::NAN
}
}
_ => f64::NAN,
};
}
out
}
pub fn scale_s(a: &Series, k: f64) -> Series {
let mut out = vec![f64::NAN; a.len()];
for i in 0..a.len() {
if a[i].is_finite() {
out[i] = a[i] * k;
}
}
out
}
/// Delay by `n` bars (C++ `shift_s`; `n` is never negative at call sites).
pub fn shift_s(a: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; a.len()];
for i in 0..a.len() {
if i >= n && a[i - n].is_finite() {
out[i] = a[i - n];
}
}
out
}
pub fn diff_s(a: &Series, n: usize) -> Series {
let mut out = vec![f64::NAN; a.len()];
for i in 0..a.len() {
if i >= n && a[i].is_finite() && a[i - n].is_finite() {
out[i] = a[i] - a[i - n];
}
}
out
}
// ------------------------------------------------------------- shared structs
/// One OHLCV candle, as in C++ `PC`.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct PC {
pub o: f64,
pub h: f64,
pub l: f64,
pub c: f64,
pub body: f64,
pub range: f64,
pub upper: f64,
pub lower: f64,
pub bull: bool,
}
/// Linear-regression bundle, as in C++ `LinReg`.
#[derive(Debug, Clone, Default)]
pub struct LinReg {
pub slope: Series,
pub intercept: Series,
pub value: Series,
}
/// ADX bundle, as in C++ `DiAdx`.
#[derive(Debug, Clone, Default)]
pub struct DiAdx {
pub plus_di: Series,
pub minus_di: Series,
pub dx: Series,
pub adx: Series,
}
/// Hilbert-transform bundle, as in C++ `HilbertData`.
#[derive(Debug, Clone, Default)]
pub struct HilbertData {
pub period: Series,
pub phase: Series,
pub inphase: Series,
pub quadrature: Series,
}
// ------------------------------------------------------------- string utils
// Port of lower_str / trim_str / parse_params in indicators.h.
pub fn lower_str(s: &str) -> String {
s.to_ascii_lowercase()
}
pub fn trim_str(s: &str) -> &str {
s.trim_matches(|c| c == ' ' || c == '\t')
}
/// Split a comma-separated parameter string, parsing each token as f64
/// (`std::atof` semantics: leading junk parses as 0.0). Empty tokens are
/// skipped, as in C++.
pub fn parse_params(s: &str) -> Vec<f64> {
let mut out = Vec::new();
for tok in s.split(',') {
let tok = trim_str(tok);
if tok.is_empty() {
continue;
}
out.push(atof(tok));
}
out
}
/// `std::atof`: parse a leading float, or 0.0 when there is none.
pub fn atof(s: &str) -> f64 {
let s = s.trim_start();
let end: usize;
let b = s.as_bytes();
let mut i = 0;
if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
i += 1;
}
let mut digits = false;
while i < b.len() && b[i].is_ascii_digit() {
digits = true;
i += 1;
}
if i < b.len() && b[i] == b'.' {
i += 1;
while i < b.len() && b[i].is_ascii_digit() {
digits = true;
i += 1;
}
}
if digits && i < b.len() && (b[i] == b'e' || b[i] == b'E') {
let mut j = i + 1;
if j < b.len() && (b[j] == b'+' || b[j] == b'-') {
j += 1;
}
let mut edigits = false;
while j < b.len() && b[j].is_ascii_digit() {
edigits = true;
j += 1;
}
if edigits {
i = j;
}
}
end = i;
if !digits {
return 0.0;
}
s[..end].parse::<f64>().unwrap_or(0.0)
}
+185
View File
@@ -0,0 +1,185 @@
//! Technical indicators — port of `src/indicators.h` (lightgui `eb0b5fc`,
//! 3,885 lines, 250 indicator modules in namespace `fdi`).
//!
//! Layout:
//!
//! * [`helpers`] — the shared math primitives (`sma_s`, `ema_s`, ...),
//! de-duplicated once (the C++ header repeats them per module).
//! * [`generated`] — the 265 indicator/helper functions, transpiled from
//! the C++ by `generator/transpile.py` (see its header; do not edit).
//! * [`hand`] — the five functions the transpiler cannot handle
//! (`f_frama`, `f_stc`, `f_cyber_cycle`, `f_pivots`, `hilbert`).
//! * [`defs_gen`] — the 250-entry registry, extracted from the C++
//! `defs_*` tables and cross-checked against `data/indicators.json`.
//! * [`plot`] — the `Indicator::draw` geometry as pure point/rect data
//! (no cairo dependency): line polylines, bar rects, marker triangles.
//!
//! Every indicator is a pure `&[Bar] + params -> Lines` function with the
//! C++ NaN warm-up semantics: outputs are `f64::NAN` until the window is
//! full, and non-finite inputs are skipped, never averaged in.
pub mod defs_gen;
pub mod generated;
pub mod hand;
pub mod helpers;
pub mod plot;
pub use helpers::{
atof, combine, diff_s, ema_s, fin, hlc3, hl2, highs, lows, lower_str, nanv,
ohlc4, opens, parse_params, pd, pi, rolling_max, rolling_min, rolling_sum,
rsi_s, scale_s, shift_s, sma_s, smma_s, stdev_s, true_range, trim_str,
vols, wma_s, DiAdx, HilbertData, LinReg, PC,
};
pub use plot::{BarRect, LinePoints, Marker, PlotArea, PLOT_PALETTE, PALETTE_SIZE};
/// One OHLCV bar (Massive aggregates), as in C++ `fdi::Bar`.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Bar {
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
/// Window start, nanoseconds since epoch (`long long` in C++).
pub time: i64,
}
impl Bar {
pub fn new(open: f64, high: f64, low: f64, close: f64, volume: f64, time: i64) -> Bar {
Bar { open, high, low, close, volume, time }
}
}
/// A series of values, one per bar. `fdi::Series`.
pub type Series = Vec<f64>;
/// One or more series. `fdi::Lines`.
pub type Lines = Vec<Series>;
/// Where an indicator plots, as in C++ `fdi::PlotKind`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlotKind {
Overlay,
Pane,
Markers,
}
/// How an indicator renders, as in C++ `fdi::Style`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Style {
Lines,
Bars,
}
/// One indicator's compute function: bars + params -> lines.
pub type ComputeFn = fn(&[Bar], &[f64]) -> Lines;
/// One registry entry, as in C++ `fdi::Def`.
#[derive(Debug, Clone, Copy)]
pub struct Def {
pub name: &'static str,
pub kind: PlotKind,
pub style: Style,
/// Palette index (line j uses `color + j`).
pub color: i32,
/// Comma-separated default parameters.
pub defaults: &'static str,
pub func: ComputeFn,
}
/// All 250 registered indicators, in C++ registration order.
pub fn all_defs() -> &'static [Def] {
defs_gen::DEFS
}
/// Find a definition by exact name (`fdi::find_def`).
pub fn find_def(name: &str) -> Option<&'static Def> {
all_defs().iter().find(|d| d.name == name)
}
/// All indicator names (`fdi::indicator_names`).
pub fn indicator_names() -> Vec<&'static str> {
all_defs().iter().map(|d| d.name).collect()
}
/// An indicator instance: a definition plus its parameters, as in C++
/// `fdi::Indicator`.
#[derive(Debug, Clone)]
pub struct Indicator {
def: &'static Def,
params: Vec<f64>,
}
impl Indicator {
pub fn new(def: &'static Def, params: Vec<f64>) -> Indicator {
Indicator { def, params }
}
pub fn name(&self) -> &'static str {
self.def.name
}
pub fn kind(&self) -> PlotKind {
self.def.kind
}
pub fn style(&self) -> Style {
self.def.style
}
pub fn color(&self) -> i32 {
self.def.color
}
pub fn params(&self) -> &[f64] {
&self.params
}
pub fn def(&self) -> &'static Def {
self.def
}
/// `fdi::Indicator::compute`.
pub fn compute(&self, bars: &[Bar]) -> Lines {
(self.def.func)(bars, &self.params)
}
/// Line-plot geometry for this indicator in `area` (see [`plot`]).
pub fn line_points(&self, area: &PlotArea, bars: &[Bar]) -> Vec<LinePoints> {
plot::line_points(self.def, &self.compute(bars), area, bars)
}
/// Marker triangles for a `Markers` indicator in `area` (see [`plot`]).
pub fn markers(&self, area: &PlotArea, bars: &[Bar]) -> Vec<Marker> {
plot::markers(self.def, &self.compute(bars), area, bars)
}
}
/// Parse a spec like `"SMA(20)"` or `"RSI"` into an indicator
/// (`fdi::make_indicator`). Returns `Err(message)` when the name is
/// unknown. Parameters override the definition's defaults positionally:
/// `"T3(10)"` yields `[10, 0.7]`, and extra parameters are appended —
/// exactly as in C++.
pub fn make_indicator(spec: &str) -> Result<Indicator, String> {
let spec = trim_str(spec);
let (name, given) = match spec.find('(') {
Some(open) => {
let name = trim_str(&spec[..open]);
let close = spec.rfind(')').unwrap_or(spec.len());
let inner = if close > open { &spec[open + 1..close] } else { "" };
(name, parse_params(inner))
}
None => (spec, Vec::new()),
};
let def = find_def(name)
.ok_or_else(|| format!("unknown indicator: {name}"))?;
let mut params = parse_params(def.defaults);
for (i, v) in given.into_iter().enumerate() {
if i < params.len() {
params[i] = v;
} else {
params.push(v);
}
}
Ok(Indicator::new(def, params))
}
+269
View File
@@ -0,0 +1,269 @@
//! `Indicator::draw` geometry — port of `fdi::Indicator::draw` in
//! `src/indicators.h`, minus cairo.
//!
//! The C++ method draws into a `cairo_t*` inside a `PlotArea`. The Rust
//! port computes the same pixel geometry and returns it as data:
//!
//! * [`line_points`] — one polyline per line (with the palette colour),
//! with `NaN` gaps breaking the pen, exactly as the C++ stroke loop;
//! * [`bar_rects`] — one rectangle per finite value for `Style::Bars`;
//! * [`markers`] — one triangle per firing for `PlotKind::Markers`.
//!
//! The render test (`tests/indicator_render_test.cpp`) asserts palette
//! ink in the price pane and in the oscillator pane; the equivalent Rust
//! assertions live in `tests/indicator_tests.rs` and check that the
//! computed points land in those panes with the right palette colours.
use crate::{Bar, Def, Lines, PlotKind, Style};
/// The 14-colour line palette, as in C++ `fdi::kPalette`
/// (RGB triples, 0..1).
pub const PLOT_PALETTE: [[f64; 3]; 14] = [
[0.13, 0.35, 0.85], // blue
[0.95, 0.55, 0.10], // orange
[0.55, 0.25, 0.80], // purple
[0.00, 0.60, 0.60], // teal
[0.85, 0.20, 0.55], // magenta
[0.55, 0.35, 0.15], // brown
[0.20, 0.65, 0.25], // green
[0.80, 0.15, 0.15], // red
[0.10, 0.55, 0.80], // steel blue
[0.65, 0.65, 0.10], // olive
[0.35, 0.35, 0.35], // grey
[0.90, 0.70, 0.10], // gold
[0.25, 0.25, 0.70], // indigo
[0.60, 0.20, 0.20], // brick
];
pub const PALETTE_SIZE: usize = 14;
/// Palette colour for line `j` of the indicator with base colour `color`
/// (`kPalette[(color + j) % kPaletteSize]`).
pub fn line_color(color: i32, j: usize) -> [f64; 3] {
PLOT_PALETTE[(color + j as i32).rem_euclid(PALETTE_SIZE as i32) as usize]
}
/// Area an indicator draws into, as in C++ `fdi::PlotArea` (minus the
/// cairo context). Covers bars `[begin, begin+count)` of the series;
/// `lo`/`hi` are the price scale for overlays and markers.
#[derive(Debug, Clone, Copy)]
pub struct PlotArea {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
pub begin: usize,
pub count: usize,
pub lo: f64,
pub hi: f64,
}
impl PlotArea {
pub fn new(x: f64, y: f64, w: f64, h: f64, begin: usize, count: usize, lo: f64, hi: f64) -> PlotArea {
PlotArea { x, y, w, h, begin, count, lo, hi }
}
/// The C++ `X` lambda: centre x of bar `i`'s slot.
pub fn x_at(&self, i: usize) -> f64 {
self.x + (i as f64 - self.begin as f64 + 0.5) * (self.w / self.count as f64)
}
/// Whether the area can draw at all (the C++ early return).
pub fn drawable(&self) -> bool {
self.count > 0 && self.w >= 4.0 && self.h >= 4.0
}
/// End index, clamped to the series length (C++ `end`).
pub fn end(&self, len: usize) -> usize {
len.min(self.begin + self.count)
}
}
/// One plotted line: its palette colour and its polyline points.
/// Consecutive points are joined; a `NaN` in the source series breaks
/// the line (the C++ code lifts the pen).
#[derive(Debug, Clone)]
pub struct LinePoints {
pub color: [f64; 3],
/// (x, y) pixel points, in bar order, skipping non-finite values.
/// `breaks` holds the indices into `points` where a new segment
/// starts (i.e. the previous value was non-finite).
pub points: Vec<(f64, f64)>,
pub breaks: Vec<usize>,
}
/// One bar-style rectangle: (x, y, width, height) in pixels.
#[derive(Debug, Clone, Copy)]
pub struct BarRect {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
pub color: [f64; 3],
}
/// One marker triangle: centre, tip y, half-width, and bull/bear sense.
#[derive(Debug, Clone, Copy)]
pub struct Marker {
pub cx: f64,
pub py: f64,
pub half_width: f64,
pub bull: bool,
pub color: [f64; 3],
}
/// Resolve the y-scale for a `Pane` indicator: the min/max of its own
/// finite values in the window (C++ `Indicator::draw`, pane branch).
/// Returns `None` when nothing finite is in view.
fn pane_scale(lines: &Lines, area: &PlotArea, end: usize) -> Option<(f64, f64)> {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for s in lines {
for i in area.begin..end.min(s.len()) {
if s[i].is_finite() {
lo = lo.min(s[i]);
hi = hi.max(s[i]);
}
}
}
if lo > hi {
return None;
}
Some((lo, hi))
}
/// Line polylines for an indicator, mirroring the C++ stroke loop
/// (including the `Bars` style's zero-baseline rule for pane scaling).
/// Returns an empty vec when the area cannot draw or there is nothing
/// finite to draw.
pub fn line_points(def: &Def, lines: &Lines, area: &PlotArea, bars: &[Bar]) -> Vec<LinePoints> {
let _ = bars;
if !area.drawable() || lines.is_empty() {
return Vec::new();
}
let end = area.end(bars.len());
let (mut lo, mut hi) = (area.lo, area.hi);
if def.kind == PlotKind::Pane {
let Some((plo, phi)) = pane_scale(lines, area, end) else {
return Vec::new();
};
lo = plo;
hi = phi;
if def.style == Style::Bars {
lo = lo.min(0.0);
hi = hi.max(0.0);
}
if hi - lo < 1e-12 {
hi = lo + 1.0;
}
}
let y_of = |v: f64| -> f64 { area.y + (hi - v) / (hi - lo) * area.h };
let mut out = Vec::new();
for (j, s) in lines.iter().enumerate() {
let mut points = Vec::new();
let mut breaks = Vec::new();
let mut pen = false;
for i in area.begin..end.min(s.len()) {
if !s[i].is_finite() {
pen = false;
continue;
}
if !pen {
breaks.push(points.len());
pen = true;
}
points.push((area.x_at(i), y_of(s[i])));
}
out.push(LinePoints { color: line_color(def.color, j), points, breaks });
}
out
}
/// Bar rectangles for a `Style::Bars` indicator, mirroring the C++
/// rectangle loop.
pub fn bar_rects(def: &Def, lines: &Lines, area: &PlotArea, bars: &[Bar]) -> Vec<BarRect> {
if !area.drawable() || lines.is_empty() {
return Vec::new();
}
let end = area.end(bars.len());
let (mut lo, mut hi) = (area.lo, area.hi);
if def.kind == PlotKind::Pane {
let Some((plo, phi)) = pane_scale(lines, area, end) else {
return Vec::new();
};
lo = plo;
hi = phi;
if def.style == Style::Bars {
lo = lo.min(0.0);
hi = hi.max(0.0);
}
if hi - lo < 1e-12 {
hi = lo + 1.0;
}
}
let y_of = |v: f64| -> f64 { area.y + (hi - v) / (hi - lo) * area.h };
let bw = (1.0f64).max(area.w / area.count as f64 * 0.7);
let y0 = y_of(0.0);
let mut out = Vec::new();
for (j, s) in lines.iter().enumerate() {
for i in area.begin..end.min(s.len()) {
if !s[i].is_finite() {
continue;
}
let y1 = y_of(s[i]);
out.push(BarRect {
x: area.x_at(i) - bw / 2.0,
y: y0.min(y1),
w: bw,
h: (y1 - y0).abs().max(1.0),
color: line_color(def.color, j),
});
}
}
out
}
/// Marker triangles for a `PlotKind::Markers` indicator, mirroring the
/// C++ triangle loop (bullish markers hang below the low, bearish above
/// the high, both clamped 8px inside the area).
pub fn markers(def: &Def, lines: &Lines, area: &PlotArea, bars: &[Bar]) -> Vec<Marker> {
if !area.drawable() || lines.is_empty() {
return Vec::new();
}
let end = area.end(bars.len());
let m = &lines[0];
let color = line_color(def.color, 0);
let slot = area.w / area.count as f64;
let hw = 3.0f64.max(slot * 0.35);
let mut out = Vec::new();
for i in area.begin..end {
if i >= m.len() || !m[i].is_finite() || m[i] == 0.0 {
continue;
}
let cx = area.x_at(i);
let bull = m[i] > 0.0;
let py = if bull {
area.y + area.h - (bars[i].low - area.lo) / (area.hi - area.lo) * area.h + 8.0
} else {
area.y + (area.hi - bars[i].high) / (area.hi - area.lo) * area.h - 8.0
};
let py = py.clamp(area.y + 8.0, area.y + area.h - 8.0);
out.push(Marker { cx, py, half_width: hw, bull, color });
}
out
}
/// Price scale (lo, hi) over a bar window, as the C++ test's
/// `draw_candles` computes it.
pub fn candle_scale(bars: &[Bar], begin: usize, count: usize) -> (f64, f64) {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for i in begin..(begin + count).min(bars.len()) {
lo = lo.min(bars[i].low);
hi = hi.max(bars[i].high);
}
if hi - lo < 1e-9 {
hi = lo + 1.0;
}
(lo, hi)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,404 @@
//! Port of `tests/indicator_test.cpp` (numeric half) and
//! `tests/indicator_render_test.cpp` (geometry half).
//!
//! The C++ test renders every indicator onto a cairo surface and counts
//! palette-coloured pixels ("ink"). There is no cairo here, so the render
//! assertions are replaced by their geometric equivalent: the computed
//! line/bar/marker geometry must land inside the target pane with the
//! indicator's palette colour. The numeric assertions — finite values,
//! pattern firing, crafted-bar detection, bounded-oscillator ranges —
//! are ported verbatim, on the same data: `tests/data/SPY_fake_long.csv`
//! (copied from the C repo) and the same seeded `make_gapped_bars`
//! generator.
use std::fs;
use xframe_indicators::plot::{candle_scale, PlotArea};
use xframe_indicators::{
all_defs, find_def, indicator_names, make_indicator, Bar, Indicator, PlotKind,
};
// ------------------------------------------------------------ test data
fn load_csv(path: &str) -> Vec<Bar> {
let text = fs::read_to_string(path).expect("read SPY_fake_long.csv");
let mut out = Vec::new();
for (n, line) in text.lines().enumerate() {
if n == 0 {
continue; // header
}
let f: Vec<&str> = line.split(',').collect();
let get = |i: usize| -> f64 { f.get(i).and_then(|s| s.parse().ok()).unwrap_or(0.0) };
out.push(Bar {
volume: get(1),
open: get(2),
close: get(3),
high: get(4),
low: get(5),
time: get(6) as i64,
});
}
out
}
/// Port of the C++ test's `make_gapped_bars`: xorshift64* with the same
/// seed, 3000 bars, forced doji every 37 bars, big bodies every 53.
fn make_gapped_bars() -> Vec<Bar> {
let mut s: u64 = 88172645463325252;
let mut rnd = move || {
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
(s >> 11) as f64 / 9007199254740992.0
};
let mut out = Vec::new();
let mut price = 100.0;
for i in 0..3000 {
let gap = (rnd() - 0.5) * 1.6;
let open = price + gap;
let mut body = (rnd() - 0.48) * 3.0;
if i % 37 == 0 {
body = (rnd() - 0.5) * 0.06; // forced doji
}
if i % 53 == 0 {
body = (if rnd() > 0.5 { 1.0 } else { -1.0 }) * (2.5 + rnd());
}
let close = open + body;
let high = open.max(close) + rnd() * 0.9;
let low = open.min(close) - rnd() * 0.9;
let volume = 1000.0 + rnd() * 40000.0;
let time = i as i64 * 60_000_000_000;
out.push(Bar { open, high, low, close, volume, time });
price = close;
if price < 20.0 {
price = 100.0;
}
}
out
}
fn spy_bars() -> Vec<Bar> {
load_csv("tests/data/SPY_fake_long.csv")
}
// ------------------------------------------------------------ registry
#[test]
fn registry_has_250_unique_indicators() {
let defs = all_defs();
assert_eq!(defs.len(), 250);
let names = indicator_names();
assert_eq!(names.len(), 250);
let mut sorted = names.clone();
sorted.sort();
sorted.dedup();
assert_eq!(sorted.len(), 250, "indicator names must be unique");
assert!(find_def("SMA").is_some());
assert!(find_def("RSI").is_some());
assert!(find_def("Doji").is_some());
assert!(find_def("No Such Indicator").is_none());
// Every def's function is callable and its defaults parse.
for d in defs {
let params = xframe_indicators::parse_params(d.defaults);
let ind = Indicator::new(d, params);
assert!(!ind.name().is_empty());
}
}
#[test]
fn make_indicator_spec_parsing() {
// No params -> defaults.
let sma = make_indicator("SMA").unwrap();
assert_eq!(sma.params(), &[20.0]);
// Positional override keeps the remaining defaults (C++ merge).
let t3 = make_indicator("T3(10)").unwrap();
assert_eq!(t3.params(), &[10.0, 0.7]);
let t3b = make_indicator("T3(10, 0.5)").unwrap();
assert_eq!(t3b.params(), &[10.0, 0.5]);
// Extra params are appended.
let alma = make_indicator("ALMA(9, 0.85, 6, 99)").unwrap();
assert_eq!(alma.params(), &[9.0, 0.85, 6.0, 99.0]);
// Whitespace tolerated.
assert!(make_indicator(" RSI(14) ").is_ok());
assert!(make_indicator("Nope").is_err());
assert!(make_indicator("Nope(1,2)").is_err());
}
// ------------------------------------------------------------ helpers
#[test]
fn helper_exact_values_and_nan_warmup() {
use xframe_indicators::{ema_s, rsi_s, sma_s};
let closes = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
let sma3 = sma_s(&closes, 3);
// NaN until the window fills, then exact means.
assert!(sma3[0].is_nan() && sma3[1].is_nan());
assert_eq!(sma3[2], 2.0);
assert_eq!(sma3[9], 9.0);
// EMA seeds on the first finite value and emits from index n-1.
let ema3 = ema_s(&closes, 3);
assert!(ema3[0].is_nan() && ema3[1].is_nan());
assert!(ema3[2].is_finite());
// RSI on a rising series trends to 100; warm-up is NaN.
let rsi = rsi_s(&closes, 3);
assert!(rsi[0].is_nan() && rsi[1].is_nan() && rsi[2].is_nan());
assert!(rsi[9] > 99.0);
// Non-finite inputs are skipped, never averaged in.
let gappy = vec![1.0, f64::NAN, 3.0, 4.0, 5.0];
let s = sma_s(&gappy, 3);
assert!(s[2].is_nan(), "window with a NaN must not emit");
assert_eq!(s[4], 4.0, "3 finite values in the window");
}
#[test]
fn combine_scale_shift_diff() {
use xframe_indicators::{combine, diff_s, scale_s, shift_s};
let a = vec![1.0, 2.0, f64::NAN, 4.0];
let b = vec![10.0, 20.0, 30.0, 0.0];
// NaN-aware series comparison (assert_eq! fails on NaN != NaN).
fn assert_series_eq(got: &[f64], want: &[f64]) {
assert_eq!(got.len(), want.len(), "series length");
for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
if w.is_nan() {
assert!(g.is_nan(), "index {i}: expected NaN, got {g}");
} else {
assert_eq!(*g, *w, "index {i}");
}
}
}
assert_series_eq(&combine(&a, &b, '+'), &[11.0, 22.0, f64::NAN, 4.0]);
assert!(combine(&a, &b, '/')[3].is_nan()); // divide by zero -> NaN
assert_series_eq(&scale_s(&a, 2.0), &[2.0, 4.0, f64::NAN, 8.0]);
assert_series_eq(&shift_s(&a, 1), &[f64::NAN, 1.0, 2.0, f64::NAN]);
assert_series_eq(&diff_s(&a, 1), &[f64::NAN, 1.0, f64::NAN, f64::NAN]);
// atof / parse_params mirror std::atof.
assert_eq!(xframe_indicators::parse_params("20,0.7"), vec![20.0, 0.7]);
assert_eq!(xframe_indicators::parse_params(""), Vec::<f64>::new());
assert_eq!(xframe_indicators::atof("abc"), 0.0);
assert_eq!(xframe_indicators::atof("12.5x"), 12.5);
}
// ------------------------------------------------- all-250 numeric sweep
// Mirrors steps 1-2 of the C++ test (compute + draw), with geometry in
// place of cairo pixels.
#[test]
fn all_250_compute_and_draw_geometry() {
let bars = spy_bars();
assert!(bars.len() >= 200, "only {} bars loaded", bars.len());
let gapped = make_gapped_bars();
assert_eq!(gapped.len(), 3000);
const VISIBLE: usize = 400;
let begin = bars.len() - VISIBLE;
let (lo, hi) = candle_scale(&bars, begin, VISIBLE);
let mut failed: Vec<String> = Vec::new();
let mut nofire: Vec<String> = Vec::new();
for def in all_defs() {
let ind = make_indicator(def.name).unwrap();
let lines = ind.compute(&bars);
let mut finite = 0usize;
let mut fired = 0usize;
for s in &lines {
for &v in s {
if v.is_finite() {
finite += 1;
}
if def.kind == PlotKind::Markers && v != 0.0 && v.is_finite() {
fired += 1;
}
}
}
// Patterns also run on the gapped series.
let mut rbegin = begin;
let mut rbars = &bars;
let mut rlo = lo;
let mut rhi = hi;
if def.kind == PlotKind::Markers {
let gl = ind.compute(&gapped);
let mut gfired = 0usize;
let mut last_fire = 0usize;
if !gl.is_empty() {
for (i, &v) in gl[0].iter().enumerate() {
if v != 0.0 && v.is_finite() {
gfired += 1;
last_fire = i;
}
}
}
fired += gfired;
if gfired > 0 {
rbars = &gapped;
rbegin = last_fire.saturating_sub(VISIBLE - 1);
let (glo, ghi) = candle_scale(&gapped, rbegin, VISIBLE);
rlo = glo;
rhi = ghi;
}
}
// Geometry in place of cairo ink: the draw must produce points
// inside the target area, in the indicator's palette colour.
// (Markers draw triangles, not lines; Bars draw rectangles.)
let is_pane = def.kind == PlotKind::Pane;
let area = if is_pane {
PlotArea::new(4.0, 206.0, 472.0, 90.0, rbegin, VISIBLE, rlo, rhi)
} else {
PlotArea::new(4.0, 4.0, 472.0, 292.0, rbegin, VISIBLE, rlo, rhi)
};
let mut geom = 0usize;
if def.kind == PlotKind::Markers {
let marks = ind.markers(&area, rbars);
for mk in &marks {
assert!(mk.cx >= area.x && mk.cx <= area.x + area.w, "{} marker x out of area", def.name);
assert!(mk.py >= area.y && mk.py <= area.y + area.h, "{} marker y out of area", def.name);
}
if fired == 0 {
nofire.push(def.name.to_string());
} else if marks.is_empty() {
failed.push(format!("{} (fired but drew nothing)", def.name));
}
continue;
}
let pts = ind.line_points(&area, rbars);
for lp in &pts {
for &(x, y) in &lp.points {
assert!(x >= area.x && x <= area.x + area.w, "{} point x out of area", def.name);
// Panes self-scale, so their points must be in-bounds.
// Overlays use the price scale, and a band/channel can
// legitimately exceed the price range (Bollinger upper
// = mid + 2σ) — the C++ draws those outside the area
// too (its test counts ink, it never asserts in-bounds).
// For overlays, require only a finite y.
if def.kind == PlotKind::Pane {
assert!(y >= area.y - 1.0 && y <= area.y + area.h + 1.0, "{} point y out of area", def.name);
} else {
assert!(y.is_finite(), "{} point y not finite", def.name);
}
geom += 1;
}
// Colour must be a palette colour.
assert!(
xframe_indicators::plot::PLOT_PALETTE.contains(&lp.color),
"{} line colour not in palette",
def.name
);
}
if def.style == xframe_indicators::Style::Bars {
let rects = xframe_indicators::plot::bar_rects(def, &ind.compute(rbars), &area, rbars);
geom += rects.len();
}
if finite == 0 {
failed.push(format!("{} (no finite values)", def.name));
} else if geom == 0 {
failed.push(format!("{} (computed but drew nothing)", def.name));
}
}
eprintln!("nofire patterns ({}): {:?}", nofire.len(), nofire);
assert!(failed.is_empty(), "failures:\n{}", failed.join("\n"));
}
// ------------------------------------------------------- crafted patterns
fn mk(o: f64, h: f64, l: f64, c: f64) -> Bar {
Bar { open: o, high: h, low: l, close: c, volume: 1000.0, time: 0 }
}
#[test]
fn crafted_pattern_detection() {
// (name, bars, index, expected sign) — verbatim from indicator_test.cpp.
let cases: Vec<(&str, Vec<Bar>, usize, f64)> = vec![
("Doji", vec![mk(100.0, 101.0, 99.0, 100.05)], 0, 1.0),
("Engulfing", vec![mk(102.0, 102.5, 99.5, 100.0), mk(99.5, 103.0, 99.0, 102.5)], 1, 1.0),
("Hammer", vec![mk(100.0, 100.5, 96.5, 97.0), mk(100.0, 100.5, 96.8, 100.4)], 1, 1.0),
("Morning Star", vec![mk(110.0, 110.5, 99.5, 100.0), mk(98.0, 98.8, 97.5, 98.5), mk(99.0, 107.5, 98.5, 107.0)], 2, 1.0),
("Shooting Star", vec![mk(100.0, 101.0, 99.0, 100.8), mk(102.0, 105.0, 101.9, 102.15)], 1, -1.0),
("Takuri", vec![mk(100.0, 101.3, 99.7, 101.0), mk(101.0, 102.3, 100.7, 102.0), mk(102.0, 103.3, 101.7, 103.0), mk(100.0, 100.4, 97.5, 100.3)], 3, 1.0),
("Thrusting", vec![mk(100.0, 110.4, 99.6, 110.0), mk(111.0, 111.3, 106.5, 107.0)], 1, -1.0),
("Two Crows", vec![mk(100.0, 110.4, 99.6, 110.0), mk(112.0, 112.3, 107.6, 108.0), mk(111.0, 111.3, 104.6, 105.0)], 2, -1.0),
("Concealing Baby Swallow", vec![mk(110.0, 110.2, 103.8, 104.0), mk(103.0, 103.4, 98.6, 99.0), mk(100.5, 101.0, 96.6, 97.0), mk(102.0, 102.3, 94.7, 95.0)], 3, 1.0),
("Kicking By Length", vec![mk(103.0, 103.2, 99.8, 100.0), mk(106.0, 112.2, 105.8, 112.0)], 1, 1.0),
("Gap Side Side White", vec![mk(100.0, 101.3, 99.7, 101.0), mk(103.0, 105.4, 102.5, 105.0), mk(103.1, 106.3, 102.9, 106.0)], 2, 1.0),
("Piercing Line", vec![mk(110.0, 110.5, 99.5, 100.0), mk(99.0, 106.5, 98.8, 106.0)], 1, 1.0),
("Dark Cloud Cover", vec![mk(100.0, 110.5, 99.5, 110.0), mk(111.0, 111.5, 103.5, 104.0)], 1, -1.0),
("Three White Soldiers", vec![mk(100.0, 104.5, 99.5, 104.0), mk(103.0, 107.5, 102.5, 107.0), mk(106.0, 110.5, 105.5, 110.0)], 2, 1.0),
("Abandoned Baby", vec![mk(110.0, 110.5, 99.5, 100.0), mk(97.0, 97.3, 96.7, 97.05), mk(99.0, 106.5, 98.5, 106.0)], 2, 1.0),
("Kicking", vec![mk(105.0, 105.2, 99.8, 100.0), mk(107.0, 112.2, 106.8, 112.0)], 1, 1.0),
("Tristar", vec![mk(100.0, 100.6, 99.4, 100.0), mk(102.0, 102.6, 101.4, 102.0), mk(100.0, 100.6, 99.4, 100.0)], 2, -1.0),
];
let mut mismatches = Vec::new();
for (name, seq, at, sign) in cases {
let ind = make_indicator(name).unwrap_or_else(|e| panic!("{name}: {e}"));
let lines = ind.compute(&seq);
let got = lines.first().and_then(|s| s.get(at)).copied().unwrap_or(0.0);
let ok = (sign > 0.0 && got > 0.0) || (sign < 0.0 && got < 0.0);
if !ok {
mismatches.push(format!("{name} at {at}: got {got:+}"));
}
}
assert!(mismatches.is_empty(), "crafted mismatches:\n{}", mismatches.join("\n"));
}
#[test]
fn bounded_oscillator_ranges() {
let bars = spy_bars();
let checks = [
("RSI", 0.0, 100.0),
("Stochastic Fast", 0.0, 100.0),
("Williams %R", -100.0, 0.0),
("MFI", 0.0, 100.0),
("Stochastic RSI", 0.0, 100.0),
];
let mut bad = Vec::new();
for (name, lo, hi) in checks {
let ind = make_indicator(name).unwrap();
let lines = ind.compute(&bars);
let mut any = false;
let mut ok = true;
for s in &lines {
for &v in s {
if v.is_finite() {
any = true;
if v < lo - 1e-6 || v > hi + 1e-6 {
ok = false;
}
}
}
}
if !ok || !any {
bad.push(format!("{name} range [{lo}, {hi}] ok={ok} any={any}"));
}
}
assert!(bad.is_empty(), "range failures:\n{}", bad.join("\n"));
}
// ------------------------------------------------- render-test geometry
// Port of tests/indicator_render_test.cpp: the SMA's palette-blue line
// must appear in the price pane, and palette-coloured points must appear
// in the oscillator pane strip (RSI/MACD live there). Geometry in place
// of cairo pixels.
#[test]
fn render_test_geometry_sma_and_rsi_panes() {
let bars = spy_bars();
let (lo, hi) = candle_scale(&bars, 0, bars.len());
// Price pane (top 2/3) and oscillator strip (bottom 1/3), mirroring
// the C++ test's 1000x700 layout split at 0.66.
let price = PlotArea::new(4.0, 4.0, 992.0, 462.0, 0, bars.len(), lo, hi);
let pane = PlotArea::new(4.0, 470.0, 992.0, 226.0, 0, bars.len(), lo, hi);
let sma = make_indicator("SMA(20)").unwrap();
let pts = sma.line_points(&price, &bars);
assert_eq!(pts.len(), 1);
assert!(!pts[0].points.is_empty());
// Palette blue (SMA line colour 0).
assert_eq!(pts[0].color, [0.13, 0.35, 0.85]);
assert!(pts[0].points.iter().all(|&(_, y)| y >= price.y && y <= price.y + price.h));
assert!(pts[0].points.len() > 100, "SMA should plot most bars");
// RSI + MACD in the oscillator pane.
let rsi = make_indicator("RSI").unwrap();
let rpts = rsi.line_points(&pane, &bars);
assert!(!rpts[0].points.is_empty());
assert!(rpts[0].points.iter().all(|&(_, y)| y >= pane.y - 1.0 && y <= pane.y + pane.h + 1.0));
let macd = make_indicator("MACD").unwrap();
let mpts = macd.line_points(&pane, &bars);
assert_eq!(mpts.len(), 2, "MACD plots line + signal");
assert!(mpts.iter().all(|lp| !lp.points.is_empty()));
}