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