Skip to main content

wickra_core/
lib.rs

1//! `wickra-core`: streaming-first technical indicators.
2//!
3//! The core engine of Wickra. Every indicator is implemented as a state machine
4//! that consumes inputs one at a time via [`Indicator::update`] in constant time.
5//! Batch evaluation is provided as a blanket extension trait so the same code
6//! path serves both online (tick-by-tick) and offline (historical) workloads.
7//!
8//! # Design
9//!
10//! - **Streaming-first.** State is held by the indicator instance, so a new value
11//!   only re-computes deltas, not the whole series.
12//! - **Batch is free.** [`BatchExt::batch`] is a blanket implementation that
13//!   simply replays `update` over a slice. Writing one implementation gives both
14//!   APIs.
15//! - **Composable.** Indicators implement [`Indicator<Input = f64, Output = f64>`]
16//!   wherever they conceptually take a price, so they can be chained via
17//!   [`Chain`].
18//! - **No `unsafe`.** The crate forbids `unsafe_code` in the workspace lints.
19//!
20//! # Quick start
21//!
22//! ```
23//! use wickra_core::{BatchExt, Indicator, Sma};
24//!
25//! // Streaming:
26//! let mut sma = Sma::new(3).unwrap();
27//! assert_eq!(sma.update(1.0), None);
28//! assert_eq!(sma.update(2.0), None);
29//! assert_eq!(sma.update(3.0), Some(2.0));
30//!
31//! // Batch (replays `update` internally):
32//! let mut sma = Sma::new(3).unwrap();
33//! let out = sma.batch(&[1.0, 2.0, 3.0, 4.0]);
34//! assert_eq!(out, vec![None, None, Some(2.0), Some(3.0)]);
35//! ```
36
37#![cfg_attr(docsrs, feature(doc_cfg))]
38// The libtest harness collects every `#[test]` into a compiler-generated array
39// of test references. With 2000+ unit tests that array exceeds clippy's 16 KB
40// `large_stack_arrays` threshold; the diagnostic is spanless libtest scaffolding,
41// not our code, so it cannot be silenced at a call site. Suppress it only in test
42// builds — library code is still linted for genuinely large stack arrays.
43#![cfg_attr(test, allow(clippy::large_stack_arrays))]
44
45mod calendar;
46mod cross_section;
47mod derivatives;
48mod error;
49mod microstructure;
50mod ohlcv;
51mod traits;
52
53pub mod indicators;
54
55pub use cross_section::{CrossSection, Member};
56pub use derivatives::DerivativesTick;
57pub use error::{Error, Result};
58pub use indicators::{
59    AbandonedBaby, Abcd, AbsoluteBreadthIndex, AccelerationBands, AccelerationBandsOutput,
60    AcceleratorOscillator, AdOscillator, AdVolumeLine, AdaptiveCci, AdaptiveCycle,
61    AdaptiveLaguerreFilter, AdaptiveRsi, Adl, AdvanceBlock, AdvanceDecline, AdvanceDeclineRatio,
62    Adx, AdxOutput, Adxr, Alligator, AlligatorOutput, Alma, Alpha, AmihudIlliquidity, AnchoredRsi,
63    AnchoredVwap, AndrewsPitchfork, AndrewsPitchforkOutput, Apo, Aroon, AroonOscillator,
64    AroonOutput, Atr, AtrBands, AtrBandsOutput, AtrRatchet, AtrRatchetOutput, AtrTrailingStop,
65    AutoFib, AutoFibOutput, Autocorrelation, AutocorrelationPeriodogram, AverageDailyRange,
66    AverageDrawdown, AvgPrice, AwesomeOscillator, AwesomeOscillatorHistogram, BalanceOfPower,
67    BandpassFilter, Bat, BeltHold, Beta, BetaNeutralSpread, BetterVolume, BipowerVariation,
68    BodySizePct, BollingerBands, BollingerBandwidth, BollingerOutput, BomarBands, BomarBandsOutput,
69    BreadthThrust, Breakaway, BullishPercentIndex, Butterfly, CalendarSpread, CalmarRatio,
70    Camarilla, CamarillaPivotsOutput, CandleVolume, CandleVolumeOutput, Cci, CenterOfGravity,
71    CentralPivotRange, CentralPivotRangeOutput, Cfo, ChaikinMoneyFlow, ChaikinOscillator,
72    ChaikinVolatility, ChandeKrollStop, ChandeKrollStopOutput, ChandelierExit,
73    ChandelierExitOutput, ChoppinessIndex, ClassicPivots, ClassicPivotsOutput, CloseVsOpen,
74    ClosingMarubozu, Cmo, CoefficientOfVariation, Cointegration, CointegrationOutput,
75    ConcealingBabySwallow, ConditionalValueAtRisk, ConnorsRsi, Coppock, CorrelationTrendIndicator,
76    Counterattack, Crab, CumulativeVolumeDelta, CumulativeVolumeIndex, CupAndHandle,
77    CyberneticCycle, Cypher, DayOfWeekProfile, DayOfWeekProfileOutput, Decycler,
78    DecyclerOscillator, Dema, DemandIndex, DemarkPivots, DemarkPivotsOutput, DepthSlope,
79    DerivativeOscillator, DetrendedStdDev, DisparityIndex, DistanceSsd, Doji, DojiStar, Donchian,
80    DonchianOutput, DonchianStop, DonchianStopOutput, DoubleBollinger, DoubleBollingerOutput,
81    DoubleTopBottom, DownsideGapThreeMethods, Dpo, DragonflyDoji, DrawdownDuration, DumplingTop,
82    Dx, DynamicMomentumIndex, EaseOfMovement, EffectiveSpread, EhlersStochastic, Ehma,
83    ElderImpulse, ElderRay, ElderRayOutput, ElderSafeZone, ElderSafeZoneOutput, Ema,
84    EmpiricalModeDecomposition, Engulfing, Equivolume, EquivolumeOutput, EvenBetterSinewave,
85    EveningDojiStar, Evwma, EwmaVolatility, Expectancy, FallingThreeMethods, Fama, FibArcs,
86    FibArcsOutput, FibChannel, FibChannelOutput, FibConfluence, FibConfluenceOutput, FibExtension,
87    FibExtensionOutput, FibFan, FibFanOutput, FibProjection, FibProjectionOutput, FibRetracement,
88    FibRetracementOutput, FibTimeZones, FibTimeZonesOutput, FibonacciPivots, FibonacciPivotsOutput,
89    FisherRsi, FisherTransform, FlagPennant, Footprint, FootprintOutput, ForceIndex,
90    FractalChaosBands, FractalChaosBandsOutput, Frama, FryPanBottom, FundingBasis, FundingRate,
91    FundingRateMean, FundingRateZScore, GainLossRatio, GapSideBySideWhite, Garch11,
92    GarmanKlassVolatility, Gartley, GatorOscillator, GatorOscillatorOutput, GeneralizedDema,
93    GeometricMa, GoldenPocket, GoldenPocketOutput, GrangerCausality, GravestoneDoji, Hammer,
94    HangingMan, Harami, HaramiCross, HeadAndShoulders, HeikinAshi, HeikinAshiOscillator,
95    HeikinAshiOutput, HiLoActivator, HighLowIndex, HighLowRange, HighWave, HighpassFilter, Hikkake,
96    HikkakeModified, HilbertDominantCycle, HistoricalVolatility, Hma, HoltWinters, HomingPigeon,
97    HtDcPhase, HtPhasor, HtPhasorOutput, HtTrendMode, HurstChannel, HurstChannelOutput,
98    HurstExponent, Ichimoku, IchimokuOutput, IdenticalThreeCrows, InNeck, Inertia,
99    InformationRatio, InitialBalance, InitialBalanceOutput, InstantaneousTrendline,
100    IntradayIntensity, IntradayMomentumIndex, IntradayVolatilityProfile,
101    IntradayVolatilityProfileOutput, InverseFisherTransform, InvertedHammer, JarqueBera, Jma,
102    JumpIndicator, KagiBars, KalmanHedgeRatio, KalmanHedgeRatioOutput, Kama, KaseDevStop,
103    KaseDevStopOutput, KasePermissionStochastic, KasePermissionStochasticOutput, KellyCriterion,
104    Keltner, KeltnerOutput, KendallTau, Kicking, KickingByLength, Kst, KstOutput, Kurtosis, Kvo,
105    KylesLambda, LadderBottom, LaguerreRsi, LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput,
106    LinRegAngle, LinRegChannel, LinRegChannelOutput, LinRegIntercept, LinRegSlope,
107    LinearRegression, LiquidationFeatures, LiquidationFeaturesOutput, LogReturn, LongLeggedDoji,
108    LongLine, LongShortRatio, MaEnvelope, MaEnvelopeOutput, MacdExt, MacdFix, MacdHistogram,
109    MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex, Marubozu, MassIndex,
110    MatHold, MatchingLow, MaxDrawdown, McClellanOscillator, McClellanSummationIndex,
111    McGinleyDynamic, MedianAbsoluteDeviation, MedianChannel, MedianChannelOutput, MedianMa,
112    MedianPrice, Mfi, Microprice, MidPoint, MidPrice, MinusDi, MinusDm, ModifiedMaStop,
113    ModifiedMaStopOutput, Mom, MorningDojiStar, MorningEveningStar, MurreyMathLines,
114    MurreyMathLinesOutput, Natr, NewHighsNewLows, NewPriceLines, Nrtr, NrtrOutput, Nvi,
115    OIPriceDivergence, OIWeighted, Obv, OmegaRatio, OnNeck, OpenInterestDelta, OpeningMarubozu,
116    OpeningRange, OpeningRangeOutput, OrderBookImbalanceFull, OrderBookImbalanceTop1,
117    OrderBookImbalanceTopN, OrderFlowImbalance, OuHalfLife, OvernightGap, OvernightIntradayReturn,
118    OvernightIntradayReturnOutput, PainIndex, PairSpreadZScore, PairwiseBeta, ParkinsonVolatility,
119    PearsonCorrelation, PercentAboveMa, PercentB, PercentageTrailingStop, Pgo, PiercingDarkCloud,
120    PivotReversal, PlusDi, PlusDm, Pmo, PointAndFigureBars, PolarizedFractalEfficiency, Ppo,
121    PpoHistogram, ProfitFactor, ProjectionBands, ProjectionBandsOutput, ProjectionOscillator, Psar,
122    Pvi, Qqe, QqeOutput, Qstick, QuartileBands, QuartileBandsOutput, QuotedSpread, RSquared,
123    RealizedSpread, RealizedVolatility, RecoveryFactor, RectangleRange, Reflex, RegimeLabel,
124    RelativeStrengthAB, RelativeStrengthOutput, RenkoBars, RenkoTrailingStop, RickshawMan,
125    RisingThreeMethods, Rmi, Roc, Rocp, Rocr, Rocr100, RogersSatchellVolatility, RollMeasure,
126    RollingCorrelation, RollingCovariance, RollingIqr, RollingMinMaxScaler, RollingPercentileRank,
127    RollingQuantile, RollingVwap, RoofingFilter, Rsi, Rsx, Rvi, RviVolatility, Rwi, RwiOutput,
128    SampleEntropy, SarExt, SeasonalZScore, SeparatingLines, SessionHighLow, SessionHighLowOutput,
129    SessionRange, SessionRangeOutput, SessionVwap, ShannonEntropy, Shark, SharpeRatio,
130    ShootingStar, ShortLine, SignedVolume, SineWave, SineWeightedMa, Skewness, Sma, Smi, Smma,
131    SmoothedHeikinAshi, SmoothedHeikinAshiOutput, SortinoRatio, SpearmanCorrelation, SpinningTop,
132    SpreadAr1Coefficient, SpreadBollingerBands, SpreadBollingerBandsOutput, SpreadHurst,
133    StalledPattern, StandardError, StandardErrorBands, StandardErrorBandsOutput, StarcBands,
134    StarcBandsOutput, Stc, StdDev, StepTrailingStop, StickSandwich, StochRsi, Stochastic,
135    StochasticCci, StochasticOutput, SuperSmoother, SuperTrend, SuperTrendOutput,
136    TakerBuySellRatio, Takuri, TasukiGap, TdCamouflage, TdClop, TdClopwin, TdCombo, TdCountdown,
137    TdDWave, TdDeMarker, TdDifferential, TdLines, TdLinesOutput, TdMovingAverage,
138    TdMovingAverageOutput, TdOpen, TdPressure, TdPropulsion, TdRangeProjection,
139    TdRangeProjectionOutput, TdRei, TdRiskLevel, TdRiskLevelOutput, TdSequential,
140    TdSequentialOutput, TdSetup, TdTrap, Tema, TermStructureBasis, ThreeDrives, ThreeInside,
141    ThreeLineBreak, ThreeLineStrike, ThreeOutside, ThreeSoldiersOrCrows, ThreeStarsInSouth,
142    Thrusting, TickIndex, Tii, TimeBasedStop, TimeOfDayReturnProfile, TimeOfDayReturnProfileOutput,
143    TowerTopBottom, TpoProfile, TpoProfileOutput, TradeImbalance, TradeVolumeIndex, TrendLabel,
144    TrendStrengthIndex, Trendflex, TreynorRatio, Triangle, Trima, Trin, TripleTopBottom, Tristar,
145    Trix, TrueRange, Tsf, TsfOscillator, Tsi, Tsv, TtmSqueeze, TtmSqueezeOutput, TtmTrend,
146    TurnOfMonth, Tweezer, TwiggsMoneyFlow, TwoCrows, TypicalPrice, UlcerIndex, UltimateOscillator,
147    UniqueThreeRiver, UniversalOscillator, UpDownVolumeRatio, UpsideGapThreeMethods,
148    UpsideGapTwoCrows, ValueArea, ValueAreaOutput, ValueAtRisk, Variance, VarianceRatio,
149    VerticalHorizontalFilter, Vidya, VolatilityCone, VolatilityConeOutput, VolatilityOfVolatility,
150    VolatilityRatio, VoltyStop, VolumeByTimeProfile, VolumeByTimeProfileOutput, VolumeOscillator,
151    VolumePriceTrend, VolumeProfile, VolumeProfileOutput, VolumeRsi, VolumeWeightedMacd,
152    VolumeWeightedMacdOutput, VolumeWeightedSr, VolumeWeightedSrOutput, Vortex, VortexOutput, Vpin,
153    Vwap, VwapStdDevBands, VwapStdDevBandsOutput, Vwma, Vzo, Wad, WavePm, WaveTrend,
154    WaveTrendOutput, Wedge, WeightedClose, WickRatio, WilliamsFractals, WilliamsFractalsOutput,
155    WilliamsR, WinRate, Wma, WoodiePivots, WoodiePivotsOutput, YangZhangVolatility, YoyoExit,
156    ZScore, ZeroLagMacd, ZeroLagMacdOutput, ZigZag, ZigZagOutput, Zlema, FAMILIES, T3,
157};
158// `FootprintLevel` is a row element of `FootprintOutput`, re-exported on its own
159// line so the indicator-count tooling (which scans the braced block above and
160// strips only `*Output` companions) does not count it as a separate indicator.
161pub use indicators::FootprintLevel;
162// `MaType` is a moving-average selector enum used by `MacdExt`, re-exported on
163// its own line so the indicator-count tooling does not count it as an indicator.
164pub use indicators::MaType;
165// Bar element types for the alt-chart builders, re-exported on their own lines so
166// the indicator-count tooling (which scans only the braced block above) does not
167// count them as separate indicators.
168pub use indicators::KagiBar;
169pub use indicators::PnfColumn;
170pub use indicators::RenkoBrick;
171pub use microstructure::{Level, OrderBook, Side, Trade, TradeQuote};
172pub use ohlcv::{Candle, Tick};
173pub use traits::{BarBuilder, BatchExt, BatchNanExt, Chain, Indicator};