tulip_rs 0.1.15

High-performance technical analysis library — 100+ indicators and 60+ candlestick patterns with SIMD acceleration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! # Ehlers CyberCycle
//!
//! **Source:** John Ehlers, *Cybernetic Analysis for Stocks and Futures* (2004), Chapter 4.
//!
//! A two-pole high-pass IIR that removes the low-frequency trend (DC and sub-cycle
//! drift) from price, leaving only the dominant short-cycle oscillation. It provides
//! cycle-mode entry/exit signals via a crossover of `Cycle` and `Trigger`.
//!
//! ## Formula
//!
//! ```text
//! c  = 1 − α/2,   b  = 1 − α         (α = options[0], default 0.07)
//!
//! Smooth = (Price + 2·Price[1] + 2·Price[2] + Price[3]) / 6
//!
//! Seeding (bars 0–5, absorbed by init_state):
//!   Cycle = (Price − 2·Price[1] + Price[2]) / 4
//!
//! Steady state (bar ≥ 6):
//!   Cycle = c²·(Smooth − 2·Smooth[1] + Smooth[2])
//!         + 2b·Cycle[1] − b²·Cycle[2]
//!
//! Trigger = Cycle[1]   (optional 1-bar lag — leads by ~1 bar)
//! ```
//!
//! ## Note on `validate_options`
//!
//! This indicator uses a **local** `validate_options` function. The common
//! `crate::common::validate_options` rejects any option `< 1.0`, which would flag
//! every valid α value. The local function checks `α ∈ (0.0, 1.0)` strictly.
//!
//! ## Adaptive alpha (`α = 0.0`)
//!
//! Adaptive alpha is **not** supported by the standalone `cybercycle::indicator`.
//! It requires a Homodyne Discriminator (HD) to derive `SmoothPeriod` each bar,
//! which is not part of this indicator. Passing `α = 0.0` will return
//! [`IndicatorError::InvalidOptions`].
//!
//! Adaptive mode is available in [`trendmode`](super::trendmode) and
//! [`ccfisher`](super::ccfisher), both of which embed an HD alongside the
//! CyberCycle and compute `α = 2 / (SmoothPeriod.max(3) + 1)` every bar.

use crate::common::validate_inputs;
pub use crate::indicator_types::TIndicatorState;
use crate::ring_buffer::fixed_single_buffer::FixedRingBuffer;
use crate::types::{DisplayGroup, DisplayType, IndicatorError, IndicatorType, Info};
use serde::{Deserialize, Serialize};

/// Number of input price series required by this indicator.
pub const INPUTS_WIDTH: usize = 1;

/// Number of option parameters required by this indicator.
pub const OPTIONS_WIDTH: usize = 1; // [alpha]

#[cfg(feature = "simd_assets")]
pub use crate::indicators::simd_indicators::cybercycle_simd::indicator_by_assets;

#[cfg(feature = "simd_options")]
pub use crate::indicators::simd_indicators::cybercycle_simd::indicator_by_options;

#[cfg(feature = "simd_assets")]
pub mod by_assets {
    /// Processes `N` assets in parallel with shared options.
    pub use crate::indicators::simd_indicators::cybercycle_simd::indicator_by_assets as indicator;
}

#[cfg(feature = "simd_options")]
pub mod by_options {
    /// Processes one asset with `N` different alpha values in parallel.
    pub use crate::indicators::simd_indicators::cybercycle_simd::indicator_by_options as indicator;
}

/// Metadata for the Ehlers CyberCycle indicator.
pub const INFO: Info = Info {
    name: "cybercycle",
    indicator_type: IndicatorType::Cycle,
    full_name: "Ehlers CyberCycle",
    inputs: &["real"],
    options: &["alpha"],
    outputs: &["cybercycle"],
    optional_outputs: &["trigger"],
    display_groups: &[DisplayGroup {
        offset: None,
        id: "cybercycle",
        label: "Ehlers Cyber Cycle",
        display_type: DisplayType::Indicator,
        outputs: &["cybercycle", "trigger"],
    }],
};

/// Persistent state for streaming / multi-batch use.
///
/// Stores the precomputed filter coefficients alongside the filter state,
/// exactly mirroring the `supersmoother::IndicatorState` pattern.
#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
    pub(crate) multipliers: (f64, f64, f64),
    pub(crate) state: State,
}

impl IndicatorState {
    pub fn new(state: State, multipliers: (f64, f64, f64)) -> Self {
        Self { multipliers, state }
    }
}

impl TIndicatorState<INPUTS_WIDTH> for IndicatorState {
    fn batch_indicator(
        &mut self,
        inputs: &[&[f64]; INPUTS_WIDTH],
        optional_outputs: Option<&[bool]>,
    ) -> Result<Vec<Vec<f64>>, IndicatorError> {
        validate_inputs(inputs, 1)?;
        let real = inputs[0];
        let n = real.len();
        let mut cycle_line = crate::uninit_vec!(f64, n);
        let mut trigger_line = crate::init_optional_outputs_eff!(
            optional_outputs, &[false],
            trigger_line: n
        );

        run_cycle(
            real,
            &mut self.state,
            self.multipliers,
            &mut cycle_line,
            &mut trigger_line,
        );

        Ok(vec![cycle_line, trigger_line])
    }
}

/// Per-bar filter state for the Ehlers CyberCycle.
///
/// **Warmup:** after [`init_state`](State::init_state) completes, all ring
/// buffers are full and the IIR feedback is seeded. The hot path
/// (`calc_unchecked`) operates unconditionally.
#[derive(Serialize, Deserialize)]
pub struct State {
    /// 4-bar price ring buffer: `[0]`=Price, `[1]`=Price[1], `[2]`=Price[2], `[3]`=Price[3].
    pub price_buf: FixedRingBuffer<f64, 4>,

    /// 3-bar smooth ring buffer: `[0]`=Smooth, `[1]`=Smooth[1], `[2]`=Smooth[2].
    pub smooth_buf: FixedRingBuffer<f64, 3>,

    /// Cycle[1] — one-bar-ago cycle value (IIR feedback state d₁).
    pub cycle_prev: f64,

    /// Cycle[2] — two-bar-ago cycle value (IIR feedback state d₂).
    pub cycle_prev2: f64,
}

impl State {
    /// Creates a zeroed state ready for the first bar.
    pub fn new() -> Self {
        Self {
            price_buf: FixedRingBuffer::new(),
            smooth_buf: FixedRingBuffer::new(),
            cycle_prev: 0.0,
            cycle_prev2: 0.0,
        }
    }

    /// Seeds the IIR through bars 0–5 **without** processing bar 6.
    ///
    /// Used by the `by_options` SIMD path where the driver writes bar 6's output
    /// directly. The returned state has both ring buffers full and
    /// `cycle_prev`/`cycle_prev2` seeded from the second-difference formula.
    pub fn seed_warmup(real: &[f64]) -> Self {
        let mut state = Self::new();
        for i in 0..6 {
            state.price_buf.push(real[i]);
            if state.price_buf.len() >= 4 {
                let ab = 2.0_f64.mul_add(state.price_buf[1], state.price_buf[0]);
                let cd = 2.0_f64.mul_add(state.price_buf[2], state.price_buf[3]);
                state.smooth_buf.push((ab + cd) * (1.0 / 6.0));
            }
            if state.price_buf.len() >= 3 {
                let seed =
                    (state.price_buf[0] - 2.0 * state.price_buf[1] + state.price_buf[2]) / 4.0;
                state.cycle_prev2 = state.cycle_prev;
                state.cycle_prev = seed;
            }
        }
        state
    }

    /// Seeds the IIR for bars 0–5, then processes bar 6 (first valid output).
    ///
    /// Writes `cycle_line[0]` and (if non-empty) `trigger_line[0]`.
    /// After the call, all ring buffers are full and `calc_unchecked` is safe.
    pub fn init_state(
        real: &[f64],
        multipliers: (f64, f64, f64),
        cycle_line: &mut [f64],
        trigger_line: &mut [f64],
    ) -> Self {
        let mut state = Self::new();

        // ── Seeding: bars 0–5 ────────────────────────────────────────────────
        // Bars 0–1: price_buf.len() < 3 → seeding formula cannot run; cycle stays 0.
        // Bar 2:    first seeding value.
        // Bars 3–5: Smooth also becomes available (price_buf.len() >= 4).
        for i in 0..6 {
            state.price_buf.push(real[i]);

            if state.price_buf.len() >= 4 {
                let ab = 2.0_f64.mul_add(state.price_buf[1], state.price_buf[0]);
                let cd = 2.0_f64.mul_add(state.price_buf[2], state.price_buf[3]);
                state.smooth_buf.push((ab + cd) * (1.0 / 6.0));
            }

            if state.price_buf.len() >= 3 {
                let seed =
                    (state.price_buf[0] - 2.0 * state.price_buf[1] + state.price_buf[2]) / 4.0;
                state.cycle_prev2 = state.cycle_prev;
                state.cycle_prev = seed;
            }
        }
        // After loop: price_buf = [P5,P4,P3,P2] (full)
        //             smooth_buf = [S5,S4,S3]   (full — first three smooths)
        //             cycle_prev  = Cycle[5]
        //             cycle_prev2 = Cycle[4]

        // ── Bar 6: first valid output ─────────────────────────────────────────
        let cycle = unsafe { state.calc_unchecked(real[6], multipliers) };
        cycle_line[0] = cycle;
        // After calc_unchecked: cycle_prev = Cycle[6], cycle_prev2 = Cycle[5].
        // Trigger[0] = Cycle[5] = the last seeded cycle before bar 6.
        if !trigger_line.is_empty() {
            trigger_line[0] = state.cycle_prev2;
        }

        state
    }

    /// Safe one-bar update. Returns `0.0` while ring buffers are still filling.
    ///
    /// Prefer `calc_unchecked` in hot loops after [`init_state`](Self::init_state).
    #[inline(always)]
    pub fn calc(&mut self, price: f64, multipliers: (f64, f64, f64)) -> f64 {
        self.price_buf.push(price);
        if self.price_buf.len() < 4 {
            return 0.0;
        }
        let ab = 2.0_f64.mul_add(self.price_buf[1], self.price_buf[0]);
        let cd = 2.0_f64.mul_add(self.price_buf[2], self.price_buf[3]);
        let smooth = (ab + cd) * (1.0 / 6.0);
        self.smooth_buf.push(smooth);
        if self.smooth_buf.len() < 3 {
            return 0.0;
        }
        let (coeff, d1, d2) = multipliers;
        let smooth_diff = (-2.0_f64).mul_add(self.smooth_buf[1], smooth) + self.smooth_buf[2];
        let cycle = coeff.mul_add(
            smooth_diff,
            d1.mul_add(self.cycle_prev, -d2 * self.cycle_prev2),
        );
        self.cycle_prev2 = self.cycle_prev;
        self.cycle_prev = cycle;
        cycle
    }

    /// Unsafe one-bar update — skips ring-buffer fullness guards.
    ///
    /// After the call:
    /// - `state.cycle_prev`  = Cycle (current bar)
    /// - `state.cycle_prev2` = Cycle[1] (previous bar)
    /// - Trigger = `state.cycle_prev2`
    ///
    /// # Safety
    ///
    /// Both `price_buf` and `smooth_buf` must be full on entry.
    /// Guaranteed after [`init_state`](Self::init_state).
    #[inline(always)]
    pub unsafe fn calc_unchecked(&mut self, price: f64, multipliers: (f64, f64, f64)) -> f64 {
        // ── Stage 1: 6-tap weighted smooth ──────────────────────────────────
        // Smooth = (P + 2·P[1] + 2·P[2] + P[3]) / 6
        // Decomposed into 2 FMAs (serial depth 2):
        //   ab = 2·P[1] + P   = P + 2·P[1]
        //   cd = 2·P[2] + P[3]
        self.price_buf.push_unchecked(price);
        let ab = 2.0_f64.mul_add(self.price_buf[1], self.price_buf[0]);
        let cd = 2.0_f64.mul_add(self.price_buf[2], self.price_buf[3]);
        let smooth = (ab + cd) * (1.0 / 6.0);

        // ── Stage 2: 2-pole high-pass IIR ───────────────────────────────────
        // Cycle = coeff·(S − 2·S[1] + S[2]) + d1·C[1] − d2·C[2]
        // Three FMAs (serial depth 2):
        //   smooth_diff = −2·S[1] + S  (FMA) + S[2]
        //   inner       = d1·C[1] − d2·C[2]
        //   cycle       = coeff·smooth_diff + inner
        self.smooth_buf.push_unchecked(smooth);
        let (coeff, d1, d2) = multipliers;
        let smooth_diff = (-2.0_f64).mul_add(self.smooth_buf[1], smooth) + self.smooth_buf[2];
        let cycle = coeff.mul_add(
            smooth_diff,
            d1.mul_add(self.cycle_prev, -d2 * self.cycle_prev2),
        );

        self.cycle_prev2 = self.cycle_prev;
        self.cycle_prev = cycle;
        cycle
    }
}

impl Default for State {
    fn default() -> Self {
        Self::new()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────────────────────────────────────

/// Returns the minimum number of input bars required for any output.
///
/// Bars 0–5 are absorbed by seeding; bar 6 is the first valid output.
pub fn min_data(_options: &[f64]) -> usize {
    7
}


/// Number of output bars for a given input length.
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
    data_len - min_data(options) + 1
}

/// Validates that `alpha` is strictly in `(0.0, 1.0)`.
///
/// `alpha = 0.0` is rejected — adaptive mode is not available in the standalone
/// CyberCycle indicator (no embedded HD). Use [`trendmode`](super::trendmode) or
/// [`ccfisher`](super::ccfisher) for adaptive alpha.
///
/// **Do not** use `crate::common::validate_options` here — it rejects any
/// option `< 1.0` and would flag all valid α values.
pub(crate) fn validate_options(options: &[f64; OPTIONS_WIDTH]) -> Result<(), IndicatorError> {
    if options[0] <= 0.0 || options[0] >= 1.0 {
        return Err(IndicatorError::InvalidOptions);
    }
    Ok(())
}

/// Precomputes the three stable IIR multipliers from `alpha`.
///
/// Returns `(coeff, d1, d2)` where:
/// - `coeff` = `(1 − α/2)²` — feedforward gain
/// - `d1`    = `2·(1 − α)` — first feedback coefficient
/// - `d2`    = `(1 − α)²`  — second feedback coefficient
pub fn multiplier(alpha: f64) -> (f64, f64, f64) {
    let c = 1.0 - 0.5 * alpha;
    let b = 1.0 - alpha;
    (c * c, 2.0 * b, b * b)
}

/// Computes adaptive alpha from the Homodyne Discriminator's `smooth_period`.
///
/// `alpha = 2 / (smooth_period.max(3) + 1)`, keeping alpha in `(0, 0.5]`.
/// Clamping to `max(3)` prevents alpha from exceeding 0.5 when `smooth_period`
/// is near zero during HD warmup (first ~22 bars of the indicator's 55-bar warmup).
///
/// This is the Ehlers α-from-period conversion: the dominant cycle period
/// acts as the EMA's equivalent period, and alpha is the corresponding coefficient.
#[inline(always)]
pub fn adaptive_alpha(smooth_period: f64) -> f64 {
    2.0 / (smooth_period.max(3.0) + 1.0)
}

/// Calculates the Ehlers CyberCycle over the full input dataset.
///
/// # Inputs
///
/// * `inputs[0]` — close (or HLC/3) price series
///
/// # Options
///
/// * `options[0]` — `alpha` ∈ (0, 1). Ehlers' default is `0.07`.
///
/// # Outputs
///
/// * `outputs[0]` — `cybercycle` oscillator
/// * `outputs[1]` — `trigger` = Cycle[1] (optional; empty unless requested)
///
/// # Returns
///
/// `Ok((outputs, state))` where `state` can be used for streaming via
/// [`IndicatorState::batch_indicator`]. Returns `Err` if inputs are too short
/// or `alpha` is outside `(0, 1)`.
pub fn indicator(
    inputs: &[&[f64]; INPUTS_WIDTH],
    options: &[f64; OPTIONS_WIDTH],
    optional_outputs: Option<&[bool]>,
) -> Result<(Vec<Vec<f64>>, IndicatorState), IndicatorError> {
    validate_options(options)?;
    validate_inputs(inputs, min_data(options))?;

    let alpha = options[0];
    let mults = multiplier(alpha);
    let real = inputs[0];
    let n = real.len();
    let capacity = output_length(n, options);
    let mut cycle_line = crate::uninit_vec!(f64, capacity);
    let mut trigger_line = crate::init_optional_outputs_eff!(
        optional_outputs, &[false],
        trigger_line: capacity
    );

    // init_state seeds bars 0–5 and processes bar 6 (output index 0).
    let mut state = State::init_state(real, mults, &mut cycle_line, &mut trigger_line);

    // Process bars 7..n (output indices 1..capacity).
    let trigger_start = crate::slice_outputs_start!(capacity - 1, trigger_line);
    run_cycle(
        &real[min_data(options)..],
        &mut state,
        mults,
        &mut cycle_line[1..],
        &mut trigger_line[trigger_start..],
    );

    Ok((
        vec![cycle_line, trigger_line],
        IndicatorState::new(state, mults),
    ))
}

/// Shared hot loop used by both `indicator` and `batch_indicator`.
///
/// After each bar: `state.cycle_prev2` = Cycle[1] = trigger for that bar.
fn run_cycle(
    real: &[f64],
    state: &mut State,
    multipliers: (f64, f64, f64),
    cycle_line: &mut [f64],
    trigger_line: &mut [f64],
) {
    let want_trigger = !trigger_line.is_empty();
    for i in 0..real.len() {
        unsafe {
            *cycle_line.get_unchecked_mut(i) =
                state.calc_unchecked(*real.get_unchecked(i), multipliers);
        }
        crate::store_optional_outputs!(i,
            want_trigger, trigger_line => state.cycle_prev2
        );
    }
}