Exponential Moving Average

View as Markdown

Indicator Tutorial 3

Exponential Moving Average is a little bit more complex indicator: it has to keep in mind its previous calculations.

The app doesn’t restrict the calculator class how it can use its fields or functions. As result, the most simple way to keep the state of the previous calculation is by saving it in the object’s fields. Like, this.initialSum = this.initialSum + d.value(). Here is our EMA that has a lot in common with our previous indicator:

1class ema {
2 init() {
3 this.previousMA = undefined;
4 this.initialSum = 0;
5 }
6
7 map(d, index) {
8 let result;
9
10 if (index < this.props.period) {
11 this.initialSum += d.value();
12 result = this.initialSum / (index + 1);
13 }
14 else {
15 const multiplier = 2.0 / (this.props.period + 1);
16 result = (d.value() - this.previousMA) * multiplier + this.previousMA;
17 }
18 this.previousMA = result;
19 return result;
20 }
21}
22
23module.exports = {
24 name: "exampleEma",
25 calculator: ema,
26 params: {
27 period: {
28 type: "number",
29 def: 10,
30 restrictions: {
31 step: 1,
32 min: 3
33 }
34 }
35 }
36};

We added one more function to the calculator class - an implementation of Calculator.init. The application calls this optional function before the calculation loop. Our EMA uses it to initialize the state’s fields.