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