mylittleindicators 0.1.8

Multi-stream financial indicators library — 556 bar indicators + 21 event primitives across 35 categories. Consumes 27 stream kinds from digdigdig3 exchange connectors: OHLCV bars, ticks, orderbook (snapshot/delta/L3), funding/predicted funding/funding settlement, mark price, index price, open interest, liquidations, ticker, agg trades, long/short ratio, option greeks, volatility index, historical volatility, basis (derived), composite index, settlement events, block trades, insurance fund, risk limit, market warning, and three kline-family variants. Live-verified on 12 exchanges (89% pass-rate on a 150s BTC slice).
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
// Logic Gates for combining indicator signals
//
// Self-contained versions: use two internal RSIs with different periods
// - RSI(7) for short-term momentum
// - RSI(21) for medium-term momentum
// AND: Both overbought/oversold
// OR: Either overbought/oversold
// XOR: Divergence between short and medium term
// SignCombiner: Sum of signal directions

use crate::bar_indicators::indicator_value::IndicatorValue;
use crate::bar_indicators::momentum::rsi::Rsi;

/// AND Gate: Returns true when both RSIs agree on overbought (>70) or oversold (<30)
#[derive(Clone)]
pub struct AndGate {
    rsi_short: Rsi,
    rsi_long: Rsi,
    pub v: bool,
}
impl Default for AndGate {
    fn default() -> Self {
        Self::new()
    }
}

impl AndGate {
    /// Default: rsi_short_period=7, rsi_long_period=21.
    pub fn new() -> Self {
        Self::with_periods(7, 21)
    }

    /// Configurable RSI periods. `short_period` < `long_period` recommended.
    pub fn with_periods(short_period: usize, long_period: usize) -> Self {
        Self {
            rsi_short: Rsi::new(short_period),
            rsi_long: Rsi::new(long_period),
            v: false,
        }
    }

    pub fn update_bar(&mut self, open: f64, high: f64, low: f64, close: f64, volume: f64) -> bool {
        self.rsi_short.update_bar(open, high, low, close, volume);
        self.rsi_long.update_bar(open, high, low, close, volume);

        if self.is_ready() {
            let short_val = self.rsi_short.value().main();
            let long_val = self.rsi_long.value().main();
            // Both overbought OR both oversold
            self.v = (short_val > 70.0 && long_val > 70.0) || (short_val < 30.0 && long_val < 30.0);
        }
        self.v
    }

    pub fn update(&mut self, a: bool, b: bool) -> bool {
        self.v = a && b;
        self.v
    }

    pub fn value(&self) -> bool {
        self.v
    }

    #[inline]
    pub fn is_ready(&self) -> bool {
        self.rsi_short.is_ready() && self.rsi_long.is_ready()
    }

    pub fn reset(&mut self) {
        self.rsi_short.reset();
        self.rsi_long.reset();
        self.v = false;
    }
}

/// OR Gate: Returns true when either RSI is overbought (>70) or oversold (<30)
#[derive(Clone)]
pub struct OrGate {
    rsi_short: Rsi,
    rsi_long: Rsi,
    pub v: bool,
}
impl Default for OrGate {
    fn default() -> Self {
        Self::new()
    }
}

impl OrGate {
    /// Default: rsi_short_period=7, rsi_long_period=21.
    pub fn new() -> Self {
        Self::with_periods(7, 21)
    }

    /// Configurable RSI periods. `short_period` < `long_period` recommended.
    pub fn with_periods(short_period: usize, long_period: usize) -> Self {
        Self {
            rsi_short: Rsi::new(short_period),
            rsi_long: Rsi::new(long_period),
            v: false,
        }
    }

    pub fn update_bar(&mut self, open: f64, high: f64, low: f64, close: f64, volume: f64) -> bool {
        self.rsi_short.update_bar(open, high, low, close, volume);
        self.rsi_long.update_bar(open, high, low, close, volume);

        if self.is_ready() {
            let short_val = self.rsi_short.value().main();
            let long_val = self.rsi_long.value().main();
            // Either is extreme
            self.v = !(30.0..=70.0).contains(&short_val) || !(30.0..=70.0).contains(&long_val);
        }
        self.v
    }

    pub fn update(&mut self, a: bool, b: bool) -> bool {
        self.v = a || b;
        self.v
    }

    pub fn value(&self) -> bool {
        self.v
    }

    #[inline]
    pub fn is_ready(&self) -> bool {
        self.rsi_short.is_ready() && self.rsi_long.is_ready()
    }

    pub fn reset(&mut self) {
        self.rsi_short.reset();
        self.rsi_long.reset();
        self.v = false;
    }
}

/// XOR Gate: Returns true when RSIs disagree (divergence)
/// True when one is overbought and other is not, or one is oversold and other is not
#[derive(Clone)]
pub struct XorGate {
    rsi_short: Rsi,
    rsi_long: Rsi,
    pub v: bool,
}
impl Default for XorGate {
    fn default() -> Self {
        Self::new()
    }
}

impl XorGate {
    /// Default: rsi_short_period=7, rsi_long_period=21.
    pub fn new() -> Self {
        Self::with_periods(7, 21)
    }

    /// Configurable RSI periods. `short_period` < `long_period` recommended.
    pub fn with_periods(short_period: usize, long_period: usize) -> Self {
        Self {
            rsi_short: Rsi::new(short_period),
            rsi_long: Rsi::new(long_period),
            v: false,
        }
    }

    pub fn update_bar(&mut self, open: f64, high: f64, low: f64, close: f64, volume: f64) -> bool {
        self.rsi_short.update_bar(open, high, low, close, volume);
        self.rsi_long.update_bar(open, high, low, close, volume);

        if self.is_ready() {
            let short_val = self.rsi_short.value().main();
            let long_val = self.rsi_long.value().main();
            let short_extreme = !(30.0..=70.0).contains(&short_val);
            let long_extreme = !(30.0..=70.0).contains(&long_val);
            // XOR: exactly one is extreme (divergence)
            self.v = short_extreme ^ long_extreme;
        }
        self.v
    }

    pub fn update(&mut self, a: bool, b: bool) -> bool {
        self.v = a ^ b;
        self.v
    }

    pub fn value(&self) -> bool {
        self.v
    }

    #[inline]
    pub fn is_ready(&self) -> bool {
        self.rsi_short.is_ready() && self.rsi_long.is_ready()
    }

    pub fn reset(&mut self) {
        self.rsi_short.reset();
        self.rsi_long.reset();
        self.v = false;
    }
}

/// SignCombiner: Combines RSI signals into {-1, 0, 1}
/// +1 if both bullish (RSI < 30), -1 if both bearish (RSI > 70), 0 otherwise
#[derive(Clone)]
pub struct SignCombiner {
    rsi_short: Rsi,
    rsi_long: Rsi,
    pub s: i8,
}
impl Default for SignCombiner {
    fn default() -> Self {
        Self::new()
    }
}

impl SignCombiner {
    /// Default: rsi_short_period=7, rsi_long_period=21.
    pub fn new() -> Self {
        Self::with_periods(7, 21)
    }

    /// Configurable RSI periods. `short_period` < `long_period` recommended.
    pub fn with_periods(short_period: usize, long_period: usize) -> Self {
        Self {
            rsi_short: Rsi::new(short_period),
            rsi_long: Rsi::new(long_period),
            s: 0,
        }
    }

    pub fn update_bar(&mut self, open: f64, high: f64, low: f64, close: f64, volume: f64) -> i8 {
        self.rsi_short.update_bar(open, high, low, close, volume);
        self.rsi_long.update_bar(open, high, low, close, volume);

        if self.is_ready() {
            let short_val = self.rsi_short.value().main();
            let long_val = self.rsi_long.value().main();

            // Convert to signals: +1 bullish (oversold), -1 bearish (overbought), 0 neutral
            let short_sig: i8 = if short_val < 30.0 { 1 } else if short_val > 70.0 { -1 } else { 0 };
            let long_sig: i8 = if long_val < 30.0 { 1 } else if long_val > 70.0 { -1 } else { 0 };

            // Combine signals
            self.s = (short_sig + long_sig).clamp(-1, 1);
        }
        self.s
    }

    pub fn update(&mut self, a: i8, b: i8) -> i8 {
        self.s = a.saturating_add(b).clamp(-1, 1);
        self.s
    }

    pub fn value(&self) -> IndicatorValue {
        IndicatorValue::Signal(self.s)
    }

    #[inline]
    pub fn is_ready(&self) -> bool {
        self.rsi_short.is_ready() && self.rsi_long.is_ready()
    }

    pub fn reset(&mut self) {
        self.rsi_short.reset();
        self.rsi_long.reset();
        self.s = 0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_logic_gates_with_periods() {
        // Verify richer ctor builds, warms up, and produces finite output for all 4 structs
        let mut and = AndGate::with_periods(5, 14);
        let mut or = OrGate::with_periods(5, 14);
        let mut xor = XorGate::with_periods(5, 14);
        let mut sc = SignCombiner::with_periods(5, 14);
        let mut price = 100.0;
        for _ in 0..30 {
            price += 1.5;
            and.update_bar(price - 0.5, price + 0.5, price - 0.5, price, 1000.0);
            or.update_bar(price - 0.5, price + 0.5, price - 0.5, price, 1000.0);
            xor.update_bar(price - 0.5, price + 0.5, price - 0.5, price, 1000.0);
            sc.update_bar(price - 0.5, price + 0.5, price - 0.5, price, 1000.0);
        }
        assert!(and.is_ready());
        assert!(or.is_ready());
        assert!(xor.is_ready());
        assert!(sc.is_ready());
        assert!(sc.value().as_signal().unwrap().abs() <= 1);
    }

    #[test]
    fn test_and_gate_legacy() {
        let mut gate = AndGate::new();
        // Legacy update method still works
        assert!(!gate.update(true, false));
        assert!(!gate.update(false, true));
        assert!(gate.update(true, true));
        assert!(!gate.update(false, false));

        gate.reset();
        assert!(!gate.value());
    }

    #[test]
    fn test_and_gate_with_data() {
        let mut gate = AndGate::new();
        assert!(!gate.is_ready()); // Needs warmup

        // Feed price data to warm up internal RSIs
        let mut price = 100.0;
        for _ in 0..30 {
            price += 0.5;
            gate.update_bar(price - 0.2, price + 0.3, price - 0.3, price, 1000.0);
        }
        assert!(gate.is_ready());
    }

    #[test]
    fn test_or_gate_legacy() {
        let mut gate = OrGate::new();
        assert!(gate.update(true, false));
        assert!(gate.update(false, true));
        assert!(gate.update(true, true));
        assert!(!gate.update(false, false));

        gate.reset();
        assert!(!gate.value());
    }

    #[test]
    fn test_or_gate_with_data() {
        let mut gate = OrGate::new();

        let mut price = 100.0;
        for _ in 0..30 {
            price += 0.5;
            gate.update_bar(price - 0.2, price + 0.3, price - 0.3, price, 1000.0);
        }
        assert!(gate.is_ready());
    }

    #[test]
    fn test_xor_gate_legacy() {
        let mut gate = XorGate::new();
        assert!(gate.update(true, false));
        assert!(gate.update(false, true));
        assert!(!gate.update(true, true));
        assert!(!gate.update(false, false));

        gate.reset();
        assert!(!gate.value());
    }

    #[test]
    fn test_xor_gate_with_divergence() {
        // XOR needs short RSI in extreme but long RSI neutral
        // Key: warmup with oscillating prices to get RSI near 50, then spike

        let mut rsi_short = Rsi::new(7);
        let mut rsi_long = Rsi::new(21);

        // Warmup with oscillating prices (up/down) to get RSI near 50
        let mut price = 100.0;
        for i in 0..30 {
            // Alternate up/down to balance gains and losses
            if i % 2 == 0 {
                price += 1.0;
            } else {
                price -= 1.0;
            }
            rsi_short.update_bar(price - 0.5, price + 0.5, price - 0.5, price, 1000.0);
            rsi_long.update_bar(price - 0.5, price + 0.5, price - 0.5, price, 1000.0);
        }

        // Both RSIs should be near 50 now
        eprintln!("After warmup: short={:.1}, long={:.1}",
            rsi_short.value().main(), rsi_long.value().main());

        // Sharp upward spike - 7 consecutive gains
        let mut any_divergence = false;
        for i in 0..10 {
            price += 3.0; // Strong up move
            rsi_short.update_bar(price - 1.0, price + 1.0, price - 1.5, price, 1000.0);
            rsi_long.update_bar(price - 1.0, price + 1.0, price - 1.5, price, 1000.0);

            let short_val = rsi_short.value().main();
            let long_val = rsi_long.value().main();
            let short_extreme = short_val > 70.0 || short_val < 30.0;
            let long_extreme = long_val > 70.0 || long_val < 30.0;

            eprintln!("Bar {}: short={:.1}, long={:.1}, xor={}",
                i, short_val, long_val, short_extreme ^ long_extreme);

            if short_extreme ^ long_extreme {
                any_divergence = true;
            }
        }

        // XOR should fire when short RSI hits extreme before long RSI does
        assert!(any_divergence, "XOR should detect divergence during sharp spike");
    }

    #[test]
    fn test_sign_combiner_legacy() {
        let mut sc = SignCombiner::new();
        // Legacy update method still works
        assert_eq!(sc.update(1, 0), 1);
        assert_eq!(sc.update(-1, 0), -1);
        assert_eq!(sc.update(1, 1), 1);  // clamped to 1
        assert_eq!(sc.update(-1, -1), -1);  // clamped to -1
        assert_eq!(sc.update(1, -1), 0);

        sc.reset();
        assert_eq!(sc.value().as_signal(), Some(0));
    }
}