//+------------------------------------------------------------------+
//|                                   supertrend-trend-ea.mq4          |
//|  A trend-following EA: enters when the SuperTrend line flips       |
//|  sides, using the flipped line value itself as the Stop Loss (not |
//|  a separate ATR multiple -- SuperTrend already gives a             |
//|  volatility-adaptive stop by design), 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"
#property strict

extern string ___Strategy___       = "--- SuperTrend Strategy ---";
extern int    ATRPeriod            = 10;
extern double Multiplier           = 3.0;

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

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

extern string ___General___        = "--- General ---";
extern int    MagicNumber          = 20260727;
extern bool   EnableTrading        = true;

#define SUPERTREND_LOOKBACK 300

datetime lastBarTime = 0;

int OnInit()
{
   return(INIT_SUCCEEDED);
}

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

   if (Time[0] == lastBarTime)
      return; // only evaluate once per new bar
   lastBarTime = Time[0];

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

   double spreadPoints = MarketInfo(Symbol(), MODE_SPREAD);
   if (spreadPoints > MaxSpreadPoints)
      return; // spread too wide right now, skip this bar

   double trendLast, trendPrev, lineLast;
   if (!CalculateSuperTrend(trendLast, trendPrev, lineLast))
      return;

   bool bullishFlip = (trendPrev == -1 && trendLast == 1);
   bool bearishFlip = (trendPrev == 1 && trendLast == -1);

   if (bullishFlip)
      OpenTrade(OP_BUY, lineLast);
   else if (bearishFlip)
      OpenTrade(OP_SELL, lineLast);
}

bool CalculateSuperTrend(double &trendLast, double &trendPrev, double &lineLast)
{
   int bars = MathMin(Bars - 1, SUPERTREND_LOOKBACK);
   if (bars < ATRPeriod + 5)
      return(false);

   double finalUpperArr[], finalLowerArr[], trendArr[], lineArr[];
   ArrayResize(finalUpperArr, bars + 1);
   ArrayResize(finalLowerArr, bars + 1);
   ArrayResize(trendArr, bars + 1);
   ArrayResize(lineArr, bars + 1);

   for (int i = bars; i >= 1; i--)
   {
      double atr = iATR(NULL, 0, ATRPeriod, i);
      double mid = (High[i] + Low[i]) / 2.0;
      double basicUpper = mid + Multiplier * atr;
      double basicLower = mid - Multiplier * atr;

      double finalUpper, finalLower;
      if (i == bars)
      {
         finalUpper = basicUpper;
         finalLower = basicLower;
      }
      else
      {
         double prevFinalUpper = finalUpperArr[i + 1];
         double prevFinalLower = finalLowerArr[i + 1];
         double prevClose      = Close[i + 1];

         finalUpper = (basicUpper < prevFinalUpper || prevClose > prevFinalUpper) ? basicUpper : prevFinalUpper;
         finalLower = (basicLower > prevFinalLower || prevClose < prevFinalLower) ? basicLower : prevFinalLower;
      }

      finalUpperArr[i] = finalUpper;
      finalLowerArr[i] = finalLower;

      double prevTrend = (i == bars) ? 1 : trendArr[i + 1];
      double trend;
      if (prevTrend == 1)
         trend = (Close[i] < finalLower) ? -1 : 1;
      else
         trend = (Close[i] > finalUpper) ? 1 : -1;

      trendArr[i] = trend;
      lineArr[i]  = (trend == 1) ? finalLower : finalUpper;
   }

   trendLast = trendArr[1];
   trendPrev = trendArr[2];
   lineLast  = lineArr[1];
   return(true);
}

int CountOpenPositions()
{
   int count = 0;
   for (int i = 0; i < OrdersTotal(); i++)
   {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
            count++;
      }
   }
   return(count);
}

void OpenTrade(int type, double lineValue)
{
   double price, sl, tp, slDistance;

   if (type == OP_BUY)
   {
      price = Ask;
      sl = lineValue; // the flipped SuperTrend line is already positioned below price
      slDistance = price - sl;
      tp = price + slDistance * RiskRewardRatio;
   }
   else
   {
      price = Bid;
      sl = lineValue; // the flipped SuperTrend line is already positioned above price
      slDistance = sl - price;
      tp = price - slDistance * RiskRewardRatio;
   }

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

   double lots = CalculateLotSize(slDistance);

   int ticket = OrderSend(Symbol(), type, lots, price, 3, sl, tp, "SuperTrend Trend EA", MagicNumber, 0,
                          type == OP_BUY ? clrLimeGreen : clrRed);
   if (ticket < 0)
      Print("SuperTrend Trend EA: OrderSend failed, error ", GetLastError());
}

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

   double riskAmount = AccountBalance() * (RiskPercent / 100.0);
   double tickValue   = MarketInfo(Symbol(), MODE_TICKVALUE);
   double tickSize    = MarketInfo(Symbol(), MODE_TICKSIZE);
   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  = MarketInfo(Symbol(), MODE_MINLOT);
   double maxLot  = MarketInfo(Symbol(), MODE_MAXLOT);
   double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   if (lotStep <= 0)
      return(minLot);

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