Skip to content
← Back to the research library
MQL5 SOURCE COLLECTION / Breakout

Time-Range Breakout: Pending Orders

Measures a configured time range and places buy-stop and sell-stop orders at its boundaries.

MT5 / MQL5Original sourceMissing include file

Timed tick range / pending stops · Published 28 October 2026

Source inspectionLimited static review
MetaEditor compilationNot performed
Backtest / live recordNot supplied

How the source is structured

  1. Record the high ask and low bid during the configured range window.
  2. After the range ends, attempt pending breakout orders at both boundaries with range-based exit levels.
  3. Use an expiry/closing time, weekday switches and optional trailing-stop management.

Default inputs

As supplied; these are not optimized or recommended settings.
Range start / duration10:00 server time / 120 minutes
Closing time20:00 server time
Fixed volume0.01 lot
Stop / target inputs150% / 200% of range
Trailing / weekdaysOff / Monday–Friday enabled
BEFORE YOU TEST

Source-review notes

These observations come from reading this uploaded version. They are not compiler output or a complete code audit. The download retains the source as supplied.

SOURCE LINES 40, 55–56, 75

TimeRangeBreakoutTrustfulTsPendingOrders0.mqh is missing from the supplied files. It supplies definitions needed by this source, so this is not a complete compilation package.

SOURCE LINES 135, 143

Both target formulas use InpStopLoss instead of InpTakeProfit. The target input only controls whether the target is enabled.

SOURCE LINES 9–16, 63–65

The header's example session times differ from the actual input defaults. The settings above follow the inputs.

Dependencies

TimeRangeBreakoutTrustfulTsPendingOrders0.mqh — not supplied. MetaTrader 5 standard Trade library.

Source & attribution

Source header: MT5 implementation © 2024-07-25, Wolfgang Melz. Original credit, links and educational-use notice are retained. Link from original header ↗

Included in the Edge Quant source collection with existing notices preserved. Free download does not imply a new license grant.

Original filename: TimeRangeBreakoutTrustfulTsPendingOrders0.mq5
Encoding: UTF-8

Inspect the original source

The browser preview is decoded for reading; the download keeps the original file bytes.

Direct .mq5 file ↓
Expand full MQL5 source · 505 lines
/*  TimeRangeBreakoutTrustfulTsPendingOrders0.mq5  MT5 Implementation: © 2024-07-25, Wolfgang Melz, wm1@gmx.de  https://melz.one  Strategy Rules  --------------    1)  Range of the asian session 00:00 - 08:00 GMT+0  2)  Allowed entry is between 08:00 - 12:00 or Session end after M15 close breaks out of the range  3a) Stop Loss will be set in the middle of the range      - or -  3b) Stop Loss will be set at the opposite side of the range  4a) Trade will be close at the end of the EU session at 17:00      - or -  4b) Trade will be close by trailing stop  Disclaimer  ==========    This EA software is no financial advise. It is for educational use only.  Backtest it carefully while using it. The author is not responsible for  any damage this software does to people who use it.  Sources  -------    trustfultrading : https://www.youtube.com/playlist?list=PLGjfbI-PZyHW4fWaAYrSo4gRpCGNPH-ae  TraderPy        : https://traderpy.com/2023/10/31/london-breakout-trading-system-coding-a-trading-bot-in-python/  Orchard Forex   : https://www.youtube.com/watch?v=IVQ-j-xFE2U  Dillon Grech    : https://www.youtube.com/watch?v=YlcIelbIOk8&t=219s    Indicators  ----------    Chandelier Exit : https://www.mql5.com/de/market/product/76373?source=Unknown*/#include "TimeRangeBreakoutTrustfulTsPendingOrders0.mqh"  // get defines#include <Trade/Trade.mqh>                                // get trade class#property copyright   ea_copyright                        // get copyright of this ea from defines#property link        ea_link                             // get link of this ea from defines#property version     ea_version                          // get version of this ea from defines#property description ea_description1#property description ea_description2#property description ea_description3#property description ea_description4//#property tester_indicator "EfficiencyRatio.ex5"//#property tester_indicator "Examples/ATR.ex5"/*  Input parameters  */input group "==== General Inputs ===="input long                InpMagicNumber      = ea_magic;   // identifierinput ENUM_LOT_MODE       InpLotMode          = LOT_FIXED;  // lot modeinput double              InpLots             = 0.01;       // lots / money / percentinput int                 InpStopLoss         = 150;        // stop loss in % of the range (0=off)input bool                InpStopLossTrailing = false;      // use trailing stopinput int                 InpTakeProfit       = 200;        // take profit in % of the range (0=off)input group "==== Range Inputs ===="input int                 InpRangeStart       = 600;        // range start time in minutes after midnight (600 = 10:00 o'clock)input int                 InpRangeDuration    = 120;        // range duration in minutes (120 = 2 hours)input int                 InpRangeClose       = 1200;       // range close time in minutes (1200 = 20:00 o'clock)input group "==== Day of Week Filter ===="input bool                InpMonday           = true;       // range on mondayinput bool                InpTuesday          = true;       // range on tuesdayinput bool                InpWednesday        = true;       // range on wednesdayinput bool                InpThursday         = true;       // range on thursdayinput bool                InpFriday           = true;       // range on friday/*  Global Variables  */RANGE_STRUCT    range;MqlTick         lastTick;CTrade          trade;        // create trade object/*  Expert initialization  */int OnInit() {  if(!CheckInputs()) return INIT_PARAMETERS_INCORRECT;      // check user inputs    trade.SetExpertMagicNumber(InpMagicNumber);               // set magic number  if(_UninitReason == REASON_PARAMETERS && CountOpenPositions() == 0) {  // calculate a new range if inputs changed and no position open    CalculateRange();  }  return(INIT_SUCCEEDED);}/*  Expert deinitialization function  */void OnDeinit(const int reason) {  //ObjectsDeleteAll(NULL, "range");}/*  Expert tick function  */void OnTick() {  SymbolInfoTick(_Symbol, lastTick);  // get last tick  // range calculation  if(lastTick.time >= range.start_time && lastTick.time < range.end_time) {    range.f_entry = true;             // set flag    if(lastTick.ask > range.high) {   // new range high?      range.high = lastTick.ask;      UpdateObjects();    }    if(lastTick.bid < range.low) {    // new range low?      range.low = lastTick.bid;      UpdateObjects();    }  }    // close positions  if(InpRangeClose >= 0 && lastTick.time >= range.close_time) {    if(!ClosePositions()) return;  }  // calculate new range if...  if(((lastTick.time >= range.close_time)                                           // close time reached   //InpRangeClose >= 0 &&     || (range.end_time == 0)                                                        // range end not calculated yet    || (range.end_time != 0 && lastTick.time > range.end_time && !range.f_entry))   // there was a range calculated but no tick inside    && CountOpenPositions() == 0) {        CalculateRange();  }  CreatePendingOrders();      // use pending orders  UpdateStopLoss();           // update stop loss}/*  create pending orders  */void CreatePendingOrders() {  //check if we are after the range  if(lastTick.time >= range.end_time && range.end_time > 0 && range.f_entry) {    if(!range.f_high_breakout) {      range.f_high_breakout = true;                                                                                                 // create pending order long for high breakout      double sl = InpStopLoss == 0 ? 0 : NormalizeDouble(range.high - ((range.high - range.low) * InpStopLoss * 0.01), _Digits);    // calculate stop loss level      double tp = InpTakeProfit == 0 ? 0 : NormalizeDouble(range.high + ((range.high - range.low) * InpStopLoss * 0.01), _Digits);  // calculate take profit level      double lots;                                                                                                                  // calculate lots      if(!CalculateLots(range.high - sl, lots)) return;      trade.BuyStop(lots, range.high, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, range.close_time, ea_comment);                         // create buy stop    }    if(!range.f_low_breakout) {      range.f_low_breakout = true;                                                                                                  // create pending order short for low breakout      double sl = InpStopLoss == 0 ? 0 : NormalizeDouble(range.low + ((range.high - range.low) * InpStopLoss * 0.01), _Digits);     // calculate stop loss level      double tp = InpTakeProfit == 0 ? 0 : NormalizeDouble(range.low - ((range.high - range.low) * InpStopLoss * 0.01), _Digits);   // calculate take profit level      double lots;                                                                                                                  // calculate lots      if(!CalculateLots(sl - range.low, lots)) return;      trade.SellStop(lots, range.low, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, range.close_time, ea_comment);                         // create sell stop    }  }}/*  count all open positions  */int CountOpenPositions() {  int counter = 0;  int total = PositionsTotal();  for(int i = total - 1; i >= 0; i--) {    ulong ticket = PositionGetTicket(i);      // select position    if(ticket <= 0) {      Print("Failed to get position ticket. Error: ", GetLastError());      return -1;    }    if(!PositionSelectByTicket(ticket)) {      Print("Failed to select position by ticket. Error: ", GetLastError());      return -1;    }    long magicNumber;    if(!PositionGetInteger(POSITION_MAGIC, magicNumber)) {      Print("Failed to get magic number. Error: ", GetLastError());      return -1;    }    if(magicNumber == InpMagicNumber) counter++;  }  return counter;}/*  calculate lot size  */bool CalculateLots(double slDistance, double &lots) {  lots = 0.0;  if(InpLotMode == LOT_FIXED) {    lots = InpLots;  } else {    double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);    double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);    double volumeStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);    double riskMoney = InpLotMode == LOT_MONEY ? InpLots : AccountInfoDouble(ACCOUNT_EQUITY) * InpLots * 0.01;    double moneyVolumeStep = (slDistance / tickSize) * tickValue * volumeStep;    lots = MathFloor(riskMoney / moneyVolumeStep) * volumeStep;  }  // check calculated lots  if(!CheckLots(lots)) return false;  return true;}/*  check lots for min, max and step  */bool CheckLots(double &lots) {  double min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);  double max = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);  double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);  if(lots < min) {    Print("Lot size will be set to the minimum allowable volume");    lots = min;    return true;  }  if(lots > max) {    Print("Lot size greater than max allowable volume, lots: ", lots, ", max: ", max);    return false;  }  lots = (int)MathFloor(lots / step) * step;  return true;}/*  update stop loss  */void UpdateStopLoss() {  // return if no stop loss or fixed stop loss  if(InpStopLoss == 0 || !InpStopLossTrailing) return;    ResetLastError();  int total = PositionsTotal();                                               // get all positions in market  for(int i = total - 1; i >= 0; i--) {                                       // iterate over them    ulong ticket = PositionGetTicket(i);      // select position              // get position ticket    if(ticket <= 0) {                                                         // if no ticket      Print("Failed to get position ticket. Error: ", GetLastError());      return;                                                                 // return    }    if(!PositionSelectByTicket(ticket)) {                                     // if cannot select position by ticket      Print("Failed to select position by ticket. Error: ", GetLastError());      return;                                                                 // return    }    ulong magicNumber;    if(!PositionGetInteger(POSITION_MAGIC, magicNumber)) {                    // if not position's magic number      Print("Failed to get position magic number. Error: ", GetLastError());      return;                                                                 // return    }    if(magicNumber == InpMagicNumber) {                                       // if position belongs to this EA      // get type      long type;                                                              // get position type, long or short      if(!PositionGetInteger(POSITION_TYPE, type)) {        Print("failed to get position type");        return;      }      // get current sl and tp      double currSl;                                                          // get current stop loss      double currTp;                                                          // get current take profit      if(!PositionGetDouble(POSITION_SL, currSl)) {        Print("Failed to get position stop loss");        return;      }      if(!PositionGetDouble(POSITION_TP, currTp)) {        Print("Failed to get position take profit");        return;      }      // calculate stop loss      double currPrice = type == POSITION_TYPE_BUY ? lastTick.bid : lastTick.ask; // get current price      int n = type == POSITION_TYPE_BUY ? 1 : -1;                                                                  // declare n used as multiplier      double newSl = NormalizeDouble(currPrice - ((range.high - range.low) * InpStopLoss * 0.01 * n), _Digits);      if((newSl * n) < (currSl * n) || NormalizeDouble(MathAbs(newSl - currSl), _Digits) < _Point) {        //Print("No new stop loss needed");        continue;      }      // check for stop level      long level = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);      if(level != 0 && MathAbs(currPrice - newSl) <= level * _Point) {        Print("New stop loss inside stop level");        continue;      }      // modify position with new stop loss      if(!trade.PositionModify(ticket, newSl, currTp)) {        Print("Failed to modify position, ticket: ", (string)ticket, ", currSl: ", (string)currSl,              ", newSl: ", (string)newSl, ", currTp: ", (string)currTp);        return;      }    }  }}/*  close all open positions  */bool ClosePositions() {  ResetLastError();  int total = PositionsTotal();  for(int i = total - 1; i >= 0; i--) {    if(total != PositionsTotal()) {      total = PositionsTotal();      i = total;      continue;    }    ulong ticket = PositionGetTicket(i);      // select position    if(ticket <= 0) {      Print("Failed to get position ticket. Error: ", GetLastError());      return false;    }    if(!PositionSelectByTicket(ticket)) {      Print("Failed to select position by ticket. Error: ", GetLastError());      return false;    }    long magicNumber;    if(!PositionGetInteger(POSITION_MAGIC, magicNumber)) {      Print("Failed to get magic number. Error: ", GetLastError());      return false;    }    if(magicNumber == InpMagicNumber) {      trade.PositionClose(ticket);      if(trade.ResultRetcode() != TRADE_RETCODE_DONE) {        Print("Failed to close position ", ticket, ", Retcode=", trade.ResultRetcode(), ":", trade.ResultRetcodeDescription());        return false;      }    }  }  return true;}/*  update chart objects  */void UpdateObjects() {  string name = "range high " + (string)range.start_time;  ObjectSetDouble(NULL, name, OBJPROP_PRICE, 0, range.high);  ObjectSetDouble(NULL, name, OBJPROP_PRICE, 1, range.high);  ObjectSetDouble(NULL, name + " ", OBJPROP_PRICE, 0, range.high);  ObjectSetDouble(NULL, name + " ", OBJPROP_PRICE, 1, range.high);  name = "range low " + (string)range.start_time;  ObjectSetDouble(NULL, name, OBJPROP_PRICE, 0, range.low);  ObjectSetDouble(NULL, name, OBJPROP_PRICE, 1, range.low);  ObjectSetDouble(NULL, name + " ", OBJPROP_PRICE, 0, range.low);  ObjectSetDouble(NULL, name + " ", OBJPROP_PRICE, 1, range.low);}/*  draw all chart objects  */void DrawObjects() {  // start time  string name = "range start" + (string)range.start_time;  ObjectCreate(NULL, name, OBJ_VLINE, 0, range.start_time, 0);  ObjectSetString(NULL, name, OBJPROP_TOOLTIP, "Start of the Range\n" + TimeToString(range.start_time, TIME_DATE|TIME_MINUTES));  ObjectSetInteger(NULL, name, OBJPROP_COLOR, clrBlue);  ObjectSetInteger(NULL, name, OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name, OBJPROP_BACK, true);  ObjectSetInteger(NULL, name, OBJPROP_HIDDEN, false);  // end time  name = "range end" + (string)range.start_time;  ObjectCreate(NULL, name, OBJ_VLINE, 0, range.end_time, 0);  ObjectSetString(NULL, name, OBJPROP_TOOLTIP, "End of the Range\n" + TimeToString(range.end_time, TIME_DATE|TIME_MINUTES));  ObjectSetInteger(NULL, name, OBJPROP_COLOR, clrBlue);  ObjectSetInteger(NULL, name, OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name, OBJPROP_BACK, true);  ObjectSetInteger(NULL, name, OBJPROP_HIDDEN, false);  // close time  name = "close time" + (string)range.start_time;  ObjectCreate(NULL, name, OBJ_VLINE, 0, range.close_time, 0);  ObjectSetString(NULL, name, OBJPROP_TOOLTIP, "Close of the Range\n" + TimeToString(range.close_time, TIME_DATE|TIME_MINUTES));  ObjectSetInteger(NULL, name, OBJPROP_COLOR, clrRed);  ObjectSetInteger(NULL, name, OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name, OBJPROP_BACK, true);  ObjectSetInteger(NULL, name, OBJPROP_HIDDEN, false);  // high  name = "range high " + (string)range.start_time;  ObjectCreate(NULL, name, OBJ_TREND, 0, range.start_time, range.high, range.end_time, range.high);  ObjectSetString(NULL, name, OBJPROP_TOOLTIP, "High of the Range\n" + DoubleToString(range.high, _Digits));  ObjectSetInteger(NULL, name, OBJPROP_COLOR, clrBlue);  ObjectSetInteger(NULL, name, OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name, OBJPROP_BACK, true);  ObjectSetInteger(NULL, name, OBJPROP_HIDDEN, false);  ObjectCreate(NULL, name + " ", OBJ_TREND, 0, range.end_time, range.high, InpRangeClose >= 0 ? range.close_time : INT_MAX, range.high);  ObjectSetString(NULL, name + " ", OBJPROP_TOOLTIP, "High of the Range \n" + DoubleToString(range.high, _Digits));  ObjectSetInteger(NULL, name + " ", OBJPROP_COLOR, clrBlue);  ObjectSetInteger(NULL, name + " ", OBJPROP_STYLE, STYLE_DOT);  ObjectSetInteger(NULL, name + " ", OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name + " ", OBJPROP_BACK, true);  ObjectSetInteger(NULL, name + " ", OBJPROP_HIDDEN, false);  // low  name = "range low " + (string)range.start_time;  ObjectCreate(NULL, name, OBJ_TREND, 0, range.start_time, range.low, range.end_time, range.low);  ObjectSetString(NULL, name, OBJPROP_TOOLTIP, "Low of Range\n" + DoubleToString(range.low, _Digits));  ObjectSetInteger(NULL, name, OBJPROP_COLOR, clrBlue);  ObjectSetInteger(NULL, name, OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name, OBJPROP_BACK, true);  ObjectSetInteger(NULL, name, OBJPROP_HIDDEN, false);  ObjectCreate(NULL, name + " ", OBJ_TREND, 0, range.end_time, range.low, InpRangeClose >= 0 ? range.close_time : INT_MAX, range.low);  ObjectSetString(NULL, name + " ", OBJPROP_TOOLTIP, "Low of Range \n" + DoubleToString(range.low, _Digits));  ObjectSetInteger(NULL, name + " ", OBJPROP_COLOR, clrBlue);  ObjectSetInteger(NULL, name + " ", OBJPROP_STYLE, STYLE_DOT);  ObjectSetInteger(NULL, name + " ", OBJPROP_WIDTH, 1);  ObjectSetInteger(NULL, name + " ", OBJPROP_BACK, true);  ObjectSetInteger(NULL, name + " ", OBJPROP_HIDDEN, false);  // refresh chart  ChartRedraw();}/*  check user inputs  */bool CheckInputs() {  if(InpMagicNumber <= 0) {    Alert("InpMagicNumber <= 0");    return false;  }  if(InpLotMode == LOT_FIXED && (InpLots <= 0 || InpLots > 10)) {    Alert("InpLots <= 0 or > 10");    return false;  }  if(InpLotMode == LOT_MONEY && (InpLots <= 0 || InpLots > 1000)) {    Alert("InpLots <= 0 or > 1000");    return false;  }  if(InpLotMode == LOT_PCT_ACCOUNT && (InpLots <= 0 || InpLots > 5)) {    Alert("InpLots <= 0 or > 5");    return false;  }  if((InpLotMode == LOT_PCT_ACCOUNT || InpLotMode == LOT_PCT_ACCOUNT) && (InpStopLoss == 0)) {    Alert("Selected lot mode needs a stop loss");    return false;  }  if(InpStopLoss < 0 || InpStopLoss > 1000) {    Alert("InpStopLoss < 0 or > 1000");    return false;  }  if(InpTakeProfit < 0 || InpTakeProfit > 1000) {    Alert("InpTakeProfit < 0 or > 1000");    return false;  }  if(InpRangeClose < 0 && InpStopLoss == 0) {    Alert("Close time and stop loss is off");    return false;  }/*  if(InpStopLoss == 0) {  //InpRangeClose < 0 ||     Alert("InpStopLoss = 0, close time and stop loss is off");    return false;  }*/  if(InpRangeStart < 0 || InpRangeStart >= 1440) {    Alert("InpRangeStart < 0 or >= 1440");    return false;  }  if(InpRangeDuration <= 0 || InpRangeDuration >= 1440) {    Alert("InpRangeDuration <= 0 or >= 1440");    return false;  }  if(InpRangeClose >= 1440 ||     (InpRangeStart + InpRangeDuration) % 1440 == InpRangeClose) {    Alert("InpRangeClose >= 1440 or end time == close time");    return false;  }  if(InpMonday + InpTuesday + InpWednesday + InpThursday + InpFriday == 0) {    Alert("Range is prohibited on all days of the week.");    return false;  }  return true;}/*  calculate a new range  */void CalculateRange() {  // reset range vars  range.start_time = 0;  range.end_time = 0;  range.close_time = 0;  range.high = 0.0;  range.low = DBL_MAX;  range.f_entry = false;  range.f_high_breakout = false;  range.f_low_breakout = false;  // calculate range start time  int time_cycle = 86400;  range.start_time = (lastTick.time - (lastTick.time % time_cycle)) + InpRangeStart * 60;  for(int i = 0; i < 8; i++) {    MqlDateTime tmpTime;    TimeToStruct(range.start_time, tmpTime);    int dow = tmpTime.day_of_week;    if(lastTick.time >= range.start_time || dow == 6 || dow == 0       || (dow == 1 && !InpMonday) || (dow == 2 && !InpTuesday)       || (dow == 3 && !InpWednesday) || (dow == 4 && !InpThursday)       || (dow == 5 && !InpFriday)) {      range.start_time += time_cycle;    }  }  // calculate range end time  range.end_time = range.start_time + InpRangeDuration * 60;  for(int i = 0; i < 2; i++) {    MqlDateTime tmpTime;    TimeToStruct(range.end_time, tmpTime);    int dow = tmpTime.day_of_week;    if(dow == 6 || dow == 0) {      range.end_time += time_cycle;    }  }  // calculate range close time  if(InpRangeClose >= 0) {    range.close_time = (range.end_time - (range.end_time % time_cycle)) + InpRangeClose * 60;    for(int i = 0; i < 3; i++) {      MqlDateTime tmpTime;      TimeToStruct(range.close_time, tmpTime);      int dow = tmpTime.day_of_week;      if(range.close_time <= range.end_time || dow == 6 || dow == 0) {        range.close_time += time_cycle;      }    }  }  DrawObjects();}

SHA-256: 3eeb5615396af06496bd62f41489aea2bd6cb0d8d6e81addfda9b0e05b9573aa

Educational source material, not investment advice. No profitability, execution quality or live-readiness claim is made for this upload.