rsta 0.1.0

Technical analysis indicators, streaming signals, and a single-asset backtesting engine for Rust
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use crate::indicators::utils::{validate_data_length, validate_period};
use crate::indicators::{Candle, Indicator, IndicatorError};
use std::collections::VecDeque;

/// Volume Rate of Change indicator
///
/// Volume Rate of Change measures the percentage change in volume over a given period.
/// This can be used to confirm price movements and identify potential reversals.
///
/// # Example
///
/// ```
/// use rsta::indicators::volume::Vroc;
/// use rsta::indicators::Indicator;
/// use rsta::indicators::Candle;
///
/// // Create a 14-period Volume Rate of Change indicator
/// let mut vroc = Vroc::new(14).unwrap();
///
/// // Create price data with volume values (need at least 15 candles for a 14-period calculation)
/// let candles = vec![
///     // Initial period (baseline volume)
///     Candle { timestamp: 1, open: 42.0, high: 43.0, low: 41.0, close: 42.5, volume: 1000.0 },
///     // Increasing volume trend
///     Candle { timestamp: 2, open: 42.5, high: 43.5, low: 41.5, close: 43.0, volume: 1050.0 },
///     Candle { timestamp: 3, open: 43.0, high: 44.0, low: 42.0, close: 43.5, volume: 1100.0 },
///     Candle { timestamp: 4, open: 43.5, high: 44.5, low: 42.5, close: 44.0, volume: 1200.0 },
///     Candle { timestamp: 5, open: 44.0, high: 45.0, low: 43.0, close: 44.5, volume: 1300.0 },
///     // Stable volume period
///     Candle { timestamp: 6, open: 44.5, high: 45.5, low: 43.5, close: 45.0, volume: 1320.0 },
///     Candle { timestamp: 7, open: 45.0, high: 46.0, low: 44.0, close: 45.5, volume: 1310.0 },
///     Candle { timestamp: 8, open: 45.5, high: 46.5, low: 44.5, close: 46.0, volume: 1330.0 },
///     // Volume surge (potential breakout)
///     Candle { timestamp: 9, open: 46.0, high: 47.0, low: 45.0, close: 46.8, volume: 2000.0 },
///     Candle { timestamp: 10, open: 46.8, high: 48.0, low: 46.5, close: 47.5, volume: 2200.0 },
///     // Volume declining (momentum fading)
///     Candle { timestamp: 11, open: 47.5, high: 48.0, low: 47.0, close: 47.8, volume: 1800.0 },
///     Candle { timestamp: 12, open: 47.8, high: 48.2, low: 47.2, close: 47.6, volume: 1500.0 },
///     Candle { timestamp: 13, open: 47.6, high: 48.0, low: 47.0, close: 47.4, volume: 1200.0 },
///     Candle { timestamp: 14, open: 47.4, high: 47.8, low: 46.8, close: 47.0, volume: 900.0 },
///     // Current candle (compared against first candle for 14-period calculation)
///     Candle { timestamp: 15, open: 47.0, high: 47.5, low: 46.5, close: 47.2, volume: 800.0 },
///     // Additional candle to see trend continuation
///     Candle { timestamp: 16, open: 47.2, high: 47.6, low: 46.8, close: 47.0, volume: 700.0 },
/// ];
///
/// // Calculate VROC values with error handling
/// match vroc.calculate(&candles) {
///     Ok(vroc_values) => {
///         // Access the latest VROC value
///         if let Some(latest_vroc) = vroc_values.last() {
///             println!("Volume Rate of Change: {:.2}%", latest_vroc); // Example output: -20.00%
///             
///             // Interpret the VROC value
///             if *latest_vroc > 0.0 {
///                 println!("Volume is higher than 14 periods ago");
///                 
///                 if *latest_vroc > 25.0 {
///                     println!("Significant volume increase - potential for trend continuation");
///                 } else if *latest_vroc > 10.0 {
///                     println!("Moderate volume increase - growing interest");
///                 } else {
///                     println!("Slight volume increase - maintain vigilance");
///                 }
///             } else if *latest_vroc < 0.0 {
///                 println!("Volume is lower than 14 periods ago");
///                 
///                 if *latest_vroc < -25.0 {
///                     println!("Significant volume decrease - waning interest");
///                 } else if *latest_vroc < -10.0 {
///                     println!("Moderate volume decrease - potential trend exhaustion");
///                 } else {
///                     println!("Slight volume decrease - monitor closely");
///                 }
///             } else {
///                 println!("Volume unchanged from 14 periods ago");
///             }
///             
///             // Check for volume divergence with price
///             if vroc_values.len() >= 2 {
///                 let previous_vroc = vroc_values[vroc_values.len() - 2];
///                 let current_close = candles.last().unwrap().close;
///                 let previous_close = candles[candles.len() - 2].close;
///                 
///                 // Potential bearish divergence: Price rising but volume falling
///                 if current_close > previous_close && *latest_vroc < previous_vroc {
///                     println!("Warning: Price rising but volume trend declining - potential weakness");
///                 }
///                 
///                 // Potential bullish confirmation: Price and volume both rising
///                 if current_close > previous_close && *latest_vroc > previous_vroc && *latest_vroc > 0.0 {
///                     println!("Bullish: Price and volume both increasing - strong trend confirmation");
///                 }
///             }
///         }
///     },
///     Err(e) => {
///         eprintln!("Error calculating Volume Rate of Change: {}", e);
///     }
/// }
/// ```
#[derive(Debug)]
pub struct Vroc {
    period: usize,
    volume_buffer: VecDeque<f64>,
}

impl Vroc {
    /// Create a new Vroc indicator
    ///
    /// # Arguments
    /// * `period` - The period for VROC calculation (must be at least 1)
    ///
    /// # Returns
    /// * `Result<Self, IndicatorError>` - A new Vroc or an error
    pub fn new(period: usize) -> Result<Self, IndicatorError> {
        validate_period(period, 1)?;

        Ok(Self {
            period,
            volume_buffer: VecDeque::with_capacity(period + 1),
        })
    }
}

impl Indicator<Candle, f64> for Vroc {
    fn calculate(&mut self, data: &[Candle]) -> Result<Vec<f64>, IndicatorError> {
        validate_data_length(data, self.period + 1)?;

        let n = data.len();
        let mut result = Vec::with_capacity(n - self.period);

        // Reset state
        self.reset();

        // Cannot calculate until we have period + 1 values
        for i in self.period..n {
            let current_volume = data[i].volume;
            let past_volume = data[i - self.period].volume;

            if past_volume == 0.0 {
                return Err(IndicatorError::CalculationError(
                    "Division by zero: past volume is zero".to_string(),
                ));
            }

            let vroc = (current_volume - past_volume) / past_volume * 100.0;
            result.push(vroc);
        }

        Ok(result)
    }

    fn next(&mut self, value: Candle) -> Result<Option<f64>, IndicatorError> {
        self.volume_buffer.push_back(value.volume);

        if self.volume_buffer.len() > self.period + 1 {
            self.volume_buffer.pop_front();
        }

        if self.volume_buffer.len() == self.period + 1 {
            let current_volume = self.volume_buffer.back().unwrap();
            let past_volume = self.volume_buffer.front().unwrap();

            if *past_volume == 0.0 {
                return Err(IndicatorError::CalculationError(
                    "Division by zero: past volume is zero".to_string(),
                ));
            }

            let vroc = (current_volume - past_volume) / past_volume * 100.0;
            Ok(Some(vroc))
        } else {
            Ok(None)
        }
    }

    fn reset(&mut self) {
        self.volume_buffer.clear();
    }
}

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

    // Vroc Tests
    #[test]
    fn test_vroc_new() {
        // Valid period should work
        assert!(Vroc::new(14).is_ok());

        // Invalid period should fail
        assert!(Vroc::new(0).is_err());
    }

    #[test]
    fn test_vroc_calculation() {
        let mut vroc = Vroc::new(2).unwrap();

        // Create candles with known volumes
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1500.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 900.0,
            },
        ];

        let result = vroc.calculate(&candles).unwrap();

        // We need at least period+1 candles, and we get n-period results
        assert_eq!(result.len(), 2);

        // First VROC: (1500 - 1000) / 1000 * 100 = 50%
        assert!((result[0] - 50.0).abs() < 0.01);

        // Second VROC: (900 - 1200) / 1200 * 100 = -25%
        assert!((result[1] - (-25.0)).abs() < 0.01);
    }

    #[test]
    fn test_vroc_next() {
        let mut vroc = Vroc::new(2).unwrap();

        // Initial values - not enough data yet
        let candle1 = Candle {
            timestamp: 1,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.0,
            volume: 1000.0,
        };
        assert_eq!(vroc.next(candle1).unwrap(), None);

        let candle2 = Candle {
            timestamp: 2,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.0,
            volume: 1200.0,
        };
        assert_eq!(vroc.next(candle2).unwrap(), None);

        // Third value - now we have enough data
        let candle3 = Candle {
            timestamp: 3,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.0,
            volume: 1500.0,
        };
        let result = vroc.next(candle3).unwrap();

        // VROC: (1500 - 1000) / 1000 * 100 = 50%
        assert!((result.unwrap() - 50.0).abs() < 0.01);
    }

    #[test]
    fn test_vroc_reset() {
        let mut vroc = Vroc::new(2).unwrap();

        // Add some values
        let candle1 = Candle {
            timestamp: 1,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.0,
            volume: 1000.0,
        };
        vroc.next(candle1).unwrap();
        let candle2 = Candle {
            timestamp: 2,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.0,
            volume: 1200.0,
        };
        vroc.next(candle2).unwrap();

        // Reset
        vroc.reset();

        // Volume buffer should be cleared
        let candle3 = Candle {
            timestamp: 3,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.0,
            volume: 1500.0,
        };
        assert_eq!(vroc.next(candle3).unwrap(), None);
    }

    #[test]
    fn test_vroc_past_volume_zero() {
        let mut vroc = Vroc::new(2).unwrap();

        // Create candles with zero volume at the reference point
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 0.0, // Zero volume at reference point
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1500.0,
            },
        ];

        // Should return an error for division by zero
        let result = vroc.calculate(&candles);
        assert!(result.is_err());

        // Verify it's the correct error type and message
        if let Err(IndicatorError::CalculationError(msg)) = result {
            assert!(msg.contains("division by zero") || msg.contains("zero"));
        } else {
            panic!("Expected CalculationError");
        }

        // Test with streaming calculation too
        vroc.reset();
        assert_eq!(vroc.next(candles[0]).unwrap(), None); // Not enough data yet
        assert_eq!(vroc.next(candles[1]).unwrap(), None); // Not enough data yet

        // This should error due to division by zero
        let next_result = vroc.next(candles[2]);
        assert!(next_result.is_err());

        // Verify it's the correct error type
        if let Err(IndicatorError::CalculationError(msg)) = next_result {
            assert!(msg.contains("division by zero") || msg.contains("zero"));
        } else {
            panic!("Expected CalculationError");
        }
    }

    #[test]
    fn test_vroc_minimum_period() {
        // Test with period = 1 (minimum valid period)
        let mut vroc = Vroc::new(1).unwrap();

        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1500.0,
            },
            Candle {
                timestamp: 3,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 2000.0,
            },
        ];

        let result = vroc.calculate(&candles).unwrap();

        // With period = 1, we should get n-1 results
        assert_eq!(result.len(), 2);

        // First VROC: (1500 - 1000) / 1000 * 100 = 50%
        assert!((result[0] - 50.0).abs() < 0.001);

        // Second VROC: (2000 - 1500) / 1500 * 100 = 33.33%
        assert!((result[1] - 33.33).abs() < 0.01);
    }

    #[test]
    fn test_vroc_large_period() {
        // Test with period close to data length
        let data_length = 10;
        let period = data_length - 1; // Use period = 9 for data length of 10

        let mut vroc = Vroc::new(period).unwrap();

        // Create 10 candles with sequential volumes
        let mut candles = Vec::with_capacity(data_length);
        for i in 0..data_length {
            candles.push(Candle {
                timestamp: i as u64,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0 * (i + 1) as f64, // Volumes: 1000, 2000, 3000, ...
            });
        }

        let result = vroc.calculate(&candles).unwrap();

        // With period = 9 and data length = 10, we should get 1 result
        assert_eq!(result.len(), 1);

        // VROC: (10000 - 1000) / 1000 * 100 = 900%
        assert!((result[0] - 900.0).abs() < 0.001);
        // Test boundary cases with data length
        // For Vroc, we need at least period+1 data points
        // With 10 candles:
        // - period = 9 works (needs 10 data points, we have 10)
        // - period = 10 doesn't work (needs 11 data points, we only have 10)

        // Test with period = 9 (should work with 10 data points)
        let mut vroc_large = Vroc::new(9).unwrap();
        let result = vroc_large.calculate(&candles);
        assert!(result.is_ok()); // Should have enough data

        // Test with period = 10 (should fail with only 10 data points since we need period+1)
        let mut vroc_too_large = Vroc::new(10).unwrap();
        let result = vroc_too_large.calculate(&candles);
        assert!(result.is_err()); // Should not be enough data
        assert!(result.is_err()); // Should not be enough data
    }

    #[test]
    fn test_vroc_reset_streaming() {
        let mut vroc = Vroc::new(2).unwrap();

        // Create test candles
        let candles = [
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1500.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1800.0,
            },
        ];

        // Process first three candles
        vroc.next(candles[0]).unwrap();
        vroc.next(candles[1]).unwrap();
        let first_result = vroc.next(candles[2]).unwrap().unwrap();

        // Reset indicator
        vroc.reset();

        // Process the candles again in a different order
        vroc.next(candles[1]).unwrap();
        vroc.next(candles[2]).unwrap();
        let second_result = vroc.next(candles[3]).unwrap().unwrap();

        // Results should be different as we've processed different candles
        // First: (1500-1000)/1000*100 = 50%
        // Second: (1800-1200)/1200*100 = 50%
        assert_eq!(first_result, 50.0);
        assert_eq!(second_result, 50.0);

        // Now reset and verify we need to process 3 candles again
        vroc.reset();
        assert_eq!(vroc.next(candles[0]).unwrap(), None);
        assert_eq!(vroc.next(candles[1]).unwrap(), None);
        assert!(vroc.next(candles[2]).unwrap().is_some());
    }

    #[test]
    fn test_vroc_batch_vs_streaming() {
        let period = 3;
        let mut batch_vroc = Vroc::new(period).unwrap();
        let mut streaming_vroc = Vroc::new(period).unwrap();

        // Create test data
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1500.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1800.0,
            },
            Candle {
                timestamp: 5,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 2100.0,
            },
        ];

        // Calculate batch result
        let batch_result = batch_vroc.calculate(&candles).unwrap();

        // Calculate streaming result
        let mut streaming_result = Vec::new();
        for candle in &candles {
            if let Some(value) = streaming_vroc.next(*candle).unwrap() {
                streaming_result.push(value);
            }
        }

        // Compare results - they should be identical
        assert_eq!(batch_result.len(), streaming_result.len());

        for i in 0..batch_result.len() {
            assert!(
                (batch_result[i] - streaming_result[i]).abs() < 0.001,
                "Batch and streaming results differ at index {}: batch={}, streaming={}",
                i,
                batch_result[i],
                streaming_result[i]
            );
        }
    }

    #[test]
    fn test_vroc_extreme_volume_values() {
        let mut vroc = Vroc::new(2).unwrap();

        // Create candles with extreme volume values
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 100.0, // Small volume
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1_000_000_000.0, // Very large volume
            },
            Candle {
                timestamp: 3,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 5_000_000_000.0, // Extremely large volume
            },
        ];

        let result = vroc.calculate(&candles).unwrap();

        // We need at least period+1 candles, and we get n-period results
        assert_eq!(result.len(), 1);

        // VROC: (5_000_000_000.0 - 100.0) / 100.0 * 100 = 4,999,999,900%
        assert!(
            result[0] > 4_000_000_000.0,
            "Extreme VROC value not calculated correctly"
        );

        // Test with streaming calculation
        vroc.reset();
        assert_eq!(vroc.next(candles[0]).unwrap(), None); // Not enough data yet
        assert_eq!(vroc.next(candles[1]).unwrap(), None); // Not enough data yet

        let streaming_result = vroc.next(candles[2]).unwrap().unwrap();
        assert!((streaming_result - result[0]).abs() < 0.001);
    }
}