By Crispin Scruby

Technical Indicators in Automated Trading

By Crispin Scruby

This article aims to describe how technical indicators can be used in the development of an Automated or Algorithmic trading system.

The indicators described are not an exhaustive list by any means but are simply those which have proved useful in the ongoing development and testing of an automated algorithmic trading system. The article is broken down as follows:-

  • Trading platforms which provide Technical Indicators and a configurable API (Application Programmers Interface)
  • Identification of useful Technical Indicators and how they can be used
  • Why multi-timeframe analysis is critical
  • An example of automated trading system using multiple timeframe analysis and appropriate indicators for entry and exit strategies
  • Pitfalls of using indicators for Automated Trading

Trading platforms which provide Technical Indicators and a configurable API (Application Programmers Interface)

If a trader has the desire to automate any of his/her trading strategies the trading platform must offer an API (Application Programmer's Interface) The API is effectively an underlying programming language which can be used to control the functionality and behaviour of the higher level trading environment.
If the vendors API also provides access to technical indicators then the trader has the perfect environment to build an automated trading system to an exact user defined specification. The automated system will need to control:-

  • Entries based on technical analysis and inter market analysis
  • Exits
  • Stops
  • Trailing Stops
  • Risk Control and Position Sizing
  • Order Management

There are numerous companies offering automated trading strategies but most are 'canned' or black box strategies which offer little freedom to tune, re-design or build a strategy from scratch. It is important to identify platform vendors with an open and highly configurable interface as complete control is essential. Metaquotes' "MetaTrader MT4" platform is widely used amongst FX brokers and has a fully configurable underlying API called MQL4 which can be accessed through the 'MetaEditor' application. Tradestation is also another widely recognised platform which provides configurable automated trading and also access to a wide range of asset classes.

Personal research is essential when selecting a suitable broker for automated FX trading as not all brokers will make the full range of API functionality available to their clients.

Technical Indicators useful for Automated Trading

"The trend is your friend"

This well known cliché has merit as trading with the underlying trend in FX carries a far lower level of risk in comparison to counter trend trading. There are a number of technical indicators which can be used to identify the presence of a trend within a given timeframe. These indicators are typically:-

  • Moving Averages (MA)
    Calculates the average price based on either the open, close or median price over a defined number of time periods. Short term moving averages on longer term charts (ie 5 period MAs on hourly charts) can be used to represent a 'smoothed' version of price action. So if the 5 period MA a given number of periods ago is less than the current 5 period MA this would indicate the current price is higher than it was previously - a possible uptrend. Again, timeframe is critical as an increasing 5 period MA on a 1,5,15 or possibly 30 minute chart could just be intraday noise.
  • Average Directional Movement Index (ADX)
    An oscillator used to assess the strength of a trend. When the ADX reading is rising and above 20 a trend could be forming depending on the timeframe being viewed. The indicator is much more accurate on longer term charts such as 60 minute and above. If the ADX is rising more than a given amount or percentage over a defined timeframe AND there is confirmation of trend formation from other indicators such as a moving average, on a medium to long term chart, then there is a good chance a trend is present.
  • Parabolic SAR (PSAR)
    Where Stop and Reverse (SAR) signals are placed either above or below price action. In uptrends PSAR signals are placed below price action and vice versa for downtrends. PSAR signals are useful in trending markets but very poor in a rangebound market as they continually flip from uptrend to downtrend or vice versa. PSAR can be used in conjunction with other indicators to confirm the presence of a trend.

Strength and Weakness Indicators - possible entry and exit conditions

There are numerous oscillator based strength and weakness indicators which can be used in conjunction with trend based indicators for generating automated entry and or exit signals. Some standard oscillator based indicators are:-

  • Relative Strength Index
    A technical momentum indicator that compares the magnitude of recent gains to recent losses in an attempt to determine overbought and oversold conditions. Readings below 30 indicate oversold, readings greater than 70 overbought.
  • Willams Percentage R
    Another momentum indicator for overbought and oversold situations with a scale from 0 to -100 where >-20 represents overbought conditions and <-80 represents oversold conditions. Williams %R when used on longer timeframes can be useful in determining turning points in the market but additional confirmation is required from price action breaching a trendline or other support/resistance level.
  • Stochastics
    Yet another momentum indicator that shows the location of the current close relative to the high/low range over a set number of periods. Closing levels that are consistently near the top of the range indicate accumulation (buying pressure) and those near the bottom of the range indicate distribution (selling pressure).

Why multiple timeframe analysis is critical.


A lot of novice traders focus on short term timeframes in an attempt to satisfy their desire for more trading signals. In Dirk du Toit's 'Birdwatching in Lion Country', Dirk compares the FX market to a kind of supercharged motorway with traffic moving at lots of different speeds. The successful traders are camped out on the high ground watching events unfold and the short term day traders are in the hard shoulder with their binoculars trying to work out what's coming. Guess who gets squashed!

The shorter term timeframes can indeed provide entry signals but, generally, only if the trade is in the same direction as the underlying trend on a higher timeframe. Obviously this does not hold true in rangebound markets but the automated system described later is essentially a trend following system which only trades in trending markets.

A trend following, automated system needs to be able to identify the presence of a trend on a higher timeframe and then execute trend following entries by buying short term weakness / selling short term strength for uptrends and downtrend respectively.

In the example system described shortly we use three timescales:- Daily, Hourly and five minute charts to identify trend and select suitable entry points.

An Example Automated Trading System using Technical Indicators.

Our example system in intended to provide the following functionality:-

Identify the market direction - uptrend, downtrend or rangebound
Identify suitable entry conditions in trending market situations
Set stop loss levels
Track profit and exit positions

Identifying market condition.
We achieve this by using three indicators; ADX, moving averages and the RSI. The pseudo code for this is as follows:-
An Uptrend is present if the current 5 period moving average > 5 period moving average 5 periods ago (on 60 minute charts)
AND
the ADX indicator is rising on the hourly charts over the last two periods (hours)
AND
the ADX on the daily charts is currently rising

We also want to stop the system entering overbought or oversold markets so we use the RSI indicator on an hourly timeframe. If the hourly RSI readings are less than 70 or greater than 30 the system wont allow any trades to be executed.

Technical Indicators in Automated Trading

Hourly Cable (GBPUSD) chart with ADX and RSI plotted in separate windows below.

The blue moving average is the 5 period MA and is clearly showing a downward move in previous price action. The ADX is rising and the RSI readings are still within acceptable limits.

System has correctly identified a short term downtrend. "GBPUSD Funky" is the comment name assigned to this algotrade.

In MT4 the MQL4 code to define an uptrend would look like:-

string Condition;
//string for defining market condition
if (iMA(NULL,PERIOD_H1,5,0,MODE_SMA,PRICE_MEDIAN,1) <iMA(NULL,PERIOD_H1,5,0,MODE_SMA,PRICE_MEDIAN,0) &&
// 5 period MA is rising on hourly basis (over current and last period)
iADX(NULL,PERIOD_H1,14,PRICE_HIGH,MODE_MAIN,1)>
iADX(NULL,PERIOD_H1,14,PRICE_HIGH,MODE_MAIN,2)+1 &&
// ADX is rising by more than 1 over last period and period prior - 60 minute charts
iADX(NULL,PERIOD_D1,14,PRICE_HIGH,MODE_MAIN,0)>
iADX(NULL,PERIOD_H1,14,PRICE_HIGH,MODE_MAIN,1) &&
// ADX is rising over current and previous period - daily charts
iRSI(NULL,PERIOD_H1,14,PRICE_CLOSE,0)<70)
//RSI is less than 70 on 60 minute charts - ie not overbought
Condition="Uptrend";

Identifying suitable market entry conditions


To achieve our automatically generated entries we need to be able to identify overbought and oversold conditions on shorter term timeframes in a trending market.

In this example we will use a fast stochastic oscillator set at 5,3,3 (the standard setting for fast)
We have two types of entry:-

Buying a dip in an uptrend

Identified using fast stochastics when the main line crosses up over the signal line

Selling a rally in a downtrend

Identified using fast stochastics when the signal line crosses down over the signal line

Technical Indicators in Automated Trading

The MT4 MQL4 code for dip buying is:-

if (Condition=="Uptrend" &&
//if market condition is uptrend
iStochastic(NULL,PERIOD_M5,5,3,3,MODE_SMA,0,MODE_MAIN,1)<
iStochastic(NULL,PERIOD_M5,5,3,3,MODE_SMA,0,MODE_SIGNAL,1) &&
iStochastic(NULL,PERIOD_M5,5,3,3,MODE_SMA,0,MODE_MAIN,0)>
iStochastic(NULL,PERIOD_M5,5,3,3,MODE_SMA,0,MODE_SIGNAL,0) &&
//main line has crossed up over signal line on 5 minute stochastics
TimeCurrent()>Entry_Time+600)

Note: The system uses an Entry time variable to restrict the trade frequency. This means that trades are always 600 seconds apart (in this case) if the appropriate entry conditions are met. Without this code snippet MT4 would open hundreds of trades until the account equity was used up and an error code 134 was generated. (134= Not enough money!)

Stop Loss Levels

In our system we set our stop loss manually at 50 pips. However, it is possible to set the stop based on more pair specific methods such as:-

  • A previously calculated swing point
  • A pivot level either above or below the current price action - depending on trade direction

All of this can be automated if required.

Track Profit and Exit Positions.

In this system we will use a 50 pip trailing stop and not define a specific exit price. Bearing in mind our system is intended to lock onto short term trends it is arguably counter productive to define a precise exit level. This of course means that our risk/reward ratio is somewhat dynamic depending on the market conditions. In volatile markets the risk reward ratio may suffer as positions may be closed prematurely for small profits by the trailing stop. However in normal trending market conditions the Risk/Reward ratio would improve markedly.

The trailing stop code for long trades in MT4 MQL4is:-

double TStop;
//variable for defining size of trailing stop

for (int o=0;o<OrdersTotal();o++)
//loop for scanning through open orders
{
OrderSelect(o,SELECT_BY_POS); //Orderselect function
if (OrderComment()==CA[ID][11]) TStop=50*Point;
//if OrderComment is specific to this system allocate a 50 pip trailing stop
if (OrderType()==OP_BUY && (OrderProfit()+OrderSwap()>0) && OrderSymbol()==Symbols)
//if order is a buy order and Profit+Swap>0 and the order Symbol is correct do the following..
{
if (Bid-OrderOpenPrice()>TStop)
{
if (OrderStopLoss()<Bid-TStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TStop,OrderTakeProfit(),Red);
//modifes the selected order by changing the take profit price according to the trailing stop
defined above
return(0);
}
}
}

Note: Our system uses a two dimensional array for holding order comment data. This method allows the system to allocate specific order types for any currency pair. In this case, our trend following system uses Comment Array location ID,11 - CA[ID][11]. Where ID is an integer used to automatically determine the Symbol() data for the currency pair ie 0="USDJPY" or 1="GBPUSD". The next number, 11, is simply the location where the order comment is stored as a string variable. This could be "Trend - Buy Dip" or "Trend - Sell Rally". This approach is very useful because it allows one generic program to be run across any currency pair therefore massively reducing coding replication.

Equity Curve for Automated Trading System.


Notes:
This was a slightly modified system with the following parameters:-

Period: 1/1/05-2/12/08 - Pair: Cable
Trend identification (uptrend)
5MA rising on daily charts
10MA rising on daily charts
5MA>10MA on daily charts
ADX rising on daily charts
ADX>30 on daily charts
Entry (Long)
Fast stochastic main crossing up over signal line
Main line is in oversold conditions <30
Stops
100 pip SL
Take Profit
100 pips - no trailing stops.

Technical Indicators in Automated Trading Technical Indicators in Automated Trading Technical Indicators in Automated Trading

Observations on system performance

The equity curve is quite interesting as the system performed well during strongly trending periods but poorly when the trend wasn't so strong. The lagging nature of the ADX indicator is partly to blame for this performance issue. Clearly there is potential merit in having multiple systems which are designed for specific market conditions.

The system above could be improved in several ways such as:-

  • Using multi-lot orders with scaling out code to leave something in the market
  • Variable position sizing based on volatility and account equity and notional account equity/risk reduction in loosing streaks
  • Inclusion of filters based around support and resistance eg pivots, longterm trendlines, Fibonacci sequences etc
  • Win /Lose logic where the system skips a trade if the previous trade was a loser

Pitfalls of using indicators for automated trading

The obvious problem with indicators is the fact that they are all lagging in nature as they are calculated from previous pricing data. Given this, there is an inherent risk in basing trading decisions on historical price action. Markets can change direction at any time but on balance if we can stay with the medium term term trend we should give our systems a fighting chance.

Technical Indicators in Automated Trading

The diagram above is a good example of where indicator lag took us into the market just as it turned. The system took a short position right at the end of a multi hour downtrend before price action reversed. This trade was stopped out. Note the Williams %R indicator was signalling a potential market turn which is in fact exactly what happened. However, our algorithm is not using Williams for it's entries! This could easily be incorporated though and backtested.

If you examine the current ADX reading on hourly charts for a fast moving currency like EURJPY the reading will flick up and down with the price action. This means that we cannot rely on the realtime reading in terms of making a decision about trend. In order to get a stable reading we need to go back to the previous hour ie an actually 'plotted' figure. This is effectively where indicator lag creeps into out system.

Overbought/Oversold conditions.

If overbought /oversold indicators are peaking it does not guarantee a change of direction. The recent price action on dollar pairs is a good example where trading on indicators could have led to incorrect decisions. There must be confirmation of a reversal before the trade is executed.

Technical Indicators in Automated Trading

Any long trades made based on oversold indicators within this multi day downtrend would most likely have failed. This pair did in fact have a small relief rally and then continued to tank down to 1.5670.

Conclusions

We have now explored the development of a simple trend following algorithmic trading system based on technical indicators and multiple timeframes. There are many additional components which could be added to such a system such as:-

  • Smarter position management where multiple lots would be traded and profit taken at progressive points by splitting the original order. From a programmatic point of view this is tricky in MT4 because when an order is split, the original order comment changes to "split from ##order number'##" We therefore lose our ability to search and select orders based on specific comments ie "Trend - Buy Dip". A more comprehensive order tracking, selection and processing system would be required to handle multi-lot orders and scale in/out functionality.
  • Inclusion of Pivot level data in our algorithms - this may be useful for intra day trades as the system could inhibit trades around key pivot levels where price action may reverse or be volatile.
  • Inclusion of major support and resistance levels - this could be automatically derived from Fibonacci sequences and swing high/low points
  • Restricting the maximum number of trades per pair -
    This allows us to control our market exposure and in turn risk management. The system could be designed to only allow x lots for any given pair to be traded simultaneously. An algorithm could be written to allow the maximum lot sizing to increase/decrease with account equity or user defined risk profile
  • Dynamic Position Sizing based on Volatility and Account Equity.
    This was a key ingredient in Salomon's Turtle system which calculated the position size for each trade based on market volatility (ATR - Average True Range) and a constant percentage risk figure such a 1% of account equity. As account equity increases so in turn does the permitted order size. This creates compounding on the system equity curve so the account equity increases more quickly over time. "The more you make the more you make!"

Creating the perfect algorithmic trading system is rather like finding the golden goose. In my opinion flow data is the magic ingredient which defines who wins and loses in FX, particularly in short term intraday trading. Without access to flow, our systems will only ever be able to follow what has already taken place in the markets. If we design our systems to track long term fundamental moves then we should be able to mitigate against the effects of intraday flow issues and general short term volatility.

Crispin Scruby has been trading FX and developing automated trading systems since 2005. He is based in Dubai, UAE and can be contacted at info@fxalgotrader.com