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, AdaptiveCycle, AdaptiveLaguerreFilter, Adl,
61    AdvanceBlock, AdvanceDecline, AdvanceDeclineRatio, Adx, AdxOutput, Adxr, Alligator,
62    AlligatorOutput, Alma, Alpha, AmihudIlliquidity, AnchoredRsi, AnchoredVwap, Apo, Aroon,
63    AroonOscillator, AroonOutput, Atr, AtrBands, AtrBandsOutput, AtrTrailingStop, AutoFib,
64    AutoFibOutput, Autocorrelation, AverageDailyRange, AverageDrawdown, AvgPrice,
65    AwesomeOscillator, AwesomeOscillatorHistogram, BalanceOfPower, Bat, BeltHold, Beta,
66    BetaNeutralSpread, BodySizePct, BollingerBands, BollingerBandwidth, BollingerOutput,
67    BreadthThrust, Breakaway, BullishPercentIndex, Butterfly, CalendarSpread, CalmarRatio,
68    Camarilla, CamarillaPivotsOutput, Cci, CenterOfGravity, Cfo, ChaikinMoneyFlow,
69    ChaikinOscillator, ChaikinVolatility, ChandeKrollStop, ChandeKrollStopOutput, ChandelierExit,
70    ChandelierExitOutput, ChoppinessIndex, ClassicPivots, ClassicPivotsOutput, CloseVsOpen,
71    ClosingMarubozu, Cmo, CoefficientOfVariation, Cointegration, CointegrationOutput,
72    ConcealingBabySwallow, ConditionalValueAtRisk, ConnorsRsi, Coppock, Counterattack, Crab,
73    CumulativeVolumeDelta, CumulativeVolumeIndex, CupAndHandle, CyberneticCycle, Cypher,
74    DayOfWeekProfile, DayOfWeekProfileOutput, Decycler, DecyclerOscillator, Dema, DemandIndex,
75    DemarkPivots, DemarkPivotsOutput, DepthSlope, DerivativeOscillator, DetrendedStdDev,
76    DisparityIndex, DistanceSsd, Doji, DojiStar, Donchian, DonchianOutput, DonchianStop,
77    DonchianStopOutput, DoubleBollinger, DoubleBollingerOutput, DoubleTopBottom,
78    DownsideGapThreeMethods, Dpo, DragonflyDoji, DrawdownDuration, Dx, DynamicMomentumIndex,
79    EaseOfMovement, EffectiveSpread, EhlersStochastic, Ehma, ElderImpulse, ElderRay,
80    ElderRayOutput, Ema, EmpiricalModeDecomposition, Engulfing, EveningDojiStar, Evwma, Expectancy,
81    FallingThreeMethods, Fama, FibArcs, FibArcsOutput, FibChannel, FibChannelOutput, FibConfluence,
82    FibConfluenceOutput, FibExtension, FibExtensionOutput, FibFan, FibFanOutput, FibProjection,
83    FibProjectionOutput, FibRetracement, FibRetracementOutput, FibTimeZones, FibTimeZonesOutput,
84    FibonacciPivots, FibonacciPivotsOutput, FisherRsi, FisherTransform, FlagPennant, Footprint,
85    FootprintOutput, ForceIndex, FractalChaosBands, FractalChaosBandsOutput, Frama, FundingBasis,
86    FundingRate, FundingRateMean, FundingRateZScore, GainLossRatio, GapSideBySideWhite,
87    GarmanKlassVolatility, Gartley, GatorOscillator, GatorOscillatorOutput, GeneralizedDema,
88    GeometricMa, GoldenPocket, GoldenPocketOutput, GrangerCausality, GravestoneDoji, Hammer,
89    HangingMan, Harami, HeadAndShoulders, HeikinAshi, HeikinAshiOutput, HiLoActivator,
90    HighLowIndex, HighLowRange, HighWave, Hikkake, HikkakeModified, HilbertDominantCycle,
91    HistoricalVolatility, Hma, HoltWinters, HomingPigeon, HtDcPhase, HtPhasor, HtPhasorOutput,
92    HtTrendMode, HurstChannel, HurstChannelOutput, HurstExponent, Ichimoku, IchimokuOutput,
93    IdenticalThreeCrows, InNeck, Inertia, InformationRatio, InitialBalance, InitialBalanceOutput,
94    InstantaneousTrendline, IntradayMomentumIndex, IntradayVolatilityProfile,
95    IntradayVolatilityProfileOutput, InverseFisherTransform, InvertedHammer, Jma, JumpIndicator,
96    KagiBars, KalmanHedgeRatio, KalmanHedgeRatioOutput, Kama, KasePermissionStochastic,
97    KasePermissionStochasticOutput, KellyCriterion, Keltner, KeltnerOutput, Kicking,
98    KickingByLength, Kst, KstOutput, Kurtosis, Kvo, KylesLambda, LadderBottom, LaguerreRsi,
99    LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput, LinRegAngle, LinRegChannel,
100    LinRegChannelOutput, LinRegIntercept, LinRegSlope, LinearRegression, LiquidationFeatures,
101    LiquidationFeaturesOutput, LogReturn, LongLeggedDoji, LongLine, LongShortRatio, MaEnvelope,
102    MaEnvelopeOutput, MacdExt, MacdFix, MacdHistogram, MacdIndicator, MacdOutput, Mama, MamaOutput,
103    MarketFacilitationIndex, Marubozu, MassIndex, MatHold, MatchingLow, MaxDrawdown,
104    McClellanOscillator, McClellanSummationIndex, McGinleyDynamic, MedianAbsoluteDeviation,
105    MedianMa, MedianPrice, Mfi, Microprice, MidPoint, MidPrice, MinusDi, MinusDm, Mom,
106    MorningDojiStar, MorningEveningStar, Natr, NewHighsNewLows, Nvi, OIPriceDivergence, OIWeighted,
107    Obv, OmegaRatio, OnNeck, OpenInterestDelta, OpeningMarubozu, OpeningRange, OpeningRangeOutput,
108    OrderBookImbalanceFull, OrderBookImbalanceTop1, OrderBookImbalanceTopN, OrderFlowImbalance,
109    OuHalfLife, OvernightGap, OvernightIntradayReturn, OvernightIntradayReturnOutput, PainIndex,
110    PairSpreadZScore, PairwiseBeta, ParkinsonVolatility, PearsonCorrelation, PercentAboveMa,
111    PercentB, PercentageTrailingStop, Pgo, PiercingDarkCloud, PlusDi, PlusDm, Pmo,
112    PointAndFigureBars, PolarizedFractalEfficiency, Ppo, PpoHistogram, ProfitFactor, Psar, Pvi,
113    Qqe, QqeOutput, Qstick, QuotedSpread, RSquared, RealizedSpread, RealizedVolatility,
114    RecoveryFactor, RectangleRange, RegimeLabel, RelativeStrengthAB, RelativeStrengthOutput,
115    RenkoBars, RenkoTrailingStop, RickshawMan, RisingThreeMethods, Rmi, Roc, Rocp, Rocr, Rocr100,
116    RogersSatchellVolatility, RollMeasure, RollingCorrelation, RollingCovariance, RollingIqr,
117    RollingPercentileRank, RollingQuantile, RollingVwap, RoofingFilter, Rsi, Rsx, Rvi,
118    RviVolatility, Rwi, RwiOutput, SarExt, SeasonalZScore, SeparatingLines, SessionHighLow,
119    SessionHighLowOutput, SessionRange, SessionRangeOutput, SessionVwap, Shark, SharpeRatio,
120    ShootingStar, ShortLine, SignedVolume, SineWave, SineWeightedMa, Skewness, Sma, Smi, Smma,
121    SortinoRatio, SpearmanCorrelation, SpinningTop, SpreadAr1Coefficient, SpreadBollingerBands,
122    SpreadBollingerBandsOutput, SpreadHurst, StalledPattern, StandardError, StandardErrorBands,
123    StandardErrorBandsOutput, StarcBands, StarcBandsOutput, Stc, StdDev, StepTrailingStop,
124    StickSandwich, StochRsi, Stochastic, StochasticCci, StochasticOutput, SuperSmoother,
125    SuperTrend, SuperTrendOutput, TakerBuySellRatio, Takuri, TasukiGap, TdCombo, TdCountdown,
126    TdDeMarker, TdDifferential, TdLines, TdLinesOutput, TdOpen, TdPressure, TdRangeProjection,
127    TdRangeProjectionOutput, TdRei, TdRiskLevel, TdRiskLevelOutput, TdSequential,
128    TdSequentialOutput, TdSetup, Tema, TermStructureBasis, ThreeDrives, ThreeInside,
129    ThreeLineStrike, ThreeOutside, ThreeSoldiersOrCrows, ThreeStarsInSouth, Thrusting, TickIndex,
130    Tii, TimeOfDayReturnProfile, TimeOfDayReturnProfileOutput, TpoProfile, TpoProfileOutput,
131    TradeImbalance, TrendLabel, TrendStrengthIndex, TreynorRatio, Triangle, Trima, Trin,
132    TripleTopBottom, Trix, TrueRange, Tsf, TsfOscillator, Tsi, Tsv, TtmSqueeze, TtmSqueezeOutput,
133    TtmTrend, TurnOfMonth, Tweezer, TwoCrows, TypicalPrice, UlcerIndex, UltimateOscillator,
134    UniqueThreeRiver, UpDownVolumeRatio, UpsideGapThreeMethods, UpsideGapTwoCrows, ValueArea,
135    ValueAreaOutput, ValueAtRisk, Variance, VarianceRatio, VerticalHorizontalFilter, Vidya,
136    VoltyStop, VolumeByTimeProfile, VolumeByTimeProfileOutput, VolumeOscillator, VolumePriceTrend,
137    VolumeProfile, VolumeProfileOutput, Vortex, VortexOutput, Vpin, Vwap, VwapStdDevBands,
138    VwapStdDevBandsOutput, Vwma, Vzo, WavePm, WaveTrend, WaveTrendOutput, Wedge, WeightedClose,
139    WickRatio, WilliamsFractals, WilliamsFractalsOutput, WilliamsR, WinRate, Wma, WoodiePivots,
140    WoodiePivotsOutput, YangZhangVolatility, YoyoExit, ZScore, ZeroLagMacd, ZeroLagMacdOutput,
141    ZigZag, ZigZagOutput, Zlema, FAMILIES, T3,
142};
143// `FootprintLevel` is a row element of `FootprintOutput`, re-exported on its own
144// line so the indicator-count tooling (which scans the braced block above and
145// strips only `*Output` companions) does not count it as a separate indicator.
146pub use indicators::FootprintLevel;
147// `MaType` is a moving-average selector enum used by `MacdExt`, re-exported on
148// its own line so the indicator-count tooling does not count it as an indicator.
149pub use indicators::MaType;
150// Bar element types for the alt-chart builders, re-exported on their own lines so
151// the indicator-count tooling (which scans only the braced block above) does not
152// count them as separate indicators.
153pub use indicators::KagiBar;
154pub use indicators::PnfColumn;
155pub use indicators::RenkoBrick;
156pub use microstructure::{Level, OrderBook, Side, Trade, TradeQuote};
157pub use ohlcv::{Candle, Tick};
158pub use traits::{BarBuilder, BatchExt, Chain, Indicator};