mql5 Copy code
//+------------------------------------------------------------------+
//| Golden Breakout EA |
//| A Clean, Professional Breakout EA |
//| Based on Previous Day High/Low |
//+------------------------------------------------------------------+
#property copyright "Your Name"
#property link "https://www.yourwebsite.com"
#property version "2.0"
#property strict
//--- Include standard trade libraries
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//--- Input Parameters (Organized & Labeled)
//+==================================================================+
//| TRADE SETTINGS |
//+==================================================================+
input double LotSize = 0.1; // Trade lot size
input int MagicNumber = 12345; // Unique magic number
//+==================================================================+
//| STOP LOSS & TAKE PROFIT OPTIONS |
//+==================================================================+
input int StopLossPoints = 50; // SL in points (0 = disabled)
input int TakeProfitPoints = 100; // TP in points (0 = disabled)
input double StopLossUSD = 0.0; // SL in USD (overrides points if > 0)
input double TakeProfitUSD = 0.0; // TP in USD (overrides points if > 0)
input bool UseATRStopLoss = true; // Use ATR-based stop loss
input int ATRPeriod = 14; // ATR period
input double ATRMultiplier = 2.0; // ATR multiplier (e.g. 2x ATR)
//+==================================================================+
//| TRAILING STOP |
//+==================================================================+
input bool UseTrailingStop = true; // Enable trailing stop
input int TrailingStopPoints = 30; // Trailing stop in points
//+==================================================================+
//| VISUAL OPTIONS |
//+==================================================================+
input color LineColorHigh = clrLimeGreen; // Color for previous day high
input color LineColorLow = clrHotPink; // Color for previous day low
input bool ShowInfoLabel = true; // Show SL/TP mode on chart
//+------------------------------------------------------------------+
//| Global Variables |
//+------------------------------------------------------------------+
double prevDayHigh = 0.0;
double prevDayLow = 0.0;
datetime prevDay = 0;
CTrade trade;
CSymbolInfo symbolInfo;
int atrHandle = INVALID_HANDLE;
//+------------------------------------------------------------------+
//| Expert Initialization Function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize symbol info
symbolInfo.Name(_Symbol);
if(!symbolInfo.Refresh())
{
Print("Error: Failed to refresh symbol info for ", _Symbol);
return(INIT_FAILED);
}
// Create ATR indicator if enabled
if(UseATRStopLoss)
{
atrHandle = iATR(_Symbol, PERIOD_D1, ATRPeriod);
if(atrHandle == INVALID_HANDLE)
{
Print("Error: Failed to create ATR indicator handle");
return(INIT_FAILED);
}
}
// Set magic number for all trades
trade.SetExpertMagicNumber(MagicNumber);
// Initial setup
UpdateDailyLevels();
PlacePendingOrders();
Print("Golden Breakout EA initialized successfully");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert Deinitialization Function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release ATR handle
if(atrHandle != INVALID_HANDLE)
IndicatorRelease(atrHandle);
// Remove chart objects
ObjectDelete(0, "PrevDayHigh");
ObjectDelete(0, "PrevDayLow");
ObjectDelete(0, "InfoLabel");
Print("Golden Breakout EA deinitialized");
}
//+------------------------------------------------------------------+
//| Expert Tick Function |
//+------------------------------------------------------------------+
void OnTick()
{
datetime currentDay = iTime(_Symbol, PERIOD_D1, 0);
// Check if a new day has started
if(currentDay != prevDay)
{
UpdateDailyLevels();
DeletePendingOrders();
PlacePendingOrders();
prevDay = currentDay;
}
// Apply trailing stop if enabled
if(UseTrailingStop)
ApplyTrailingStop();
}
//+------------------------------------------------------------------+
//| Update Previous Day High/Low and Draw Lines |
//+------------------------------------------------------------------+
void UpdateDailyLevels()
{
prevDayHigh = iHigh(_Symbol, PERIOD_D1, 1);
prevDayLow = iLow(_Symbol, PERIOD_D1, 1);
// Draw horizontal lines
DrawHorizontalLine("PrevDayHigh", prevDayHigh, LineColorHigh, "Previous Day High");
DrawHorizontalLine("PrevDayLow", prevDayLow, LineColorLow, "Previous Day Low");
// Update info label
if(ShowInfoLabel)
UpdateInfoLabel();
}
//+------------------------------------------------------------------+
//| Draw Horizontal Line with Label |
//+------------------------------------------------------------------+
void DrawHorizontalLine(string name, double price, color lineColor, string label = "")
{
ObjectDelete(0, name);
ObjectCreate(0, name, OBJ_HLINE, 0, 0, price);
ObjectSetInteger(0, name, OBJPROP_COLOR, lineColor);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DASHDOT);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 2);
ObjectSetString(0, name, OBJPROP_TOOLTIP, label);
// Optional label on the line
string labelName = name + "_Label";
ObjectDelete(0, labelName);
ObjectCreate(0, labelName, OBJ_TEXT, 0, iTime(_Symbol, PERIOD_H1, 0), price);
ObjectSetString(0, labelName, OBJPROP_TEXT, label);
ObjectSetInteger(0, labelName, OBJPROP_COLOR, lineColor);
ObjectSetInteger(0, labelName, OBJPROP_FONTSIZE, 10);
ObjectSetString(0, labelName, OBJPROP_FONT, "Arial");
}
//+------------------------------------------------------------------+
//| Update Info Label (SL/TP Mode) |
//+------------------------------------------------------------------+
void UpdateInfoLabel()
{
string mode = "SL/TP: ";
if(StopLossUSD > 0 || TakeProfitUSD > 0)
mode += "USD";
else if(UseATRStopLoss)
mode += "ATR x" + DoubleToString(ATRMultiplier, 1);
else
mode += "Points";
ObjectDelete(0, "InfoLabel");
ObjectCreate(0, "InfoLabel", OBJ_LABEL, 0, 0, 0);
ObjectSetString(0, "InfoLabel", OBJPROP_TEXT, "Golden Breakout\n" + mode);
ObjectSetInteger(0, "InfoLabel", OBJPROP_COLOR, clrWhite);
ObjectSetInteger(0, "InfoLabel", OBJPROP_FONTSIZE, 10);
ObjectSetString(0, "InfoLabel", OBJPROP_FONT, "Arial");
ObjectSetInteger(0, "InfoLabel", OBJPROP_CORNER, 0); // Top-left
ObjectSetInteger(0, "InfoLabel", OBJPROP_XDISTANCE, 10);
ObjectSetInteger(0, "InfoLabel", OBJPROP_YDISTANCE, 10);
}
//+------------------------------------------------------------------+
//| Delete All Pending Orders |
//+------------------------------------------------------------------+
void DeletePendingOrders()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong ticket = OrderGetTicket(i);
if(OrderSelect(ticket) &&
OrderGetInteger(ORDER_MAGIC) == MagicNumber &&
OrderGetString(ORDER_SYMBOL) == _Symbol)
{
if(!trade.OrderDelete(ticket))
Print("Failed to delete order #", ticket, " Error: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Place BuyStop and SellStop Orders |
//+------------------------------------------------------------------+
void PlacePendingOrders()
{
double slPoints = CalculateStopLossPoints();
double tpPoints = TakeProfitPoints;
// Override with USD if specified
if(TakeProfitUSD > 0.0)
tpPoints = USDToPoints(TakeProfitUSD);
// Buy Stop at Previous Day High
double buyPrice = prevDayHigh;
double buySL = (slPoints > 0) ? buyPrice - slPoints * _Point : 0.0;
double buyTP = (tpPoints > 0) ? buyPrice + tpPoints * _Point : 0.0;
if(!trade.BuyStop(LotSize, buyPrice, _Symbol, buySL, buyTP, ORDER_TIME_DAY, 0, "Buy: Day High Breakout"))
Print("Failed to place BuyStop. Error: ", GetLastError());
// Sell Stop at Previous Day Low
double sellPrice = prevDayLow;
double sellSL = (slPoints > 0) ? sellPrice + slPoints * _Point : 0.0;
double sellTP = (tpPoints > 0) ? sellPrice - tpPoints * _Point : 0.0;
if(!trade.SellStop(LotSize, sellPrice, _Symbol, sellSL, sellTP, ORDER_TIME_DAY, 0, "Sell: Day Low Breakout"))
Print("Failed to place SellStop. Error: ", GetLastError());
}
//+------------------------------------------------------------------+
//| Calculate Stop Loss in Points |
//+------------------------------------------------------------------+
double CalculateStopLossPoints()
{
if(StopLossUSD > 0.0)
return USDToPoints(StopLossUSD);
if(UseATRStopLoss && atrHandle != INVALID_HANDLE)
{
double atrBuffer[];
if(CopyBuffer(atrHandle, 0, 1, 1, atrBuffer) > 0)
return (atrBuffer[0] * ATRMultiplier) / _Point;
else
{
Print("Warning: ATR buffer copy failed. Using default points.");
return StopLossPoints;
}
}
return StopLossPoints; // Default to point-based SL
}
//+------------------------------------------------------------------+
//| Convert USD to Points |
//+------------------------------------------------------------------+
double USDToPoints(double usdAmount)
{
if(!symbolInfo.Refresh())
{
Print("Error: Could not refresh symbol info for USD conversion");
return 0;
}
double tickValue = symbolInfo.TickValue();
double tickSize = symbolInfo.TickSize();
if(tickValue <= 0 || LotSize <= 0)
{
Print("Error: Invalid tick value or lot size");
return 0;
}
// Convert USD to points
return (usdAmount / (tickValue * LotSize)) * (tickSize / _Point);
}
//+------------------------------------------------------------------+
//| Apply Trailing Stop to Open Positions |
//+------------------------------------------------------------------+
void ApplyTrailingStop()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetInteger(POSITION_MAGIC) != MagicNumber ||
PositionGetString(POSITION_SYMBOL) != _Symbol)
continue;
double currentPrice = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
? SymbolInfoDouble(_Symbol, SYMBOL_BID)
: SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentSL = PositionGetDouble(POSITION_SL);
double takeProfit = PositionGetDouble(POSITION_TP);
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
double newSL = currentPrice - TrailingStopPoints * _Point;
if(newSL > currentSL && newSL > openPrice)
{
if(!trade.PositionModify(ticket, newSL, takeProfit))
Print("Trailing Stop failed on Buy #", ticket, " | Error: ", GetLastError());
}
}
else // Sell position
{
double newSL = currentPrice + TrailingStopPoints * _Point;
if((newSL < currentSL || currentSL == 0) && newSL < openPrice)
{
if(!trade.PositionModify(ticket, newSL, takeProfit))
Print("Trailing Stop failed on Sell #", ticket, " | Error: ", GetLastError());
}
}
}
}
Let me know if you'd like a version with email alerts, sound alerts, or risk % instead of fixed lot! 🚀