Train_05_02a

Download script
Author: Copyright � 2008, MetaQuotes Software Corp.
Train_05_02a

This script is designed as a specialized analysis tool for MetaTrader that evaluates historical market data to identify specific trading patterns. Rather than simply following a standard trend, it acts as a "simulator" that looks back at past price movements to see how certain trade setups would have performed under specific conditions.

Core Logic and Functionality

1. Pattern Backtesting and Simulation The primary logic of the script is to scan through a defined window of historical data (the "training" period). It simulates what would happen if a buy or sell order were placed at every price point during that timeframe. It essentially "replays" history to see which entries were successful and which failed based on your predefined risk parameters.

2. Risk Validation (Stop Loss and Take Profit) For every historical data point, the script checks two critical rules:

  • Safety Check (Stop Loss): It looks forward into a small "future window" of price action. If the price moved against the simulated trade enough to hit a Stop Loss threshold, that specific entry is marked as invalid.
  • Success Check (Take Profit): Simultaneously, it checks if the price reached the target Take Profit level within that same window.

3. Outcome Classification The script categorizes these historical simulations into different results:

  • If a "Buy" simulation met the profit target without hitting the stop loss, it is recorded as a success (positive result).
  • If a "Sell" simulation met the profit target without hitting the stop loss, it is recorded as a success (negative result).
  • If the trade hit the stop loss or failed to reach the profit target within the timeframe, it is treated as a neutral or failed entry.

4. Data Visualization The results of these simulations are plotted onto your chart in a separate window. The script uses four different buffers (visual channels):

  • It uses histograms to represent the frequency and direction of successful simulated trades.
  • It uses lines (which are currently configured but not actively drawing data in this specific version) to potentially provide further trend analysis or secondary data points.

5. Timeframe Synchronization The script is designed to be smart about time. It looks at prices on a higher timeframe (like 5-minute charts) while being triggered by updates on a lower timeframe (1-minute charts). This allows it to analyze broader market trends while maintaining high-frequency updates.

Summary for the User

In plain terms, this script doesn't tell you where to trade right now; instead, it scans the past to show you how often certain types of trades would have succeeded or failed given your specific Stop Loss and Take Profit settings. It serves as a diagnostic tool to visualize the "win rate" of potential trading entries across a historical period.

5 Views
0 Downloads
0 Favorites
Train_05_02a
//+------------------------------------------------------------------+
//|                                                  Train_04_01.mq4 |
//|                      Copyright © 2008, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

#define NR_OF_SAMPLE_LINES   400
#define NR_OF_TEST_LINES     800
#define NR_OF_TEST_BARS      10
#define FUTURE_WINDOW        10

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1 Blue
#property indicator_color2 Red
#property indicator_color3 Lime
#property indicator_color4 Magenta
#property indicator_level1 0.0

extern int TrainPeriod=PERIOD_M5;
extern int StopLoss=30;		//70
extern int TakeProfit=30;	//70	

int NrTrainBars=NR_OF_SAMPLE_LINES;
int NrTestBars=NR_OF_TEST_LINES;
int FutureWindow=FUTURE_WINDOW;
int c;
double Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[];

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int myBars1;

bool isNewBar1(int tf1)
  {
//----
   bool res=false;
   if (myBars1!=iBars(Symbol(),tf1))
   {
      res=true;
      myBars1=iBars(Symbol(),tf1);
   }  
  
//----
   return(res);
  }
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
//---- 3 indicator buffers mapping
   SetIndexBuffer(0,Buffer1);
   SetIndexBuffer(1,Buffer2);
   SetIndexBuffer(2,Buffer3);
   SetIndexBuffer(4,Buffer4);   
//---- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexStyle(2,DRAW_LINE);
   SetIndexStyle(3,DRAW_LINE);  

   SetIndexEmptyValue(0,EMPTY_VALUE);
   SetIndexEmptyValue(1,EMPTY_VALUE);
   SetIndexEmptyValue(2,EMPTY_VALUE);
   SetIndexEmptyValue(3,EMPTY_VALUE);     
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+

int start()
  {
   int limit;

   int counted_bars=IndicatorCounted();
//---- check for possible errors
   if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;
//---- main loop



if(isNewBar1(PERIOD_M1))
{  






							
   int spread=MarketInfo(Symbol(),MODE_SPREAD);
   double Point1=MarketInfo(Symbol(),MODE_POINT);
   double sp=spread*Point;  
   double entry_buy;//entry_buy=bid0+sp 
   double entry_sell;//entry_sell=bid0 
   bool longOk;
   bool shortOk; 
   int FW=FutureWindow;       
   int i,j,fw;  
   double l,h; 
   datetime t1=iTime(Symbol(),TrainPeriod,FW);
   int FW2=iBarShift(Symbol(),0,t1,true);

   datetime t2=iTime(Symbol(),TrainPeriod,NrTrainBars);
   int NrTrainBars2=iBarShift(Symbol(),0,t2,true);
   Print("NrTrainBars(1min): "+NrTrainBars2+" FutureWindow(1min): "+FW2+"="+(NrTrainBars2+FW2)); 
	  for(i=FW2,j=0;j<NrTrainBars2;i++,j++)
      //for ( i=nr_of_sample_lines-1; i>=0; i--) 
	  {    
        c=-2;
        datetime time1=iTime(Symbol(),0,i);
        int ii=iBarShift(Symbol(),TrainPeriod,time1,true);        
        entry_buy = iClose(Symbol(),TrainPeriod,ii)+sp;//entry_buy=bid0+sp 
        entry_sell = iClose(Symbol(),TrainPeriod,ii);//entry_sell=bid0 
        longOk=true;
        shortOk=true;                                                
        for (fw=0; fw<FW; fw++) 
        {
          l=iLow(Symbol(),TrainPeriod,ii-fw);
          h=iHigh(Symbol(),TrainPeriod,ii-fw); 
          if (l<=entry_buy-StopLoss*Point) longOk=false;
          if (h+sp>=entry_sell+StopLoss*Point) shortOk=false;
          if (longOk && (h>=entry_buy+TakeProfit*Point)) { c=(+1)*fw;  break; }
          if (shortOk && (l+sp<=entry_sell-TakeProfit*Point)) { c=(-1)*fw;  break; }                       
        } 
        if(c != -2)
          if(c>0) 
            Buffer1[i]=c;
          else
            Buffer2[i]=c;  
        else  
        {
          Buffer1[i]=0;
          Buffer2[i]=0;
        }  
    }
/*   
   //for( i=0; i<limit; i++)
   for(i=FUTURE_WINDOW ;i<NR_OF_SAMPLE_LINES;i++)
   {
     
       Buffer1[i]=Close[i];

              
     //if(svm_samples_class_dyn_1[i]==-1)        
     //  Buffer2[i]=-1;
    
   }
*/   
/*   
   for(i=0;i<NR_OF_TEST_LINES;i++)
   {    
     if(ptr_predict_label_1[i]==1)
       Buffer3[i]=1.1;

       
     if(ptr_predict_label_1[i]==-1)       
        Buffer4[i]=-1.1;
       
   }   
*/   
 
}   


//----
   return(0);
  }
//+------------------------------------------------------------------+

Comments