1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
use sma_rs::SMA; use ta_common::traits::Indicator; use ta_common::helpers::trend; use ta_common::fixed_queue::FixedQueue; pub struct CMO { period: u32, sma_up: SMA, sma_down: SMA, history: FixedQueue<f64>, prev: Option<f64>, } impl CMO { pub fn new(period: u32) -> CMO { Self { period, sma_up: SMA::new(period), sma_down: SMA::new(period), history: FixedQueue::new(period), prev: None, } } } impl Indicator<f64, Option<f64>> for CMO { fn next(&mut self, input: f64) -> Option<f64> { self.history.add(input); let res = match self.prev { None => None, Some(pre) => { let trend = trend(pre, input); self.sma_up.next(trend[0]); self.sma_down.next(trend[1]); return if self.history.is_full() { let up_total=self.sma_up.get_total(); let down_total=self.sma_down.get_total(); let cmo = ((up_total - down_total) / (up_total + down_total) ) as f64 * 100.0; println!("cmo:{},up_total:{},down_total:{} trendup:{} trenddown:{}", cmo, up_total, down_total, trend[0], trend[1]); Some(cmo) } else { None }; } }; self.prev = Some(input); res } fn reset(&mut self) { self.sma_down.reset(); self.history.clear(); self.sma_up.reset(); self.prev = None; } } #[cfg(test)] mod tests { use crate::CMO; use ta_common::traits::Indicator; #[test] fn it_works() { let mut cmo = CMO::new(5); assert_eq!(cmo.next(81.59), None); assert_eq!(cmo.next(81.06), None); assert_eq!(cmo.next(82.87), None); assert_eq!(cmo.next(83.00), None); assert_eq!(cmo.next(83.61), Some(79.77099236641216)); assert_eq!(cmo.next(83.15), Some(84.4117647058823)); assert_eq!(cmo.next(82.84), Some(100.0)); assert_eq!(cmo.next(83.99), Some(100.0)); assert_eq!(cmo.next(84.55), Some(100.0)); assert_eq!(cmo.next(84.36), Some(100.0)); assert_eq!(cmo.next(85.53), Some(100.0)); assert_eq!(cmo.next(86.54), Some(100.0)); assert_eq!(cmo.next(86.89), Some(100.0)); assert_eq!(cmo.next(87.77), Some(100.0)); assert_eq!(cmo.next(87.29), Some(100.0)); } }