Tester_v04_5a_GBPUSD

Download script
Author: Copyright � 2008, MetaQuotes Software Corp.
Profit factor:
0.00

This automated trading script is designed to execute trades on the MetaTrader 4 platform by using a sophisticated machine learning approach. Rather than relying on simple, fixed rules (like "if the price goes up, then buy"), this script analyzes historical data to identify patterns and make predictions.

Here is a breakdown of how the logic works in plain English:

Data Collection and Analysis

The core of the script revolves around gathering a large amount of historical market information. It looks at several different timeframes simultaneously—specifically 5-minute, 1-hour, and 4-hour charts. For each of these, it tracks:

  • Price Action: The high, low, and closing prices of the candles.
  • Moving Averages: It calculates various moving averages (5, 10, and 15 periods) across all those different timeframes.

By combining this data from multiple horizons, the script builds a multi-dimensional view of the market, attempting to understand both short-term momentum and long-term trends at the same time.

The Machine Learning Engine

The script utilizes a "Support Vector Machine" (SVM) logic (referenced via external libraries). This is an advanced statistical method used to classify data into categories.

  1. Training & Testing: The script processes a large sample of historical lines (2,000 lines) to "learn" how the market behaves. It then applies this learning to a separate set of test lines (800 lines) to see if its predictions hold up.
  2. Prediction: Based on the patterns it recognizes, the engine generates a prediction for the current market state. It labels these predictions as either "Buy" signals or "Sell" signals.

Execution Logic

Once the machine learning model produces a prediction, the script follows a specific set of rules to manage your trades:

  • Timing: The script is designed to check for new data every time a new 1-minute candle appears.
  • Order Management: It checks if you already have an open position. If the "Max Orders" limit hasn't been reached, it looks at the latest predictions from the model.
  • Decision Making: If the majority of the recent short-term predictions lean toward a "Buy," it opens a Buy order. If they lean toward a "Sell," it opens a Sell order.
  • Safety Measures: Every trade is automatically equipped with a Stop Loss (to limit losses) and a Take Profit (to secure gains), based on the specific pip values defined in the settings.

Monitoring and Logging

The script also includes a "Global Variable" monitoring system. It tracks the status of various major currency pairs (like EURUSD, GBPUSD, etc.) and displays this information directly on your trading chart as a comment. Additionally, it maintains a detailed log file (SVM_EA.log) that records every successful trade, every error encountered, and the specific price levels at which actions were taken, allowing you to review the performance of the logic after the fact.

Price Data Components
Series array that contains close prices for each barSeries array that contains the lowest prices of each barSeries array that contains the highest prices of each barSeries array that contains open time of each bar
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reached
Indicators Used
Moving average indicator
Miscellaneous
Uses files from the file systemIt writes information to file
3 Views
0 Downloads
0 Favorites
Tester_v04_5a_GBPUSD
//+------------------------------------------------------------------+
//|                                                   Tester_v02.mq4 |
//|                      Copyright © 2008, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
#include <Train_04.mqh>

/*
EURUSD s/l=160 pips      70
EURJPY s/l=200 pips
GBPUSD s/l=152 pips
EURCHF s/l=50pips
AUDUSD s/l=75pips

EURUSD s/l=70 pips
EURJPY s/l=90 pips
GBPUSD s/l=67 pips
EURCHF s/l=22pips
AUDUSD s/l=33pips

*/
#define NR_OF_SAMPLE_LINES   2000
#define NR_OF_TEST_LINES     800
#define NR_OF_TEST_BARS      10
#define FUTURE_WINDOW        300
#include <stdlib.mqh>

extern string Symbol1= "GBPUSD";
extern	int StopLoss=70;		//70
extern	int TakeProfit=70;	//70								

extern datetime BeginDate= D'2008.09.01 00:00';
int CurrBar1;
int      MagicNumber1 = 1001;
extern double  Lots=0.1;
int     MaxOrdersTotal1=1;
   double C=32.0;
   double gamma=2.0;
int f1=     0;  //0-no file ,1-file ma,2-file ma diff,3-file libsvm
int f2=     1;  //0-don't normalize, 1-normalize with std, 2-normalize with train mean, 3-normalize with range, 4-normalize with train range
int f3=    3;  //0-do nothing 1-create model 2-predict only 3-create model and predict
int f4=     0;   //0-no predict file, 1-predict file, 2-predict and range file
   
   
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int myBars1;

bool isNewBar1(int tf1)
  {
//----
   bool res=false;
   if (myBars1!=iBars(Symbol(),tf1))
   {
      res=true;
      myBars1=iBars(Symbol(),tf1);
   }  
  
//----
   return(res);
  }
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
  CurrBar1=iBarShift(Symbol(),PERIOD_M1,BeginDate,false); 
  if(StringFind(Symbol(),"m",0)>0)  
  {
    Symbol1=Symbol1+"m";
  }
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+

double t[NR_OF_SAMPLE_LINES];
double c[NR_OF_SAMPLE_LINES];
double l[NR_OF_SAMPLE_LINES];
double h[NR_OF_SAMPLE_LINES];       
double ma5_M5[NR_OF_SAMPLE_LINES];
double ma10_M5[NR_OF_SAMPLE_LINES];
double ma15_M5[NR_OF_SAMPLE_LINES];
double ma5_H1[NR_OF_SAMPLE_LINES];
double ma10_H1[NR_OF_SAMPLE_LINES];
double ma15_H1[NR_OF_SAMPLE_LINES];
double ma5_H4[NR_OF_SAMPLE_LINES];
double ma10_H4[NR_OF_SAMPLE_LINES];
double ma15_H4[NR_OF_SAMPLE_LINES];

double ptr_predict_label_1[NR_OF_TEST_LINES];
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int NrOrdersBuy(int Magic ) 
{
   int total = OrdersTotal();
   int nrLongs = 0;
   for(int cnt=0; cnt<total; cnt++) {
      OrderSelect(cnt, SELECT_BY_POS);
      if( OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic )
         continue;
      if (OrderType()==OP_BUY) nrLongs++;
   }
   return(nrLongs);
}   
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int NrOrdersSell(int Magic ) 
{
   int total = OrdersTotal();
   int nrShorts = 0;
   for(int cnt=0; cnt<total; cnt++) {
      OrderSelect(cnt, SELECT_BY_POS);
      if( OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic )
         continue;
      if (OrderType()==OP_SELL) nrShorts++;
   }
   return(nrShorts);
} 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string GVAR(string sym)
{
  GlobalVariableSet(sym,2);
  int buy=0;
  int sell=0;
  string s1;
  buy=NrOrdersBuy(MagicNumber1);//0  
  sell=NrOrdersSell(MagicNumber1);//1
  if(buy>0)
    GlobalVariableSet(sym,0);
  if(sell>0)
    GlobalVariableSet(sym,1);
    
  if(StringFind(sym,"m",0)>0)  
  {
    s1=""+DoubleToStr(GlobalVariableGet("EURUSDm"),0)+
               DoubleToStr(GlobalVariableGet("EURCHFm"),0)+
               DoubleToStr(GlobalVariableGet("EURJPYm"),0)+
               DoubleToStr(GlobalVariableGet("GBPUSDm"),0)+
               DoubleToStr(GlobalVariableGet("AUDUSDm"),0);  
  }
  else
  {
    s1=""+DoubleToStr(GlobalVariableGet("EURUSD"),0)+
               DoubleToStr(GlobalVariableGet("EURCHF"),0)+
               DoubleToStr(GlobalVariableGet("EURJPY"),0)+
               DoubleToStr(GlobalVariableGet("GBPUSD"),0)+
               DoubleToStr(GlobalVariableGet("AUDUSD"),0);
  }           
    return(s1);            
}  
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int start()
  {
  int i;
  string s1="";

//----
   if (Period() !=PERIOD_M1) 
   {
      Comment("WARNING: Invalid timeframe! Valid timeframe = "+PERIOD_M1);
      return(0);
   }
   if (Symbol() != Symbol1 ) 
   {
      Comment("WARNING: Invalid symbol! Valid symbol = "+Symbol1);
      return(0);
   }
   if (Time[0]<BeginDate) 
   {
      return(0);
   }
   
  //////////////////////////
  string s2=GVAR(Symbol1);  
  Comment(s2);
  //////////////////////////   
if(NrOrders(MagicNumber1 )<MaxOrdersTotal1)    
if(isNewBar1(PERIOD_M1))
{

       int res1=buysell();
       if (res1==1) 
       {
           Sell(MagicNumber1,Lots,TakeProfit,StopLoss );
       }  
       else if (res1==0) 
       {
           Buy(MagicNumber1,Lots,TakeProfit,StopLoss );
       }  
           		       
} 
   
//----
   return(0);
}
//+------------------------------------------------------------------+

int buysell()
{
   for(int i=0;i<NR_OF_SAMPLE_LINES;i++)
   {
      t[i]=iTime(NULL,PERIOD_M5,i);
      c[i]=iClose(NULL,PERIOD_M5,i);
      l[i]=iLow(NULL,PERIOD_M5,i);
      h[i]=iHigh(NULL,PERIOD_M5,i);
      
      ma5_M5[i]=iMA(NULL,PERIOD_M5,5,0,MODE_SMA,PRICE_CLOSE,i);
      ma10_M5[i]=iMA(NULL,PERIOD_M5,10,0,MODE_SMA,PRICE_CLOSE,i);
      ma15_M5[i]=iMA(NULL,PERIOD_M5,15,0,MODE_SMA,PRICE_CLOSE,i);  

      ma5_H1[i]=iMA(NULL,PERIOD_H1,5,0,MODE_SMA,PRICE_CLOSE,i);
      ma10_H1[i]=iMA(NULL,PERIOD_H1,10,0,MODE_SMA,PRICE_CLOSE,i);
      ma15_H1[i]=iMA(NULL,PERIOD_H1,15,0,MODE_SMA,PRICE_CLOSE,i);  

      ma5_H4[i]=iMA(NULL,PERIOD_H4,5,0,MODE_SMA,PRICE_CLOSE,i);
      ma10_H4[i]=iMA(NULL,PERIOD_H4,10,0,MODE_SMA,PRICE_CLOSE,i);
      ma15_H4[i]=iMA(NULL,PERIOD_H4,15,0,MODE_SMA,PRICE_CLOSE,i);
      
      
   }
   for(i=0;i<NR_OF_TEST_LINES;i++)
   {
     ptr_predict_label_1[i]=0;   
   }   
   //Print(t[0]);
   int NrTrainBars=NR_OF_SAMPLE_LINES;
   int NrTestBars=NR_OF_TEST_LINES;
   int FutureWindow=FUTURE_WINDOW;
   int spread=MarketInfo(Symbol(),MODE_SPREAD);
   double Point1=MarketInfo(Symbol(),MODE_POINT);
   //string filename1="c:\\mt4\\t4\\test04_1_"+(myBars1-CurrBar1)+".libsvm";
   string filename1="c:\\mt4\\t4\\test04_1_"+Symbol()+".libsvm";

   Example5(  
                        t,
                        c,
                        l,
                        h,
                        ma5_M5,
                        ma10_M5,
                        ma15_M5,
                        ma5_H1,
                        ma10_H1,
                        ma15_H1,
                        ma5_H4,
                        ma10_H4,
                        ma15_H4,      
						      NrTrainBars, //2200
						      NrTestBars, //800
					         FutureWindow,	//200
					         StopLoss,		//70
					         TakeProfit,	//70								
					         Point1,
					         spread,
		                  filename1,
								C,
								gamma,
								ptr_predict_label_1, //output label 		                  
		                  f1,  //0-no file ,1-file ma,2-file ma diff,3-file libsvm
		                  f2,  //0-don't normalize, 1-normalize with std, 2-normalize with train mean, 3-normalize with range, 4-normalize with train range
		                  f3,  //0-do nothing 1-create model 2-predict only 3-create model and predict
		                  f4   //0-no predict file, 1-predict file, 2-predict and range file
		                  
		       );  
		       
   int buy=0;
   int sell=0; 
   string ss1=""; 
   int res1=2;		         
   //for(i=FUTURE_WINDOW/2;i>=0;i--)   
   //for(i=0;i<NR_OF_TEST_LINES/2;i++)
   //for(i=0;i<NR_OF_TEST_BARS;i++)
   //for(i=NR_OF_TEST_LINES;i>=(NR_OF_TEST_LINES-NR_OF_TEST_BARS);i--)   
   for(i=NR_OF_TEST_BARS;i>=0;i--)
   {
         if (ptr_predict_label_1[i]==1)
         {
           buy++;   
           ss1=ss1+"0";
         }  
         if (ptr_predict_label_1[i]==-1)
         {
           sell++;              
           ss1=ss1+"1";
         }     
   }
   
       if(buy>sell)
         res1=0;
       else if(buy<sell)
         res1=1;
       Print("class=",res1,"->",ss1); 
       
return(res1);

}
int Write2(string filename,string str)
{
//Write log file
   
   int handle; 
   handle = FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV,"/t");
   FileSeek(handle, 0, SEEK_END);      
   //FileWrite(handle,"" + TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS) + ": " + str);
   FileWrite(handle,str);
   FileClose(handle);
	//Print(str);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void Buy(int Magic,double Lots,int TakeProfit, int StopLoss )
{
    //if(NrOrders(MagicNumber1 )<MaxOrdersTotal1)    
    {
      int ticket=OrdSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point,"SVM_EA",Magic,0,Green);
      if(ticket>0)
      {
        if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
      }
      else 
        Print("Error opening BUY order : ",GetLastError()); 
    }    
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void Sell(int Magic,double Lots,int TakeProfit, int StopLoss )
{
    //if(NrOrders(MagicNumber1 )<MaxOrdersTotal1)    
    {
      int ticket=OrdSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point,"SVM_EA",Magic,0,Red);
      if(ticket>0)
      {
        if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
      }
      else 
        Print("Error opening SELL order : ",GetLastError()); 
     }
} 

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int NrOrders(int Magic ) 
{
   int total = OrdersTotal();
   int nrLongs = 0;
   int nrShorts = 0;
   for(int cnt=0; cnt<total; cnt++) {
      OrderSelect(cnt, SELECT_BY_POS);
      if( OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic )
         continue;
      if (OrderType()==OP_BUY) nrLongs++;
      if (OrderType()==OP_SELL) nrShorts++;
   }
   return(nrLongs+nrShorts);
}   

int Write(string str)
{
//Write log file
   string filename="SVM_EA.log";
   int handle; 
   handle = FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV,"/t");
   FileSeek(handle, 0, SEEK_END);      
   FileWrite(handle," Time " + TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS) + ": " + str);
   FileClose(handle);
	Print(str);
}
int OrdSend(string _symbol, int _cmd, double _volume, double _price, int _slippage, double _stoploss, double _takeprofit, string _comment="", int _magic=0, datetime _expiration=0, color _arrow_color=CLR_NONE) 
{
int NumberOfTries=10;
int RetryTime=2;
//Send order with retry capabilities and log
int _stoplevel=MarketInfo(_symbol,MODE_STOPLEVEL);
double _priceop=0;
int ticket,err,tries;
tries = 0;
switch (_cmd) {
    case OP_BUY:
        if (!IsTradeContextBusy() && IsTradeAllowed()) {
        while (tries < NumberOfTries) {
            RefreshRates();
            ticket = OrderSend(_symbol,OP_BUY,_volume,Ask,_slippage,NormalizeDouble(_stoploss,Digits),NormalizeDouble(_takeprofit,Digits),_comment,_magic,_expiration,_arrow_color);
            if(ticket<=0) {
                Write("Error Occured : "+ErrorDescription(GetLastError()));
                Write(Symbol()+" Buy @ "+Ask+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
                tries++;
            } else {
                tries = NumberOfTries;
                Write("Order opened : "+Symbol()+" Buy @ "+Ask+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
            }
            Sleep(RetryTime*1000);
        }
        }
        err=ticket;
        break;
 
    case OP_SELL:
        if (!IsTradeContextBusy() && IsTradeAllowed()) {
        while (tries < NumberOfTries) {
            RefreshRates();
            ticket = OrderSend(_symbol,OP_SELL,_volume,Bid,_slippage,NormalizeDouble(_stoploss,Digits),NormalizeDouble(_takeprofit,Digits),_comment,_magic,_expiration,_arrow_color);
            if(ticket<=0) {
                Write("Error Occured : "+ErrorDescription(GetLastError()));
                Write(Symbol()+" Sell @ "+Bid+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
                tries++;
            } else {
                tries = NumberOfTries;
                Write("Order opened : "+Symbol()+" Sell @ "+Bid+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
            }
            Sleep(RetryTime*1000);    
        }
        }
        err=ticket;
        break;
 
    case OP_BUYSTOP:
        while (tries < NumberOfTries) {
            RefreshRates();
            if ((_price-Ask)<_stoplevel*Point) _priceop=Ask+_stoplevel*Point; else _priceop=_price;            
            ticket = OrderSend(_symbol,OP_BUYSTOP,_volume,NormalizeDouble(_priceop,Digits),_slippage,NormalizeDouble(_stoploss,Digits),NormalizeDouble(_takeprofit,Digits),_comment,_magic,_expiration,_arrow_color);
            if(ticket<=0) {
                Write("Error Occured : "+ErrorDescription(GetLastError()));
                Write(Symbol()+" Buy Stop @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
                tries++;
            } else {
                tries = NumberOfTries;
                Write("Order opened : "+Symbol()+" Buy Stop@ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
            }
            Sleep(RetryTime*1000);
        }
        err=ticket;
        break;
 
 
    case OP_SELLSTOP:
        if (!IsTradeContextBusy() && IsTradeAllowed()) {
        while (tries < NumberOfTries) {
            RefreshRates();
            if ((Bid-_price)<_stoplevel*Point) _priceop=Bid-_stoplevel*Point; else _priceop=_price;            
            ticket = OrderSend(_symbol,OP_SELLSTOP,_volume,NormalizeDouble(_priceop,Digits),_slippage,NormalizeDouble(_stoploss,Digits),NormalizeDouble(_takeprofit,Digits),_comment,_magic,_expiration,_arrow_color);
            if(ticket<=0) {
                Write("Error Occured : "+ErrorDescription(GetLastError()));
                Write(Symbol()+" Sell Stop @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
                tries++;
            } else {
                tries = NumberOfTries;
                Write("Order opened : "+Symbol()+" Sell Stop @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
            }
            Sleep(RetryTime*1000);
        }
        }
        err=ticket;
        break;
 
 
    case OP_BUYLIMIT:
        if (!IsTradeContextBusy() && IsTradeAllowed()) {
        while (tries < NumberOfTries) {
            RefreshRates();
            if ((Ask-_price)<_stoplevel*Point) _priceop=Ask-_stoplevel*Point; else _priceop=_price;            
            ticket = OrderSend(_symbol,OP_BUYLIMIT,_volume,NormalizeDouble(_priceop,Digits),_slippage,NormalizeDouble(_stoploss,Digits),NormalizeDouble(_takeprofit,Digits),_comment,_magic,_expiration,_arrow_color);
            if(ticket<=0) {
                Write("Error Occured : "+ErrorDescription(GetLastError()));
                Write(Symbol()+" Buy Limit @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
                tries++;
            } else {
                tries = NumberOfTries;
                Write("Order opened : "+Symbol()+" Buy Limit @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
            }
            Sleep(RetryTime*1000);
        }
        }
        err=ticket;
        break;
 
    case OP_SELLLIMIT:
        if (!IsTradeContextBusy() && IsTradeAllowed()) {
        while (tries < NumberOfTries) {
            RefreshRates();
            if ((_price-Bid)<_stoplevel*Point) _priceop=Bid+_stoplevel*Point; else _priceop=_price;            
            ticket = OrderSend(_symbol,OP_BUYLIMIT,_volume,NormalizeDouble(_priceop,Digits),_slippage,NormalizeDouble(_stoploss,Digits),NormalizeDouble(_takeprofit,Digits),_comment,_magic,_expiration,_arrow_color);
            if(ticket<=0) {
                Write("Error Occured : "+ErrorDescription(GetLastError()));
                Write(Symbol()+" Sell Limit @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
                tries++;
            } else {
                tries = NumberOfTries;
                Write("Order opened : "+Symbol()+" Sell Limit @ "+_priceop+" SL @ "+_stoploss+" TP @"+_takeprofit+" ticket ="+ticket);
            }
            Sleep(RetryTime*1000);
        }
        err=ticket;
        }
        break;
 
    default:
        Write("No valid type of order found");
        err=-1;
        break;
}
return(err);
}
     

Comments