Skip to content

ExponentialMovingAverage

Summary

The exponential moving average of the price data source over a period of time.

Remarks

The exponential moving average is similar to the simple moving average, but applies more weight to more recent data. The weighting for each older price data decreases exponentially. Therefore the exponential moving average reacts faster to latest price changes than the simple moving average.

Signature

1
public abstract interface ExponentialMovingAverage

Namespace

cAlgo.API.Indicators

Examples

 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
        [Indicator]
        public class EmaExample : Indicator
        {
            private ExponentialMovingAverage _emaFast;
            private ExponentialMovingAverage _emaSlow;
            [Parameter("Data Source")]
            public DataSeries Price { get; set; }
            [Parameter("Slow Periods", DefaultValue = 10)]
            public int SlowPeriods { get; set; }
            [Parameter("Fast Periods", DefaultValue = 5)]
            public int FastPeriods { get; set; }
            protected override void Initialize()
            {
              // initialize new instances of ExponentialMovingAverage Indicator class
                _emaFast = Indicators.ExponentialMovingAverage(Price, FastPeriods);
              // _emaSlow is the exponential moving average of the emaFast
                _emaSlow = Indicators.ExponentialMovingAverage(_emaFast.Result, SlowPeriods);
            }
            public override void Calculate(int index)
            {
              // If the index is less than SlowPeriods don't calculate
                if(index <= SlowPeriods)
                {
                    return;
                }
                if(_emaFast.Result.HasCrossedAbove(_emaSlow.Result,0))
                {
                  // Print the index at which the fast ema crossed the slow ema
                    Print("Fast EMA Has Crossed Above at index = {0}", index);
                }
            }
      }
 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
 using cAlgo.API;
 using cAlgo.API.Indicators;
 namespace cAlgo.Robots
 {
     // This sample cBot shows how to use the Exponential Moving Average indicator
     [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
     public class ExponentialMovingAverageSample : Robot
     {
         private double _volumeInUnits;
         private ExponentialMovingAverage _fastExponentialMovingAverage;
         private ExponentialMovingAverage _slowExponentialMovingAverage;
         [Parameter("Volume (Lots)", DefaultValue = 0.01)]
         public double VolumeInLots { get; set; }
         [Parameter("Stop Loss (Pips)", DefaultValue = 10)]
         public double StopLossInPips { get; set; }
         [Parameter("Take Profit (Pips)", DefaultValue = 10)]
         public double TakeProfitInPips { get; set; }
         [Parameter("Label", DefaultValue = "Sample")]
         public string Label { get; set; }
         public Position[] BotPositions
         {
             get
             {
                 return Positions.FindAll(Label);
             }
         }
         protected override void OnStart()
         {
             _volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots);
             _fastExponentialMovingAverage = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 9);
             _slowExponentialMovingAverage = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 20);
         }
         protected override void OnBar()
         {
             if (_fastExponentialMovingAverage.Result.Last(1) > _slowExponentialMovingAverage.Result.Last(1) && _fastExponentialMovingAverage.Result.Last(2) < _slowExponentialMovingAverage.Result.Last(2))
             {
                 ClosePositions(TradeType.Sell);
                 ExecuteMarketOrder(TradeType.Buy, SymbolName, _volumeInUnits, Label, StopLossInPips, TakeProfitInPips);
             }
             else if (_fastExponentialMovingAverage.Result.Last(1) < _slowExponentialMovingAverage.Result.Last(1) && _fastExponentialMovingAverage.Result.Last(2) > _slowExponentialMovingAverage.Result.Last(2))
             {
                 ClosePositions(TradeType.Buy);
                 ExecuteMarketOrder(TradeType.Sell, SymbolName, _volumeInUnits, Label, StopLossInPips, TakeProfitInPips);
             }
         }
         private void ClosePositions(TradeType tradeType)
         {
             foreach (var position in BotPositions)
             {
                 if (position.TradeType != tradeType) continue;
                 ClosePosition(position);
             }
         }
     }
 }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 import clr
 clr.AddReference("cAlgo.API")
 from cAlgo.API import *
 class Test():    
     def initialize(self):
         # Price and FastPeriods are parameters defined in indicator C# file
         # initialize new instances of ExponentialMovingAverage Indicator class
         self.emaFast = api.Indicators.ExponentialMovingAverage(api.Price, api.FastPeriods)
         # emaSlow is the exponential moving average of the emaFast
         self.emaSlow = api.Indicators.ExponentialMovingAverage(self.emaFast.Result, api.SlowPeriods)
     def calculate(self, index):
         # If the index is less than SlowPeriods don't calculate
         if index <= api.SlowPeriods:
             return
         if Functions.HasCrossedAbove(self.emaFast.Result, self.emaSlow.Result, 0):
             # Print the index at which the fast ema crossed the slow ema
             api.Print(f"Fast EMA Has Crossed Above at index = {index}")
 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
 import clr
 clr.AddReference("cAlgo.API")
 # Import cAlgo API types
 from cAlgo.API import *
 # Import trading wrapper functions
 from robot_wrapper import *
 class ExponentialMovingAverageSample():
     def on_start(self):
         self.volumeInUnits = api.Symbol.QuantityToVolumeInUnits(api.VolumeInLots)
         self.fastExponentialMovingAverage = api.Indicators.ExponentialMovingAverage(api.SourceFirst, api.PeriodsFirst);
         self.fastExponentialMovingAverage.Result.Line.Color = Color.Blue;
         self.slowExponentialMovingAverage = api.Indicators.ExponentialMovingAverage(api.SourceSecond, api.PeriodsSecond);
         self.slowExponentialMovingAverage.Result.Line.Color = Color.Red;
     def on_bar_closed(self):
         if self.fastExponentialMovingAverage.Result.Last(0) > self.slowExponentialMovingAverage.Result.Last(0) and self.fastExponentialMovingAverage.Result.Last(1) < self.slowExponentialMovingAverage.Result.Last(1):
             self.close_positions(TradeType.Sell)
             api.ExecuteMarketOrder(TradeType.Buy, api.SymbolName, self.volumeInUnits, api.Label)
         elif self.fastExponentialMovingAverage.Result.Last(0) < self.slowExponentialMovingAverage.Result.Last(0) and self.fastExponentialMovingAverage.Result.Last(1) > self.slowExponentialMovingAverage.Result.Last(1):
             self.close_positions(TradeType.Buy)
             api.ExecuteMarketOrder(TradeType.Sell, api.SymbolName, self.volumeInUnits, api.Label)
     def get_bot_positions(self):
         return api.Positions.FindAll(api.Label)
     def close_positions(self, tradeType):
         for position in self.get_bot_positions():
             if position.TradeType != tradeType:
                 continue
             api.ClosePosition(position)