use crate::error::{Error, Result};
use crate::indicators::ema::Ema;
use crate::indicators::heikin_ashi::HeikinAshi;
use crate::ohlcv::Candle;
use crate::traits::Indicator;
#[derive(Debug, Clone)]
pub struct HeikinAshiOscillator {
period: usize,
ha: HeikinAshi,
ema: Ema,
last: Option<f64>,
}
impl HeikinAshiOscillator {
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if period > crate::error::MAX_PERIOD {
return Err(Error::InvalidPeriod {
message: crate::error::PERIOD_ABOVE_MAX,
});
}
Ok(Self {
period,
ha: HeikinAshi::new(),
ema: Ema::new(period)?,
last: None,
})
}
pub const fn period(&self) -> usize {
self.period
}
pub const fn value(&self) -> Option<f64> {
self.last
}
}
impl Indicator for HeikinAshiOscillator {
type Input = Candle;
type Output = f64;
#[inline]
fn update(&mut self, candle: Candle) -> Option<f64> {
let ha = self.ha.update(candle).expect("HeikinAshi emits every bar");
let body = ha.close - ha.open;
let v = self.ema.update(body)?;
self.last = Some(v);
Some(v)
}
fn reset(&mut self) {
self.ha.reset();
self.ema.reset();
self.last = None;
}
#[inline]
fn warmup_period(&self) -> usize {
self.period
}
#[inline]
fn is_ready(&self) -> bool {
self.last.is_some()
}
#[inline]
fn name(&self) -> &'static str {
"HeikinAshiOscillator"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(open: f64, high: f64, low: f64, close: f64) -> Candle {
Candle::new_unchecked(open, high, low, close, 1_000.0, 0)
}
#[test]
fn rejects_zero_period() {
assert!(matches!(
HeikinAshiOscillator::new(0),
Err(Error::PeriodZero)
));
}
#[test]
fn accessors_and_metadata() {
let h = HeikinAshiOscillator::new(5).unwrap();
assert_eq!(h.period(), 5);
assert_eq!(h.warmup_period(), 5);
assert_eq!(h.name(), "HeikinAshiOscillator");
assert!(!h.is_ready());
assert_eq!(h.value(), None);
}
#[test]
fn first_emission_at_warmup_period() {
let mut h = HeikinAshiOscillator::new(3).unwrap();
let candles: Vec<Candle> = (0..6)
.map(|i| {
let b = 100.0 + f64::from(i);
c(b, b + 1.0, b - 1.0, b + 0.5)
})
.collect();
let out = h.batch(&candles);
for v in out.iter().take(2) {
assert!(v.is_none());
}
assert!(out[2].is_some());
}
#[test]
fn uptrend_is_positive() {
let mut h = HeikinAshiOscillator::new(3).unwrap();
let candles: Vec<Candle> = (0..40)
.map(|i| {
let b = 100.0 + 2.0 * f64::from(i);
c(b, b + 1.0, b - 1.0, b + 1.5)
})
.collect();
let last = h.batch(&candles).into_iter().flatten().last().unwrap();
assert!(
last > 0.0,
"uptrend should give a positive HA body, got {last}"
);
}
#[test]
fn downtrend_is_negative() {
let mut h = HeikinAshiOscillator::new(3).unwrap();
let candles: Vec<Candle> = (0..40)
.map(|i| {
let b = 200.0 - 2.0 * f64::from(i);
c(b, b + 1.0, b - 1.0, b - 1.5)
})
.collect();
let last = h.batch(&candles).into_iter().flatten().last().unwrap();
assert!(
last < 0.0,
"downtrend should give a negative HA body, got {last}"
);
}
#[test]
fn flat_market_near_zero() {
let mut h = HeikinAshiOscillator::new(3).unwrap();
let last = h
.batch(&[c(100.0, 100.5, 99.5, 100.0); 30])
.into_iter()
.flatten()
.last()
.unwrap();
assert_relative_eq!(last, 0.0, epsilon = 1e-9);
}
#[test]
fn reset_clears_state() {
let mut h = HeikinAshiOscillator::new(3).unwrap();
h.batch(
&(0..10)
.map(|i| {
let b = 100.0 + f64::from(i);
c(b, b + 1.0, b - 1.0, b)
})
.collect::<Vec<_>>(),
);
assert!(h.is_ready());
h.reset();
assert!(!h.is_ready());
assert_eq!(h.value(), None);
assert_eq!(h.update(c(100.0, 101.0, 99.0, 100.0)), None);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..80)
.map(|i| {
let b = 100.0 + (f64::from(i) * 0.25).sin() * 9.0;
c(b, b + 1.0, b - 1.0, b + 0.3)
})
.collect();
let batch = HeikinAshiOscillator::new(5).unwrap().batch(&candles);
let mut b = HeikinAshiOscillator::new(5).unwrap();
let streamed: Vec<_> = candles.iter().map(|x| b.update(*x)).collect();
assert_eq!(batch, streamed);
}
}