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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Technical analysis operations with parameter descriptors.

use rand::Rng;

use cxmr_ta_core::indicators;

use super::{impls, traits, Error, Operation};

/// Technical analysis operation parameter type alias.
pub type Param = u32;

/// Technical analysis operation parameter vector type alias.
pub type Params = Vec<Param>;

/// Technical analysis operation parameter descriptor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParamDescriptor {
    /// Step parameter.
    Step {
        /// Minimum parameter amount.
        min: Param,
        /// Maximum parameter amount.
        max: Param,
        /// Parameter step amount.
        step: Param,
    },
    /// Power parameter.
    Power {
        /// Minimum parameter amount.
        min: Param,
        /// Maximum parameter amount.
        max: Param,
        /// Parameter step power.
        power: Param,
    },
}

impl ParamDescriptor {
    /// Generates random parameter.
    pub fn rand<R: Rng>(&self, r: &mut R) -> Param {
        match self {
            ParamDescriptor::Step { min, max, step } => {
                let rand = r.gen_range(min, max);
                rand * step
            }
            ParamDescriptor::Power { min, max, power } => {
                let rand = r.gen_range(min, max);
                rand.pow(*power)
            }
        }
    }
}

#[macro_export]
macro_rules! param {
    ( $min:expr, $max:expr, $step:expr ) => {
        ParamDescriptor::Step {
            min: $min,
            max: $max,
            step: $step,
        }
    };
}

#[macro_export]
macro_rules! pow_param {
    ( $min:expr, $max:expr, $power:expr ) => {
        ParamDescriptor::Power {
            min: $min,
            max: $max,
            power: $power,
        }
    };
}

/// Indicator mode marker.
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Serialize, Deserialize)]
pub enum Marker {
    /// Rate indicator.
    Rate,
    /// Frequency indicator.
    Freq,
}

impl From<&Indicator> for Marker {
    fn from(indicator: &Indicator) -> Marker {
        match indicator {
            Indicator::FastStochastic
            | Indicator::SlowStochastic
            | Indicator::EfficiencyRatio
            | Indicator::RelativeStrengthIndex
            | Indicator::MoneyFlowIndex
            | Indicator::RateOfChange
            | Indicator::AverageTrueRange
            | Indicator::TrueRange
            | Indicator::Spread => Marker::Freq,
            _ => Marker::Rate,
        }
    }
}

/// Operation is technical analysis or orderbook method.
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Serialize, Deserialize)]
pub enum Indicator {
    /// Average true range (ATR).
    AverageTrueRange,
    /// Kaufman's Efficiency Ratio (ER).
    EfficiencyRatio,
    /// An exponential moving average (EMA), also known as an exponentially weighted moving average (EWMA).
    ExponentialMovingAverage,
    /// Fast stochastic oscillator.
    FastStochastic,
    /// Returns the highest value in a given time frame.
    Maximum,
    /// Returns the lowest value in a given time frame.
    Minimum,
    /// Money Flow Index (MFI).
    MoneyFlowIndex,
    /// On Balance Volume (OBV).
    OnBalanceVolume,
    /// Rate of Change (ROC)
    RateOfChange,
    /// The relative strength index (RSI).
    RelativeStrengthIndex,
    /// Simple moving average (SMA).
    SimpleMovingAverage,
    /// Slow stochastic oscillator.
    SlowStochastic,
    /// The range of a day's trading is simply high - low. The true range extends it to yesterday's closing price if it was outside of today's range.
    TrueRange,
    /// Spread in the orderbook.
    Spread,
    /// Moving average converge divergence (MACD).
    MovingAverageConvergenceDivergence,
    /// Closing price.
    ClosePrice,
    /// Ask rate in the orderbook.
    AskRate,
    /// Bid rate in the orderbook.
    BidRate,
    /// Market entry rate.
    EntryRate,
    /// Market exit rate.
    ExitRate,
}

/// Boxed indicator implementation.
pub type BoxIndicator<S> = Box<dyn traits::Next<S>>;

#[macro_export]
macro_rules! construct_indicator {
    ( $s:ident, $p:ident, $t:ident, $( $x:tt ), * ) => {
        {
            let params = $p.ok_or_else(|| Error::ExpectedParams($s.clone()))?;
            Box::new(indicators::$t::new(
                $(
                    $s.get_param(&params, $x)?,
                )*
            )?) as BoxIndicator<S>
        }
    };
}

#[macro_export]
macro_rules! construct_indicator_local {
    ( $s:ident, $p:ident, $t:ident, $i:expr, $( $x:tt ), * ) => {
        {
            let params = $p.ok_or_else(|| Error::ExpectedParams($s.clone()))?;
            Box::new($i(
                $(
                    $s.get_param(&params, $x)? as usize,
                )*
            )) as BoxIndicator<S>
        }
    };
}

#[macro_export]
macro_rules! construct_indicator_wrapper {
    ( $s:ident, $p:ident, $t:ident, $i:expr, $( $x:tt ), * ) => {
        {
            let params = $p.ok_or_else(|| Error::ExpectedParams($s.clone()))?;
            Box::new($i(indicators::$t::new(
                $(
                    $s.get_param(&params, $x)?,
                )*
            )?)) as BoxIndicator<S>
        }
    };
}

#[macro_export]
macro_rules! static_params {
    ( $( $x:expr ), *  ) => {
        {
            static LIST: &'static [ParamDescriptor] = &[$($x,)*];
            LIST
        }
    };
}

impl Indicator {
    /// Returns amount of expected parameters.
    pub fn parameters(&self) -> usize {
        match self {
            Indicator::ExponentialMovingAverage
            | Indicator::SimpleMovingAverage
            | Indicator::RelativeStrengthIndex
            | Indicator::FastStochastic
            | Indicator::Maximum
            | Indicator::Minimum
            | Indicator::MoneyFlowIndex
            | Indicator::AverageTrueRange
            | Indicator::EfficiencyRatio
            | Indicator::ClosePrice
            | Indicator::Spread
            | Indicator::AskRate
            | Indicator::BidRate
            | Indicator::EntryRate
            | Indicator::ExitRate
            | Indicator::RateOfChange => 1,
            Indicator::SlowStochastic => 2,
            Indicator::TrueRange | Indicator::OnBalanceVolume => 0,
            Indicator::MovingAverageConvergenceDivergence => 3,
        }
    }

    /// Returns descriptors of expected parameters.
    /// It can be `None` if doesn't expect any arguments
    pub fn descriptors(&self) -> Option<&'static [ParamDescriptor]> {
        match self {
            Indicator::MovingAverageConvergenceDivergence => Some(static_params!(
                param!(1, 4, 10),
                param!(1, 4, 20),
                param!(1, 4, 3)
            )),
            Indicator::ExponentialMovingAverage => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::SimpleMovingAverage => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::RelativeStrengthIndex => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::FastStochastic => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::SlowStochastic => {
                Some(static_params!(pow_param!(2, 8, 3), pow_param!(2, 8, 3)))
            }
            Indicator::Maximum => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::Minimum => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::MoneyFlowIndex => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::EfficiencyRatio => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::AverageTrueRange => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::RateOfChange => Some(static_params!(pow_param!(2, 8, 3))),
            Indicator::Spread => Some(static_params!(param!(0, 2, 1))),
            Indicator::AskRate => Some(static_params!(param!(0, 2, 1))),
            Indicator::BidRate => Some(static_params!(param!(0, 2, 1))),
            Indicator::EntryRate => Some(static_params!(param!(0, 2, 1))),
            Indicator::ExitRate => Some(static_params!(param!(0, 2, 1))),
            Indicator::TrueRange | Indicator::OnBalanceVolume | Indicator::ClosePrice => None,
        }
    }

    /// Constructs technical analysis operator using parameters.
    /// Returns error only if amount of parameters is wrong.
    pub fn construct<S: traits::State>(
        &self,
        params: Option<&Params>,
    ) -> Result<BoxIndicator<S>, Error> {
        match self {
            Indicator::ExponentialMovingAverage => Ok(construct_indicator!(
                self,
                params,
                ExponentialMovingAverage,
                0
            )),
            Indicator::SimpleMovingAverage => {
                Ok(construct_indicator!(self, params, SimpleMovingAverage, 0))
            }
            Indicator::RelativeStrengthIndex => {
                Ok(construct_indicator!(self, params, RelativeStrengthIndex, 0))
            }
            Indicator::FastStochastic => Ok(construct_indicator!(self, params, FastStochastic, 0)),
            Indicator::SlowStochastic => {
                Ok(construct_indicator!(self, params, SlowStochastic, 0, 1))
            }
            Indicator::Maximum => Ok(construct_indicator!(self, params, Maximum, 0)),
            Indicator::Minimum => Ok(construct_indicator!(self, params, Minimum, 0)),
            Indicator::MoneyFlowIndex => Ok(construct_indicator!(self, params, MoneyFlowIndex, 0)),
            Indicator::AverageTrueRange => Ok(construct_indicator_wrapper!(
                self,
                params,
                AverageTrueRange,
                impls::AverageTrueRange,
                0
            )),
            Indicator::EfficiencyRatio => Ok(construct_indicator_wrapper!(
                self,
                params,
                EfficiencyRatio,
                impls::EfficiencyRatio,
                0
            )),
            Indicator::RateOfChange => Ok(construct_indicator!(self, params, EfficiencyRatio, 0)),
            Indicator::TrueRange => {
                Ok(Box::new(impls::TrueRange(indicators::TrueRange::new())) as BoxIndicator<S>)
            }
            Indicator::OnBalanceVolume => {
                Ok(Box::new(indicators::OnBalanceVolume::new()) as BoxIndicator<S>)
            }
            Indicator::ClosePrice => Ok(Box::new(impls::ClosePrice) as BoxIndicator<S>),
            Indicator::Spread => Ok(construct_indicator_local!(
                self,
                params,
                Spread,
                impls::Spread,
                0
            )),
            Indicator::AskRate => Ok(construct_indicator_local!(
                self,
                params,
                AskRate,
                impls::AskRate,
                0
            )),
            Indicator::BidRate => Ok(construct_indicator_local!(
                self,
                params,
                BidRate,
                impls::BidRate,
                0
            )),
            Indicator::EntryRate => Ok(construct_indicator_local!(
                self,
                params,
                EntryRate,
                impls::EntryRate,
                0
            )),
            Indicator::ExitRate => Ok(construct_indicator_local!(
                self,
                params,
                ExitRate,
                impls::ExitRate,
                0
            )),
            Indicator::MovingAverageConvergenceDivergence => {
                Err(Error::IndicatorNotImplemented(self.clone()))
            }
        }
    }

    /// Constructs indicator operation with params.
    pub fn into_op(self) -> Result<Operation, Error> {
        Operation::new(self, None)
    }

    /// Constructs indicator operation with params.
    pub fn with_params(self, params: Params) -> Result<Operation, Error> {
        Operation::new(self, Some(params))
    }

    fn get_param(&self, params: &Params, index: usize) -> Result<Param, Error> {
        params
            .get(index)
            .map(|v| v.clone())
            .ok_or_else(|| Error::ExpectedParameter(self.clone(), index))
    }
}

impl std::fmt::Debug for Indicator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Indicator::AverageTrueRange => write!(f, "ATR"),
            Indicator::EfficiencyRatio => write!(f, "ER"),
            Indicator::ExponentialMovingAverage => write!(f, "EMA"),
            Indicator::FastStochastic => write!(f, "FST"),
            Indicator::Maximum => write!(f, "MAX"),
            Indicator::Minimum => write!(f, "MIN"),
            Indicator::MoneyFlowIndex => write!(f, "MFI"),
            Indicator::OnBalanceVolume => write!(f, "OBV"),
            Indicator::RateOfChange => write!(f, "ROC"),
            Indicator::RelativeStrengthIndex => write!(f, "RSI"),
            Indicator::SimpleMovingAverage => write!(f, "SMA"),
            Indicator::SlowStochastic => write!(f, "SST"),
            Indicator::TrueRange => write!(f, "TR"),
            Indicator::Spread => write!(f, "Spread"),
            Indicator::MovingAverageConvergenceDivergence => write!(f, "MACD"),
            Indicator::AskRate => write!(f, "Ask"),
            Indicator::BidRate => write!(f, "Bid"),
            Indicator::EntryRate => write!(f, "Entry"),
            Indicator::ExitRate => write!(f, "Exit"),
            Indicator::ClosePrice => write!(f, "Close"),
        }
    }
}

impl std::str::FromStr for Indicator {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "AverageTrueRange" => Ok(Indicator::AverageTrueRange),
            "EfficiencyRatio" => Ok(Indicator::EfficiencyRatio),
            "ExponentialMovingAverage" => Ok(Indicator::ExponentialMovingAverage),
            "FastStochastic" => Ok(Indicator::FastStochastic),
            "Maximum" => Ok(Indicator::Maximum),
            "Minimum" => Ok(Indicator::Minimum),
            "MoneyFlowIndex" => Ok(Indicator::MoneyFlowIndex),
            "OnBalanceVolume" => Ok(Indicator::OnBalanceVolume),
            "RateOfChange" => Ok(Indicator::RateOfChange),
            "RelativeStrengthIndex" => Ok(Indicator::RelativeStrengthIndex),
            "SimpleMovingAverage" => Ok(Indicator::SimpleMovingAverage),
            "SlowStochastic" => Ok(Indicator::SlowStochastic),
            "TrueRange" => Ok(Indicator::TrueRange),
            "Spread" => Ok(Indicator::Spread),
            "MovingAverageConvergenceDivergence" => {
                Ok(Indicator::MovingAverageConvergenceDivergence)
            }
            "AskRate" => Ok(Indicator::AskRate),
            "BidRate" => Ok(Indicator::BidRate),
            "EntryRate" => Ok(Indicator::EntryRate),
            "ExitRate" => Ok(Indicator::ExitRate),
            "ClosePrice" => Ok(Indicator::ClosePrice),
            _ => Err(()),
        }
    }
}