//+------------------------------------------------------------------+
//| OpeningRangeBreakoutEA.mq5 |
//| Author: GeminiAI |
//| https://github.com/AI |
//+------------------------------------------------------------------+
#property copyright "Author: GeminiAI"
#property link "https://github.com/AI"
#property version "1.00"
#property description "Opening Range Breakout EA with Fibonacci retracement entry for both buy and sell."
#include <Trade\Trade.mqh>
//--- Input parameters for custom time settings (visible in EA properties)
input int StartHour = 9; // Opening Range Start Hour (0-23)
input int StartMinute = 0; // Opening Range Start Minute (0-59)
input int EndHour = 10; // Opening Range End Hour (0-23)
input int EndMinute = 0; // Opening Range End Minute (0-59)
input double LotSize = 0.01; // Trading lot size
input bool CloseAtEndOfDay = true; // Close all positions at end of day
input int EndOfDayHour = 23; // End of day hour (0-23)
input int EndOfDayMinute = 0; // End of day minute (0-59)
//--- Create a CTrade class instance for trade operations
CTrade trade;
//--- Global variables to store the initial balance
double initialBalance = 0.0;
//--- Variables to store the opening range
double openingRangeHigh = 0.0;
double openingRangeLow = 0.0;
bool openingRangeEstablished = false;
bool inOpeningPeriod = false;
//--- Variables for Fibonacci and trading state
string fiboObjectName = "OpeningRangeFibo";
bool buyBreakoutConfirmed = false;
bool sellBreakoutConfirmed = false;
double fiboEntryLevel = 0.0;
double fiboStopLossLevel = 0.0;
double fiboTakeProfitLevel = 0.0;
bool positionOpened = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Get the initial account balance when the EA is first attached to the chart
initialBalance = AccountInfoDouble(ACCOUNT_BALANCE);
//--- Reset the opening range variables
ResetState();
//--- Print the initial balance to the Experts log
Print("EA Initialized. Initial Balance: ", DoubleToString(initialBalance, 2), " ", AccountInfoString(ACCOUNT_CURRENCY));
//--- Check if we're using the 5-minute timeframe
if(Period() != PERIOD_M5)
{
Print("Warning: This EA is designed for the 5-minute timeframe. Current timeframe: ", EnumToString(Period()));
// We'll continue anyway, but the user should be aware
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Display a message in the Experts log when the EA is removed
Print("EA Deinitialized. Reason: ", reason);
Comment(""); // Clear the chart comment
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- Declare a structure to hold the current time
MqlDateTime currentTimeStruct;
TimeCurrent(currentTimeStruct);
//--- New day reset logic
if(currentTimeStruct.hour == 0 && currentTimeStruct.min < 5 && openingRangeEstablished)
{
ResetState();
}
//--- Handle the opening range period
bool currentlyInOpeningPeriod = IsInTimeRange(currentTimeStruct, StartHour, StartMinute, EndHour, EndMinute);
if(currentlyInOpeningPeriod)
{
inOpeningPeriod = true;
// Update the opening range high and low
if(openingRangeHigh == 0 || iHigh(Symbol(), PERIOD_M5, 0) > openingRangeHigh)
openingRangeHigh = iHigh(Symbol(), PERIOD_M5, 0);
if(openingRangeLow == 0 || iLow(Symbol(), PERIOD_M5, 0) < openingRangeLow)
openingRangeLow = iLow(Symbol(), PERIOD_M5, 0);
Comment("Initial Balance: ", DoubleToString(initialBalance, 2), " ", AccountInfoString(ACCOUNT_CURRENCY),
"\nOpening Range Time: ", StartHour, ":", StringFormat("%02d", StartMinute), " - ", EndHour, ":", StringFormat("%02d", EndMinute),
"\nBuilding Opening Range...",
"\nRange High: ", DoubleToString(openingRangeHigh, _Digits),
"\nRange Low: ", DoubleToString(openingRangeLow, _Digits));
}
else if(inOpeningPeriod && !currentlyInOpeningPeriod)
{
inOpeningPeriod = false;
openingRangeEstablished = true;
Print("Opening Range Established - High: ", DoubleToString(openingRangeHigh, _Digits), " Low: ", DoubleToString(openingRangeLow, _Digits));
}
//--- Trading logic after the opening range is established
if(openingRangeEstablished)
{
// Check for a wick breakout to the upside
if (!buyBreakoutConfirmed && iHigh(Symbol(), PERIOD_M5, 0) > openingRangeHigh)
{
buyBreakoutConfirmed = true;
PlotFibonacciAndSetLevels(ORDER_TYPE_BUY);
}
// Check for a downside wick breakout
else if (!sellBreakoutConfirmed && iLow(Symbol(), PERIOD_M5, 0) < openingRangeLow)
{
sellBreakoutConfirmed = true;
PlotFibonacciAndSetLevels(ORDER_TYPE_SELL);
}
else if (buyBreakoutConfirmed || sellBreakoutConfirmed)
{
// Check for retracement and execute trade
if (buyBreakoutConfirmed && !positionOpened)
{
// Check if price has retraced to the 0.45 fib level
if (iLow(Symbol(), PERIOD_M5, 0) <= fiboEntryLevel)
{
double risk = fiboEntryLevel - fiboStopLossLevel;
fiboTakeProfitLevel = fiboEntryLevel + 4 * risk;
// Execute the market buy trade
if(trade.Buy(LotSize, Symbol(), 0, fiboStopLossLevel, fiboTakeProfitLevel))
{
Print("Buy order executed at ", DoubleToString(fiboEntryLevel, _Digits), " after retracement to 0.45 Fib level.");
positionOpened = true;
}
else
{
Print("Error executing buy order: ", GetLastError());
}
}
// Display current state
Comment("Initial Balance: ", DoubleToString(initialBalance, 2), " ", AccountInfoString(ACCOUNT_CURRENCY),
"\nBreakout Confirmed: BUY",
"\nEntry Target: ", DoubleToString(fiboEntryLevel, _Digits), " (0.45 Fib)",
"\nStop Loss: ", DoubleToString(fiboStopLossLevel, _Digits), " (0.80 Fib)",
"\nTake Profit: ", DoubleToString(fiboTakeProfitLevel, _Digits), " (4:1 R:R)",
"\nWaiting for retracement to entry...");
}
else if (sellBreakoutConfirmed && !positionOpened)
{
// Check if price has retraced to the 0.45 fib level
if (iHigh(Symbol(), PERIOD_M5, 0) >= fiboEntryLevel)
{
double risk = fiboStopLossLevel - fiboEntryLevel;
fiboTakeProfitLevel = fiboEntryLevel - 4 * risk;
// Execute the market sell trade
if(trade.Sell(LotSize, Symbol(), 0, fiboStopLossLevel, fiboTakeProfitLevel))
{
Print("Sell order executed at ", DoubleToString(fiboEntryLevel, _Digits), " after retracement to 0.45 Fib level.");
positionOpened = true;
}
else
{
Print("Error executing sell order: ", GetLastError());
}
}
// Display current state
Comment("Initial Balance: ", DoubleToString(initialBalance, 2), " ", AccountInfoString(ACCOUNT_CURRENCY),
"\nBreakout Confirmed: SELL",
"\nEntry Target: ", DoubleToString(fiboEntryLevel, _Digits), " (0.45 Fib)",
"\nStop Loss: ", DoubleToString(fiboStopLossLevel, _Digits), " (0.80 Fib)",
"\nTake Profit: ", DoubleToString(fiboTakeProfitLevel, _Digits), " (4:1 R:R)",
"\nWaiting for retracement to entry...");
}
}
}
//--- Close positions at end of day
if(CloseAtEndOfDay && IsInTimeRange(currentTimeStruct, EndOfDayHour, EndOfDayMinute, 23, 59))
{
CloseAllPositions();
}
}
//+------------------------------------------------------------------+
//| Plot the Fibonacci object and set levels |
//+------------------------------------------------------------------+
void PlotFibonacciAndSetLevels(ENUM_ORDER_TYPE direction)
{
// Delete any previous Fibonacci object
ObjectDelete(0, fiboObjectName);
double fiboStartPrice