Download MetaTrader 5

Using MetaTrader 4 for a Time Based Pattern Analysis

5 February 2008, 12:27
Giampiero Raschetti
1 802


Reading posts at the Automated Trading Championship forum and interviews leads always to a lot of interesting information buried in a lot of noise.

The arguments provided by William Boatright (Wackena) in his interview, aroused my attention for the time based approach used to chose one single hour of the day to take one single trade in a daily swing trading technique.

So I started gathering information about the time based entry approach and decided to realize a system that should be able to verify the real effectiveness of this technique.

A code attached to the article is realized without a real exit strategy just to give you an example of what kind of time patterns you could expect using MetaTrader for data mining and statistical investigation over a relatively long data sequence.

Searching Literature

First of all I looked for the confirmation of this idea in literature and I found a very interesting article about this subject in "New Trading Systems and Methods" by Perry J. Kaufman, a really heavy bible in technical analysis adventure. Chapter 15 tells about pattern recognition, and one of the very first arguments is the time of day and trading habits.

In this chapter he mentions Frank Tubbs' Stock Market Correspondence Lessons where he explained the six dominant patterns in the stock market based on US trading hours, and where in rule 4 he asserts: "if the market has been bullish until 2:00 p.m. it will probably continue until the close and into the next day".

Well 2:00 p.m. GMT-5, is exactly 20:00 GMT+1, the time in which Wackena puts his trades in the contest. This is the first interesting confirmation about the effectiveness of this technique. Other interesting references about the subject are presented in this Kaufman's chapter.

Implementing the Basic EA

The first consideration about implementing a system that should catch a trade direction at a specific time of the day, is that the only relevant signals you can look for are those that give you information about a trend direction, and that countertrend methods or breakout systems are not suitable for this purpose.

A basic Expert Advisor was presented in this article and a block diagram representing the operation flow is reported here.


  • Analyzer routine calls a sequence of signal detectors and gives response about the trend strength at that moment.
  • TrailingStopEngine dynamically evaluates next profit target and new trailing stop depending on average true range or something like that.
  • CurrentOpenOrders returns the number of opened orders.
  • A LoopThroughOrders loops through all orders and if necessary applies new trailing stops and new profit targets, or decides to close out the trade for some particular event.
  • BlockFilterTrading decides if there are specific conditions, in which we do not want to trade at all.
  • MoneyManagement returns the lot size as a function of risk.
  • PlaceOrder, if possible, places orders in the direction defined by the Analyzer.

Operation and Optimization Results

I use MetaTrader engine on Apple MacBookPro using a virtual pc running under Parallel Desktop where it runs fast and reliably and I can take fast snapshots of the MS-windows virtual machine very easily for documentation.

Backtesting has been done over the EURUSD currency pair over available data from January, 1 2007 up to December, 29 2007 in a 15 minutes time frame where results seem to be satisfactory.

Main operation parameters used in this article are taken from a first optimization process and you can try yourself different combination of such parameters.

The only consideration about choosing Take Profit and Stop Loss parameters used for this test, is that here we are not really interested in maximizing the balance nor any other possible optimization parameter presented by MetaTrader, but indeed we only need to maximize the number of profit trades to stress the entry strategy.

Any optimization of other results should be done in a later phase.

Here is the code of the Analyzer module where, for testing purpose, you can add any other signal detector.

Two different signals must agree to chose the right direction.

//| Price Direction Analyzer 
int Analyzer()  
 int  signalCount=0; 
 signalCount += EntrySignal1(); 
 signalCount += EntrySignal2(); 
int EntrySignal1() 
{ // Long term SMA trend detect 
 int i,Signal; 
 int LongTrend=0; 
   if (iMA(Symbol(),PERIOD_H4,S1_MA_FAST,0,MODE_LWMA,PRICE_TYPICAL,i) > iMA(Symbol(),PERIOD_H4,S1_MA_FAST,0,
 if( LongTrend < 0) 
int EntrySignal2() 
{ // Daily MACD 
   int Signal; 
   return (Signal); 

Trading hour is matched in a block trading filter module that can be simply realized as follows.

Modular architecture described can easily leave space for new blocking filters in the operation flow.

bool BlockTradingFilter1() 
 bool BlockTrade=false;  //trade by default 
 if (UseHourTrade) 
   if( !(Hour() >= FromHourTrade && Hour() <= ToHourTrade && Minute()<= 3) ) 
      //  Comment("Non-Trading Hours!"); 
 return (BlockTrade);  

As a matter of fact we should be able to have a lot of small profit trades without considering the whole balance at all.

Here is the main optimization setting:

To analyze time intervals that give best results you must set the FromHourTrades from 0 to 23 running at step of 1 hour and check Optimization flag in the backtesting setting form before starting the process.

Here are the optimization results:

As you can see there are hours in which trading using trend detection techniques should be very dangerous, while during other day hours choosing trend direction should be considerably more profitable, and this time interval, between 19:00 and 22:00 GMT+1, the afternoon in Eastern Time zone, is when every news has been digested by the market.

In this case, with available historic data, the peak hour obtained from optimization process corresponds to 21:00 GMT+1 (Central Europe Time).

Sure this results should be considered valid for the 2007 forex market, but Frank Tubbs old consideration about trading habits let us hope they should be valid in larger time periods.

And here are the detailed results from optimization process:

You must consider that this results depend also on trending signals chosen to decide on the direction of orders, and I can tell you that in this time-based strategy, choosing from a large number of different signals leads to quite similar results, but surely you can test other signals and maybe let me know your results.

And here are backtesting reports at 21:00 GMT+1

As you can see there are 160 total trades and 154 profit trades (96.86%).

This information confirms the one made by Wackena in his interview.

Introducing Time-Based Stop Loss

The number of trades during one year backtesting process may suggest that we should be able to improve trading results by introducing a time based Stop Loss, that should leave room for new orders, if there are any losses after 23 hours being in the market.

To do this you can simply set the UseTimeBasedStopLoss flag to true and try different optimization parameters.

The following report table shows the consequence of this strategy change.

As you can see this exit strategy lets you guess that some long swing trade, in a weak market, could protect you from adding undesirable orders in bad moments, so it should be better to be patient and wait till the market exits dangerous sideways.


The strategy of analyzing time based pattern recognition on trading habits suggests further more investigation and justifies adding a valid money management strategy to this Expert Advisor and most of all a valid trailing stop engine, but this should be the argument of a new article.

The code attached can also be used to make further investigation over other patterns and currency pairs to analyze other timely based trading habits and behavior. Just let me know your experience in this investigation.


New Trading Systems and Methods, by Perry J. Kaufman>

The Encyclopedia of Trading Strategies, by Jeffrey Owen Katz,Donna L. McCormick/p>

Forex conquered, by J.L.Person/p>

Trading with the odds, by Cynthia A.Kase

Attached files |
Sauron_1_3.mq4 (7.15 KB)
Last comments | Go to discussion (6)
Giampiero Raschetti
Giampiero Raschetti | 5 Feb 2008 at 17:33
Erik.VH wrote:

Hi Giampiero,

Can't find the code ?

Great article.




Just a misunderstanding in publication work flow.
It will be attached as soon as possible.
thanks and best regards
Rosh | 6 Feb 2008 at 07:20
Just a misunderstanding in publication work flow.
It will be attached as soon as possible.
thanks and best regards

Mariusz Woloszyn
Mariusz Woloszyn | 8 Feb 2008 at 13:39
There is no file with EA attached to this article again.
Giampiero Raschetti
Giampiero Raschetti | 15 Feb 2008 at 12:13
The actual Time Based Stop Loss is incorrect and it does not work for more than 23 hours.
This code should correct the problem considering closed trading hours too.
It should be placed in BUY and SELL position.

int k=0;
while(k < TradeHoldingPeriod)
  if(iTime(NULL,PERIOD_H1,k) > OrderOpenTime())
  else break;
if(UseTimeBasedStopLoss && k >= TradeHoldingPeriod && OrderProfit() < 0 )
  if(SignalCount > 0)
MQL4 Comments
MQL4 Comments | 9 Feb 2009 at 02:08
Giampiero Raschetti your timezone idea is actually works ! I also in my practice looked such good zones for opening of trade positions ! Please contact me for discussion ... very very -))
Step on New Rails: Custom Indicators in MQL5 Step on New Rails: Custom Indicators in MQL5

I will not list all of the new possibilities and features of the new terminal and language. They are numerous, and some novelties are worth the discussion in a separate article. Also there is no code here, written with object-oriented programming, it is a too serous topic to be simply mentioned in a context as additional advantages for developers. In this article we will consider the indicators, their structure, drawing, types and their programming details, as compared to MQL4. I hope that this article will be useful both for beginners and experienced developers, maybe some of them will find something new.

Here Comes the New MetaTrader 5 and MQL5 Here Comes the New MetaTrader 5 and MQL5

This is just a brief review of MetaTrader 5. I can't describe all the system's new features for such a short time period - the testing started on 2009.09.09. This is a symbolical date, and I am sure it will be a lucky number. A few days have passed since I got the beta version of the MetaTrader 5 terminal and MQL5. I haven't managed to try all its features, but I am already impressed.

Applying fuzzy logic in trading by means of MQL4 Applying fuzzy logic in trading by means of MQL4

The article deals with examples of applying fuzzy set theory in trading by means of MQL4. The use of FuzzyNet library for MQL4 in the development of an indicator and an Expert Advisor is described as well.

Deep neural network with Stacked RBM. Self-training, self-control Deep neural network with Stacked RBM. Self-training, self-control

This article is a continuation of previous articles on deep neural network and predictor selection. Here we will cover features of a neural network initiated by Stacked RBM, and its implementation in the "darch" package.