1use std::fmt;
20
21use ferrochart_core::Chart;
22use ferrochart_core::data::{IndicatorId, SeriesId};
23
24use crate::{Builtin, Source, VwapAnchor};
25
26#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct ParamError(pub String);
29
30impl fmt::Display for ParamError {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 f.write_str(&self.0)
33 }
34}
35
36impl std::error::Error for ParamError {}
37
38impl From<String> for ParamError {
39 fn from(s: String) -> Self {
40 Self(s)
41 }
42}
43
44impl From<&str> for ParamError {
45 fn from(s: &str) -> Self {
46 Self(s.to_owned())
47 }
48}
49
50#[derive(Clone, Debug, PartialEq)]
52pub enum Error {
53 Param(ParamError),
55 Chart(ferrochart_core::Error),
57}
58
59impl fmt::Display for Error {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match self {
62 Self::Param(e) => e.fmt(f),
63 Self::Chart(e) => e.fmt(f),
64 }
65 }
66}
67
68impl std::error::Error for Error {}
69
70impl From<ParamError> for Error {
71 fn from(e: ParamError) -> Self {
72 Self::Param(e)
73 }
74}
75
76impl From<ferrochart_core::Error> for Error {
77 fn from(e: ferrochart_core::Error) -> Self {
78 Self::Chart(e)
79 }
80}
81
82#[derive(Clone, Debug, PartialEq)]
86pub enum Value {
87 Missing,
89 Number(f64),
91 Text(String),
93 Other,
95}
96
97pub const NAMES: [&str; 30] = [
100 "sma",
101 "ema",
102 "wma",
103 "hma",
104 "vwma",
105 "dema",
106 "tema",
107 "volumeMa",
108 "boll",
109 "keltner",
110 "donchian",
111 "ichimoku",
112 "sar",
113 "supertrend",
114 "vwap",
115 "macd",
116 "rsi",
117 "stoch",
118 "stochRsi",
119 "cci",
120 "willr",
121 "mfi",
122 "adx",
123 "atr",
124 "obv",
125 "cmf",
126 "roc",
127 "momentum",
128 "trix",
129 "aroon",
130];
131
132pub fn build(name: &str, get: impl Fn(&str) -> Value) -> Result<Builtin, ParamError> {
140 let camel = camel(name);
141 let name = camel.as_str();
142 let int = |key: &str, default: usize| -> Result<usize, String> {
143 match get(key) {
144 Value::Missing => Ok(default),
145 Value::Number(v) if v.fract() == 0.0 && (0.0..=1e9).contains(&v) => Ok(v as usize),
146 _ => Err(format!("'{key}' must be a non-negative integer")),
147 }
148 };
149 let num = |key: &str, default: f64| -> Result<f64, String> {
150 match get(key) {
151 Value::Missing => Ok(default),
152 Value::Number(v) if v.is_finite() => Ok(v),
153 _ => Err(format!("'{key}' must be a finite number")),
154 }
155 };
156 let source = || -> Result<Source, String> {
157 Ok(match get("source") {
158 Value::Missing => Source::Close,
159 Value::Text(s) => match s.as_str() {
160 "close" => Source::Close,
161 "open" => Source::Open,
162 "high" => Source::High,
163 "low" => Source::Low,
164 "hl2" => Source::Hl2,
165 "hlc3" => Source::Hlc3,
166 "ohlc4" => Source::Ohlc4,
167 _ => return Err(format!("unknown source '{s}'")),
168 },
169 _ => return Err("'source' must be a string".into()),
170 })
171 };
172 let r = match name {
173 "sma" => crate::sma(int("n", 20)?, source()?),
174 "ema" => crate::ema(int("n", 20)?, source()?),
175 "wma" => crate::wma(int("n", 20)?, source()?),
176 "hma" => crate::hma(int("n", 20)?, source()?),
177 "vwma" => crate::vwma(int("n", 20)?, source()?),
178 "dema" => crate::dema(int("n", 20)?, source()?),
179 "tema" => crate::tema(int("n", 20)?, source()?),
180 "volumeMa" => crate::volume_ma(int("n", 20)?),
181 "boll" => crate::boll(int("n", 20)?, num("k", 2.0)?, source()?),
182 "keltner" => crate::keltner(int("n", 20)?, num("m", 2.0)?, int("atrN", 10)?),
183 "donchian" => crate::donchian(int("n", 20)?),
184 "ichimoku" => crate::ichimoku(
185 int("tenkan", 9)?,
186 int("kijun", 26)?,
187 int("senkou", 52)?,
188 int("shift", 26)?,
189 ),
190 "sar" => crate::sar(
191 num("afStart", 0.02)?,
192 num("afStep", 0.02)?,
193 num("afMax", 0.2)?,
194 ),
195 "supertrend" => crate::supertrend(int("atrN", 10)?, num("m", 3.0)?),
196 "vwap" => {
197 let anchor = match get("anchor") {
198 Value::Missing => VwapAnchor::Day,
199 Value::Text(s) if s == "day" => VwapAnchor::Day,
200 Value::Text(s) if s == "week" => VwapAnchor::Week,
201 Value::Text(s) if s == "month" => VwapAnchor::Month,
202 Value::Number(t) if t.fract() == 0.0 && t.abs() < 9.0e15 => {
203 VwapAnchor::Time(t as i64)
204 }
205 _ => {
206 return Err("'anchor' must be 'day', 'week', 'month' or a time in ms".into());
207 }
208 };
209 let offset = num("utcOffsetMs", 0.0)?;
210 if offset.fract() != 0.0 || offset.abs() > 1e9 {
211 return Err("'utcOffsetMs' must be an integer".into());
212 }
213 crate::vwap(anchor, offset as i64)
214 }
215 "macd" => crate::macd(
216 int("fast", 12)?,
217 int("slow", 26)?,
218 int("signal", 9)?,
219 source()?,
220 ),
221 "rsi" => crate::rsi(int("n", 14)?, source()?),
222 "stoch" => crate::stoch(int("k", 14)?, int("smoothK", 3)?, int("d", 3)?),
223 "stochRsi" => crate::stochrsi(
224 int("rsiN", 14)?,
225 int("stochN", 14)?,
226 int("smoothK", 3)?,
227 int("d", 3)?,
228 source()?,
229 ),
230 "cci" => crate::cci(int("n", 20)?),
231 "willr" => crate::willr(int("n", 14)?),
232 "mfi" => crate::mfi(int("n", 14)?),
233 "adx" => crate::adx(int("n", 14)?),
234 "atr" => crate::atr(int("n", 14)?),
235 "obv" => crate::obv(),
236 "cmf" => crate::cmf(int("n", 20)?),
237 "roc" => crate::roc(int("n", 10)?, source()?),
238 "momentum" => crate::momentum(int("n", 10)?, source()?),
239 "trix" => crate::trix(int("n", 15)?, source()?),
240 "aroon" => crate::aroon(int("n", 14)?),
241 _ => return Err(ParamError(format!("unknown indicator '{name}'"))),
242 };
243 r.map_err(|e| ParamError(e.to_string()))
244}
245
246impl From<f64> for Value {
247 fn from(v: f64) -> Self {
248 Self::Number(v)
249 }
250}
251
252impl From<i32> for Value {
253 fn from(v: i32) -> Self {
254 Self::Number(f64::from(v))
255 }
256}
257
258impl From<u32> for Value {
259 fn from(v: u32) -> Self {
260 Self::Number(f64::from(v))
261 }
262}
263
264impl From<&str> for Value {
265 fn from(v: &str) -> Self {
266 Self::Text(v.to_owned())
267 }
268}
269
270fn camel(s: &str) -> String {
272 let mut out = String::with_capacity(s.len());
273 let mut up = false;
274 for c in s.chars() {
275 if c == '_' {
276 up = true;
277 } else if up {
278 out.extend(c.to_uppercase());
279 up = false;
280 } else {
281 out.push(c);
282 }
283 }
284 out
285}
286
287pub fn by_name(name: &str, params: &[(&str, Value)]) -> Result<Builtin, ParamError> {
295 build(name, |key| {
296 params
297 .iter()
298 .find(|(k, _)| *k == key || camel(k) == key)
299 .map_or(Value::Missing, |(_, v)| v.clone())
300 })
301}
302
303pub trait ChartExt {
305 fn add_indicator_by_name(
314 &mut self,
315 source: SeriesId,
316 name: &str,
317 params: &[(&str, Value)],
318 ) -> Result<IndicatorId, Error>;
319}
320
321impl ChartExt for Chart {
322 fn add_indicator_by_name(
323 &mut self,
324 source: SeriesId,
325 name: &str,
326 params: &[(&str, Value)],
327 ) -> Result<IndicatorId, Error> {
328 use ferrochart_core::plugin::Indicator as _;
329 let ind = by_name(name, params)?;
330 let placement = ind.default_placement();
331 Ok(self.add_indicator(source, Box::new(ind), placement)?)
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn names_build_with_defaults_in_both_spellings() {
341 for n in NAMES {
342 assert!(build(n, |_| Value::Missing).is_ok(), "{n}");
343 }
344 assert!(by_name("stoch_rsi", &[("rsi_n", 10.into())]).is_ok());
345 assert!(by_name("volume_ma", &[]).is_ok());
346 }
347
348 #[test]
349 fn bad_input_names_the_problem() {
350 assert_eq!(
351 by_name("nope", &[]).unwrap_err().0,
352 "unknown indicator 'nope'"
353 );
354 assert!(
355 by_name("ema", &[("n", 2.5.into())])
356 .unwrap_err()
357 .0
358 .contains("'n'")
359 );
360 assert!(by_name("ema", &[("source", "x".into())]).is_err());
361 }
362}