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
use crate::common::validate_inputs;
pub use crate::indicator_types::TIndicatorState;
use crate::indicators::tr::output_length as tr_output_length;
use crate::ring_buffer::multi_buffer::multi_buffer::{MultiBuffer as Buffer, RingBuffer};
use crate::types::{DisplayGroup, DisplayType, IndicatorError, IndicatorType, Info};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
//use wide::*;
use std::simd::{num::SimdFloat, Simd};
/// Number of input price series required by this indicator.
pub const INPUTS_WIDTH: usize = 3;

/// Number of option parameters required by this indicator.
pub const OPTIONS_WIDTH: usize = 3;

/// SIMD-parallel variant that processes `N` assets with identical options simultaneously.
/// Requires the `simd_assets` Cargo feature. See [`by_assets`] for the module form.
#[cfg(feature = "simd_assets")]
pub use crate::indicators::simd_indicators::ultosc_simd::indicator_by_assets;

/// SIMD-parallel variant that processes a single asset with `N` different option
/// sets simultaneously. Requires the `simd_options` Cargo feature. See [`by_options`].
#[cfg(feature = "simd_options")]
pub use crate::indicators::simd_indicators::ultosc_simd::indicator_by_options;

/// Convenience module that re-exports [`indicator_by_assets`] as `indicator`,
/// allowing SIMD multi-asset computation to be used as a drop-in replacement
/// for the standard single-asset [`indicator`] function.
/// Requires the `simd_assets` Cargo feature.
#[cfg(feature = "simd_assets")]
pub mod by_assets {
    /// Processes `N` assets in parallel with shared options.
    pub use crate::indicators::simd_indicators::ultosc_simd::indicator_by_assets as indicator;
}

/// Convenience module that re-exports [`indicator_by_options`] as `indicator`,
/// allowing SIMD multi-option computation to be used as a drop-in replacement
/// for the standard single-asset [`indicator`] function.
/// Requires the `simd_options` Cargo feature.
#[cfg(feature = "simd_options")]
pub mod by_options {
    /// Processes a single asset with `N` different option sets in parallel.
    pub use crate::indicators::simd_indicators::ultosc_simd::indicator_by_options as indicator;
}
const MULTIPLIERS: Simd<f64, 2> = Simd::from_array([4.0, 2.0]);
/// Returns information about the Ultimate Oscillator (ULTOSC) indicator.
///
/// # Returns
///
/// An `Info` struct containing metadata about the ULTOSC indicator.
pub const INFO: Info = Info {
    name: "ultosc",
    full_name: "Ultimate Oscillator",
    indicator_type: IndicatorType::Momentum,
    // Inputs are expected to be: high, low, close
    inputs: &["high", "low", "close"],
    // Options: short_period, medium_period, long_period
    options: &["short_period", "medium_period", "long_period"],
    outputs: &["ultosc", "tr", "bp"],
    optional_outputs: &[],
    display_groups: &[
        DisplayGroup {
            offset: None,
            id: "ultosc",
            label: "ULTOSC",
            display_type: DisplayType::Indicator,
            outputs: &["ultosc"],
        },
        DisplayGroup {
            offset: None,
            id: "tr_bp",
            label: "Buying Pressure",
            display_type: DisplayType::Indicator,
            outputs: &["tr", "bp"],
        },
    ],
};
#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
    state: State,
    periods: (usize, usize),
}
impl IndicatorState {
    pub fn new(state: State, periods: (usize, usize)) -> Self {
        Self { state, periods }
    }
}

impl TIndicatorState<3> 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 [high, low, close] = *inputs;
        let (mut ultosc_line, (mut tr_line, mut bp_line)) = {
            let len = high.len();
            (
                crate::uninit_vec!(f64, inputs[0].len()),
                crate::init_optional_outputs_eff!(
                    optional_outputs, &[false, false],
                    tr_line: len,
                    bp_line: len
                ),
            )
        };

        cycle(
            high,
            low,
            close,
            self.periods,
            &mut self.state,
            &mut ultosc_line,
            (&mut tr_line, &mut bp_line),
        );

        Ok(vec![ultosc_line, tr_line, bp_line])
    }
}
#[derive(Serialize, Deserialize)]
pub struct State {
    pub buffer: Buffer<2>,

    #[serde(
        serialize_with = "serialize_f64x2",
        deserialize_with = "deserialize_f64x2"
    )]
    pub bp_sums_2x: Simd<f64, 2>,

    #[serde(
        serialize_with = "serialize_f64x2",
        deserialize_with = "deserialize_f64x2"
    )]
    pub tr_sums_2x: Simd<f64, 2>,
    pub bp_long_sum: f64,
    pub tr_long_sum: f64,
    pub prev_close: f64,
}
// Custom serialization functions
fn serialize_f64x2<S>(data: &Simd<f64, 2>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    data.to_array().serialize(serializer)
}

fn deserialize_f64x2<'de, D>(deserializer: D) -> Result<Simd<f64, 2>, D::Error>
where
    D: Deserializer<'de>,
{
    let array = <[f64; 2]>::deserialize(deserializer)?;
    Ok(Simd::from_array(array))
}

impl State {
    pub fn new(long_period: usize, prev_close: f64) -> Self {
        Self {
            buffer: Buffer::new(long_period),
            bp_long_sum: 0.0,
            bp_sums_2x: Simd::<f64, 2>::splat(0.0),
            tr_long_sum: 0.0,
            tr_sums_2x: Simd::<f64, 2>::splat(0.0),
            prev_close,
        }
    }
    pub fn init_state(
        high: &[f64],
        low: &[f64],
        close: &[f64],
        periods: (usize, usize, usize),
        ultosc_line: &mut [f64],
        tr_line: &mut [f64],
        bp_line: &mut [f64],
    ) -> Self {
        let long_period = periods.2;
        let mut state = Self::new(long_period, close[0]);
        let (has_optional, want_tr, want_bp) = crate::calc_want_flags!(tr_line, bp_line);
        for (i, ((high_val, low_val), close_val)) in high
            .iter()
            .zip(low.iter())
            .zip(close.iter())
            .enumerate()
            .skip(1)
            .take(long_period)
        {
            let (ult, tr, bp) = state.calc(high_val, low_val, close_val, (periods.0, periods.1));
            if i == long_period {
                ultosc_line[0] = ult;
            }
            if has_optional {
                crate::store_optional_outputs!(i-1,
                    want_tr, tr_line => tr,
                    want_bp, bp_line => bp
                );
            }
        }
        state
    }

    #[inline(always)]
    pub fn calc(
        &mut self,
        high: &f64,
        low: &f64,
        close: &f64,
        periods: (usize, usize),
    ) -> (f64, f64, f64) {
        const DIV: f64 = 100.0 / 7.0;
        let (short_period, medium_period) = periods;

        let true_low = low.min(self.prev_close);
        let true_high = high.max(self.prev_close);
        let bp = close - true_low;
        let tr = true_high - true_low;

        if let Some([old_bp, old_tr]) = self.buffer.push_with_info([bp, tr]) {
            self.bp_long_sum += bp - old_bp;
            self.tr_long_sum += tr - old_tr;
        } else {
            self.bp_long_sum += bp;
            self.tr_long_sum += tr;
        }

        let (bp_x2, tr_x2) = (Simd::<f64, 2>::splat(bp), Simd::<f64, 2>::splat(tr));
        let (bp_r, tr_r) = {
            let [bp, tr] = self
                .buffer
                .get_by_periods::<2>([short_period, medium_period]);
            (
                Simd::<f64, 2>::from_array(bp),
                Simd::<f64, 2>::from_array(tr),
            )
        };

        self.bp_sums_2x += bp_x2 - bp_r;
        self.tr_sums_2x += tr_x2 - tr_r;
        self.prev_close = *close;

        if self.buffer.is_full() {
            let weight_sum = (MULTIPLIERS * self.bp_sums_2x / self.tr_sums_2x).reduce_sum();

            let third = self.bp_long_sum / self.tr_long_sum;
            return (((weight_sum + third) * DIV), tr, bp);
        }
        (0.0, tr, bp)
    }
    #[inline(always)]
    pub unsafe fn calc_unchecked(
        &mut self,
        high: f64,
        low: f64,
        close: f64,
        periods: (usize, usize),
    ) -> (f64, f64, f64) {
        const DIV: f64 = 100.0 / 7.0;

        let (short_period, medium_period) = periods;
        let true_low = low.min(self.prev_close);
        let true_high = high.max(self.prev_close);
        let bp = close - true_low;
        let tr = true_high - true_low;

        let [old_bp, old_tr] = self.buffer.push_with_info_unchecked([bp, tr]);
        self.bp_long_sum += bp - old_bp;
        self.tr_long_sum += tr - old_tr;

        let (bp_x2, tr_x2) = (Simd::<f64, 2>::splat(bp), Simd::<f64, 2>::splat(tr));
        let (bp_r, tr_r) = {
            let [bp, tr] = self
                .buffer
                .get_by_periods::<2>([short_period, medium_period]);
            (
                Simd::<f64, 2>::from_array(bp),
                Simd::<f64, 2>::from_array(tr),
            )
        };

        self.bp_sums_2x += bp_x2 - bp_r;
        self.tr_sums_2x += tr_x2 - tr_r;

        let weight_sum = (MULTIPLIERS * self.bp_sums_2x / self.tr_sums_2x).reduce_sum();
        //let weight_sum = first_second.reduce_add();
        let third = self.bp_long_sum / self.tr_long_sum;
        self.prev_close = close;
        (((weight_sum + third) * DIV), tr, bp)
    }
}
/// Returns the minimum amount of data required for the ULTOSC indicator.
///
/// # Arguments
///
/// * `options` - A slice containing `[short_period, medium_period, long_period]` for the ULTOSC calculation.
///
/// # Returns
///
/// The minimum amount of data required.
pub fn min_data(options: &[f64]) -> usize {
    options[2] as usize + 1
}
/// Calculates the output length based on the data length and options.
///
/// # Arguments
///
/// * `data_len` - The length of the input data.
/// * `options` - A slice containing the options for the ULTOSC calculation.
///
/// # Returns
///
/// The output length.
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
    data_len - min_data(options) + 1
}
pub(crate) fn validate_options(options: &[f64; OPTIONS_WIDTH]) -> Result<(), IndicatorError> {
    if options[0] < 1.0 || options[1] < options[0] || options[2] < options[1] {
        return Err(IndicatorError::InvalidOptions);
    }
    Ok(())
}
/// Calculates the Ultimate Oscillator (ULTOSC) indicator over the full input dataset.
///
/// # Inputs
///
/// * `inputs[0]` — high prices
/// * `inputs[1]` — low prices
/// * `inputs[2]` — close prices
///
/// # Options
///
/// * `options[0]` — short_period
/// * `options[1]` — medium_period
/// * `options[2]` — long_period
///
/// # Arguments
///
/// * `inputs` - Array of input price slices (see Inputs above).
/// * `options` - Array of indicator options (see Options above).
/// * `_optional_outputs` - Unused; ULTOSC has no optional outputs.
///
/// # Returns
///
/// `Ok((outputs, state))` where `outputs[0]` is `ultosc` and
/// `state` can be passed to `IndicatorState::batch_indicator` for streaming.
/// Returns `Err(IndicatorError)` if inputs are too short or options are invalid.
pub fn indicator(
    inputs: &[&[f64]; INPUTS_WIDTH],
    options: &[f64; OPTIONS_WIDTH],
    optional_outputs: Option<&[bool]>,
) -> Result<(Vec<Vec<f64>>, IndicatorState), IndicatorError> {
    validate_options(options)?;
    let periods = (
        options[0] as usize,
        options[1] as usize,
        options[2] as usize,
    );

    validate_inputs(inputs, min_data(options))?;
    let [high, low, close] = inputs;

    let (mut ultosc_line, (mut tr_line, mut bp_line)) = {
        let capacity = output_length(high.len(), options);
        let tr_capacity = tr_output_length(high.len(), options);
        (
            crate::uninit_vec!(f64, capacity),
            crate::init_optional_outputs_eff!(
                optional_outputs, &[false, false],
                tr_line: tr_capacity,
                bp_line: tr_capacity
            ),
        )
    };

    let mut state = State::init_state(
        high,
        low,
        close,
        periods,
        &mut ultosc_line,
        &mut tr_line,
        &mut bp_line,
    );
    let (tr, bp) = {
        let mut offset = crate::slice_outputs_start!(ultosc_line.len(), tr_line);
        if offset > 0 {
            offset += 1;
        }
        (&mut tr_line[offset..], &mut bp_line[offset..])
    };
    // Single-pass calculation loop.
    cycle(
        &high[periods.2 + 1..],
        &low[periods.2 + 1..],
        &close[periods.2 + 1..],
        (periods.0, periods.1),
        &mut state,
        &mut ultosc_line[1..],
        (tr, bp),
    );

    Ok((
        vec![ultosc_line, tr_line, bp_line],
        IndicatorState {
            periods: (periods.0, periods.1),
            state,
        },
    ))
}

/// Performs the main calculation loop for the ULTOSC indicator.
///
/// # Arguments
///
/// * `high` - A slice of high prices.
/// * `low` - A slice of low prices.
/// * `close` - A slice of close prices.
/// * `periods` - A tuple `(short_period, medium_period)` used for the weighted sums.
/// * `state` - A mutable reference to the current indicator state.
/// * `ultosc_line` - A mutable slice for storing the ULTOSC output values.
fn cycle(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    periods: (usize, usize),
    state: &mut State,
    ultosc_line: &mut [f64],
    optional_outputs: (&mut [f64], &mut [f64]),
) {
    let (tr_line, bp_line) = optional_outputs;
    let (has_optional, want_tr, want_bp) = crate::calc_want_flags!(tr_line, bp_line);

    for i in 0..high.len() {
        let (ultosc, tr, bp);
        unsafe {
            (ultosc, tr, bp) = state.calc_unchecked(
                *high.get_unchecked(i),
                *low.get_unchecked(i),
                *close.get_unchecked(i),
                periods,
            );
            *ultosc_line.get_unchecked_mut(i) = ultosc;
        }
        if has_optional {
            crate::store_optional_outputs!(i,
                want_tr, tr_line => tr,
                want_bp, bp_line => bp
            );
        }
    }
}