//+------------------------------------------------------------------+
//|                                     fractals-breakout-ea.mq5       |
//|  A breakout EA: enters when price closes beyond the most recent   |
//|  confirmed Fractal, using the broken Fractal level itself as the  |
//|  Stop Loss (not ATR — the fractal is already a natural support/   |
//|  resistance level), with risk-based position sizing. One position |
//|  at a time.                                                       |
//|  EDUCATIONAL — test on a demo account first. Past performance     |
//|  does not guarantee future results. This is not financial advice.|
//|  Source: web-forex (educational, free to use and modify)          |
//+------------------------------------------------------------------+
#property copyright "web-forex"
#include <Trade\Trade.mqh>

CTrade trade;

input string       ___Strategy___       = "--- Fractals Breakout Strategy ---";

input string       ___RiskManagement___ = "--- Risk Management ---";
input double       RiskRewardRatio      = 2.0;
input bool         UseFixedLot          = false;
input double       FixedLotSize         = 0.01;
input double       RiskPercent          = 1.0;

input string       ___Filters___        = "--- Filters ---";
input int          MaxSpreadPoints      = 30;

input string       ___General___        = "--- General ---";
input ulong        MagicNumber          = 20260730;
input bool         EnableTrading        = true;

int fractalsHandle = INVALID_HANDLE;
datetime lastBarTime = 0;
double storedUpFractal = 0;
double storedDownFractal = 0;

int OnInit()
{
   trade.SetExpertMagicNumber(MagicNumber);

   fractalsHandle = iFractals(_Symbol, _Period);

   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   IndicatorRelease(fractalsHandle);
}

void OnTick()
{
   if (!EnableTrading)
      return;

   datetime currentBarTime = iTime(_Symbol, _Period, 0);
   if (currentBarTime == lastBarTime)
      return; // only evaluate once per new bar
   lastBarTime = currentBarTime;

   double upArr[], downArr[];
   ArraySetAsSeries(upArr, true);
   ArraySetAsSeries(downArr, true);
   if (CopyBuffer(fractalsHandle, 0, 0, 3, upArr) < 3) return;
   if (CopyBuffer(fractalsHandle, 1, 0, 3, downArr) < 3) return;

   double upFrac   = upArr[2];
   double downFrac = downArr[2];
   if (upFrac != 0)
      storedUpFractal = upFrac;
   if (downFrac != 0)
      storedDownFractal = downFrac;

   if (CountOpenPositions() > 0)
      return; // one position at a time

   long spreadPoints = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
   if (spreadPoints > MaxSpreadPoints)
      return; // spread too wide right now, skip this bar

   double closeArr[];
   ArraySetAsSeries(closeArr, true);
   if (CopyClose(_Symbol, _Period, 0, 3, closeArr) < 3) return;

   double closePrev = closeArr[2];
   double closeLast = closeArr[1];

   bool bullishBreak = (storedUpFractal > 0 && closePrev <= storedUpFractal && closeLast > storedUpFractal);
   bool bearishBreak = (storedDownFractal > 0 && closePrev >= storedDownFractal && closeLast < storedDownFractal);

   if (bullishBreak)
      OpenTrade(ORDER_TYPE_BUY, storedUpFractal);
   else if (bearishBreak)
      OpenTrade(ORDER_TYPE_SELL, storedDownFractal);
}

int CountOpenPositions()
{
   int count = 0;
   for (int i = 0; i < PositionsTotal(); i++)
   {
      ulong ticket = PositionGetTicket(i);
      if (ticket > 0 && PositionSelectByTicket(ticket))
      {
         if (PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == (long)MagicNumber)
            count++;
      }
   }
   return(count);
}

void OpenTrade(ENUM_ORDER_TYPE type, double fractalLevel)
{
   double price, sl, tp, slDistance;

   if (type == ORDER_TYPE_BUY)
   {
      price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      sl = fractalLevel; // the broken up-fractal now treated as support
      slDistance = price - sl;
      tp = price + slDistance * RiskRewardRatio;
   }
   else
   {
      price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      sl = fractalLevel; // the broken down-fractal now treated as resistance
      slDistance = sl - price;
      tp = price - slDistance * RiskRewardRatio;
   }

   if (slDistance <= 0)
      return; // guard against a degenerate stop distance

   double lots = CalculateLotSize(slDistance);

   if (type == ORDER_TYPE_BUY)
      trade.Buy(lots, _Symbol, price, sl, tp, "Fractals Breakout EA");
   else
      trade.Sell(lots, _Symbol, price, sl, tp, "Fractals Breakout EA");
}

double CalculateLotSize(double slDistance)
{
   if (UseFixedLot || slDistance <= 0)
      return(NormalizeLotSize(FixedLotSize));

   double riskAmount = AccountInfoDouble(ACCOUNT_BALANCE) * (RiskPercent / 100.0);
   double tickValue   = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSize    = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   if (tickSize <= 0 || tickValue <= 0)
      return(NormalizeLotSize(FixedLotSize));

   double slTicks = slDistance / tickSize;
   double lots    = riskAmount / (slTicks * tickValue);

   return(NormalizeLotSize(lots));
}

double NormalizeLotSize(double lots)
{
   double minLot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   if (lotStep <= 0)
      return(minLot);

   lots = MathFloor(lots / lotStep) * lotStep;
   if (lots < minLot)
      lots = minLot;
   if (lots > maxLot)
      lots = maxLot;
   return(lots);
}
