You need to enable JavaScript in order to visit our site!
 
Logo PTMC
NAVIGATION
CANCEL
 
or via PTMC account
Restore password
or via PTMC account
Logo PTMC
NAVIGATION
or via PTMC account
Restore password
or via PTMC account
or via PTMC account
Restore password
or via PTMC account
PTMC team 13.03 2014

Trend strategy implementation example

Hey there, Protraders!

I want to share with you my thoughts about the Algotrading that is very popular recently. And also consider the example of its implementation using the Protrader terminal.

So what is Algotrading? As follows from the term itself, it is the usage of the formal algorithms for decision making in trading.

Why is Algotrading? What is the advantage of Algotrading before any other method of trading? The fact is that the trading systems which are able to profit from market, in any case, are characterized by a statistical advantage of its algorithm over the market. When implementing the strategy of "manual" method the errors are inevitable due to the impact of external and internal factors on the trader. These implementation errors of the strategy are commonly referred to the "human factor". Error that is introduced into the trading system by trader may negate statistical advantage of the selected trade algorithm. Therefore the implementation of the trading system from the moment of market analysis in finding the entry point to the moment of closing the position is passed on to the shoulders of specialized programs - trading robots. Trading robot implements your chosen trading strategy with ideal accuracy, seven days a week, 365 days a year. It is noteworthy that this approach is only possible in cases when the algorithm of the trading system lends itself to complete formalization.

How to create a working algorithm and trading robot based on it? Let's consider the process of formalization of the trading system in the Protrader terminal.

The basis of the trading system is a trading idea, i.e. such a market situation and corresponding strategy that somehow allows you to get a statistical advantage. Let's consider the simplest pattern. An interesting feature was noted during long-term observation of the currency pair EUR/USD. After a unidirectional momentum of certain strength we can expect continuation of the movement in the same direction with some probability. Traders call this effect as "the inertia of price". On the price chart of the terminal Protraderit looks like this:

Trend strategy implementation

Here: 1 – momentum, 2 - inertial movement.

How to profit from this observation? Naturally, buy asset after bullish momentum and sell the asset after the bearish momentum. Trading idea was formed. Need to proceed to its implementation. Our challenge is to describe the most accurately the investigated trading situation in any available for us way. Using the «AlgoStudio» tool that is built-in Protrader terminal, let's implement the trading algorithm in a programming language MQL4 («AlgoStudio» also enables us to use an alternative programming language - C #).

To start «AlgoStudio» go to menu «Tools»:

«AlgoStudio» go to menu «Tools»

The appropriate window will be opened, select the item «New module» – «MQL4» – «Advisor». Let’s name the trading robot: «Momentum».

«AlgoStudio» go to menu «Tools»

What algorithm will match the selected trading idea? Let's describe it with the help of two well-known technical indicators: «Standard Deviation» and «Alligator». With the help of the indicator «Standard Deviation » we will measure the relative strength of the momentum. After all, the indicator «Standard Deviation » measures the market volatility or to be more precise, it shows the magnitude of price fluctuations around its moving average. And with the help of the disclosed averages fan of the indicator «Alligator» we will determine the side of the position. After all, the creator of this indicator, Bill Williams used it as pointer of the trend. Disclosed fan of the averages indicates not only the direction of the prevailing trend but also says about sufficiently strength of the directional movement which gives us the opportunity to catch the inertial movement of the asset.

Let’s create external variables of our trading robot that will be the parameters of indicators and other variables of the trading system.

#define MAGIC  20050320                //  The unique position number
extern double lot               = 0.1; // Position volume
extern int TPbuy                = 60;  // Profit amount in pips upon reaching which the position will be closed. Long positions.    
extern int SLbuy                = 30;  // Profit amount in pips upon reaching which the position will be closed.  Long positions.
extern int TPsell               = 60;  // Profit amount in pips upon reaching which the position will be closed. Short positions.        
extern int SLsell               = 30;  // Loss amount in pips upon reaching which the position will be closed.  Short positions. 
extern int std_minbuy           = 348; // The minimum value of the indicator StandartDiviation at which the long position will be opened.
extern int std_maxbuy           = 362; // The maximum value of the indicator StandartDiviation at which the long position will be opened.
extern int std_minsell          = 273; // The minimum value of the indicator StandartDiviation at which the short position will be opened.
extern int std_maxsell          = 316; // The maximum value of the indicator StandartDiviation at which the short position will be opened.

To visually assess the correct application of the above indicators let’s take them out on the working chart of Protrader terminal. To provide this, select the needed indicators with standard setting in the menu «Add indicator».

menu «Add indicator»

The following shows how working charts will look like during the formation of the signals on the opening long and short positions. Signal to open a long position:

Signal to open a short position:

Signal to open a short position:

Here: 1 – the maximum level of SD indicator below which it is possible to open a position; 2 – the minimum level of SD indicator above which it is possible to open a position; 3 – disclosed fan of the averages.

The signal identification units to buy and to sell in MQL4 will look like this:

//+------------------------------------------------------------------+  The signal processing unit of the long position opening.
bool Signal_Buy() {
   double std_now = iStdDev(NULL,19,20,0,1,0,1)*100000;                              // Obtaining values of the indicator StandartDiviation.
   double   JAW=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORJAW,1);                   // Obtaining values of the indicator Alligator.
   double   TEETH=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORTEETH,1);               // Obtaining values of the indicator Alligator.
   double   LIPS=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORLIPS,1);                 // Obtaining values of the indicator Alligator.
   if (JAW<TEETH && TEETH<LIPS && std_now > std_minbuy && std_now < std_maxbuy)      // Conditions of disclosed fan for the long position and limit StandartDiviation values.
   return(true);
   return(false);
}
//+------------------------------------------------------------------+ The signal processing unit of the short position opening.
bool Signal_Sell() {
   double std_now = iStdDev(NULL,19,20,0,1,0,1)*100000;                              // Obtaining values of the indicator StandartDiviation.
   double   JAW=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORJAW,1);                   // Obtaining values of the indicator Alligator.
   double   TEETH=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORTEETH,1);               // Obtaining values of the indicator Alligator.
   double   LIPS=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORLIPS,1);                 // Obtaining values of the indicator Alligator.
   if (JAW>TEETH && TEETH>LIPS && std_now > std_minbuy && std_now < std_maxbuy)      // Conditions of disclosed fan for the short position and limit StandartDiviation values.
   return(true);
   return(false);
}

We will enter the position by a market order. The positions opening unit:

//+------------------------------------------------------------------+ The signal processing unit of the short position opening.
bool Signal_Sell() {
   double std_now = iStdDev(NULL,19,20,0,1,0,1)*100000;                              // Obtaining values of the indicator StandartDiviation.
   double   JAW=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORJAW,1);                   // Obtaining values of the indicator Alligator.
   double   TEETH=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORTEETH,1);               // Obtaining values of the indicator Alligator.
   double   LIPS=iAlligator(0,30,13,0,8,0,5,0,1,0,MODE_GATORLIPS,1);                 // Obtaining values of the indicator Alligator.
   if (JAW>TEETH && TEETH>LIPS && std_now > std_minbuy && std_now < std_maxbuy)      // Conditions of disclosed fan for the short position and limit StandartDiviation values.
   return(true);
   return(false);
}

Now we need to specify the criteria for position exit, as in the case of profit and in the case of loss. For simplicity, we will use fixed levels «Take Profit» and «Stop Loss» separately for long and short positions. No additional conditions of the open position accompanying we will not use.

Also not to open several positions on one signal, enter the open positions control unit:

//+------------------------------------------------------------------+ The control unit of open positions.
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
   for(int i=0;i<OrdersTotal();i++)                              // Running a cycle of sorting orders.
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break; // The open position selecting.
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC)   
        {
         if(OrderType()==OP_BUY)  buys++;                        // Determination of the position type.
         if(OrderType()==OP_SELL) sells++;                       // Determination of the position type.
        }
     }
   if(buys>0) return(buys);
   else       return(-sells);
  }

The next step in the implementation of the trading strategy algorithm will be the determination of the optimal values of the variables («Take Profit», «Stop Loss», signal levels of SD indicator) separately for long and short positions. To provide this use the built-in AlgoStudio optimizer of trading strategies. Open the tab «Optimization», in «Strategy Variables»window select the optimized parameters, and the boundaries of their optimization. Select the target parameter of optimization in «Targets» window, in this case we will optimize by profitability «Profit Factor». In the window «Properties – Optimization setup» indicate the period of optimization: time-frame m15, from 01/01/2008 to 01/01/2010. Symbol: EUR/USD.

window «Properties – Optimization setup»

At the end of the optimization we will see a table with possible combinations of optimized parameters values which suited to the objective optimization function, also you can build the optimization charts using different combinations of optimized parameters. These charts can be useful in determining of the most stable combinations of the trading system parameters. After selecting one of the parameters sets, we can check it out at the plot of history, which was not included in the optimization. Thus, measurably, determine whether the resulting set of parameters is profitable or optimizer "has adjusted" it under the optimized plot of the history. Question of the optimization plots selection «In-Sample»and checking «Out-Of-Sample» is too extensive and requires separate consideration. The described method of the optimized parameters verification has the common name «Walk Forward». This optimization method is also implemented in Protrader terminal, but its usage will be discussed in detail in one of the next articles.

Let's move on to the checking of the trading system parameters' set obtained through optimization. To provide this, open the tab «Backtesting».The workspace will be opened where we will see the quotes chart of the tested symbol, the «Performance»window and also the «Properties» window, in which you can modify testing parameters of the trading strategy. In «Backtesting» settings select the range so as not to capture the period of history in which the optimization was performed. In this case the test was carried out from 01/01/2010 to 01/01/2014. After opening the «Performance» tab we can see a summary table of statistical indicators of our system with the selected settings.

window «Properties – Optimization setup» 2

Also Protrader terminal allows generating the detailed report in HTML format («Export to HTML» button). Tab «Charts» gives you an opportunity to get acquainted with detailed graphical representation of «Backtesting» statistics.

trend strategy

It may be noted that on the plot «Out-Of-Sample», the trading system that was created by us, remained stable, although its statistical parameters are not very high. The sampling is large enough and it can be considered representational. This says about the existence of a statistical advantage when trading the selected signal on the selected symbol. Since this system was chosen as a training example then the descriptive methods of trading signals that are used, are not optimal and cannot be taken as a finished trading solution. The above example is only a first approximation in a long and painstaking process of creating a profitable trading strategy. It is also worth noting that the system lacks filters and competent management of the position. The code of trading strategy with comments and detailed report is in an attachment.

Momentum

Report.zip

Discussion
Join PTMC community to post your comments
No comments yet. Be the first.
PTMC is a professional trading platform that combines all the best charting and analytical tools to trade on different financial markets. It is developed by PFSOFT UK LTD, a global provider of trading technology for banks & brokers
© 2017. PTMC is based on Protrader technology
Head office
PFSOFT UK LTD
20 Centenary Avenue
South Shields, Tyne and Wear,
NE34 6QH
United Kingdom
Ukraine office
TOV PTMC
26, Naberezhna str., Dnipro,
Dnipropetrovs'k region,
Ukraine
Contact us
Phone: +380 56 740 30 01
E-mail: info@protrader.org
Skype: PTMC_support
Social groups