Extracting historic data from MetaTrader
Written by andrew on September 16, 2009 – 9:18 pm
If you’ve looked at my plan for forex, you’ll know that my first step is to create an EA that dumps the historic data out of MetaTrader into a CSV file so that I can load this into my Scheme programs creating the genetic programs.
Here’s the code for DataDumper.mq4 that does just that :-
//+---------------------------+
//| Historic Data Dumping EA |
//+---------------------------+
#property copyright "Andrew Whaley"
extern int min_year = 2008;
extern int max_year = 2009;
// Global scope
int handle;
int init()
{
int p = Period();
string pd;
if (p == 1) pd = "M1";
else if (p == 5) pd = "M5";
else if (p == 15) pd = "M15";
else if (p == 30) pd = "M30";
else if (p == 60) pd = "H1";
else if (p == 240) pd = "H4";
else pd = "D1";
string filename = StringConcatenate(Symbol(), "_", pd, ".csv");
handle = FileOpen(filename, FILE_CSV|FILE_WRITE, ',');
FileWrite(handle, "Date", "Time", "Volume", "Low", "Open", "Close", "High", "Bid", "Ask");
return(0);
}
int deinit()
{
FileClose(handle);
return(0);
}
int start()
{
string d,m,y,h,mi;
double open,close,high,low;
double vol;
if ((Year() >= min_year) && (Year() <= max_year))
{
if (Day() < 10) d = StringConcatenate("0", DoubleToStr(Day(),0));
else d = DoubleToStr(Day(),0);
if (Month() < 10) m = StringConcatenate("0", DoubleToStr(Month(),0));
else m = DoubleToStr(Month(),0);
y = DoubleToStr(Year(),0);
if (TimeHour(TimeCurrent()) < 10) h = StringConcatenate("0", DoubleToStr(TimeHour(TimeCurrent()),0));
else h = DoubleToStr(TimeHour(TimeCurrent()),0);
if (TimeMinute(TimeCurrent()) < 10) mi = StringConcatenate("0", DoubleToStr(TimeMinute(TimeCurrent()),0));
else mi = DoubleToStr(TimeMinute(TimeCurrent()),0);
string ds = StringConcatenate(""", d, "-", m, "-", y, """);
string ts = StringConcatenate(""", h, ":", mi, """);
open = iOpen(NULL, 0, 1);
close = iClose(NULL, 0, 1);
high = iHigh(NULL, 0, 1);
low = iLow(NULL, 0, 1);
vol = iVolume(NULL, 0, 1);
FileWrite(handle, ds, ts, vol, low, open, close, high, Bid, Ask);
}
return(0);
}
Here’s how to use it :-
- Open the chart that you want use it on and attach the DataDumper EA,
- Press F6 for the Tester
- Select the symbol and period
- Select the ‘Open prices only’ model
- Configure the EA properties for start and end year
- Run the backtest
When the test has finished, check your <METATRADER>/tester/files directory for the resultant CSV file.
Hi, I am the webmaster of the french community on automated trading (http://www.trading-automatique.fr) and I find your job very interesting.
Would it be possible in exchange of links to your pages to translate some of your articles like this one?
Nicolas
Hi Nicolas,
Thanks for the comment – I’ve added your site as a link. Please feel free to link to or translate any of the articles.
Thanks
Andrew