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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Supertrend - популярный трендовый индикатор
//! Supertrend = (High + Low) / 2 ± (Multiplier × ATR)
//! Показывает динамические уровни поддержки и сопротивления
//! Очень популярен среди трейдеров для определения направления тренда

use crate::bar_indicators::volatility::atr::Atr;
use crate::bar_indicators::average::MovingAverageType;
use crate::bar_indicators::indicator_value::IndicatorValue;

/// Supertrend индикатор
#[derive(Debug, Clone)]
pub struct Supertrend {
    period: usize,
    multiplier: f64,
    
    // Буферы для расчетов
    supertrend_values: Vec<f64>,
    trend_direction: Vec<i8>,
    
    // ATR для расчета волатильности
    atr: Atr,
    
    // Текущие значения
    supertrend_value: f64,
    current_trend: i8,  // 1 = восходящий тренд, -1 = нисходящий тренд
    
    // Предыдущие значения для расчета
    prev_supertrend: f64,
    prev_trend: i8,
    
    // Состояние
    bars_count: usize,
    is_ready: bool,
}

impl Supertrend {
    /// Создать новый Supertrend с параметрами по умолчанию (10, 3.0)
    pub fn new() -> Self {
        Self::with_params(10, 3.0)
    }

    /// Создать новый Supertrend с настраиваемыми параметрами (RMA по умолчанию)
    pub fn with_params(period: usize, multiplier: f64) -> Self {
        Self::with_atr_ma_type(period, multiplier, MovingAverageType::RMA)
    }

    /// Создать Supertrend с настраиваемым типом MA для ATR
    pub fn with_atr_ma_type(period: usize, multiplier: f64, atr_ma_type: MovingAverageType) -> Self {
        assert!(period > 0, "Period must be greater than 0");
        assert!(multiplier > 0.0, "Multiplier must be greater than 0");

        Self {
            period,
            multiplier,
            supertrend_values: Vec::with_capacity(512),
            trend_direction: Vec::with_capacity(512),
            atr: Atr::new(period, atr_ma_type),
            supertrend_value: 0.0,
            current_trend: 1,
            prev_supertrend: 0.0,
            prev_trend: 1,
            bars_count: 0,
            is_ready: false,
        }
    }
    
    /// Обновить индикатор новым баром
    pub fn update_bar(&mut self, open: f64, high: f64, low: f64, close: f64, volume: f64) -> f64 {
        self.bars_count += 1;
        
        // Обновляем ATR
        let atr_value = self.atr.update_bar(open, high, low, close, volume);
        
        // Рассчитываем медианную цену (HL2)
        let hl2 = (high + low) / 2.0;
        
        // Рассчитываем базовые уровни
        let upper_band = hl2 + (self.multiplier * atr_value);
        let lower_band = hl2 - (self.multiplier * atr_value);
        
        // Рассчитываем финальные уровни с учетом предыдущих значений
        let final_upper_band = if self.bars_count == 1 {
            upper_band
        } else {
            let prev_final_upper = if !self.supertrend_values.is_empty() && self.prev_trend == 1 {
                self.prev_supertrend
            } else {
                upper_band
            };
            
            if upper_band < prev_final_upper || close > prev_final_upper {
                upper_band
            } else {
                prev_final_upper
            }
        };
        
        let final_lower_band = if self.bars_count == 1 {
            lower_band
        } else {
            let prev_final_lower = if !self.supertrend_values.is_empty() && self.prev_trend == -1 {
                self.prev_supertrend
            } else {
                lower_band
            };
            
            if lower_band > prev_final_lower || close < prev_final_lower {
                lower_band
            } else {
                prev_final_lower
            }
        };
        
        // Определяем направление тренда
        if self.bars_count == 1 {
            // Первый бар - определяем направление по позиции цены
            self.current_trend = if close <= final_upper_band { -1 } else { 1 };
        } else {
            // Определяем смену тренда
            if self.prev_trend == 1 && close <= final_lower_band {
                self.current_trend = -1;
            } else if self.prev_trend == -1 && close >= final_upper_band {
                self.current_trend = 1;
            } else {
                self.current_trend = self.prev_trend;
            }
        }
        
        // Устанавливаем значение Supertrend
        self.supertrend_value = if self.current_trend == 1 {
            final_lower_band
        } else {
            final_upper_band
        };
        
        // Добавляем в буферы
        if self.supertrend_values.len() >= 512 {
            self.supertrend_values.remove(0);
        }
        if self.trend_direction.len() >= 512 {
            self.trend_direction.remove(0);
        }
        
        self.supertrend_values.push(self.supertrend_value);
        self.trend_direction.push(self.current_trend);
        
        // Обновляем предыдущие значения
        self.prev_supertrend = self.supertrend_value;
        self.prev_trend = self.current_trend;
        
        // Проверяем готовность
        if self.bars_count >= self.period + 2 {
            self.is_ready = true;
        }
        
        self.supertrend_value
    }
    
    /// Получить значение Supertrend
    pub fn value(&self) -> IndicatorValue {
        IndicatorValue::Single(self.supertrend_value)
    }
    
    /// Получить направление тренда
    pub fn trend_direction(&self) -> i8 {
        self.current_trend
    }
    
    /// Получить значение и направление тренда
    pub fn values(&self) -> (f64, i8) {
        (self.supertrend_value, self.current_trend)
    }
    
    /// Проверить, готов ли индикатор
    pub fn is_ready(&self) -> bool {
        self.is_ready
    }
    
    /// Получить параметры индикатора
    pub fn parameters(&self) -> (usize, f64) {
        (self.period, self.multiplier)
    }
    
    /// Сбросить состояние индикатора
    pub fn reset(&mut self) {
        self.supertrend_values.clear();
        self.trend_direction.clear();
        self.atr.reset();
        self.supertrend_value = 0.0;
        self.current_trend = 1;
        self.prev_supertrend = 0.0;
        self.prev_trend = 1;
        self.bars_count = 0;
        self.is_ready = false;
    }
    
    /// Определить состояние тренда
    pub fn trend_condition(&self) -> &'static str {
        match self.current_trend {
            1 => "Uptrend",
            -1 => "Downtrend",
            _ => "Neutral"
        }
    }
    
    /// Получить торговый сигнал
    /// 1 = покупка, -1 = продажа, 0 = нейтрально
    pub fn trading_signal(&self, close: f64) -> i8 {
        if !self.is_ready() {
            return 0;
        }
        
        // Простой сигнал на основе позиции цены относительно Supertrend
        match self.current_trend {
            1 => {
                if close > self.supertrend_value {
                    1  // Покупка - цена выше Supertrend в восходящем тренде
                } else {
                    0
                }
            },
            -1 => {
                if close < self.supertrend_value {
                    -1 // Продажа - цена ниже Supertrend в нисходящем тренде
                } else {
                    0
                }
            },
            _ => 0
        }
    }
    
    /// Получить сигнал смены тренда
    pub fn trend_change_signal(&self) -> i8 {
        if !self.is_ready() || self.trend_direction.len() < 2 {
            return 0;
        }
        
        let len = self.trend_direction.len();
        let current = self.current_trend;
        let prev = self.trend_direction[len - 2];
        
        // Сигнал смены тренда
        if prev == -1 && current == 1 {
            1  // Смена на восходящий тренд
        } else if prev == 1 && current == -1 {
            -1 // Смена на нисходящий тренд
        } else {
            0  // Нет смены тренда
        }
    }
    
    /// Получить продвинутый сигнал с подтверждением
    pub fn advanced_signal(&self, close: f64, volume: f64, avg_volume: f64) -> i8 {
        if !self.is_ready() {
            return 0;
        }
        
        let basic_signal = self.trading_signal(close);
        let trend_change = self.trend_change_signal();
        
        // Подтверждение объемом
        let volume_confirmation = volume > avg_volume * 1.2;
        
        // Сильный сигнал при смене тренда с подтверждением объемом
        if trend_change != 0 && volume_confirmation {
            return trend_change;
        }
        
        // Обычный сигнал
        basic_signal
    }
    
    /// Получить расстояние до Supertrend
    pub fn distance_to_supertrend(&self, price: f64) -> f64 {
        if !self.is_ready() {
            return 0.0;
        }
        
        (price - self.supertrend_value) / self.supertrend_value * 100.0
    }
    
    /// Получить силу тренда
    pub fn trend_strength(&self, periods: usize) -> f64 {
        if !self.is_ready() || self.trend_direction.len() < periods {
            return 0.0;
        }
        
        let start_idx = self.trend_direction.len() - periods;
        let slice = &self.trend_direction[start_idx..];
        
        // Считаем процент времени в текущем тренде
        let current_trend_count = slice.iter()
            .filter(|&&x| x == self.current_trend)
            .count();
        
        current_trend_count as f64 / periods as f64 * 100.0
    }
    
    /// Получить продолжительность текущего тренда
    pub fn trend_duration(&self) -> usize {
        if !self.is_ready() || self.trend_direction.is_empty() {
            return 0;
        }
        
        let mut duration = 1;
        let current = self.current_trend;
        
        // Идем назад от текущего значения
        for i in (0..self.trend_direction.len().saturating_sub(1)).rev() {
            if self.trend_direction[i] == current {
                duration += 1;
            } else {
                break;
            }
        }
        
        duration
    }
    
    /// Получить волатильность Supertrend
    pub fn volatility(&self, periods: usize) -> f64 {
        if !self.is_ready() || self.supertrend_values.len() < periods {
            return 0.0;
        }
        
        let start_idx = self.supertrend_values.len() - periods;
        let slice = &self.supertrend_values[start_idx..];
        
        // Рассчитываем стандартное отклонение
        let mean = slice.iter().sum::<f64>() / slice.len() as f64;
        let variance = slice.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f64>() / slice.len() as f64;
        
        variance.sqrt()
    }
    
    /// Получить скорость изменения Supertrend
    pub fn rate_of_change(&self, periods: usize) -> f64 {
        if !self.is_ready() || self.supertrend_values.len() < periods + 1 {
            return 0.0;
        }
        
        let current = self.supertrend_value;
        let past = self.supertrend_values[self.supertrend_values.len() - periods - 1];
        
        if past.abs() > 1e-12 {
            (current - past) / past * 100.0
        } else {
            0.0
        }
    }
    
    /// Получить уровень поддержки/сопротивления
    pub fn support_resistance_level(&self) -> (&'static str, f64) {
        if !self.is_ready() {
            return ("Unknown", 0.0);
        }
        
        match self.current_trend {
            1 => ("Support", self.supertrend_value),
            -1 => ("Resistance", self.supertrend_value),
            _ => ("Neutral", self.supertrend_value)
        }
    }
    
    /// Получить статистику по трендам
    pub fn trend_statistics(&self, periods: usize) -> (f64, f64, usize) {
        if !self.is_ready() || self.trend_direction.len() < periods {
            return (0.0, 0.0, 0);
        }
        
        let start_idx = self.trend_direction.len() - periods;
        let slice = &self.trend_direction[start_idx..];
        
        let uptrend_count = slice.iter().filter(|&&x| x == 1).count();
        let downtrend_count = slice.iter().filter(|&&x| x == -1).count();
        
        let uptrend_percentage = uptrend_count as f64 / periods as f64 * 100.0;
        let downtrend_percentage = downtrend_count as f64 / periods as f64 * 100.0;
        
        // Количество смен тренда
        let mut trend_changes = 0;
        for i in 1..slice.len() {
            if slice[i] != slice[i - 1] {
                trend_changes += 1;
            }
        }
        
        (uptrend_percentage, downtrend_percentage, trend_changes)
    }
    
    /// Получить информацию о состоянии индикатора
    pub fn info(&self) -> String {
        let duration = self.trend_duration();
        let strength = self.trend_strength(20);
        let (level_type, level_value) = self.support_resistance_level();

        format!(
            "Supertrend: {:.2}, Trend: {}, Duration: {} bars, Strength: {:.1}%, {} Level: {:.2}",
            self.supertrend_value,
            self.trend_condition(),
            duration,
            strength,
            level_type,
            level_value
        )
    }
}

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

    #[test]
    fn test_supertrend_creation() {
        let st = Supertrend::new();
        assert!(!st.is_ready());
        assert_eq!(st.parameters(), (10, 3.0));
    }

    #[test]
    fn test_supertrend_with_ema_atr_warmup_finite() {
        let mut st = Supertrend::with_atr_ma_type(10, 3.0, MovingAverageType::EMA);
        for i in 0..25 {
            let price = 100.0 + (i as f64 * 0.2).sin() * 5.0;
            let v = st.update_bar(price, price + 2.0, price - 2.0, price, 1000.0);
            assert!(v.is_finite());
        }
        assert!(st.is_ready());
    }

    #[test]
    fn test_supertrend_with_params() {
        let st = Supertrend::with_params(14, 2.5);
        assert!(!st.is_ready());
        assert_eq!(st.parameters(), (14, 2.5));
    }

    #[test]
    fn test_supertrend_warmup() {
        let mut st = Supertrend::new();
        for i in 0..20 {
            let price = 100.0 + (i as f64 * 0.1).sin() * 5.0;
            st.update_bar(price, price + 1.0, price - 1.0, price, 1000.0);
        }
        assert!(st.is_ready());
    }

    #[test]
    fn test_supertrend_values() {
        let mut st = Supertrend::new();
        for i in 0..30 {
            let price = 100.0 + i as f64;
            let value = st.update_bar(price, price + 2.0, price - 2.0, price, 1000.0);
            assert!(value.is_finite());
        }
        let dir = st.trend_direction();
        assert!(dir == 1 || dir == -1);
    }

    #[test]
    fn test_supertrend_reset() {
        let mut st = Supertrend::new();
        for i in 0..30 {
            st.update_bar(100.0 + i as f64, 105.0, 95.0, 101.0, 1000.0);
        }
        st.reset();
        assert!(!st.is_ready());
    }
}