//+------------------------------------------------------------------+
//|                                                   TrapDemoEA.mq5 |
//|                                         Copyright 2026, B. Aliev |
//|  Demo EA for the article "Six Backtest Traps".                   |
//|  Rule (long only, for illustration, not a trading system):       |
//|   the bar closes above EMA after closing below it on the bar     |
//|   before -> buy. Stop = InpStopAtr * ATR, target = InpTakeR * risk.|
//|  The rule stays the same, only the decision and fill handling    |
//|  change, so you can see how much of the result comes from them. |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, B. Aliev"
#property version   "1.00"
#property description "Same rule, different entry handling: see how the backtest result changes."

#include <Trade\Trade.mqh>
#include <BacktestTraps\BacktestTraps.mqh>

enum ENUM_ENTRY_MODE
  {
   ENTRY_NEXT_BAR_MARKET = 0, // Market order at the open of the next bar
   ENTRY_LIMIT_TOUCH     = 1, // Pending buy limit, the tester fills it on a touch
   ENTRY_LIMIT_PASS      = 2  // Virtual limit, the price must pass the level
  };

input ENUM_ENTRY_MODE InpEntryMode    = ENTRY_NEXT_BAR_MARKET; // Entry handling
input bool            InpDecideOnTick = false;  // Trap 1: decide on the unfinished bar
input int             InpEmaPeriod    = 20;     // EMA period
input int             InpAtrPeriod    = 14;     // ATR period
input double          InpStopAtr      = 1.5;    // Stop distance, ATR
input double          InpTakeR        = 2.0;    // Take profit, multiples of the stop
input double          InpLimitAtr     = 0.5;    // Limit distance below the close, ATR
input int             InpLimitBars    = 6;      // Limit lifetime, bars
input double          InpPassPoints   = 20;     // Required pass through the limit level, points
input double          InpLots         = 0.10;   // Volume
input long            InpMagic        = 250001; // Magic number

CTrade     g_trade;
CNewBar    g_bar;
CExitAudit g_audit;
int        g_ema = INVALID_HANDLE, g_atr = INVALID_HANDLE;
datetime   g_last_signal = 0;
//--- pending order (touch mode) or virtual limit (pass mode)
ulong      g_pending = 0;
bool       g_v_active = false;
double     g_v_level = 0, g_v_sl = 0, g_v_tp = 0;
datetime   g_expire = 0;

//+------------------------------------------------------------------+
int OnInit()
  {
   g_ema = iMA(_Symbol, _Period, InpEmaPeriod, 0, MODE_EMA, PRICE_CLOSE);
   g_atr = iATR(_Symbol, _Period, InpAtrPeriod);
   if(g_ema == INVALID_HANDLE || g_atr == INVALID_HANDLE)
      return(INIT_FAILED);
   g_trade.SetExpertMagicNumber(InpMagic);
   g_bar.Init(_Symbol, _Period);
   g_audit.Init(_Symbol, _Period);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   IndicatorRelease(g_ema);
   IndicatorRelease(g_atr);
  }

//+------------------------------------------------------------------+
bool HasPosition()
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
      if(PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         return(true);
   return(false);
  }

//+------------------------------------------------------------------+
//| Signal on bar 'shift': close above EMA, the bar before below     |
//+------------------------------------------------------------------+
bool Signal(const int shift, double &atr)
  {
   double ema[2], a[1];
   if(CopyBuffer(g_ema, 0, shift, 2, ema) != 2 || CopyBuffer(g_atr, 0, shift, 1, a) != 1)
      return(false);
   // ema[1] is bar 'shift', ema[0] is bar 'shift + 1'
   double c0 = iClose(_Symbol, _Period, shift);
   double c1 = iClose(_Symbol, _Period, shift + 1);
   atr = a[0];
   return(c0 > ema[1] && c1 <= ema[0] && atr > 0);
  }

//+------------------------------------------------------------------+
void OnTick()
  {
   bool new_bar = g_bar.IsNew();
   MqlTick tick;
   if(!SymbolInfoTick(_Symbol, tick))
      return;

//--- the pending order was filled or removed by the server
   if(g_pending > 0 && !OrderSelect(g_pending))
     {
      g_pending = 0;
      g_expire = 0;
     }
//--- expiry of pending or virtual limits
   if(new_bar && g_expire > 0 && TimeCurrent() >= g_expire)
     {
      if(g_pending > 0 && OrderSelect(g_pending))
         g_trade.OrderDelete(g_pending);
      g_pending = 0;
      g_v_active = false;
      g_expire = 0;
     }
//--- virtual limit: filled only if the price passed the level
   if(g_v_active && !HasPosition() && HonestLimitTouched(true, g_v_level, InpPassPoints, tick.bid, tick.ask))
     {
      g_v_active = false;
      g_expire = 0;
      g_trade.Buy(InpLots, _Symbol, tick.ask, g_v_sl, g_v_tp, "limit pass");
     }

//--- Trap 1 switch: the honest way decides once, on the closed bar
   int shift = 1;
   if(InpDecideOnTick)
      shift = 0;
   else
      if(!new_bar)
         return;

   datetime bar_time = iTime(_Symbol, _Period, shift);
   if(bar_time == g_last_signal || HasPosition() || g_pending > 0 || g_v_active)
      return;
   double atr;
   if(!Signal(shift, atr))
      return;
   g_last_signal = bar_time;

   double risk = InpStopAtr * atr;
   if(InpEntryMode == ENTRY_NEXT_BAR_MARKET)
     {
      g_trade.Buy(InpLots, _Symbol, tick.ask, tick.ask - risk, tick.ask + InpTakeR * risk, "market");
      return;
     }
   double level = NormalizeDouble(iClose(_Symbol, _Period, shift) - InpLimitAtr * atr, _Digits);
   double sl = NormalizeDouble(level - risk, _Digits);
   double tp = NormalizeDouble(level + InpTakeR * risk, _Digits);
   g_expire = iTime(_Symbol, _Period, 0) + InpLimitBars * PeriodSeconds(_Period);
   if(InpEntryMode == ENTRY_LIMIT_TOUCH)
     {
      if(g_trade.BuyLimit(InpLots, level, _Symbol, sl, tp, ORDER_TIME_GTC, 0, "limit touch"))
         g_pending = g_trade.ResultOrder();
     }
   else
     {
      g_v_active = true;
      g_v_level = level;
      g_v_sl = sl;
      g_v_tp = tp;
     }
  }

//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result)
  {
   g_audit.OnTransaction(trans);
//--- the pending order is gone (filled or deleted)
   if(g_pending > 0 && trans.type == TRADE_TRANSACTION_ORDER_DELETE && trans.order == g_pending)
     {
      g_pending = 0;
      g_expire = 0;
     }
  }

//+------------------------------------------------------------------+
double OnTester()
  {
   g_audit.Report("TrapDemoEA_exit_audit.csv");
   return(TesterStatistics(STAT_PROFIT));
  }
//+------------------------------------------------------------------+
