use crate::core::{Action, Error, IndicatorResult, PeriodType, Source, ValueType, OHLCV};
use crate::prelude::*;
use crate::methods::Cross;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Example {
price: ValueType,
period: PeriodType,
source: Source,
}
impl IndicatorConfig for Example {
type Instance = ExampleInstance;
const NAME: &'static str = "Example";
fn init<T: OHLCV>(self, _candle: &T) -> Result<Self::Instance, Error> {
if !self.validate() {
return Err(Error::WrongConfig);
}
let cfg = self;
Ok(Self::Instance {
cross: Cross::default(),
last_signal: Action::None,
last_signal_position: 0,
cfg,
})
}
fn validate(&self) -> bool {
self.price > 0.0
}
fn set(&mut self, name: &str, value: String) -> Result<(), Error> {
match name {
"price" => match value.parse() {
Err(_) => return Err(Error::ParameterParse(name.to_string(), value.to_string())),
Ok(value) => self.price = value,
},
_ => {
return Err(Error::ParameterParse(name.to_string(), value));
}
};
Ok(())
}
fn size(&self) -> (u8, u8) {
(1, 2)
}
}
impl Default for Example {
fn default() -> Self {
Self {
price: 2.0,
period: 3,
source: Source::Close,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ExampleInstance {
cfg: Example,
cross: Cross,
last_signal: Action,
last_signal_position: PeriodType,
}
impl IndicatorInstance for ExampleInstance {
type Config = Example;
fn config(&self) -> &Self::Config {
&self.cfg
}
fn next<T: OHLCV>(&mut self, candle: &T) -> IndicatorResult {
let new_signal = self.cross.next(&(candle.close(), self.cfg.price));
let signal = if new_signal == Action::None {
self.last_signal = new_signal;
self.last_signal_position = 0;
new_signal
} else {
if Action::None != self.last_signal {
self.last_signal_position += 1;
if self.last_signal_position > self.cfg.period {
self.last_signal = Action::None;
}
}
self.last_signal
};
let some_other_signal = Action::from(0.5);
IndicatorResult::new(&[candle.close()], &[signal, some_other_signal])
}
}