indicators/trend/
parabolic_sar.rs1use std::collections::HashMap;
15
16use crate::error::IndicatorError;
17use crate::indicator::{Indicator, IndicatorOutput};
18use crate::registry::param_f64;
19use crate::types::Candle;
20
21#[derive(Debug, Clone)]
22pub struct PsarParams {
23 pub step: f64,
25 pub max_step: f64,
27}
28impl Default for PsarParams {
29 fn default() -> Self {
30 Self {
31 step: 0.02,
32 max_step: 0.2,
33 }
34 }
35}
36
37#[derive(Debug, Clone)]
38pub struct ParabolicSar {
39 pub params: PsarParams,
40}
41
42impl ParabolicSar {
43 pub fn new(params: PsarParams) -> Self {
44 Self { params }
45 }
46}
47
48impl Default for ParabolicSar {
49 fn default() -> Self {
50 Self::new(PsarParams::default())
51 }
52}
53
54impl Indicator for ParabolicSar {
55 fn name(&self) -> &'static str {
56 "ParabolicSAR"
57 }
58 fn required_len(&self) -> usize {
59 2
60 }
61 fn required_columns(&self) -> &[&'static str] {
62 &["high", "low"]
63 }
64
65 fn calculate(&self, candles: &[Candle]) -> Result<IndicatorOutput, IndicatorError> {
67 self.check_len(candles)?;
68
69 let n = candles.len();
70 let step = self.params.step;
71 let max_step = self.params.max_step;
72
73 let mut sar = vec![0.0f64; n];
74 let mut trend: i8 = 1; let mut ep = candles[0].low;
76 let mut af = step;
77
78 for i in 1..n {
80 let prev_sar = sar[i - 1];
81 sar[i] = prev_sar + af * (ep - prev_sar);
82
83 if trend == 1 {
84 if candles[i].high > ep {
85 ep = candles[i].high;
86 af = (af + step).min(max_step);
87 }
88 if candles[i].low < sar[i] {
89 trend = -1;
90 sar[i] = ep;
91 ep = candles[i].low;
92 af = step;
93 }
94 } else {
95 if candles[i].low < ep {
96 ep = candles[i].low;
97 af = (af + step).min(max_step);
98 }
99 if candles[i].high > sar[i] {
100 trend = 1;
101 sar[i] = ep;
102 ep = candles[i].high;
103 af = step;
104 }
105 }
106 }
107
108 Ok(IndicatorOutput::from_pairs([("PSAR".to_string(), sar)]))
109 }
110}
111
112pub fn factory<S: ::std::hash::BuildHasher>(params: &HashMap<String, String, S>) -> Result<Box<dyn Indicator>, IndicatorError> {
113 Ok(Box::new(ParabolicSar::new(PsarParams {
114 step: param_f64(params, "step", 0.02)?,
115 max_step: param_f64(params, "max_step", 0.2)?,
116 })))
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122
123 fn candles(n: usize) -> Vec<Candle> {
124 (0..n)
125 .map(|i| Candle {
126 time: i64::try_from(i).expect("time index fits i64"),
127 open: 10.0,
128 high: 10.0 + i as f64 * 0.1,
129 low: 10.0 - i as f64 * 0.05,
130 close: 10.0,
131 volume: 100.0,
132 })
133 .collect()
134 }
135
136 #[test]
137 fn psar_output_column() {
138 let out = ParabolicSar::default().calculate(&candles(10)).unwrap();
139 assert!(out.get("PSAR").is_some());
140 }
141
142 #[test]
143 fn psar_correct_length() {
144 let bars = candles(20);
145 let out = ParabolicSar::default().calculate(&bars).unwrap();
146 assert_eq!(out.get("PSAR").unwrap().len(), 20);
147 }
148
149 #[test]
150 fn psar_af_bounded() {
151 let out = ParabolicSar::default().calculate(&candles(50)).unwrap();
153 let vals = out.get("PSAR").unwrap();
154 for &v in vals {
156 assert!(v.is_finite(), "non-finite SAR: {v}");
157 }
158 }
159
160 #[test]
161 fn factory_creates_psar() {
162 assert_eq!(factory(&HashMap::new()).unwrap().name(), "ParabolicSAR");
163 }
164}