Reader Request: Multiple Moving Averages Strategy

Reader Scott asked for a strategy where the long entry is a close above each of three moving averages, and the exit is the first close below any of them. I’m away from a pc now, so this is all off the top of my head, done on my iPhone. Let me know if there are errors! I’ll be able to fully check this out on Friday.

First, the Long Entry:

# 3 EMA Long Entry
#
# Input Declarations:
#
declare LONG_ENTRY;
input opentime=0930;
input closetime=1600;
input EMA_1=50;
input EMA_2=100;
input EMA_3=200;
#
# If intraday, only enter during market hours:
# Note: Tick charts return Aggregation Period = 0
#
def AP=getaggregationperiod();
def daily=if AP>=aggregationPeriod.DAY then 1 else 0;
def isopen=if daily then 1 else if secondsFromTime(opentime)>=0 and secondstillTime(closetime)>=0 then 1 else 0;
#
# Define the entry trigger:
# In this example, we are using a close above
# each of 3 EMA’s:
#
def signal = if close>expaverage(close,EMA_1) AND close>expaverage(close,EMA_2) AND close>expaverage(close,EMA_3) then 1 else 0;
#
# If market open and close above EMA’s then enter on bar close:
#
def trigger=if isopen and signal then 1 else 0;
def orderprice=close;
#
# This code triggers the strategy on the chart.
# Arg. 1 adds order if true, nothing if false
# Arg. 2 is the entry price
#
#
# Formatting:
#
setcolor(color.green);

Now, the Long Exit:

# 3 EMA Long Exit
#
# Input Declarations:
#
declare LONG_EXIT;
input closetime=1600;
input EMA_1=50;
input EMA_2=100;
input EMA_3=200;
#
# Always exit at close:
#
def AP=getaggregationperiod();
def daily=if AP>=aggregationPeriod.DAY then 1 else 0;
def islastcandle=if daily then 0 else if secondstillTime(closetime)<=AP/1000 then 1 else 0;
#
# Define the exit trigger:
# In this example, we are using a close below any of the EMA’s:
#
def signal = if close<expaverage(close,EMA_1) OR close<expaverage(close,EMA_2) OR close<expaverage(close,EMA_3) then 1 else 0;
#
# If market is closing OR close under any EMA’s then exit on bar close:
#
def trigger=if islastcandle OR signal then 1 else 0;
def orderprice=close;
#
# This code triggers the strategy on the chart.
# Arg. 1 adds order if true, nothing if false
# Arg. 2 is the entry price
#
#
# Formatting:
#
setcolor(color.gray);

You should be able to make the short side strategies by simply reversing the > and < signs in the “signal” definitions above, along with changing the “LONG_ENTRY” and “LONG_EXIT” declarations to “SHORT_ENTRY” and “SHORT_EXIT”, respectively.

Let me know if it works!

Tags: , ,