//+------------------------------------------------------------------+
//|                                     ichimoku-breakout-ea.mq5       |
//|  A trend-following EA: enters on a Tenkan/Kijun cross once price  |
//|  has already broken out of the cloud, using the Kijun-sen level   |
//|  itself as the Stop Loss (not ATR — Kijun-sen already tracks the  |
//|  mid-term trend and gives a naturally trend-following stop),      |
//|  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___       = "--- Ichimoku Breakout Strategy ---";
input int          TenkanSen            = 9;
input int          KijunSen             = 26;
input int          SenkouSpanB          = 52;

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          = 20260726;
input bool         EnableTrading        = true;

int ichimokuHandle = INVALID_HANDLE;
datetime lastBarTime = 0;

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

   ichimokuHandle = iIchimoku(_Symbol, _Period, TenkanSen, KijunSen, SenkouSpanB);

   return(INIT_SUCCEEDED);
}

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

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

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

   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 tenkanArr[], kijunArr[], spanAArr[], spanBArr[], closeArr[];
   ArraySetAsSeries(tenkanArr, true);
   ArraySetAsSeries(kijunArr, true);
   ArraySetAsSeries(spanAArr, true);
   ArraySetAsSeries(spanBArr, true);
   ArraySetAsSeries(closeArr, true);

   if (CopyBuffer(ichimokuHandle, 0, 0, 3, tenkanArr) < 3) return;
   if (CopyBuffer(ichimokuHandle, 1, 0, 3, kijunArr) < 3) return;
   if (CopyBuffer(ichimokuHandle, 2, 0, 3, spanAArr) < 3) return;
   if (CopyBuffer(ichimokuHandle, 3, 0, 3, spanBArr) < 3) return;
   if (CopyClose(_Symbol, _Period, 0, 3, closeArr) < 3) return;

   double tenkanPrev = tenkanArr[2];
   double kijunPrev  = kijunArr[2];
   double tenkanLast = tenkanArr[1];
   double kijunLast  = kijunArr[1];
   double cloudTop    = MathMax(spanAArr[1], spanBArr[1]);
   double cloudBottom = MathMin(spanAArr[1], spanBArr[1]);
   double closeLast   = closeArr[1];

   bool bullishBreak = (tenkanPrev <= kijunPrev && tenkanLast > kijunLast && closeLast > cloudTop);
   bool bearishBreak = (tenkanPrev >= kijunPrev && tenkanLast < kijunLast && closeLast < cloudBottom);

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

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 kijunValue)
{
   double price, sl, tp, slDistance;

   if (type == ORDER_TYPE_BUY)
   {
      price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      sl = kijunValue; // Kijun-sen doubles as the trend-following Stop Loss
      slDistance = price - sl;
      tp = price + slDistance * RiskRewardRatio;
   }
   else
   {
      price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      sl = kijunValue;
      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, "Ichimoku Breakout EA");
   else
      trade.Sell(lots, _Symbol, price, sl, tp, "Ichimoku 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);
}
