//+------------------------------------------------------------------+
//|                                   parabolic-sar-trend-ea.mq4       |
//|  A trend-following EA: enters when Parabolic SAR flips sides,     |
//|  using the flipped SAR dot itself as the Stop Loss (not ATR —     |
//|  SAR 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___       = "--- Parabolic SAR Trend Strategy ---";
extern double Step                 = 0.02;
extern double Maximum              = 0.20;

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          = 20260722;
extern bool   EnableTrading        = true;

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 sarPrev   = iSAR(NULL, 0, Step, Maximum, 2);
   double closePrev = iClose(NULL, 0, 2);
   double sarLast   = iSAR(NULL, 0, Step, Maximum, 1);
   double closeLast = iClose(NULL, 0, 1);

   bool bullishFlip = (sarPrev > closePrev && sarLast < closeLast);
   bool bearishFlip = (sarPrev < closePrev && sarLast > closeLast);

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

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

   if (type == OP_BUY)
   {
      price = Ask;
      sl = sarValue; // the flipped SAR dot is already positioned below price
      slDistance = price - sl;
      tp = price + slDistance * RiskRewardRatio;
   }
   else
   {
      price = Bid;
      sl = sarValue; // the flipped SAR dot 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, "Parabolic SAR Trend EA", MagicNumber, 0,
                          type == OP_BUY ? clrDodgerBlue : clrOrangeRed);
   if (ticket < 0)
      Print("Parabolic SAR 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);
}
