March 30

1 comments

Free Trend Following System With Indicator Tracker

By George Pruitt

March 30, 2020


Free Trend Following System

Here is a free Trend Following System that I read about on Andreas Clenow’s www.followthetrend.com website and from his book. This is my interpretation of the rules as they were explained. However, the main impetus behind this post wasn’t to provide a free trading system, but to show how you can program a simple system with a complete input interface and program a tracking indicator. You might be asking, what is a “tracking indicator?” We use a tracking indicator to help provide insight to what the strategy is doing and what it might do in the near future. The indicator can let you know that a new signal is imminent and also what the risk is in a graphical form. The indicator can also plot the indicators that are used in the strategy itself.

Step 1:  Program the Strategy

This system is very simple. Trade on a 50-day Donchian in the direction of the trend and use a 3 X ATR trailing stop. So the trend is defined as bullish when the 50-day exponential moving average is greater than the 100-day exponential moving average. A bearish trend is defined when the 50-day is below the 100-day. Long positions are initiated on the following day when a new 50-day high has been established and the trend is bullish. Selling short occurs when the trend is bearish and a new 50-day low is established. The initial stop is set to 3 X ATR below the high of the day of entry. I tested using a 3 X ATR stop initially from the entryPrice for protection on the day of entry, but it made very little difference. As the trade moves more into your favor, the trailing stop ratchets up and tracks the higher intra-trade extremes. Eventually, once the market reverses you get stopped out of a long position 3 X ATR from the highest high since you entered the long trade. Hopefully, with a big winner. The Clenow model also uses a position sizing equation that uses ATR to determine market risk and $2,000 for the allocated amount to risk. Size= 2000 / ATR – this equation will normalize size across a portfolio of markets.

Here is the code.

//Based on Andreas Clenow's description from www.followingthetrend.com
//This is my interpretation and may or may not be what Andreas intended
//Check his books out at amazon.com
//

inputs:
xAvgShortLen(50),
xAvgLongLen(100),
hhllLen(50),
buyTrigPrice(h),
shortTrigPrice(l),
risk$Alloc(2000);

inputs: atrLen(30),trailATRMult(3);
vars: avg1(0),avg2(0),lXit(0),sXit(0),posSize(0),atr(0);
avg1 = xaverage(c,xAvgShortLen);
avg2 = xaverage(c,xAvgLongLen);

atr = avgTrueRange(atrLen);
posSize = maxList(1,intPortion(risk$Alloc/(atr*bigPointValue)));
If marketPosition <> 1 and avg1 > avg2 and buyTrigPrice = highest(buyTrigPrice,hhllLen) then buy posSize contracts next bar at open;

If marketPosition <> -1 and avg1 < avg2 and shortTrigPrice = lowest(shortTrigPrice,hhllLen) then sellshort posSize contracts next bar at open;

If marketPosition = 0 then Begin
lXit = o - trailATRMult * atr ;
sXit = o + trailATRMult * atr;
//if c < lXit then Sell currentcontracts contracts next bar at open;
//If c > sXit then buyToCover currentcontracts contracts next bar at open;
end;

If marketPosition = 1 then begin
lXit = maxList(lXit,h - trailATRMult * atr);
If c < lXit then sell currentContracts contracts next bar at open;
end;

If marketPosition = -1 then begin
sXit = minList(sXit,l + trailATRMult * atr);
If c > sXit then buyToCover currentContracts contracts next bar at open;
end;

What I like about this code is how you can use it as a template for any trend following approach. All the variables that could be optimized are included as inputs. 

Many may not know that you can actually change the data series that you want to use as your signal generator right in the input. Here I have provided two inputs : buyTrigPrice(H), shortTrigPrice(L). If you want to use the closing price, then all you need to do is change the H and L to C.

The next lines of code performs the calculations needed to calculate the trend. PosSize is then calculated next. Here I am dividing the variable risk$Alloc by atr*bigPointValue.  

Basically, I am taking $2,000 and dividing the average true range over the past 30 days multiplied by the point value of the market being tested. Always remember, when doing calculations with $s, you have to convert whatever else you are using into dollars as well. The ATR is expressed in the form of a price difference. You can’t divide dollars by a price component, hence the multiplication by bigPointValue.

So now we have the trend calculation and the position sizing taken care of, and all we need now is the trend direction and the entry levels. If avg1 > avg2 then the market is in a bullish posture, and if today’s High = highest(High,50) days back then initiate a long position with posSize contracts at the next bar’s open.

Notice how I used the keyword contracts after posSize. This lets TS know that I want to trade more than one contract. If the current position is flat I set the lXit and sXit price levels to the open -/+ 3 X ATR. Once a position (long or short) is initiated then I start ratcheting the trailing stop up or down.

Assuming a long position, I compare the current lXit and the current bar’s HIGH- 3 X ATR and take the larger of the two valuesSo lXit always moves up and never down. Notice if the close is less than lXit I used the keyword currentContracts and contracts in the directive to exit a long trade. CurrentContracts contains the current number of contracts currently long and contracts informs TS that more than one contract is being liquidated. Getting out of a short position is exactly the same but in a different direction.

Step 2: Program the System Tracking Indicator

Now you can take the exact code and eliminate all the order directives, and use it to create a tracking indicator. Take a look at this code:

//Based on Andreas Clenow's description from www.followingthetrend.com
//This is my interpretation and may or may not be what Andreas intended
//Check his books out at amazon.com
//

inputs:
xAvgShortLen(50)
,xAvgLongLen(100),
hhllLen(50),
buyTrigPrice(h),
shortTrigPrice(l), 
atrLen(30),
trailATRMult(3);

vars:
avg1(0),
avg2(0),lXit(0),
sXit(0),posSize(0),
atr(0),
mp(0);

avg1 = xaverage(c,xAvgShortLen);avg2 = xaverage(c,xAvgLongLen);
atr = avgTrueRange(atrLen);

plot1(avg1,"stXavg");
plot2(avg2,"ltXavg");

If avg1[1] > avg2[1] and buyTrigPrice[1] = highest(buyTrigPrice[1],hhllLen) then mp = 1;
If avg1[1] < avg2[1] and shortTrigPrice[1] = lowest(shortTrigPrice[1],hhllLen) then mp = -1;

If mp = 0 then Begin
lXit = o - trailATRMult * atr;
sXit = o + trailATRMult * atr;
end;

If mp = 1 then begin
lXit = maxList(lXit,h - trailATRMult * atr);plot3(lXit,"LongTrail");
If c < lXit then mp = 0;
end;

If mp = -1 then begin
sXit = minList(sXit,l + trailATRMult * atr);
plot4(sXit,"ShortTrail");
If c > sXit then mp = 0;
end;

However, you do need to keep track if the underlying strategy is long or short and you can do this by pretending you are the computer and using the mp variable. You know if yesterday's avg1 > avg2 and HIGH[1] = highestHigh(HIGH[1],50), then a long position should have been initiated. If this happens just set mp to 1You set mp to -1 by checking the trend and lowestLow(LOW[1],50).

Once you know the mp or implied market position then you can calculate the lXit and sXit. You will always plot the moving averages to help determine trend direction, but you only plot the lXit and sXit when a position is on. So, plot3 and plot4 should only be plotted when a position is long or short.

Here is a screenshot of the strategy and tracking indicator.

Notice how the Yellow and Cyan plots follow the correct market position. You will need to tell TS not to connect these plot lines when they are not designed to be plotted.

Turn-Off Auto Plot Line Connection

Do this for Plot3 and Plot4 and you will be good to go.

I hope you found this post useful. Also, don’t forget to check out my new book at Amazon.com. If you really want to learn programming that will help across different platforms I think it would be a great learning experience.

--By George Pruitt from blog Georgepruitt

George Pruitt

About the author

I have a degree in computer science from UNC-Asheville. I was the Director of Research for Futures Truth (magazine and CTA) for 31 years and have authored many articles in magazines and trade journals. I have written and co-written eight books: The Easing into EasyLanguage Series (four books): Foundation, Hi-Res, Advanced Topics and DayTrade edition. Older books published by John Wiley: The Ultimate Trading Guide, Building Winning Trading Systems with TradeStation (two editions), The Ultimate Algorithmic Trading System Toolbox, Trend Following Systems-A DIY Project: Batteries Included! My research is now focused on day-trading and longer-term trend following systems.

  • Hi George
    I was able to run the first step of the code you provided but when running the second step I keep getting this compile error.

    —— Compiled with error(s): ——
    Keyword “Plot**” can’t been used in this type of study
    line 0, column 0

    Thanks
    Mike

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    Learn To Code & Build Strategies
    Using EasyLanguage. 

    >