Below is a complete, well-commented MetaTrader-5 Expert Advisor that implements the logic you described.
Copy the code into a new file called OpeningRangeBreakout.mq5 and compile it in MetaEditor.
//+------------------------------------------------------------------+
//| OpeningRangeBreakout |
//| © 2024 – freely usable for personal needs |
//+------------------------------------------------------------------+
#property copyright "2024"
#property version "1.00"
#property description "5-min Opening-Range-Breakout EA with retest entry"
#property description "Plots the range box and the trigger wick line"
#property indicator_chart_window
//--- INPUTS ---------------------------------------------------------
input group "==== Opening Range ===="
input int InpRangeStartHour = 9; // Range start hour (broker time)
input int InpRangeStartMinute = 30; // Range start minute
input int InpRangeEndHour = 10; // Range end hour
input int InpRangeEndMinute = 0; // Range end minute
input group "==== Trade Parameters ===="
input double InpLotSize = 0.1; // Fixed lot size
input int InpStopLossPips = 20; // SL distance in pips
input int InpTakeProfitPips = 40; // TP distance in pips
input int InpSlippage = 3; // Slippage in points
input int InpMagicNumber = 123456; // EA magic number
//--- GLOBAL VARIABLES ----------------------------------------------
datetime g_rangeStart, g_rangeEnd;
double g_rangeHigh, g_rangeLow;
double g_triggerLevel; // wick high (bull) or wick low (bear)
bool g_triggerDirection; // true = bullish breakout, false = bearish
bool g_triggerCandleFound; // true after the first close outside range
bool g_tradeExecuted; // true after the retest trade is taken
int g_boxId, g_lineId; // chart-object IDs
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
g_boxId = 0;
g_lineId = 0;
g_tradeExecuted = false;
g_triggerCandleFound = false;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectsDeleteAll(0, "ORB_");
}
//+------------------------------------------------------------------+
//| Main handler |
//+------------------------------------------------------------------+
void OnTick()
{
//--- only run on 5-minute chart
if(Period() != PERIOD_M5)
{
Print("EA works only on 5-minute chart");
return;
}
//--- build today's range times
if(!setTodayRangeTimes())
return;
//--- plot / update the range box
drawRangeBox();
//--- wait until the range is finished
if(TimeCurrent() < g_rangeEnd)
return;
//--- STEP 1: find the first candle that closes outside the range
if(!g_triggerCandleFound)
{
findTriggerCandle();
return;
}
//--- STEP 2: wait for a close beyond the trigger wick, then retest
if(!g_tradeExecuted)
checkRetestAndTrade();
}
//+------------------------------------------------------------------+
//| Build today's range start/end datetimes |
//+------------------------------------------------------------------+
bool setTodayRangeTimes()
{
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
dt.hour = InpRangeStartHour;
dt.min = InpRangeStartMinute;
dt.sec = 0;
g_rangeStart = StructToTime(dt);
dt.hour = InpRangeEndHour;
dt.min = InpRangeEndMinute;
g_rangeEnd = StructToTime(dt);
if(g_rangeEnd <= g_rangeStart)
{
Print("Invalid range times");
return(false);
}
return(true);
}
//+------------------------------------------------------------------+
//| Draw the opening-range box |
//+------------------------------------------------------------------+
void drawRangeBox()
{
//--- get highest high and lowest low inside the range
int startIdx = iBarShift(NULL, 0, g_rangeStart, true);
int endIdx = iBarShift(NULL, 0, g_rangeEnd, true);
if(startIdx < 0 || endIdx < 0)
return;
g_rangeHigh = High[iHighest(NULL, 0, MODE_HIGH, startIdx - endIdx + 1, endIdx)];
g_rangeLow = Low [iLowest (NULL, 0, MODE_LOW, startIdx - endIdx + 1, endIdx)];
//--- create or move the rectangle
if(ObjectFind(0, "ORB_RangeBox") < 0)
{
ObjectCreate(0, "ORB_RangeBox", OBJ_RECTANGLE, 0, g_rangeStart, g_rangeHigh, g_rangeEnd, g_rangeLow);
ObjectSetInteger(0, "ORB_RangeBox", OBJPROP_COLOR, clrRoyalBlue);
ObjectSetInteger(0, "ORB_RangeBox", OBJPROP_FILL, false);
ObjectSetInteger(0, "ORB_RangeBox", OBJPROP_WIDTH, 2);
}
else
{
ObjectMove(0, "ORB_RangeBox", 0, g_rangeStart, g_rangeHigh);
ObjectMove(0, "ORB_RangeBox", 1, g_rangeEnd, g_rangeLow);
}
}
//+------------------------------------------------------------------+
//| Find the first candle that closes outside the range |
//+------------------------------------------------------------------+
void findTriggerCandle()
{
int i = 1; // start from last completed candle
while(i < 100 && Time[i] >= g_rangeEnd)
{
double close = Close[i];
bool outsideUp = close > g_rangeHigh;
bool outsideDn = close < g_rangeLow;
if(outsideUp || outsideDn)
{
g_triggerCandleFound = true;
g_triggerDirection = outsideUp;
if(outsideUp)
g_triggerLevel = High[i]; // wick high
else
g_triggerLevel = Low[i]; // wick low
//--- draw the trigger line
if(ObjectFind(0, "ORB_TriggerLine") < 0)
{
ObjectCreate(0, "ORB_TriggerLine", OBJ_HLINE, 0, 0, g_triggerLevel);
ObjectSetInteger(0, "ORB_TriggerLine", OBJPROP_COLOR, outsideUp ? clrGreen : clrRed);
ObjectSetInteger(0, "ORB_TriggerLine", OBJPROP_WIDTH, 2);
ObjectSetInteger(0, "ORB_TriggerLine", OBJPROP_STYLE, STYLE_DASH);
}
else
ObjectSetDouble(0, "ORB_TriggerLine", OBJPROP_PRICE, 0, g_triggerLevel);
break;
}
i++;
}
}
//+------------------------------------------------------------------+
//| Wait for close beyond trigger wick, then retest |
//+------------------------------------------------------------------+
void checkRetestAndTrade()
{
//--- ensure no open orders from this EA
if(OrdersTotalMagic(InpMagicNumber) > 0)
return;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool longCondition = g_triggerDirection &&
Close[1] > g_triggerLevel &&
bid <= g_triggerLevel + _Point; // retest
bool shortCondition = !g_triggerDirection &&
Close[1] < g_triggerLevel &&
ask >= g_triggerLevel - _Point; // retest
if(longCondition || shortCondition)
{
double price, sl, tp;
if(longCondition)
{
price = ask;
sl = price - InpStopLossPips * _Point * _Digits;
tp = price + InpTakeProfitPips * _Point * _Digits;
}
else
{
price = bid;
sl = price + InpStopLossPips * _Point * _Digits;
tp = price - InpTakeProfitPips * _Point * _Digits;
}
tradeOrder(longCondition ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, price, sl, tp);
g_tradeExecuted = true;
}
}
//+------------------------------------------------------------------+
//| Send the market order |
//+------------------------------------------------------------------+
void tradeOrder(ENUM_ORDER_TYPE type, double price, double sl, double tp)
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL;
req.symbol = _Symbol;
req.volume = InpLotSize;
req.type = type;
req.price = price;
req.sl = sl;
req.tp = tp;
req.magic = InpMagicNumber;
req.deviation= InpSlippage;
if(!OrderSend(req, res))
Print("OrderSend failed: ", GetLastError(), " retcode=", res.retcode);
else
Print("Trade opened: ticket=", res.order);
}
//+------------------------------------------------------------------+
//| Count open orders with this EA's magic |
//+------------------------------------------------------------------+
int OrdersTotalMagic(int magic)
{
int total = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderGetTicket(i))
if(OrderGetInteger(ORDER_MAGIC) == magic)
total++;
}
return(total);
}
//+------------------------------------------------------------------+
How it works (quick recap)
- You set the start / end time of the opening range (broker time).
- The EA draws a rectangle covering the high/low of that period.
- After the range ends it waits for the first 5-minute candle whose body closes outside the range.
• Bullish breakout → remembers the wick high of that candle.
• Bearish breakout → remembers the wick low.
- A dashed line is plotted at that wick level.
- When price closes beyond the wick and then retests it (price touches or pierces the line), the EA fires a market order.
- SL & TP are placed at the distances you specify in pips.
Compile, attach to a 5-minute chart, and adjust the inputs as desired.