Using MetaTrader 4 for a Time Based Pattern Analysis
Introduction
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, https://championship.mql5.com 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.
Where:
- 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(); return(signalCount); } //+------------------------------------------------------------------+ //| ENTRY SIGNALS BLOCK MODULES //+------------------------------------------------------------------+ int EntrySignal1() { // Long term SMA trend detect int i,Signal; int LongTrend=0; for(i=0;i<3;i++) { if (iMA(Symbol(),PERIOD_H4,S1_MA_FAST,0,MODE_LWMA,PRICE_TYPICAL,i) > iMA(Symbol(),PERIOD_H4,S1_MA_FAST,0, MODE_LWMA,PRICE_TYPICAL,i+1)) LongTrend++; else LongTrend--; } if( LongTrend < 0) Signal=-1; else Signal=1; return(Signal); } int EntrySignal2() { // Daily MACD int Signal; if (iMACD(NULL,PERIOD_D1,S2_OSMAFast,S2_OSMASlow,S2_OSMASignal,PRICE_WEIGHTED,MODE_MAIN,0) > iMACD(NULL,PERIOD_D1,S2_OSMAFast,S2_OSMASlow,S2_OSMASignal,PRICE_WEIGHTED,MODE_MAIN,1) ) Signal=1; else Signal=-1; 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.
//+------------------------------------------------------------------+ //| FILTER BLOCK MODULES //+------------------------------------------------------------------+ bool BlockTradingFilter1() { bool BlockTrade=false; //trade by default if (UseHourTrade) { if( !(Hour() >= FromHourTrade && Hour() <= ToHourTrade && Minute()<= 3) ) { // Comment("Non-Trading Hours!"); BlockTrade=true; } } 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.
Conclusion
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.
References
New Trading Systems and Methods, by Perry J. Kaufman
https://championship.mql5.com/p>
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
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Hi Giampiero,
Regards
Erik
It will be attached as soon as possible.
thanks and best regards
Giampiero
Just a misunderstanding in publication work flow.
It will be attached as soon as possible.
thanks and best regards
Giampiero
This code should correct the problem considering closed trading hours too.
It should be placed in BUY and SELL position.