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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::core::{Error, Method, PeriodType, ValueType, OHLCV};
use crate::core::{IndicatorConfig, IndicatorInstance, IndicatorResult};
use crate::methods::{Highest, Lowest};

/// Price Channel Strategy
///
/// Calculates price channel by highest high and lowest low for last `period` candles.
///
/// ## Links
///
/// * <https://www.investopedia.com/terms/p/price-channel.asp>
///
/// # 2 values
///
/// * `Upper bound` value
///
/// Range of values is the same as the range of the source values.
///
/// * `Lower bound` value
///
/// Range of values is the same as the range of the source values.
///
/// # 1 signal
///
/// When current `high` price touches `upper bound`, returns full buy signal.
/// When current `low` price touches `lower bound`, returns full sell signal.
/// When both touches occure, or no toucher, then returns no signal.
///
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PriceChannelStrategy {
	/// Main period length. Default is `20`.
	///
	/// Range in \[`2`; [`PeriodType::MAX`](crate::core::PeriodType)\)
	pub period: PeriodType,

	/// Relative channel size. Default is `1.0`.
	///
	/// Range in \(`0.0`; `1.0`\]
	pub sigma: ValueType,
}

impl IndicatorConfig for PriceChannelStrategy {
	type Instance = PriceChannelStrategyInstance;

	const NAME: &'static str = "PriceChannelStrategy";

	fn init<T: OHLCV>(self, candle: &T) -> Result<Self::Instance, Error> {
		if !self.validate() {
			return Err(Error::WrongConfig);
		}

		let cfg = self;
		Ok(Self::Instance {
			highest: Highest::new(cfg.period, &candle.high())?,
			lowest: Lowest::new(cfg.period, &candle.low())?,
			cfg,
		})
	}

	fn validate(&self) -> bool {
		self.period > 1 && self.sigma > 0. && self.sigma <= 1.0
	}

	fn set(&mut self, name: &str, value: String) -> Result<(), Error> {
		match name {
			"period" => match value.parse() {
				Err(_) => return Err(Error::ParameterParse(name.to_string(), value.to_string())),
				Ok(value) => self.period = value,
			},
			"sigma" => match value.parse() {
				Err(_) => return Err(Error::ParameterParse(name.to_string(), value.to_string())),
				Ok(value) => self.sigma = value,
			},

			_ => {
				return Err(Error::ParameterParse(name.to_string(), value));
			}
		};

		Ok(())
	}

	fn size(&self) -> (u8, u8) {
		(2, 1)
	}
}

impl Default for PriceChannelStrategy {
	fn default() -> Self {
		Self {
			period: 20,
			sigma: 1.0,
		}
	}
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PriceChannelStrategyInstance {
	cfg: PriceChannelStrategy,

	highest: Highest,
	lowest: Lowest,
}

impl IndicatorInstance for PriceChannelStrategyInstance {
	type Config = PriceChannelStrategy;

	fn config(&self) -> &Self::Config {
		&self.cfg
	}

	fn next<T: OHLCV>(&mut self, candle: &T) -> IndicatorResult {
		let (high, low) = (candle.high(), candle.low());
		let highest = self.highest.next(&high);
		let lowest = self.lowest.next(&low);

		let middle = (highest + lowest) * 0.5;
		let delta = highest - middle;

		let upper = delta.mul_add(self.cfg.sigma, middle);
		let lower = delta.mul_add(-self.cfg.sigma, middle);

		let signal_up = (candle.high() >= upper) as i8;
		let signal_down = (candle.low() <= lower) as i8;

		let signal = signal_up - signal_down;

		IndicatorResult::new(&[upper, lower], &[signal.into()])
	}
}