use crate::error::FinError;
use crate::signals::{BarInput, Signal, SignalValue};
use rust_decimal::Decimal;
use std::collections::VecDeque;
pub struct FairValueGap {
name: String,
atr_period: usize,
atr: Option<Decimal>,
prev_close: Option<Decimal>,
bars_seen: usize,
highs: VecDeque<Decimal>,
lows: VecDeque<Decimal>,
}
impl FairValueGap {
pub fn new(name: impl Into<String>, atr_period: usize) -> Result<Self, FinError> {
if atr_period == 0 {
return Err(FinError::InvalidPeriod(atr_period));
}
Ok(Self {
name: name.into(),
atr_period,
atr: None,
prev_close: None,
bars_seen: 0,
highs: VecDeque::with_capacity(3),
lows: VecDeque::with_capacity(3),
})
}
}
impl Signal for FairValueGap {
fn name(&self) -> &str {
&self.name
}
fn period(&self) -> usize {
self.atr_period
}
fn is_ready(&self) -> bool {
self.bars_seen >= self.atr_period + 2
}
fn update(&mut self, bar: &BarInput) -> Result<SignalValue, FinError> {
let tr = bar.true_range(self.prev_close);
self.prev_close = Some(bar.close);
self.bars_seen += 1;
let period_d = Decimal::from(self.atr_period as u32);
self.atr = Some(match self.atr {
None => tr,
Some(prev) => (prev * (period_d - Decimal::ONE) + tr) / period_d,
});
self.highs.push_back(bar.high);
self.lows.push_back(bar.low);
if self.highs.len() > 3 {
self.highs.pop_front();
self.lows.pop_front();
}
if self.bars_seen < self.atr_period + 2 {
return Ok(SignalValue::Unavailable);
}
let atr = self.atr.unwrap();
if atr.is_zero() {
return Ok(SignalValue::Unavailable);
}
let high_t2 = self.highs[0];
let low_t2 = self.lows[0];
let high_t = self.highs[2];
let low_t = self.lows[2];
let gap_size = if low_t > high_t2 {
let gap = low_t - high_t2;
gap.checked_div(atr).ok_or(FinError::ArithmeticOverflow)?
} else if high_t < low_t2 {
let gap = high_t - low_t2; gap.checked_div(atr).ok_or(FinError::ArithmeticOverflow)?
} else {
Decimal::ZERO
};
Ok(SignalValue::Scalar(gap_size))
}
fn reset(&mut self) {
self.atr = None;
self.prev_close = None;
self.bars_seen = 0;
self.highs.clear();
self.lows.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ohlcv::OhlcvBar;
use crate::signals::Signal;
use crate::types::{NanoTimestamp, Price, Quantity, Symbol};
use rust_decimal_macros::dec;
fn bar(h: &str, l: &str, c: &str) -> OhlcvBar {
let hp = Price::new(h.parse().unwrap()).unwrap();
let lp = Price::new(l.parse().unwrap()).unwrap();
let cp = Price::new(c.parse().unwrap()).unwrap();
OhlcvBar {
symbol: Symbol::new("X").unwrap(),
open: lp, high: hp, low: lp, close: cp,
volume: Quantity::zero(),
ts_open: NanoTimestamp::new(0),
ts_close: NanoTimestamp::new(1),
tick_count: 1,
}
}
#[test]
fn test_fvg_invalid_period() {
assert!(FairValueGap::new("fvg", 0).is_err());
}
#[test]
fn test_fvg_unavailable_before_atr_period_plus_2() {
let mut fvg = FairValueGap::new("fvg", 3).unwrap();
for _ in 0..4 {
assert_eq!(fvg.update_bar(&bar("110", "90", "100")).unwrap(), SignalValue::Unavailable);
}
assert!(!fvg.is_ready());
}
#[test]
fn test_fvg_no_gap_gives_zero() {
let mut fvg = FairValueGap::new("fvg", 3).unwrap();
for _ in 0..6 {
fvg.update_bar(&bar("110", "90", "100")).unwrap();
}
let v = fvg.update_bar(&bar("110", "90", "100")).unwrap();
assert_eq!(v, SignalValue::Scalar(dec!(0)));
}
#[test]
fn test_fvg_bullish_gap_positive() {
let mut fvg = FairValueGap::new("fvg", 3).unwrap();
fvg.update_bar(&bar("110", "90", "100")).unwrap();
fvg.update_bar(&bar("110", "90", "100")).unwrap();
fvg.update_bar(&bar("110", "90", "100")).unwrap();
fvg.update_bar(&bar("100", "90", "95")).unwrap();
fvg.update_bar(&bar("105", "95", "100")).unwrap();
let v = fvg.update_bar(&bar("125", "115", "120")).unwrap();
if let SignalValue::Scalar(r) = v {
assert!(r > dec!(0), "bullish FVG should be positive: {r}");
} else {
panic!("expected Scalar");
}
}
#[test]
fn test_fvg_bearish_gap_negative() {
let mut fvg = FairValueGap::new("fvg", 3).unwrap();
fvg.update_bar(&bar("110", "90", "100")).unwrap();
fvg.update_bar(&bar("110", "90", "100")).unwrap();
fvg.update_bar(&bar("110", "90", "100")).unwrap();
fvg.update_bar(&bar("110", "100", "105")).unwrap();
fvg.update_bar(&bar("105", "95", "100")).unwrap();
let v = fvg.update_bar(&bar("85", "75", "80")).unwrap();
if let SignalValue::Scalar(r) = v {
assert!(r < dec!(0), "bearish FVG should be negative: {r}");
} else {
panic!("expected Scalar");
}
}
#[test]
fn test_fvg_reset() {
let mut fvg = FairValueGap::new("fvg", 3).unwrap();
for _ in 0..7 {
fvg.update_bar(&bar("110", "90", "100")).unwrap();
}
assert!(fvg.is_ready());
fvg.reset();
assert!(!fvg.is_ready());
}
#[test]
fn test_fvg_period_and_name() {
let fvg = FairValueGap::new("my_fvg", 14).unwrap();
assert_eq!(fvg.period(), 14);
assert_eq!(fvg.name(), "my_fvg");
}
}