Range Trader for Metatrader5 sample

The source for Range Trader Metatrader5 version

Range Trader for Metatrader5 description

After several request to post Metatrader version of source codes I decided to install MT5 and see how to convert my C code to Metatrader MQL.

This example is about RangeTrader I have posted earlier. It follows previously posted flow:


MQL Code flow goes this way:

  1. MqlRates hourly_bar[] is used to store bars data.
  2. PERIOD_H1 means hourly bars and we copy those to hourly_bar array.
  3. MqlTick tick_data is where system stores tick data.
  4. If tick time is 10.59 we start meas frame.
  5. When we get tick time 12.00 we know previous hourly bar is finished and we can read it.
  6. We store range high and range low and start our trade frame.
  7. Finally we check check buy/sell conditions and store those to bool variables.

   MqlRates hourly_bar[]; //array to store hourly bar values
    
// Write last 3 hourly bars to hourly array
   if(CopyRates(_Symbol,PERIOD_H1,0,3,hourly_bar)<0)
     {
      Alert("Error copying rates/history data - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }
 
   MqlTick tick_data;
   MqlDateTime tick_time_str;
   TimeToStruct(tick_data.time,tick_time_str);
   
   bool trade_allowed = false;
   double range_high = 0;
   double range_low = 0;

   if(tick_time_str.hour == 10 && tick_time_str.min == 59) //meas frame starts
   {
      trade_allowed = false;
   }
   
   if(tick_time_str.hour == 12 && tick_time_str.min == 0) //trade frame starts
   {
      range_high = hourly_bar[0].high; //hourly_bar[0] contains latest hourly bar data
      range_low = hourly_bar[0].low; //hourly_bar[0] contains latest hourly bar data
      trade_allowed = true;
   }
   bool Buy_Range_Break = ( trade_allowed && tick_data.last > range_high ); //buy condition
   bool Sell_Range_Break = ( trade_allowed && tick_data.last < range_low ); //sell condition

The differences between my previous C samples and MQL sample are where platform stores data and how to access data via API.

I leave MT4 version to your homework.