//+------------------------------------------------------------------+
//|                                       trix-cross-ea.mq4           |
//|  A TRIX EA: enters when TRIX (triple-smoothed EMA rate of change, |
//|  custom calculated, no built-in TRIX function) crosses its signal |
//|  line, with ATR-based Stop Loss/Take Profit and 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___       = "--- TRIX Cross Strategy ---";
extern int    TrixPeriod           = 14;
extern int    SignalPeriod         = 9;

extern string ___RiskManagement___ = "--- Risk Management ---";
extern int    ATRPeriod            = 14;
extern double ATRMultiplier        = 2.0;
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          = 20260815;
extern bool   EnableTrading        = true;

int WarmupBars = 150; // bars of history used to converge the triple-EMA cascade

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

   if (Bars < WarmupBars + SignalPeriod + 3)
      return; // not enough history yet

   double trixLast, signalLast, trixPrev, signalPrev;
   ComputeTrix(1, trixLast, signalLast);
   ComputeTrix(2, trixPrev, signalPrev);

   double atr = iATR(NULL, 0, ATRPeriod, 1);

   bool bullishCross = (trixPrev <= signalPrev && trixLast > signalLast);
   bool bearishCross = (trixPrev >= signalPrev && trixLast < signalLast);

   if (bullishCross)
      OpenTrade(OP_BUY, atr);
   else if (bearishCross)
      OpenTrade(OP_SELL, atr);
}

// Recomputes the triple-smoothed EMA cascade over a bounded lookback window
// ending at 'shift', since MQL4 has no built-in TRIX function to call.
void ComputeTrix(int shift, double &trixOut, double &signalOut)
{
   double alpha = 2.0 / (TrixPeriod + 1.0);
   int oldest = shift + WarmupBars - 1;

   double ema1 = Close[oldest];
   double ema2 = Close[oldest];
   double ema3 = Close[oldest];

   double trixArr[];
   ArrayResize(trixArr, WarmupBars);
   trixArr[WarmupBars - 1] = 0;

   for (int idx = oldest - 1; idx >= shift; idx--)
   {
      double ema3Prev = ema3;
      ema1 = alpha * Close[idx] + (1 - alpha) * ema1;
      ema2 = alpha * ema1 + (1 - alpha) * ema2;
      ema3 = alpha * ema2 + (1 - alpha) * ema3;

      double trixVal = (ema3Prev != 0) ? (ema3 - ema3Prev) / ema3Prev * 100.0 : 0;
      trixArr[idx - shift] = trixVal;
   }

   trixOut = trixArr[0];

   double sum = 0;
   for (int j = 0; j < SignalPeriod; j++)
      sum += trixArr[j];
   signalOut = sum / SignalPeriod;
}

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 atr)
{
   double slDistance = atr * ATRMultiplier;
   double tpDistance = slDistance * RiskRewardRatio;
   double lots       = CalculateLotSize(slDistance);
   double price, sl, tp;

   if (type == OP_BUY)
   {
      price = Ask;
      sl = price - slDistance;
      tp = price + tpDistance;
   }
   else
   {
      price = Bid;
      sl = price + slDistance;
      tp = price - tpDistance;
   }

   int ticket = OrderSend(Symbol(), type, lots, price, 3, sl, tp, "TRIX Cross EA", MagicNumber, 0,
                          type == OP_BUY ? clrDodgerBlue : clrOrangeRed);
   if (ticket < 0)
      Print("TRIX Cross 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);
}
