Our strategy rules
Here are the parameters of our strategy:
- 200EMA and 50EMA must be headed in same direction (Long or short)
- If parameter 1 is true, 20EMA Must be leading the 50EMA in the current direction + 10EMA must be leading the 200EMA in current direction
- If parameter 1 AND 2 are met, they must be true for at least 10 consecutive candles and false 11 candles ago
To recap what I am trying to do here is build a trend following strategy that is designed to ignore any small movements in the market by capture true trends. By ensuring multiple moving averages are headed in the same direction we ensure that. In my back testing I found that this still caught too many false moves so I included the need for these parameters to be met for a 10 consecutive periods before I enter.
As of this writing the strategy still does not do exactly what I’m looking for but it’s pretty close and will give a beginner a more advanced strategy they can practice on.
Source code: Link
Overview: Steps we will take to add to our strategy:
- Add more moving averages
- Create long and short conditions
- Create close trade conditions for long and short strategy
- Plot our moving averages
- Update our entry and close conditions to take in new variables in the “When” parameters.
1- Add more moving averages
First we need to add a 10 and a 200 exponential moving average next to our current 20 and 50 EMA’s
2- Create long and short conditions
Let’s use two variables that represent what long and short opportunities look like to us. we will then use those two varibles to create long and short conditions. This part can get tricky so I will add an image then explain what’s going on.
let’s use the long condition as our example. When the 10ema is greater than the 200ema AND the 20ema is greater than the 50ema we have a “long” opportunity but we don’t want to buy just yet. So we expand on the long opportunity by creating a long condition.
Now our condition says when the current condition is long and the condition 10 periods ago was long (long – “Series subscript“) and the condition 11 periods ago, then we buy..
What this does is ensures that we have kept this long condition for 10 periods like we specified in parameter 3 and that we are not buying again if we are currently in a position.
3 – Close conditions
Our close conditions are simple. If any of our pairs of moving averages (10 and 200 and 20 & 50) disagree for 11 periods we close our positions.
4 – Plot moving averages
Let’s use the plot function to add our moving averages to the chart so we can thoroughly analyze our strategy.
To view these moving averages on your chart with the candles, update the “strategy” function to have the following:
5 – Update our entry and close conditions
If you followed the previous tutorials make sure to update the entry and close functions when parameters to our new conditions likes so:
Let’s add this to our chart and run the strategy!
you can find the source code here: source code