wickra_core/indicators/
weighted_close.rs1use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6#[derive(Debug, Clone, Default)]
29pub struct WeightedClose {
30 has_emitted: bool,
31}
32
33impl WeightedClose {
34 pub const fn new() -> Self {
36 Self { has_emitted: false }
37 }
38}
39
40impl Indicator for WeightedClose {
41 type Input = Candle;
42 type Output = f64;
43
44 fn update(&mut self, candle: Candle) -> Option<f64> {
45 self.has_emitted = true;
46 Some(candle.weighted_close())
47 }
48
49 fn reset(&mut self) {
50 self.has_emitted = false;
51 }
52
53 fn warmup_period(&self) -> usize {
54 1
55 }
56
57 fn is_ready(&self) -> bool {
58 self.has_emitted
59 }
60
61 fn name(&self) -> &'static str {
62 "WeightedClose"
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69 use crate::traits::BatchExt;
70 use approx::assert_relative_eq;
71
72 fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
73 Candle::new(open, high, low, close, 1.0, ts).unwrap()
74 }
75
76 #[test]
77 fn reference_value() {
78 let mut wc = WeightedClose::new();
80 assert_relative_eq!(
81 wc.update(candle(10.0, 12.0, 8.0, 11.0, 0)).unwrap(),
82 10.5,
83 epsilon = 1e-12
84 );
85 }
86
87 #[test]
89 fn name_metadata() {
90 let wc = WeightedClose::new();
91 assert_eq!(wc.name(), "WeightedClose");
92 }
93
94 #[test]
95 fn emits_from_first_candle() {
96 let mut wc = WeightedClose::new();
97 assert_eq!(wc.warmup_period(), 1);
98 assert!(!wc.is_ready());
99 assert!(wc.update(candle(10.0, 11.0, 9.0, 10.0, 0)).is_some());
100 assert!(wc.is_ready());
101 }
102
103 #[test]
104 fn reset_clears_state() {
105 let mut wc = WeightedClose::new();
106 wc.update(candle(10.0, 11.0, 9.0, 10.0, 0));
107 assert!(wc.is_ready());
108 wc.reset();
109 assert!(!wc.is_ready());
110 }
111
112 #[test]
113 fn batch_equals_streaming() {
114 let candles: Vec<Candle> = (0..40)
115 .map(|i| {
116 let base = 100.0 + i as f64;
117 candle(base, base + 2.0, base - 2.0, base + 1.0, i)
118 })
119 .collect();
120 let mut a = WeightedClose::new();
121 let mut b = WeightedClose::new();
122 assert_eq!(
123 a.batch(&candles),
124 candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
125 );
126 }
127}