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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! # Ehlers TrendMode
//!
//! **Source:** John Ehlers, *Cybernetic Analysis for Stocks and Futures* (2004), Chapter 8.
//!
//! Classifies each bar as either Trend Mode or Cycle Mode by comparing the
//! current CyberCycle amplitude to its running peak envelope. When the
//! oscillator amplitude collapses to less than 20 % of its decaying peak,
//! the instrument is trending and the CyberCycle signal should be ignored;
//! otherwise the market is cycling and the CyberCycle is reliable.
//!
//! ## Algorithm
//!
//! ```text
//! Cycle = Ehlers CyberCycle oscillator (α = options[0], default 0.07)
//!
//! Peak = max(Peak[1] × 0.991, |Cycle|)   (exponential-decay amplitude latch)
//!
//! TrendMode = 1  if  Peak > 0  and  |Cycle| < 0.2 × Peak
//!           = 0  otherwise
//! ```
//!
//! ## Warmup
//!
//! `init_state` absorbs bars 0–54 (HD warmup + CyberCycle seeding + peak
//! accumulation) and produces the first output at bar 55. `min_data` = 56.
//!
//! ## Alpha / adaptive mode
//!
//! * `options[0] > 0.0` — fixed α, e.g. Ehlers' default `0.07`.
//! * `options[0] = 0.0` — **adaptive**: α is re-derived every bar from the
//!   Homodyne Discriminator's `SmoothPeriod` via `2 / (SmoothPeriod.max(3) + 1)`.
//!   The filter self-tunes to the dominant cycle; no parameter selection needed.
//!   Small extra cost vs fixed α: one `max` + one division per bar.

use crate::common::validate_inputs;
pub use crate::indicator_types::TIndicatorState;
use crate::indicators::{cybercycle, homodynediscriminator};
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::trendmode_simd::indicator_by_assets;
#[cfg(feature = "simd_options")]
pub use crate::indicators::simd_indicators::trendmode_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::trendmode_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::trendmode_simd::indicator_by_options as indicator;
}

/// Metadata for the Ehlers TrendMode indicator.
pub const INFO: Info = Info {
    name: "trendmode",
    indicator_type: IndicatorType::Trend,
    full_name: "Ehlers TrendMode",
    inputs: &["real"],
    options: &["alpha"],
    outputs: &["trendmode"],
    optional_outputs: &["cycle", "peak"],
    display_groups: &[
        DisplayGroup {
            offset: None,
            id: "trendmode",
            label: "Ehlers TrendMode",
            display_type: DisplayType::Indicator,
            outputs: &["trendmode"],
        },
        DisplayGroup {
            offset: None,
            id: "trendmode_cycle",
            label: "TrendMode CyberCycle",
            display_type: DisplayType::Indicator,
            outputs: &["cycle"],
        },
        DisplayGroup {
            offset: None,
            id: "trendmode_peak",
            label: "TrendMode Peak",
            display_type: DisplayType::Indicator,
            outputs: &["peak"],
        },
    ],
};

/// Per-bar filter state for the Ehlers TrendMode.
///
/// Composes the full [`homodynediscriminator::State`] pipeline (adaptive DC period)
/// and [`cybercycle::State`] (2-pole high-pass oscillator), then extends them with
/// a decaying peak-amplitude latch.
///
/// **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 {
    /// Embedded Homodyne Discriminator — provides `SmoothPeriod` (DC) per bar.
    pub hd: homodynediscriminator::State,
    /// Embedded CyberCycle oscillator — produces `Cycle` per bar.
    pub cc: cybercycle::State,
    /// Running peak amplitude: `max(pk[1] × 0.991, |Cycle|)`.
    pub pk: f64,
}

impl State {
    /// Creates a zeroed state ready for the first bar.
    pub fn new() -> Self {
        Self {
            hd: homodynediscriminator::State::new(),
            cc: cybercycle::State::new(),
            pk: 0.0,
        }
    }

    /// Builds a warmed-up state by seeding the HD and CC pipelines over 55
    /// bars, then processes bar 55 (the first valid output).
    ///
    /// **Three phases:**
    /// 1. Bars 0–5:  CC seeding (second-difference formula) + `hd.calc()` (safe).
    /// 2. Bars 6–21: `hd.calc()` (safe) + `cc.calc_unchecked()` + peak tracking.
    /// 3. Bars 22–54: `hd.calc_unchecked()` + `cc.calc_unchecked()` + peak tracking.
    ///
    /// Writes the first output values to the respective output slices at index 0.
    /// Pass empty slices (`&mut []`) for any optional output that is not needed.
    pub fn init_state(
        real: &[f64],
        alpha: f64, // 0.0 = adaptive; (0,1) = fixed
        trendmode_line: &mut [f64],
        cycle_line: &mut [f64],
        peak_line: &mut [f64],
    ) -> Self {
        let mut state = Self::new();
        let fixed_mults = if alpha > 0.0 {
            Some(cybercycle::multiplier(alpha))
        } else {
            None
        };

        // ── Phase 1: bars 0–5 — CC seeding + HD warmup ───────────────────────
        for i in 0..6 {
            state.cc.price_buf.push(real[i]);
            if state.cc.price_buf.len() >= 4 {
                let ab = 2.0_f64.mul_add(state.cc.price_buf[1], state.cc.price_buf[0]);
                let cd = 2.0_f64.mul_add(state.cc.price_buf[2], state.cc.price_buf[3]);
                state.cc.smooth_buf.push((ab + cd) * (1.0 / 6.0));
            }
            if state.cc.price_buf.len() >= 3 {
                let seed = (state.cc.price_buf[0] - 2.0 * state.cc.price_buf[1]
                    + state.cc.price_buf[2])
                    / 4.0;
                state.cc.cycle_prev2 = state.cc.cycle_prev;
                state.cc.cycle_prev = seed;
            }
            state.hd.calc(real[i]);
        }

        // ── Phase 2: bars 6–21 — HD safe + CC unchecked + peak tracking ──────
        for i in 6..22 {
            state.hd.calc(real[i]);
            let mults = match fixed_mults {
                Some(m) => m,
                None => cybercycle::multiplier(cybercycle::adaptive_alpha(state.hd.smooth_period)),
            };
            let cycle = unsafe { state.cc.calc_unchecked(real[i], mults) };
            state.pk = (state.pk * 0.991).max(cycle.abs());
        }

        // ── Phase 3: bars 22–54 — both unchecked + peak tracking ─────────────
        for i in 22..55 {
            unsafe { state.hd.calc_unchecked(real[i]) };
            let mults = match fixed_mults {
                Some(m) => m,
                None => cybercycle::multiplier(cybercycle::adaptive_alpha(state.hd.smooth_period)),
            };
            let cycle = unsafe { state.cc.calc_unchecked(real[i], mults) };
            state.pk = (state.pk * 0.991).max(cycle.abs());
        }

        // ── Bar 55: first valid output ────────────────────────────────────────
        let trendmode = if alpha == 0.0 {
            unsafe { state.calc_unchecked_adaptive(real[55]) }
        } else {
            unsafe { state.calc_unchecked(real[55], fixed_mults.unwrap()) }
        };
        trendmode_line[0] = trendmode;
        if !cycle_line.is_empty() {
            cycle_line[0] = state.cc.cycle_prev;
        }
        if !peak_line.is_empty() {
            peak_line[0] = state.pk;
        }

        state
    }

    /// Unsafe one-bar update — skips all ring-buffer fullness guards.
    ///
    /// After the call:
    /// - `state.hd.smooth_period` = DC period (current bar)
    /// - `state.cc.cycle_prev`    = Cycle (current bar)
    /// - `state.pk`               = peak amplitude (current bar)
    ///
    /// Returns `1.0` (Trend Mode) or `0.0` (Cycle Mode).
    ///
    /// # Safety
    ///
    /// All HD and CC ring buffers 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 {
        self.hd.calc_unchecked(price);
        let cycle = self.cc.calc_unchecked(price, multipliers);
        self.pk = (self.pk * 0.991).max(cycle.abs());
        if self.pk > 0.0 && cycle.abs() < 0.2 * self.pk {
            1.0
        } else {
            0.0
        }
    }

    /// Unsafe one-bar update using **adaptive alpha** derived from the HD's `smooth_period`.
    ///
    /// After the call:
    /// - `state.hd.smooth_period` = DC period (updated)
    /// - `state.cc.cycle_prev`    = Cycle (current bar)
    /// - `state.pk`               = peak amplitude (current bar)
    ///
    /// Returns `1.0` (Trend Mode) or `0.0` (Cycle Mode).
    ///
    /// # Safety
    ///
    /// All HD and CC ring buffers must be full on entry.
    /// Guaranteed after [`init_state`](Self::init_state).
    #[inline(always)]
    pub unsafe fn calc_unchecked_adaptive(&mut self, price: f64) -> f64 {
        self.hd.calc_unchecked(price);
        let alpha = cybercycle::adaptive_alpha(self.hd.smooth_period);
        let multipliers = cybercycle::multiplier(alpha);
        let cycle = self.cc.calc_unchecked(price, multipliers);
        self.pk = (self.pk * 0.991).max(cycle.abs());
        if self.pk > 0.0 && cycle.abs() < 0.2 * self.pk {
            1.0
        } else {
            0.0
        }
    }
}

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

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

impl IndicatorState {
    pub fn new(state: State, alpha: f64) -> Self {
        let multipliers = if alpha > 0.0 {
            cybercycle::multiplier(alpha)
        } else {
            (0.0, 0.0, 0.0)
        };
        Self {
            alpha,
            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 trendmode_line = crate::uninit_vec!(f64, n);
        let (mut cycle_line, mut peak_line) = crate::init_optional_outputs_eff!(
            optional_outputs, &[false, false],
            cycle_line: n,
            peak_line: n
        );

        run_trendmode(
            real,
            &mut self.state,
            self.alpha,
            self.multipliers,
            &mut trendmode_line,
            &mut cycle_line,
            &mut peak_line,
        );

        Ok(vec![trendmode_line, cycle_line, peak_line])
    }
}

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

/// Returns the minimum number of input bars required for any output.
///
/// Bars 0–54 are absorbed by the HD + CC + peak warmup; bar 55 is the first
/// valid output.
pub fn min_data(_options: &[f64]) -> usize {
    56
}


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

/// Validates `alpha`.
///
/// * `0.0` — adaptive (derived from `SmoothPeriod` each bar via the embedded HD).
/// * `(0.0, 1.0)` — fixed user-supplied alpha. Ehlers' default is `0.07`.
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(())
}

/// Calculates the Ehlers TrendMode over the full input dataset.
///
/// # Inputs
///
/// * `inputs[0]` — close (or HLC/3) price series
///
/// # Options
///
/// * `options[0]` — `alpha` ∈ [0, 1). `0` = adaptive (derived from DC period each bar).
///   Ehlers' default fixed value is `0.07`.
///
/// # Outputs
///
/// * `outputs[0]` — `trendmode`: `1.0` = Trend Mode, `0.0` = Cycle Mode
/// * `outputs[1]` — `cycle`:    CyberCycle oscillator (optional; empty unless requested)
/// * `outputs[2]` — `peak`:     decaying amplitude peak (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 multipliers = if alpha > 0.0 {
        cybercycle::multiplier(alpha)
    } else {
        (0.0, 0.0, 0.0)
    };
    let real = inputs[0];
    let n = real.len();
    let capacity = output_length(n, options);

    let mut trendmode_line = crate::uninit_vec!(f64, capacity);
    let (mut cycle_line, mut peak_line) = crate::init_optional_outputs_eff!(
        optional_outputs, &[false, false],
        cycle_line: capacity,
        peak_line: capacity
    );

    // init_state seeds bars 0–54 and processes bar 55 (output index 0).
    let mut state = State::init_state(
        real,
        alpha,
        &mut trendmode_line,
        &mut cycle_line,
        &mut peak_line,
    );

    let (cycle_tail, peak_tail) = {
        let o = crate::slice_outputs_start!(capacity - 1, cycle_line, peak_line);
        (&mut cycle_line[o.0..], &mut peak_line[o.1..])
    };

    // Process bars 56..n (output indices 1..capacity).
    run_trendmode(
        &real[min_data(options)..],
        &mut state,
        alpha,
        multipliers,
        &mut trendmode_line[1..],
        cycle_tail,
        peak_tail,
    );

    Ok((
        vec![trendmode_line, cycle_line, peak_line],
        IndicatorState::new(state, alpha),
    ))
}

/// Shared hot loop used by both `indicator` and `batch_indicator`.
///
/// All HD and CC ring buffers must be full on entry (guaranteed after
/// `init_state`). Writes `trendmode` for every bar, and optionally `cycle` and
/// `peak`.
fn run_trendmode(
    real: &[f64],
    state: &mut State,
    alpha: f64,
    multipliers: (f64, f64, f64),
    trendmode_line: &mut [f64],
    cycle_line: &mut [f64],
    peak_line: &mut [f64],
) {
    let (has_optional, want_cycle, want_peak) = crate::calc_want_flags!(cycle_line, peak_line);
    if alpha == 0.0 {
        for i in 0..real.len() {
            let trendmode = unsafe { state.calc_unchecked_adaptive(*real.get_unchecked(i)) };
            unsafe {
                *trendmode_line.get_unchecked_mut(i) = trendmode;
            }
            if has_optional {
                crate::store_optional_outputs!(i,
                    want_cycle, cycle_line => state.cc.cycle_prev,
                    want_peak,  peak_line  => state.pk
                );
            }
        }
    } else {
        for i in 0..real.len() {
            let trendmode = unsafe { state.calc_unchecked(*real.get_unchecked(i), multipliers) };
            unsafe {
                *trendmode_line.get_unchecked_mut(i) = trendmode;
            }
            if has_optional {
                crate::store_optional_outputs!(i,
                    want_cycle, cycle_line => state.cc.cycle_prev,
                    want_peak,  peak_line  => state.pk
                );
            }
        }
    }
}