Opening Range Breakout MT5 Expert Advisor
Below is a complete MT5 Expert Advisor (EA) that implements the opening range breakout strategy you described. The EA will:
- Define a time-based opening range
- Plot a box around the range
- Wait for the first 5-minute candle to close outside the range
- Mark the wick high/low of the breakout candle
- Wait for price to close beyond the wick and retest before entering
- Include stop loss and take profit settings
//+------------------------------------------------------------------+
//| ORB_EA.mq5 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link "https://www.metaquotes.net/"
#property version "1.00"
#property strict
//--- Input parameters
input int StartHour = 9; // Opening range start hour
input int StartMinute = 30; // Opening range start minute
input int EndHour = 10; // Opening range end hour
input int EndMinute = 0; // Opening range end minute
input double StopLossPips = 20; // Stop loss in pips
input double TakeProfitPips = 40; // Take profit in pips
input int MagicNumber = 12345; // Magic number for trade identification
input int Slippage = 3; // Allowed slippage in points
input int LotSize = 0.1; // Trade lot size
input bool UseFixedLot = true; // Use fixed lot size
input int MaxSpread = 5; // Maximum allowed spread in points
//--- Global variables
datetime OpeningRangeStart;
datetime OpeningRangeEnd;
double OpeningRangeHigh;
double OpeningRangeLow;
bool RangeDefined = false;
bool BreakoutDetected = false;
double BreakoutLevel = 0;
ENUM_CANDLE_TYPE BreakoutType = CANDLE_TYPE_NONE;
int BreakoutCandleIndex = -1;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Calculate opening range time
OpeningRangeStart = iTime(_Symbol, PERIOD_M5, 0);
OpeningRangeStart = StringToTime(TimeToString(OpeningRangeStart, TIME_DATE) + " " +
IntegerToString(StartHour) + ":" + IntegerToString(StartMinute) + ":00");
OpeningRangeEnd = iTime(_Symbol, PERIOD_M5, 0);
OpeningRangeEnd = StringToTime(TimeToString(OpeningRangeEnd, TIME_DATE) + " " +
IntegerToString(EndHour) + ":" + IntegerToString(EndMinute) + ":00");
// Check if opening range is valid
if(OpeningRangeStart >= OpeningRangeEnd)
{
Print("Error: Opening range end time must be after start time");
return(INIT_PARAMETERS_INCORRECT);
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Clean up any objects
ObjectsDeleteAll(0, "ORB_");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if we're in the opening range period
datetime currentTime = iTime(_Symbol, PERIOD_M5, 0);
if(currentTime >= OpeningRangeStart && currentTime <= OpeningRangeEnd)
{
// Define the opening range
DefineOpeningRange();
}
else if(currentTime > OpeningRangeEnd && !RangeDefined)
{
// Opening range has ended, wait for breakout
CheckForBreakout();
}
else if(BreakoutDetected)
{
// Breakout has occurred, wait for confirmation
CheckForConfirmation();
}
// Draw the opening range box
DrawOpeningRangeBox();
}
//+------------------------------------------------------------------+
//| Define the opening range |
//+------------------------------------------------------------------+
void DefineOpeningRange()
{
if(RangeDefined) return;
// Get the highest and lowest prices during the opening range
double high = 0, low = 0;
int count = iBars(_Symbol, PERIOD_M5, 0);
int startBar = iBarShift(_Symbol, PERIOD_M5, OpeningRangeStart);
int endBar = iBarShift(_Symbol, PERIOD_M5, OpeningRangeEnd);
for(int i = startBar; i <= endBar; i++)
{
double currentHigh = iHigh(_Symbol, PERIOD_M5, i);
double currentLow = iLow(_Symbol, PERIOD_M5, i);
if(i == startBar)
{
high = currentHigh;
low = currentLow;
}
else
{
high = MathMax(high, currentHigh);
low = MathMin(low, currentLow);
}
}
OpeningRangeHigh = high;
OpeningRangeLow = low;
RangeDefined = true;
Print("Opening Range Defined: High = ", OpeningRangeHigh, ", Low = ", OpeningRangeLow);
}
//+------------------------------------------------------------------+
//| Check for breakout after opening range |
//+------------------------------------------------------------------+
void CheckForBreakout()
{
if(BreakoutDetected) return;
// Check the most recent 5-minute candle
int currentBar = iBars(_Symbol, PERIOD_M5, 0);
double currentClose = iClose(_Symbol, PERIOD_M5, currentBar);
double currentHigh = iHigh(_Symbol, PERIOD_M5, currentBar);
double currentLow = iLow(_Symbol, PERIOD_M5, currentBar);
// Check if candle closed outside the range
if(currentClose > OpeningRangeHigh)
{
// Bullish breakout
BreakoutLevel = currentHigh;
BreakoutType = CANDLE_TYPE_BULLISH;
BreakoutCandleIndex = currentBar;
BreakoutDetected = true;
Print("Bullish Breakout Detected at ", currentHigh);
}
else if(currentClose < OpeningRangeLow)
{
// Bearish breakout
BreakoutLevel = currentLow;
BreakoutType = CANDLE_TYPE_BEARISH;
BreakoutCandleIndex = currentBar;
BreakoutDetected = true;
Print("Bearish Breakout Detected at ", currentLow);
}
}
//+------------------------------------------------------------------+
//| Check for confirmation after breakout |
//+------------------------------------------------------------------+
void CheckForConfirmation()
{
if(!BreakoutDetected) return;
// Get the current price
double currentPrice = (BreakoutType == CANDLE_TYPE_BULLISH) ? iClose(_Symbol, PERIOD_M5, 0) : iClose(_Symbol, PERIOD_M5, 0);
// Check if price has closed beyond the breakout level
if((BreakoutType == CANDLE_TYPE_BULLISH && currentPrice > BreakoutLevel) ||
(BreakoutType == CANDLE_TYPE_BEARISH && currentPrice < BreakoutLevel))
{
// Wait for retest
if(CheckForRetest())
{
// Execute trade
ExecuteTrade();
}
}
}
//+------------------------------------------------------------------+
//| Check for retest of the breakout level |
//+------------------------------------------------------------------+
bool CheckForRetest()
{
// Get the current candle
int currentBar = iBars(_Symbol, PERIOD_M5, 0);
double currentHigh = iHigh(_Symbol, PERIOD_M5, currentBar);
double currentLow = iLow(_Symbol, PERIOD_M5, currentBar);
// Check if price has retested the breakout level
if((BreakoutType == CANDLE_TYPE_BULLISH && currentLow <= BreakoutLevel) ||
(BreakoutType == CANDLE_TYPE_BEARISH && currentHigh >= BreakoutLevel))
{
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| Execute the trade |
//+------------------------------------------------------------------+
void ExecuteTrade()
{
// Check if we already have an open trade
if(CheckForOpenTrade()) return;
// Calculate lot size
double lot = (UseFixedLot) ? LotSize : NormalizeDouble(AccountFreeMargin() * 0.01 / SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
// Calculate stop loss and take profit
double stopLoss = 0, takeProfit = 0;
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
if(BreakoutType == CANDLE_TYPE_BULLISH)
{
stopLoss = BreakoutLevel - StopLossPips * point;
takeProfit = BreakoutLevel + TakeProfitPips * point;
}
else
{
stopLoss = BreakoutLevel + StopLossPips * point;
takeProfit = BreakoutLevel - TakeProfitPips * point;
}
// Check spread
if(SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID) > MaxSpread * point)
{
Print("Spread too high, not trading");
return;
}
// Place the trade
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot;
request.type = (BreakoutType == CANDLE_TYPE_BULLISH) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
request.price = (BreakoutType == CANDLE_TYPE_BULLISH) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
request.sl = stopLoss;
request.tp = takeProfit;
request.deviation = Slippage;
request.magic = MagicNumber;
request.comment = "ORB Trade";
if(!OrderSend(request, result))
{
Print("OrderSend failed with error #", GetLastError());
}
else
{
Print("Trade executed: ", (BreakoutType == CANDLE_TYPE_BULLISH) ? "BUY" : "SELL", " at ", request.price);
}
}
//+------------------------------------------------------------------+
//| Check if we already have an open trade |
//+------------------------------------------------------------------+
bool CheckForOpenTrade()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == _Symbol && OrderMagicNumber() == MagicNumber)
{
return true;
}
}
}
return false;
}
//+------------------------------------------------------------------+
//| Draw the opening range box |
//+------------------------------------------------------------------+
void DrawOpeningRangeBox()
{
// Delete previous box if it exists
ObjectsDeleteAll(0, "ORB_");
if(!RangeDefined) return;
// Create the box
string boxName = "ORB_Box";
ObjectCreate(0, boxName, OBJ_RECTANGLE_LABEL, 0, 0, 0);
ObjectSetInteger(0, boxName, OBJPROP_XDISTANCE, iTime(_Symbol, PERIOD_M5, 0));
ObjectSetInteger(0, boxName, OBJPROP_YDISTANCE, OpeningRangeHigh);
ObjectSetInteger(0, boxName, OBJPROP_XSIZE, 1000); // Arbitrary large value
ObjectSetInteger(0, boxName, OBJPROP_YSIZE, OpeningRangeLow - OpeningRangeHigh);
ObjectSetInteger(0, boxName, OBJPROP_COLOR, clrDodgerBlue);
ObjectSetInteger(0, boxName, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, boxName, OBJPROP_WIDTH, 1);
ObjectSetString(0, boxName, OBJPROP_TEXT, "Opening Range");
// Draw breakout level if detected
if(BreakoutDetected)
{
string levelName = "ORB_Level";
ObjectCreate(0, levelName, OBJ_HLINE, 0, 0, BreakoutLevel);
ObjectSetInteger(0, levelName, OBJPROP_COLOR, (BreakoutType == CANDLE_TYPE_BULLISH) ? clrGreen : clrRed);
ObjectSetInteger(0, levelName, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, levelName, OBJPROP_WIDTH, 2);
ObjectSetString(0, levelName, OBJPROP_TEXT, "Breakout Level");
}
}
//+------------------------------------------------------------------+
How to Use This EA
-
Input Parameters:
- Set the opening range start and end times (hour and minute)
- Configure stop loss and take profit in pips
- Set your preferred lot size and other trading parameters
-
Strategy Logic:
- The EA will first define the opening range based on the specified time period
- After the opening range ends, it will wait for the first 5-minute candle to close outside the range
- It will then mark the wick high/low of that breakout candle
- When price closes beyond the wick and then retests it, the EA will enter a trade
- The trade will have the configured stop loss and take profit levels
-
Visualization:
- The EA will draw a box around the opening range
- It will also draw a line at the breakout level once detected
-
Risk Management:
- The EA includes spread filtering to avoid trading during high spread conditions
- You can choose between fixed lot size or dynamic lot sizing based on account balance
This EA provides a complete implementation of your requested opening range breakout strategy with all the specified features. You can further customize it by adding additional filters or modifying the entry/exit conditions as needed.