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