mantis-ta 0.6.7

Composable technical analysis and strategy engine for Rust
Documentation
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
423
424
425
426
427
428
429
430
431
432
use super::types::{CompareTarget, Condition, ConditionGroup, ConditionNode, Operator};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Reference to an indicator within a strategy, with convenience methods for building conditions.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct IndicatorRef {
    pub name: String,
}

impl IndicatorRef {
    /// Create a new indicator reference.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }

    /// SMA convenience constructor.
    pub fn sma(period: usize) -> Self {
        Self::new(format!("sma{period}"))
    }

    /// EMA convenience constructor.
    pub fn ema(period: usize) -> Self {
        Self::new(format!("ema{period}"))
    }

    /// MACD convenience constructor.
    pub fn macd(fast: usize, slow: usize, signal: usize) -> Self {
        Self::new(format!("macd_{fast}_{slow}_{signal}_line"))
    }

    /// MACD signal line convenience constructor.
    pub fn macd_signal(fast: usize, slow: usize, signal: usize) -> Self {
        Self::new(format!("macd_{fast}_{slow}_{signal}_signal"))
    }

    /// RSI convenience constructor.
    pub fn rsi(period: usize) -> Self {
        Self::new(format!("rsi{period}"))
    }

    /// Stochastic %K convenience constructor.
    pub fn stoch_k(k_period: usize, d_period: usize) -> Self {
        Self::new(format!("stoch_{k_period}_{d_period}_k"))
    }

    /// Stochastic %D convenience constructor.
    pub fn stoch_d(k_period: usize, d_period: usize) -> Self {
        Self::new(format!("stoch_{k_period}_{d_period}_d"))
    }

    /// Bollinger Bands upper convenience constructor.
    pub fn bb_upper(period: usize, std_dev: f64) -> Self {
        Self::new(format!("bb_{period}_{std_dev}_upper"))
    }

    /// Bollinger Bands middle convenience constructor.
    pub fn bb_middle(period: usize, std_dev: f64) -> Self {
        Self::new(format!("bb_{period}_{std_dev}_middle"))
    }

    /// Bollinger Bands lower convenience constructor.
    pub fn bb_lower(period: usize, std_dev: f64) -> Self {
        Self::new(format!("bb_{period}_{std_dev}_lower"))
    }

    /// ATR convenience constructor.
    pub fn atr(period: usize) -> Self {
        Self::new(format!("atr{period}"))
    }

    /// Volume SMA convenience constructor.
    pub fn volume_sma(period: usize) -> Self {
        Self::new(format!("volume_sma_{period}"))
    }

    /// OBV convenience constructor.
    pub fn obv() -> Self {
        Self::new("obv")
    }

    /// Pivot Points convenience constructor.
    pub fn pivot_points() -> Self {
        Self::new("pivot_points")
    }

    /// ADX convenience constructor.
    pub fn adx(period: usize) -> Self {
        Self::new(format!("adx{period}"))
    }

    /// WMA convenience constructor.
    pub fn wma(period: usize) -> Self {
        Self::new(format!("wma{period}"))
    }

    /// DEMA convenience constructor.
    pub fn dema(period: usize) -> Self {
        Self::new(format!("dema{period}"))
    }

    /// TEMA convenience constructor.
    pub fn tema(period: usize) -> Self {
        Self::new(format!("tema{period}"))
    }

    /// CCI convenience constructor.
    pub fn cci(period: usize) -> Self {
        Self::new(format!("cci{period}"))
    }

    /// Williams %R convenience constructor.
    pub fn williams_r(period: usize) -> Self {
        Self::new(format!("williams_r{period}"))
    }

    /// ROC convenience constructor.
    pub fn roc(period: usize) -> Self {
        Self::new(format!("roc{period}"))
    }

    /// Standard Deviation convenience constructor.
    pub fn stddev(period: usize) -> Self {
        Self::new(format!("stddev{period}"))
    }

    // Condition building methods

    /// Create a condition: this indicator crosses above a value.
    pub fn crosses_above(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::CrossesAbove,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this indicator crosses above another indicator.
    pub fn crosses_above_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::CrossesAbove,
            CompareTarget::Indicator(other.name),
        ))
    }

    /// Create a condition: this indicator crosses below a value.
    pub fn crosses_below(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::CrossesBelow,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this indicator crosses below another indicator.
    pub fn crosses_below_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::CrossesBelow,
            CompareTarget::Indicator(other.name),
        ))
    }

    /// Create a condition: this indicator is above a value.
    pub fn is_above(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsAbove,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this indicator is above another indicator.
    pub fn is_above_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsAbove,
            CompareTarget::Indicator(other.name),
        ))
    }

    /// Create a condition: this indicator is below a value.
    pub fn is_below(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsBelow,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this indicator is below another indicator.
    pub fn is_below_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsBelow,
            CompareTarget::Indicator(other.name),
        ))
    }

    /// Create a condition: this indicator equals a value (within epsilon).
    pub fn equals(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::Equals,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this indicator equals another indicator (within epsilon).
    pub fn equals_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::Equals,
            CompareTarget::Indicator(other.name),
        ))
    }

    /// Create a condition: this indicator is between two values.
    pub fn is_between(self, lower: f64, upper: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsBetween,
            CompareTarget::Range(lower, upper),
        ))
    }

    /// Create a condition: this indicator is rising over `bars` bars.
    pub fn is_rising(self, bars: u32) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsRising(bars),
            CompareTarget::None,
        ))
    }

    /// Create a condition: this indicator is falling over `bars` bars.
    pub fn is_falling(self, bars: u32) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            self.name,
            Operator::IsFalling(bars),
            CompareTarget::None,
        ))
    }

    /// Create a condition: this indicator scaled by a multiplier is above a value.
    pub fn scaled(self, multiplier: f64) -> ScaledIndicatorRef {
        ScaledIndicatorRef {
            name: self.name,
            multiplier,
        }
    }
}

/// A scaled indicator reference for use in conditions.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ScaledIndicatorRef {
    pub name: String,
    pub multiplier: f64,
}

impl ScaledIndicatorRef {
    /// Create a condition: this scaled indicator is above a value.
    pub fn is_above_value(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            format!("{}*{}", self.name, self.multiplier),
            Operator::IsAbove,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this scaled indicator is above another indicator.
    pub fn is_above_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            format!("{}*{}", self.name, self.multiplier),
            Operator::IsAbove,
            CompareTarget::Indicator(other.name),
        ))
    }

    /// Create a condition: this scaled indicator is below a value.
    pub fn is_below_value(self, value: f64) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            format!("{}*{}", self.name, self.multiplier),
            Operator::IsBelow,
            CompareTarget::Value(value),
        ))
    }

    /// Create a condition: this scaled indicator is below another indicator.
    pub fn is_below_indicator(self, other: IndicatorRef) -> ConditionNode {
        ConditionNode::Condition(Condition::new(
            format!("{}*{}", self.name, self.multiplier),
            Operator::IsBelow,
            CompareTarget::Indicator(other.name),
        ))
    }
}

/// Create an AllOf condition group.
pub fn all_of(conditions: Vec<ConditionNode>) -> ConditionNode {
    ConditionNode::Group(ConditionGroup::AllOf(conditions))
}

/// Create an AnyOf condition group.
pub fn any_of(conditions: Vec<ConditionNode>) -> ConditionNode {
    ConditionNode::Group(ConditionGroup::AnyOf(conditions))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn indicator_ref_convenience_constructors() {
        let sma = IndicatorRef::sma(20);
        assert_eq!(sma.name, "sma20");

        let ema = IndicatorRef::ema(14);
        assert_eq!(ema.name, "ema14");

        let rsi = IndicatorRef::rsi(14);
        assert_eq!(rsi.name, "rsi14");

        let obv = IndicatorRef::obv();
        assert_eq!(obv.name, "obv");
    }

    #[test]
    fn batch_a_indicator_ref_convenience_constructors() {
        let adx = IndicatorRef::adx(14);
        assert_eq!(adx.name, "adx14");

        let wma = IndicatorRef::wma(20);
        assert_eq!(wma.name, "wma20");

        let dema = IndicatorRef::dema(10);
        assert_eq!(dema.name, "dema10");

        let tema = IndicatorRef::tema(10);
        assert_eq!(tema.name, "tema10");

        let cci = IndicatorRef::cci(20);
        assert_eq!(cci.name, "cci20");

        let williams_r = IndicatorRef::williams_r(14);
        assert_eq!(williams_r.name, "williams_r14");

        let roc = IndicatorRef::roc(12);
        assert_eq!(roc.name, "roc12");

        let stddev = IndicatorRef::stddev(20);
        assert_eq!(stddev.name, "stddev20");
    }

    #[test]
    fn condition_building() {
        let sma = IndicatorRef::sma(20);
        let cond = sma.crosses_above(100.0);
        assert!(matches!(cond, ConditionNode::Condition(_)));
    }

    #[test]
    fn condition_grouping() {
        let sma = IndicatorRef::sma(20);
        let rsi = IndicatorRef::rsi(14);

        let cond1 = sma.is_above(100.0);
        let cond2 = rsi.is_below(70.0);

        let group = all_of(vec![cond1, cond2]);
        assert!(matches!(
            group,
            ConditionNode::Group(ConditionGroup::AllOf(_))
        ));
    }

    #[test]
    fn scaled_indicator_ref() {
        let atr = IndicatorRef::atr(14);
        let scaled = atr.scaled(2.0);
        assert_eq!(scaled.multiplier, 2.0);
    }

    #[test]
    fn scaled_is_above_indicator_has_correct_semantics() {
        // atr.scaled(2.0).is_above_indicator(price) should mean "atr*2 is above price"
        let cond = IndicatorRef::atr(14)
            .scaled(2.0)
            .is_above_indicator(IndicatorRef::new("price"));
        match cond {
            ConditionNode::Condition(c) => {
                assert_eq!(c.left, "atr14*2");
                assert_eq!(c.operator, Operator::IsAbove);
                assert_eq!(c.right, CompareTarget::Indicator("price".to_string()));
            }
            _ => panic!("expected Condition"),
        }
    }

    #[test]
    fn scaled_is_below_indicator_has_correct_semantics() {
        // atr.scaled(1.5).is_below_indicator(price) should mean "atr*1.5 is below price"
        let cond = IndicatorRef::atr(14)
            .scaled(1.5)
            .is_below_indicator(IndicatorRef::new("price"));
        match cond {
            ConditionNode::Condition(c) => {
                assert_eq!(c.left, "atr14*1.5");
                assert_eq!(c.operator, Operator::IsBelow);
                assert_eq!(c.right, CompareTarget::Indicator("price".to_string()));
            }
            _ => panic!("expected Condition"),
        }
    }

    #[test]
    fn scaled_is_above_value_has_correct_semantics() {
        let cond = IndicatorRef::atr(14).scaled(2.0).is_above_value(50.0);
        match cond {
            ConditionNode::Condition(c) => {
                assert_eq!(c.left, "atr14*2");
                assert_eq!(c.operator, Operator::IsAbove);
                assert_eq!(c.right, CompareTarget::Value(50.0));
            }
            _ => panic!("expected Condition"),
        }
    }
}