//+------------------------------------------------------------------+
//|                                       trix-cross-ea.mq5           |
//|  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"
#include <Trade\Trade.mqh>

CTrade trade;

input string       ___Strategy___       = "--- TRIX Cross Strategy ---";
input int          TrixPeriod           = 14;
input int          SignalPeriod         = 9;

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

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

int atrHandle = INVALID_HANDLE;
datetime lastBarTime = 0;

int OnInit()
{
   trade.SetExpertMagicNumber(MagicNumber);
   atrHandle = iATR(_Symbol, _Period, ATRPeriod);
   return(INIT_SUCCEEDED);
}

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

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

   int needed = WarmupBars + SignalPeriod + 3;
   double c[];
   ArraySetAsSeries(c, true);
   if (CopyClose(_Symbol, _Period, 0, needed, c) < needed) return;

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

   double atrArr[];
   ArraySetAsSeries(atrArr, true);
   if (CopyBuffer(atrHandle, 0, 0, 2, atrArr) < 2) return;
   double atr = atrArr[1];

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

   if (bullishCross)
      OpenTrade(ORDER_TYPE_BUY, atr);
   else if (bearishCross)
      OpenTrade(ORDER_TYPE_SELL, atr);
}

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

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

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

   for (int idx = oldest - 1; idx >= shift; idx--)
   {
      double ema3Prev = ema3;
      ema1 = alpha * c[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 < 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 atr)
{
   double slDistance = atr * ATRMultiplier;
   double tpDistance = slDistance * RiskRewardRatio;
   double lots       = CalculateLotSize(slDistance);
   double price, sl, tp;

   if (type == ORDER_TYPE_BUY)
   {
      price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      sl = price - slDistance;
      tp = price + tpDistance;
      trade.Buy(lots, _Symbol, price, sl, tp, "TRIX Cross EA");
   }
   else
   {
      price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      sl = price + slDistance;
      tp = price - tpDistance;
      trade.Sell(lots, _Symbol, price, sl, tp, "TRIX Cross 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);
}
