//+------------------------------------------------------------------+
//|                       2TF Waddah Attar Explosion (SMC) BT EA.mq5 |
//|        Expert Advisor based on "2TF Waddah Attar Explosion (SMC) |
//|        BT" indicator. WAE core © 2006, Ahmad Waddah Attar        |
//+------------------------------------------------------------------+
#property copyright   "WAE core © 2006, Ahmad Waddah Attar"
#property link        "https://www.mql5.com/en/code/7051"
#property version     "1.00"
#property description "EA built on the 2TF Waddah Attar Explosion (SMC) BT indicator."
#property description "Trades 2-timeframe WAE agreement signals (optionally confirmed by BOS/CHoCH),"
#property description "with EMA, market-structure and S&R deviation-zone filters, ATR/swing/fixed SL,"
#property description "RR/ATR/fixed TP, break-even, trailing stop and risk-based position sizing."
#property tester_indicator "2TF Waddah Attar Explosion (SMC) BT.ex5"

#include <Trade\Trade.mqh>

#define VIS_INDICATOR_NAME "2TF Waddah Attar Explosion (SMC) BT"

//+------------------------------------------------------------------+
//| Enumerations                                                     |
//+------------------------------------------------------------------+
enum ENUM_WAE_TREND_MODE
{
   WAE_MODE_TREND_ONLY        = 0, // Trend Direction Only (Green = Up, Red = Down)
   WAE_MODE_EXPLOSION_ONLY    = 1, // Explosion (Histogram > Explosion Line)
   WAE_MODE_EXPLOSION_DEAD    = 2, // Explosion & DeadZone (Histogram > Explosion & DeadZone)
   WAE_MODE_CHART_EXP_HTF_DIR = 3  // Chart TF Explosion+DeadZone & HTF Trend Direction
};

enum ENUM_ENTRY_MODE
{
   ENTRY_AGREE_FIRST = 0, // 2TF Agreement - First Bar Only (= Indicator Arrow)
   ENTRY_AGREE_ANY   = 1, // 2TF Agreement - Any Bar While Agreeing
   ENTRY_BOS_AGREE   = 2, // BOS/CHoCH Break + 2TF Agreement Same Direction
   ENTRY_BOS_HTF     = 3  // BOS/CHoCH Break + MTF WAE Direction
};

enum ENUM_SL_MODE
{
   SL_NONE  = 0, // None
   SL_FIXED = 1, // Fixed Points
   SL_ATR   = 2, // ATR Multiple
   SL_SWING = 3  // Last Swing Pivot (fallback ATR)
};

enum ENUM_TP_MODE
{
   TP_NONE  = 0, // None
   TP_FIXED = 1, // Fixed Points
   TP_ATR   = 2, // ATR Multiple
   TP_RR    = 3  // Risk:Reward Multiple of SL
};

enum ENUM_LOT_MODE
{
   LOT_FIXED = 0, // Fixed Lots
   LOT_RISK  = 1  // Risk % of Balance (needs SL)
};

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input group "=== Signal Settings (2TF WAE) ==="
input ENUM_TIMEFRAMES      InpChartTf          = PERIOD_CURRENT;      // Chart Timeframe (Current by default)
input ENUM_TIMEFRAMES      InpHtfTf            = PERIOD_H4;           // MTF Timeframe (Higher - Main)
input bool                 InpHtfUseClosedBar  = false;               // MTF: Use Closed Bar (Shift 1)
input ENUM_WAE_TREND_MODE  InpTrendMode        = WAE_MODE_TREND_ONLY; // Trend Agreement Mode
input ENUM_ENTRY_MODE      InpEntryMode        = ENTRY_AGREE_FIRST;   // Entry Signal Mode
input int                  InpWaeBars          = 1000;                // Bars Used for WAE Calculation

input group "=== Waddah Attar Explosion Settings ==="
input int                  Fast_MA             = 20;                  // Fast MACD EMA Period
input int                  Slow_MA             = 40;                  // Slow MACD EMA Period
input int                  BBPeriod            = 20;                  // Bollinger Bands Period
input double               BBDeviation         = 2.0;                 // Bollinger Bands Deviation
input int                  Sensetive           = 150;                 // Sensitivity Multiplier
input int                  DeadZonePip         = 400;                 // DeadZone Level (in Points)

input group "=== Entry Filters ==="
input bool                 InpUseEmaFilter     = true;                // EMA Filter (Prices above EMA = BUY only, below = SELL only)
input int                  InpEmaPeriod        = 200;                 // EMA Period
input ENUM_APPLIED_PRICE   InpEmaPrice         = PRICE_CLOSE;         // EMA Applied Price
input bool                 InpUseStructFilter  = false;               // BOS/CHoCH Structure Trend Must Match
input bool                 InpUseZoneFilter    = false;               // Block Entries Into Opposing S&R Zone
input double               InpZoneBufferAtr    = 0.0;                 // Zone Filter Extra Buffer (ATR)

input group "=== BOS / CHoCH & S&R Deviation Zones ==="
input int                  bos_swing_len       = 5;                   // Swing Lookback Length (Pivots)
input double               process_noise       = 0.01;                // Process Noise (Q)
input double               measurement_noise   = 0.5;                 // Measurement Noise (R)
input double               zero_lag_factor     = 1.0;                 // Zero Lag Factor
input double               velocity_weight     = 0.5;                 // Velocity Weight
input double               deviation_thresh    = 1.5;                 // Deviation Threshold (ATR)
input double               level_width         = 0.25;                // Level Width (ATR)
input int                  max_levels          = 6;                   // Maximum Active Levels
input int                  InpSmcWarmupBars    = 3000;                // Structure Warm-up Bars

input group "=== Trade Settings ==="
input bool                 InpAllowBuy         = true;                // Allow Buy Trades
input bool                 InpAllowSell        = true;                // Allow Sell Trades
input ulong                InpMagic            = 20261124;            // Magic Number
input string               InpComment          = "2TF WAE SMC EA";    // Order Comment
input ENUM_LOT_MODE        InpLotMode          = LOT_FIXED;           // Lot Sizing Mode
input double               InpLots             = 0.10;                // Fixed Lots
input double               InpRiskPct          = 1.0;                 // Risk % per Trade (Risk mode)
input int                  InpMaxSpreadPts     = 0;                   // Max Spread in Points (0 = Off)
input int                  InpSlippagePts      = 10;                  // Max Slippage (Points)

input group "=== Exit Rules ==="
input bool                 InpCloseOnOpposite  = true;                // Close on Opposite Signal (allows reversal)
input bool                 InpExitOnAgreeLoss  = false;               // Close When 2TF Agreement Is Lost
input bool                 InpExitOnStructBrk  = false;               // Close on Opposite BOS/CHoCH Break
input bool                 InpExitOnStoch      = true;                // Close on Stochastic Cross (Buy: Cross Dn / Sell: Cross Up)
input int                  InpStochK           = 5;                   // Stochastic %K Period
input int                  InpStochD           = 3;                   // Stochastic %D Period
input int                  InpStochSlowing     = 3;                   // Stochastic Slowing
input ENUM_MA_METHOD       InpStochMethod      = MODE_SMA;            // Stochastic MA Method
input ENUM_STO_PRICE       InpStochPrice       = STO_LOWHIGH;         // Stochastic Price Field

input group "=== Stop Loss / Take Profit ==="
input ENUM_SL_MODE         InpSlMode           = SL_ATR;              // Stop Loss Mode
input int                  InpSlPoints         = 300;                 // SL Fixed (Points)
input int                  InpAtrPeriod        = 14;                  // ATR Period (SL / TP / Trailing)
input double               InpSlAtrMult        = 1.5;                 // SL ATR Multiplier
input int                  InpSwingBufferPts   = 50;                  // Swing SL Buffer (Points)
input ENUM_TP_MODE         InpTpMode           = TP_RR;               // Take Profit Mode
input int                  InpTpPoints         = 600;                 // TP Fixed (Points)
input double               InpTpAtrMult        = 3.0;                 // TP ATR Multiplier
input double               InpTpRR             = 2.0;                 // TP Risk:Reward Ratio

input group "=== Break-Even & Trailing ==="
input bool                 InpUseBreakeven     = false;               // Use Break-Even
input int                  InpBeTriggerPts     = 300;                 // BE Trigger Profit (Points)
input int                  InpBeLockPts        = 20;                  // BE Lock-in (Points)
input bool                 InpUseTrailing      = false;               // Use Trailing Stop
input int                  InpTrailStartPts    = 400;                 // Trailing Start Profit (Points)
input bool                 InpTrailUseAtr      = false;               // Trailing Distance by ATR
input int                  InpTrailDistPts     = 300;                 // Trailing Distance (Points)
input double               InpTrailAtrMult     = 2.0;                 // Trailing Distance (ATR Mult)
input int                  InpTrailStepPts     = 20;                  // Trailing Step (Points)

input group "=== Trading Hours (Server Time) ==="
input bool                 InpUseTimeFilter    = false;               // Use Trading Hours
input int                  InpStartHour        = 7;                   // Start Hour (0-23)
input int                  InpEndHour          = 20;                  // End Hour (0-23, exclusive)

input group "=== Display & Notifications ==="
input bool                 InpShowIndicator    = true;                // Attach Indicator for Visuals (live / visual test)
input bool                 InpShowPanel        = true;                // Show Status Panel (Comment)
input bool                 InpAlertOnTrade     = false;               // Popup Alert on Trade
input bool                 InpPushOnTrade      = false;               // Push Notification on Trade

//+------------------------------------------------------------------+
//| Data Structures                                                  |
//+------------------------------------------------------------------+
struct WaeBarResult
{
   double trend;
   double absTrend;
   double explo;
   double dead;
   int    dir;
};

struct DevLevel
{
   double   price;
   double   top;
   double   bottom;
   bool     isRes;
   datetime t;
};

struct KalmanState
{
   double est;
   double vel;
   double err_cov;
   double vel_cov;
   double zlk;
   bool   initialized;

   void Reset()
   {
      est = 0.0; vel = 0.0; err_cov = 1.0; vel_cov = 1.0; zlk = 0.0; initialized = false;
   }

   double Update(const double src, const double src_prev, const double q, const double r,
                 const double zl_factor, const double vel_weight)
   {
      if(!initialized)
      {
         est = src; vel = 0.0; err_cov = 1.0; vel_cov = 1.0; zlk = src; initialized = true;
         return zlk;
      }
      double pred_est  = est + vel * vel_weight;
      double pred_cov  = err_cov + q;
      double price_chg = src - src_prev;
      double pred_vel  = vel * 0.95 + price_chg * 0.05;

      double k_gain    = pred_cov / (pred_cov + r);
      double innov     = src - pred_est;
      est              = pred_est + k_gain * innov;
      err_cov          = (1.0 - k_gain) * pred_cov;

      double vel_gain  = vel_cov / (vel_cov + r * 2.0);
      vel              = pred_vel + vel_gain * (price_chg - pred_vel);
      vel_cov          = (1.0 - vel_gain) * vel_cov + q * 0.5;

      double lag_err   = src - est;
      double zl_est    = est + lag_err * zl_factor * k_gain;
      zlk              = zlk * 0.8 + zl_est * 0.2;
      return zlk;
   }
};

//+------------------------------------------------------------------+
//| Globals                                                          |
//+------------------------------------------------------------------+
CTrade            g_trade;
ENUM_TIMEFRAMES   g_chartTf;
ENUM_TIMEFRAMES   g_htfTf;
int               g_atrHandle   = INVALID_HANDLE;
int               g_emaHandle   = INVALID_HANDLE;
int               g_stochHandle = INVALID_HANDLE;
int               g_visHandle   = INVALID_HANDLE;
int               g_visWindow   = -1;
string            g_visName     = "";
datetime          g_lastBarTime = 0;
double            g_atr         = 0.0;
int               g_maxLevels   = 6;

// Panel state
int               g_pChartDir = 0, g_pHtfDir = 0;
string            g_pLastSignal = "-";

// SMC state
KalmanState       g_km;
double            g_atrW = 0.0;
int               g_atrN = 0;
bool              g_wasExtUp = false, g_wasExtDn = false;
double            g_extHigh = EMPTY_VALUE, g_extLow = EMPTY_VALUE;
datetime          g_extHighT = 0, g_extLowT = 0;
double            g_lastSh = EMPTY_VALUE, g_lastSl = EMPTY_VALUE;
int               g_structTrend = 0;
double            g_pivotHigh = EMPTY_VALUE, g_pivotLow = EMPTY_VALUE;
datetime          g_bullBreakTime = 0, g_bearBreakTime = 0;
bool              g_bullBreakChoch = false, g_bearBreakChoch = false;
DevLevel          g_levels[];
datetime          g_smcLastTime = 0;
bool              g_smcReady = false;

//+------------------------------------------------------------------+
//| Helpers                                                          |
//+------------------------------------------------------------------+
string TfStr(ENUM_TIMEFRAMES tf) { return StringSubstr(EnumToString(tf), 7); }
string DirStr(int d)             { return (d > 0) ? "UP" : (d < 0 ? "DOWN" : "-"); }

void Notify(const string msg)
{
   string full = _Symbol + " " + TfStr((ENUM_TIMEFRAMES)_Period) + ": " + msg;
   Print(full);
   if(InpAlertOnTrade) Alert(full);
   if(InpPushOnTrade)  SendNotification(full);
}

//+------------------------------------------------------------------+
//| WAE direction from values (identical to indicator)               |
//+------------------------------------------------------------------+
int DirFromValues(const double trendVal, const double exploVal, const double deadVal, const bool isChartTf)
{
   switch(InpTrendMode)
   {
      case WAE_MODE_TREND_ONLY:
         return (trendVal > 0.0) ? 1 : (trendVal < 0.0 ? -1 : 0);

      case WAE_MODE_EXPLOSION_ONLY:
         if(trendVal > 0.0 && trendVal > exploVal) return 1;
         if(trendVal < 0.0 && MathAbs(trendVal) > exploVal) return -1;
         return 0;

      case WAE_MODE_EXPLOSION_DEAD:
         if(trendVal > 0.0 && trendVal > exploVal && trendVal > deadVal) return 1;
         if(trendVal < 0.0 && MathAbs(trendVal) > exploVal && MathAbs(trendVal) > deadVal) return -1;
         return 0;

      case WAE_MODE_CHART_EXP_HTF_DIR:
         if(isChartTf)
         {
            if(trendVal > 0.0 && trendVal > exploVal && trendVal > deadVal) return 1;
            if(trendVal < 0.0 && MathAbs(trendVal) > exploVal && MathAbs(trendVal) > deadVal) return -1;
            return 0;
         }
         return (trendVal > 0.0) ? 1 : (trendVal < 0.0 ? -1 : 0);
   }
   return 0;
}

//+------------------------------------------------------------------+
//| WAE value of timeframe 'tf' as it was at moment 'tEval' with the |
//| price 'priceAtT' (non-repainting snapshot of the forming bar).   |
//+------------------------------------------------------------------+
bool CalcWaeAt(const ENUM_TIMEFRAMES tf, const datetime tEval, const double priceAtT,
               const bool useClosedBar, const bool isChartTf, WaeBarResult &res)
{
   ZeroMemory(res);
   int minBars = MathMax(Fast_MA, Slow_MA) + BBPeriod + 10;

   int shift = iBarShift(_Symbol, tf, tEval, false);
   if(shift < 0) return false;

   MqlRates r[];
   ArraySetAsSeries(r, false);
   int n = CopyRates(_Symbol, tf, shift, InpWaeBars, r);
   if(n < minBars + 1) return false;

   double c[];
   ArrayResize(c, n);
   for(int k = 0; k < n; k++) c[k] = r[k].close;

   if(useClosedBar)
      n--;                    // previous (fully closed) bar of this timeframe
   else
      c[n - 1] = priceAtT;    // snapshot of the bar that contains tEval

   if(n < minBars) return false;

   double af = 2.0 / (Fast_MA + 1.0);
   double as = 2.0 / (Slow_MA + 1.0);
   double ef = c[0], es = c[0];
   double macdPrev = 0.0;
   for(int i = 1; i < n; i++)
   {
      ef = af * c[i] + (1.0 - af) * ef;
      es = as * c[i] + (1.0 - as) * es;
      if(i == n - 2) macdPrev = ef - es;
   }
   double macd = ef - es;

   int last  = n - 1;
   int cnt   = (last >= BBPeriod - 1) ? BBPeriod : (last + 1);
   int start = last - cnt + 1;
   double sum = 0.0;
   for(int j = start; j <= last; j++) sum += c[j];
   double sma = sum / cnt;
   double sq = 0.0;
   for(int j = start; j <= last; j++) { double d = c[j] - sma; sq += d * d; }
   double stdDev = MathSqrt(sq / cnt);

   res.explo    = 2.0 * BBDeviation * stdDev;
   res.trend    = (macd - macdPrev) * (double)Sensetive;
   res.absTrend = MathAbs(res.trend);
   res.dead     = _Point * DeadZonePip;
   res.dir      = DirFromValues(res.trend, res.explo, res.dead, isChartTf);
   return true;
}

//+------------------------------------------------------------------+
//| SMC: BOS/CHoCH structure + S&R deviation zones (no drawing)      |
//+------------------------------------------------------------------+
void ResetSmc()
{
   g_km.Reset();
   g_atrW = 0.0; g_atrN = 0;
   g_wasExtUp = false; g_wasExtDn = false;
   g_extHigh = EMPTY_VALUE; g_extLow = EMPTY_VALUE;
   g_extHighT = 0; g_extLowT = 0;
   g_lastSh = EMPTY_VALUE; g_lastSl = EMPTY_VALUE;
   g_structTrend = 0;
   g_pivotHigh = EMPTY_VALUE; g_pivotLow = EMPTY_VALUE;
   g_bullBreakTime = 0; g_bearBreakTime = 0;
   g_bullBreakChoch = false; g_bearBreakChoch = false;
   ArrayResize(g_levels, 0);
   g_smcLastTime = 0;
   g_smcReady = false;
}

void AddLevel(const double price, const bool isRes, const datetime t, const double atrv)
{
   if(ArraySize(g_levels) >= g_maxLevels)
   {
      int sz = ArraySize(g_levels);
      for(int m = 0; m < sz - 1; m++) g_levels[m] = g_levels[m + 1];
      ArrayResize(g_levels, sz - 1);
   }
   float half_w = (float)(atrv * level_width);
   int n = ArraySize(g_levels);
   ArrayResize(g_levels, n + 1);
   g_levels[n].price  = price;
   g_levels[n].top    = price + half_w;
   g_levels[n].bottom = price - half_w;
   g_levels[n].isRes  = isRes;
   g_levels[n].t      = t;
}

void ProcessSmcBar(const MqlRates &r[], const int b)
{
   // 1. Wilder ATR(14)
   double tr;
   if(b == 0) tr = r[0].high - r[0].low;
   else
   {
      double hl = r[b].high - r[b].low;
      double hc = MathAbs(r[b].high - r[b - 1].close);
      double lc = MathAbs(r[b].low  - r[b - 1].close);
      tr = MathMax(hl, MathMax(hc, lc));
   }
   if(g_atrN == 0)      g_atrW = tr;
   else if(g_atrN < 14) g_atrW = (g_atrW * g_atrN + tr) / (g_atrN + 1.0);
   else                 g_atrW = (g_atrW * 13.0 + tr) / 14.0;
   g_atrN++;
   double atrv = (g_atrW > 0.0) ? g_atrW : _Point * 10;

   // 2. Pivots & BOS / CHoCH
   int L = bos_swing_len;
   int p = b - L;
   if(p - L >= 0)
   {
      bool is_ph = true;
      for(int k = 1; k <= L; k++)
         if(r[p].high <= r[p - k].high || r[p].high < r[p + k].high) { is_ph = false; break; }
      if(is_ph) { g_lastSh = r[p].high; g_pivotHigh = r[p].high; }

      bool is_pl = true;
      for(int k = 1; k <= L; k++)
         if(r[p].low >= r[p - k].low || r[p].low > r[p + k].low) { is_pl = false; break; }
      if(is_pl) { g_lastSl = r[p].low; g_pivotLow = r[p].low; }
   }

   bool bull_break = (g_lastSh != EMPTY_VALUE) && (b > 0) && (r[b].close > g_lastSh) && (r[b - 1].close <= g_lastSh);
   bool bear_break = (g_lastSl != EMPTY_VALUE) && (b > 0) && (r[b].close < g_lastSl) && (r[b - 1].close >= g_lastSl);

   if(bull_break)
   {
      g_bullBreakChoch = (g_structTrend == -1);
      g_bullBreakTime  = r[b].time;
      g_structTrend    = 1;
      g_lastSh         = EMPTY_VALUE;
   }
   if(bear_break)
   {
      g_bearBreakChoch = (g_structTrend == 1);
      g_bearBreakTime  = r[b].time;
      g_structTrend    = -1;
      g_lastSl         = EMPTY_VALUE;
   }

   // 3. Kalman zero-lag filter & deviation zones
   double src  = r[b].close;
   double prev = (b > 0) ? r[b - 1].close : src;
   double k1   = g_km.Update(src, prev, process_noise, measurement_noise, zero_lag_factor, velocity_weight);

   double deviation      = r[b].close - k1;
   bool is_extended_up   = (deviation >  atrv * deviation_thresh);
   bool is_extended_down = (deviation < -atrv * deviation_thresh);

   if(is_extended_up)
   {
      g_wasExtUp = true;
      if(g_extHigh == EMPTY_VALUE || r[b].high > g_extHigh) { g_extHigh = r[b].high; g_extHighT = r[b].time; }
   }
   if(is_extended_down)
   {
      g_wasExtDn = true;
      if(g_extLow == EMPTY_VALUE || r[b].low < g_extLow) { g_extLow = r[b].low; g_extLowT = r[b].time; }
   }

   bool snapHigh = g_wasExtUp && !is_extended_up   && (deviation <  atrv * deviation_thresh * 0.5);
   bool snapLow  = g_wasExtDn && !is_extended_down && (deviation > -atrv * deviation_thresh * 0.5);

   if(snapHigh && g_extHigh != EMPTY_VALUE)
   {
      AddLevel(g_extHigh, true, (g_extHighT > 0 ? g_extHighT : r[b].time), atrv);
      g_wasExtUp = false; g_extHigh = EMPTY_VALUE; g_extHighT = 0;
   }
   if(snapLow && g_extLow != EMPTY_VALUE)
   {
      AddLevel(g_extLow, false, (g_extLowT > 0 ? g_extLowT : r[b].time), atrv);
      g_wasExtDn = false; g_extLow = EMPTY_VALUE; g_extLowT = 0;
   }

   for(int idx = ArraySize(g_levels) - 1; idx >= 0; idx--)
   {
      bool broken = g_levels[idx].isRes ? (r[b].close > g_levels[idx].top)
                                        : (r[b].close < g_levels[idx].bottom);
      if(broken)
      {
         int sz = ArraySize(g_levels);
         for(int m = idx; m < sz - 1; m++) g_levels[m] = g_levels[m + 1];
         ArrayResize(g_levels, sz - 1);
      }
   }
}

bool InitSmc()
{
   ResetSmc();
   MqlRates r[];
   ArraySetAsSeries(r, false);
   int want = MathMax(InpSmcWarmupBars, 2 * bos_swing_len + 50);
   int avail = Bars(_Symbol, _Period) - 1;
   if(avail < 2 * bos_swing_len + 5) return false;
   int n = CopyRates(_Symbol, _Period, 1, MathMin(want, avail), r);
   if(n < 2 * bos_swing_len + 5) return false;

   for(int b = 0; b < n; b++) ProcessSmcBar(r, b);
   g_smcLastTime = r[n - 1].time;
   g_smcReady = true;
   return true;
}

void UpdateSmc()
{
   if(!g_smcReady) { InitSmc(); return; }

   int shiftLast = iBarShift(_Symbol, _Period, g_smcLastTime, true);
   if(shiftLast < 0) { InitSmc(); return; }      // history changed - rebuild
   int newCount = shiftLast - 1;                 // closed bars not yet processed
   if(newCount <= 0) return;

   int ctx   = 2 * bos_swing_len + 1;
   int total = newCount + ctx;
   MqlRates r[];
   ArraySetAsSeries(r, false);
   int n = CopyRates(_Symbol, _Period, 1, total, r);
   if(n < total) { InitSmc(); return; }

   for(int b = n - newCount; b < n; b++) ProcessSmcBar(r, b);
   g_smcLastTime = r[n - 1].time;
}

//+------------------------------------------------------------------+
//| Position helpers                                                 |
//+------------------------------------------------------------------+
bool IsOurPosition(const ulong ticket)
{
   if(!PositionSelectByTicket(ticket)) return false;
   return (PositionGetString(POSITION_SYMBOL) == _Symbol &&
           (ulong)PositionGetInteger(POSITION_MAGIC) == InpMagic);
}

int CountPositions(const int type) // type: POSITION_TYPE_BUY / SELL, or -1 for any
{
   int cnt = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong t = PositionGetTicket(i);
      if(t == 0 || !IsOurPosition(t)) continue;
      if(type < 0 || PositionGetInteger(POSITION_TYPE) == type) cnt++;
   }
   return cnt;
}

void ClosePositions(const int type, const string reason)
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong t = PositionGetTicket(i);
      if(t == 0 || !IsOurPosition(t)) continue;
      if(PositionGetInteger(POSITION_TYPE) != type) continue;
      if(g_trade.PositionClose(t, InpSlippagePts))
         Notify(StringFormat("Closed %s #%I64u (%s)", (type == POSITION_TYPE_BUY ? "BUY" : "SELL"), t, reason));
      else
         Print("Close failed #", t, " retcode=", g_trade.ResultRetcode(), " ", g_trade.ResultRetcodeDescription());
   }
}

double MinStopDist()
{
   long stops  = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   long freeze = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);
   return (double)MathMax(stops, freeze) * _Point;
}

double NormalizeLots(double lots)
{
   double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   if(step <= 0.0) step = 0.01;
   lots = MathFloor(lots / step + 1e-9) * step;
   if(lots < vmin) lots = vmin;
   if(lots > vmax) lots = vmax;
   int digits = 0;
   double s = step;
   while(s < 1.0 - 1e-9 && digits < 8) { s *= 10.0; digits++; }
   return NormalizeDouble(lots, digits);
}

double CalcLots(const ENUM_ORDER_TYPE type, const double price, const double sl)
{
   double lots = InpLots;
   if(InpLotMode == LOT_RISK)
   {
      if(sl <= 0.0)
         Print("Risk lot mode needs a stop loss - using fixed lots.");
      else
      {
         double riskMoney = AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPct / 100.0;
         double pl = 0.0;
         if(OrderCalcProfit(type, _Symbol, 1.0, price, sl, pl) && pl < 0.0)
            lots = riskMoney / (-pl);
      }
   }
   lots = NormalizeLots(lots);

   double margin = 0.0, freeM = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
   if(OrderCalcMargin(type, _Symbol, lots, price, margin) && margin > freeM && margin > 0.0)
   {
      double scaled = lots * freeM / margin * 0.95;
      if(scaled < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)) return 0.0;
      lots = NormalizeLots(scaled);
   }
   return lots;
}

bool TradingTimeOk()
{
   if(!InpUseTimeFilter) return true;
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(), dt);
   int h = dt.hour;
   if(InpStartHour == InpEndHour) return true;
   if(InpStartHour < InpEndHour) return (h >= InpStartHour && h < InpEndHour);
   return (h >= InpStartHour || h < InpEndHour); // overnight session
}

bool SpreadOk()
{
   if(InpMaxSpreadPts <= 0) return true;
   return (SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) <= InpMaxSpreadPts);
}

bool PassFilters(const int dir, const double c1, const double ema)
{
   if(InpUseEmaFilter)
   {
      if(dir > 0 && !(c1 > ema)) return false;
      if(dir < 0 && !(c1 < ema)) return false;
   }
   if(InpUseStructFilter && g_structTrend != dir) return false;
   if(InpUseZoneFilter)
   {
      double buf = InpZoneBufferAtr * g_atr;
      for(int i = 0; i < ArraySize(g_levels); i++)
      {
         if(dir > 0 && g_levels[i].isRes && c1 >= g_levels[i].bottom - buf && c1 <= g_levels[i].top)
            return false;
         if(dir < 0 && !g_levels[i].isRes && c1 <= g_levels[i].top + buf && c1 >= g_levels[i].bottom)
            return false;
      }
   }
   return true;
}

//+------------------------------------------------------------------+
//| Open a trade                                                     |
//+------------------------------------------------------------------+
void OpenTrade(const int dir, const string reason)
{
   MqlTick tk;
   if(!SymbolInfoTick(_Symbol, tk)) return;
   double price  = (dir > 0) ? tk.ask : tk.bid;
   double spread = tk.ask - tk.bid;
   double minD   = MinStopDist() + spread + _Point;

   // Stop loss distance
   double slDist = 0.0;
   switch(InpSlMode)
   {
      case SL_FIXED: slDist = InpSlPoints * _Point; break;
      case SL_ATR:   slDist = g_atr * InpSlAtrMult; break;
      case SL_SWING:
         if(dir > 0 && g_pivotLow != EMPTY_VALUE && g_pivotLow < price)
            slDist = price - (g_pivotLow - InpSwingBufferPts * _Point);
         else if(dir < 0 && g_pivotHigh != EMPTY_VALUE && g_pivotHigh > price)
            slDist = (g_pivotHigh + InpSwingBufferPts * _Point) - price;
         else
            slDist = g_atr * InpSlAtrMult;
         break;
      default: slDist = 0.0;
   }
   if(slDist > 0.0 && slDist < minD) slDist = minD;

   // Take profit distance
   double tpDist = 0.0;
   switch(InpTpMode)
   {
      case TP_FIXED: tpDist = InpTpPoints * _Point; break;
      case TP_ATR:   tpDist = g_atr * InpTpAtrMult; break;
      case TP_RR:    tpDist = (slDist > 0.0) ? slDist * InpTpRR : 0.0; break;
      default:       tpDist = 0.0;
   }
   if(tpDist > 0.0 && tpDist < minD) tpDist = minD;

   double sl = 0.0, tp = 0.0;
   if(slDist > 0.0) sl = NormalizeDouble(dir > 0 ? price - slDist : price + slDist, _Digits);
   if(tpDist > 0.0) tp = NormalizeDouble(dir > 0 ? price + tpDist : price - tpDist, _Digits);

   ENUM_ORDER_TYPE type = (dir > 0) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   double lots = CalcLots(type, price, sl);
   if(lots <= 0.0) { Print("Not enough margin to open a trade."); return; }

   bool ok = (dir > 0) ? g_trade.Buy(lots, _Symbol, price, sl, tp, InpComment)
                       : g_trade.Sell(lots, _Symbol, price, sl, tp, InpComment);
   if(ok && (g_trade.ResultRetcode() == TRADE_RETCODE_DONE || g_trade.ResultRetcode() == TRADE_RETCODE_PLACED))
      Notify(StringFormat("Opened %s %.2f @ %s SL=%s TP=%s (%s)", (dir > 0 ? "BUY" : "SELL"), lots,
                          DoubleToString(g_trade.ResultPrice(), _Digits), DoubleToString(sl, _Digits),
                          DoubleToString(tp, _Digits), reason));
   else
      Print("Open failed retcode=", g_trade.ResultRetcode(), " ", g_trade.ResultRetcodeDescription());
}

//+------------------------------------------------------------------+
//| Break-even & trailing stop (every tick)                          |
//+------------------------------------------------------------------+
void ManageOpenPositions()
{
   if(!InpUseBreakeven && !InpUseTrailing) return;
   MqlTick tk;
   if(!SymbolInfoTick(_Symbol, tk)) return;
   double minD = MinStopDist();
   double trailDist = (InpTrailUseAtr && g_atr > 0.0) ? g_atr * InpTrailAtrMult : InpTrailDistPts * _Point;
   double step = InpTrailStepPts * _Point;

   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong t = PositionGetTicket(i);
      if(t == 0 || !IsOurPosition(t)) continue;

      long   type = PositionGetInteger(POSITION_TYPE);
      double open = PositionGetDouble(POSITION_PRICE_OPEN);
      double sl   = PositionGetDouble(POSITION_SL);
      double tp   = PositionGetDouble(POSITION_TP);
      double newSl = sl;

      if(type == POSITION_TYPE_BUY)
      {
         double profit = tk.bid - open;
         if(InpUseBreakeven && profit >= InpBeTriggerPts * _Point)
         {
            double be = open + InpBeLockPts * _Point;
            if(newSl < be) newSl = be;
         }
         if(InpUseTrailing && profit >= InpTrailStartPts * _Point)
         {
            double tsl = tk.bid - trailDist;
            if(newSl == 0.0 || tsl >= newSl + step) newSl = tsl;
         }
         newSl = NormalizeDouble(newSl, _Digits);
         if(newSl > sl + _Point * 0.5 && tk.bid - newSl > minD)
            if(!g_trade.PositionModify(t, newSl, tp))
               Print("Modify failed #", t, " retcode=", g_trade.ResultRetcode());
      }
      else if(type == POSITION_TYPE_SELL)
      {
         double profit = open - tk.ask;
         if(InpUseBreakeven && profit >= InpBeTriggerPts * _Point)
         {
            double be = open - InpBeLockPts * _Point;
            if(newSl == 0.0 || newSl > be) newSl = be;
         }
         if(InpUseTrailing && profit >= InpTrailStartPts * _Point)
         {
            double tsl = tk.ask + trailDist;
            if(newSl == 0.0 || tsl <= newSl - step) newSl = tsl;
         }
         newSl = NormalizeDouble(newSl, _Digits);
         if(newSl > 0.0 && (sl == 0.0 || newSl < sl - _Point * 0.5) && newSl - tk.ask > minD)
            if(!g_trade.PositionModify(t, newSl, tp))
               Print("Modify failed #", t, " retcode=", g_trade.ResultRetcode());
      }
   }
}

//+------------------------------------------------------------------+
//| Status panel                                                     |
//+------------------------------------------------------------------+
void UpdatePanel()
{
   if(!InpShowPanel) return;
   int nRes = 0, nSup = 0;
   for(int i = 0; i < ArraySize(g_levels); i++) { if(g_levels[i].isRes) nRes++; else nSup++; }
   string agree = (g_pChartDir != 0 && g_pChartDir == g_pHtfDir) ? DirStr(g_pChartDir) : "NO";
   string s = "2TF Waddah Attar Explosion (SMC) EA   [magic " + (string)InpMagic + "]\n";
   s += "Chart TF " + TfStr(g_chartTf) + ": " + DirStr(g_pChartDir) +
        "   |   MTF " + TfStr(g_htfTf) + ": " + DirStr(g_pHtfDir) +
        "   |   Agreement: " + agree + "\n";
   s += "Structure: " + (g_structTrend > 0 ? "BULLISH" : (g_structTrend < 0 ? "BEARISH" : "-")) +
        "   |   Zones: " + (string)nRes + " R / " + (string)nSup + " S" +
        "   |   EMA(" + (string)InpEmaPeriod + "): " + (InpUseEmaFilter ? "ACTIVE" : "OFF") +
        "   |   ATR: " + DoubleToString(g_atr, _Digits) + "\n";
   s += "Positions: " + (string)CountPositions(POSITION_TYPE_BUY) + " buy / " +
        (string)CountPositions(POSITION_TYPE_SELL) + " sell   |   Last signal: " + g_pLastSignal;
   Comment(s);
}

//+------------------------------------------------------------------+
//| Evaluate the last closed bar. Returns false if data not ready.   |
//+------------------------------------------------------------------+
bool EvaluateBar()
{
   int ps = PeriodSeconds(_Period);
   datetime t1 = iTime(_Symbol, _Period, 1);
   datetime t2 = iTime(_Symbol, _Period, 2);
   double   c1 = iClose(_Symbol, _Period, 1);
   double   c2 = iClose(_Symbol, _Period, 2);
   if(t1 == 0 || t2 == 0 || c1 == 0.0 || c2 == 0.0) return false;

   // End-of-bar evaluation moments (last second of bar 1 / bar 2)
   datetime e1 = t1 + ps - 1;
   datetime e2 = t2 + ps - 1;
   if(e2 >= t1) e2 = t1 - 1;
   datetime t0 = iTime(_Symbol, _Period, 0);
   if(t0 > 0 && e1 >= t0) e1 = t0 - 1;

   WaeBarResult ch1, ht1, ch2, ht2;
   if(!CalcWaeAt(g_chartTf, e1, c1, false,              true,  ch1)) return false;
   if(!CalcWaeAt(g_htfTf,   e1, c1, InpHtfUseClosedBar, false, ht1)) return false;
   if(!CalcWaeAt(g_chartTf, e2, c2, false,              true,  ch2)) return false;
   if(!CalcWaeAt(g_htfTf,   e2, c2, InpHtfUseClosedBar, false, ht2)) return false;

   double buf[1];
   if(CopyBuffer(g_atrHandle, 0, 1, 1, buf) != 1) return false;
   g_atr = buf[0];
   double ema = 0.0;
   if(InpUseEmaFilter)
   {
      if(CopyBuffer(g_emaHandle, 0, 1, 1, buf) != 1) return false;
      ema = buf[0];
   }

   // Stochastic cross detection on bar 1 vs bar 2
   bool stochCrossDn = false; // %K crosses below %D
   bool stochCrossUp = false; // %K crosses above %D
   if(InpExitOnStoch && g_stochHandle != INVALID_HANDLE)
   {
      double mainK[2], sigD[2];
      // Copy last 2 closed bars (shift 1 and shift 2)
      if(CopyBuffer(g_stochHandle, 0, 1, 2, mainK) == 2 &&
         CopyBuffer(g_stochHandle, 1, 1, 2, sigD) == 2)
      {
         // In CopyBuffer without ArraySetAsSeries, index 0 is older (shift 2), index 1 is newer (shift 1)
         double k2 = mainK[0], k1 = mainK[1];
         double d2 = sigD[0],  d1 = sigD[1];

         if(k2 >= d2 && k1 < d1) stochCrossDn = true;
         if(k2 <= d2 && k1 > d1) stochCrossUp = true;
      }
   }

   g_pChartDir = ch1.dir;
   g_pHtfDir   = ht1.dir;

   bool agreeUp1 = (ch1.dir ==  1 && ht1.dir ==  1);
   bool agreeDn1 = (ch1.dir == -1 && ht1.dir == -1);
   bool agreeUp2 = (ch2.dir ==  1 && ht2.dir ==  1);
   bool agreeDn2 = (ch2.dir == -1 && ht2.dir == -1);
   bool bullBrk  = (g_bullBreakTime == t1);
   bool bearBrk  = (g_bearBreakTime == t1);

   bool buySig = false, sellSig = false;
   string why = "";
   switch(InpEntryMode)
   {
      case ENTRY_AGREE_FIRST:
         buySig  = agreeUp1 && !agreeUp2;
         sellSig = agreeDn1 && !agreeDn2;
         why = "2TF agreement start";
         break;
      case ENTRY_AGREE_ANY:
         buySig  = agreeUp1;
         sellSig = agreeDn1;
         why = "2TF agreement";
         break;
      case ENTRY_BOS_AGREE:
         buySig  = bullBrk && agreeUp1;
         sellSig = bearBrk && agreeDn1;
         why = "structure break + 2TF agreement";
         break;
      case ENTRY_BOS_HTF:
         buySig  = bullBrk && ht1.dir ==  1;
         sellSig = bearBrk && ht1.dir == -1;
         why = "structure break + MTF direction";
         break;
   }
   if(buySig && sellSig) { buySig = false; sellSig = false; }
   if(buySig)  g_pLastSignal = "BUY @ "  + TimeToString(t1);
   if(sellSig) g_pLastSignal = "SELL @ " + TimeToString(t1);

   // --- Exits
   if(CountPositions(POSITION_TYPE_BUY) > 0)
   {
      string r = "";
      if(InpCloseOnOpposite && sellSig)              r = "opposite signal";
      else if(InpExitOnStoch && stochCrossDn)        r = "Stoch cross down";
      else if(InpExitOnAgreeLoss && !agreeUp1)       r = "agreement lost";
      else if(InpExitOnStructBrk && bearBrk)         r = (g_bearBreakChoch ? "bearish CHoCH" : "bearish BOS");
      if(r != "") ClosePositions(POSITION_TYPE_BUY, r);
   }
   if(CountPositions(POSITION_TYPE_SELL) > 0)
   {
      string r = "";
      if(InpCloseOnOpposite && buySig)               r = "opposite signal";
      else if(InpExitOnStoch && stochCrossUp)        r = "Stoch cross up";
      else if(InpExitOnAgreeLoss && !agreeDn1)       r = "agreement lost";
      else if(InpExitOnStructBrk && bullBrk)         r = (g_bullBreakChoch ? "bullish CHoCH" : "bullish BOS");
      if(r != "") ClosePositions(POSITION_TYPE_SELL, r);
   }

   // --- Entries (one position at a time)
   if(CountPositions(-1) == 0 && TradingTimeOk() && SpreadOk())
   {
      if(buySig && InpAllowBuy && PassFilters(1, c1, ema))
         OpenTrade(1, why);
      else if(sellSig && InpAllowSell && PassFilters(-1, c1, ema))
         OpenTrade(-1, why);
   }
   return true;
}

//+------------------------------------------------------------------+
//| Visual indicator (original indicator with matching settings)     |
//+------------------------------------------------------------------+
void PInt (MqlParam &p[], long v)   { int n = ArraySize(p); ArrayResize(p, n + 1); p[n].type = TYPE_INT;    p[n].integer_value = v; }
void PBool(MqlParam &p[], bool v)   { int n = ArraySize(p); ArrayResize(p, n + 1); p[n].type = TYPE_BOOL;   p[n].integer_value = v ? 1 : 0; }
void PDbl (MqlParam &p[], double v) { int n = ArraySize(p); ArrayResize(p, n + 1); p[n].type = TYPE_DOUBLE; p[n].double_value = v; }
void PClr (MqlParam &p[], color v)  { int n = ArraySize(p); ArrayResize(p, n + 1); p[n].type = TYPE_COLOR;  p[n].integer_value = (long)v; }

void CreateVisualIndicator()
{
   if(!InpShowIndicator) return;
   bool tester = (bool)MQLInfoInteger(MQL_TESTER);
   if(tester && !MQLInfoInteger(MQL_VISUAL_MODE)) return;   // no visuals needed in fast/optimization runs

   MqlParam p[];
   ArrayResize(p, 1);
   p[0].type = TYPE_STRING;
   p[0].string_value = VIS_INDICATOR_NAME;

   // Main Settings
   PInt (p, InpChartTf);  PInt(p, InpHtfTf);  PBool(p, true);  PBool(p, true);  PBool(p, InpHtfUseClosedBar);
   // BOS / CHoCH
   PBool(p, true);  PInt(p, bos_swing_len);  PInt(p, 1);  PClr(p, clrLime);  PClr(p, clrRed);
   PBool(p, false); PBool(p, false);                                   // indicator alerts off
   // Filter Settings
   PDbl (p, process_noise);  PDbl(p, measurement_noise);  PDbl(p, zero_lag_factor);  PDbl(p, velocity_weight);
   // S&R Zones
   PBool(p, true);  PDbl(p, deviation_thresh);  PDbl(p, level_width);  PInt(p, g_maxLevels);  PInt(p, 50);
   PClr (p, C'216,254,216');  PClr(p, clrMistyRose);  PBool(p, false);
   // History
   PInt (p, 1000);
   // Color Fill
   PBool(p, true);  PInt(p, 128);  PClr(p, C'213,253,213');  PClr(p, clrMistyRose);  PInt(p, 0);  PInt(p, 1);
   PBool(p, false); PBool(p, false); PBool(p, true);
   // EMA
   PBool(p, true);  PInt(p, InpEmaPeriod);  PInt(p, InpEmaPrice);  PClr(p, clrGainsboro);  PInt(p, 2);
   PInt (p, STYLE_SOLID);  PInt(p, 500);  PBool(p, false);
   // WAE
   PInt (p, Fast_MA);  PInt(p, Slow_MA);  PInt(p, BBPeriod);  PDbl(p, BBDeviation);  PInt(p, Sensetive);  PInt(p, DeadZonePip);
   // Display & Colors
   PClr (p, clrLimeGreen);  PClr(p, clrRed);  PInt(p, 2);  PClr(p, clrAqua);  PClr(p, clrOrange);  PInt(p, 4);
   PInt (p, 0);  PDbl(p, 1.25);  PDbl(p, 1.0);  PClr(p, clrGoldenrod);  PInt(p, 2);  PClr(p, clrRed);  PInt(p, 1);
   PInt (p, STYLE_DASHDOTDOT);
   // Trend & Agreement
   PInt (p, InpTrendMode);  PBool(p, InpEntryMode != ENTRY_AGREE_ANY);

   g_visHandle = IndicatorCreate(_Symbol, _Period, IND_CUSTOM, ArraySize(p), p);
   if(g_visHandle == INVALID_HANDLE)
   {
      Print("Visual indicator '", VIS_INDICATOR_NAME, "' could not be loaded (error ", GetLastError(), "). Trading is unaffected.");
      return;
   }

   if(!tester)
   {
      int win = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
      if(ChartIndicatorAdd(0, win, g_visHandle))
      {
         g_visWindow = win;
         int cnt = ChartIndicatorsTotal(0, win);
         if(cnt > 0) g_visName = ChartIndicatorName(0, win, cnt - 1);
      }
   }
}

//+------------------------------------------------------------------+
//| Expert initialization                                            |
//+------------------------------------------------------------------+
int OnInit()
{
   if(Fast_MA <= 0 || Slow_MA <= 0 || BBPeriod <= 0 || bos_swing_len < 1 || InpAtrPeriod <= 0 || InpEmaPeriod <= 0)
   {
      Print("Invalid input parameters (periods must be > 0).");
      return INIT_PARAMETERS_INCORRECT;
   }
   if(InpWaeBars < MathMax(Fast_MA, Slow_MA) + BBPeriod + 20)
   {
      Print("InpWaeBars is too small for the selected WAE periods.");
      return INIT_PARAMETERS_INCORRECT;
   }

   g_chartTf   = (InpChartTf == PERIOD_CURRENT) ? (ENUM_TIMEFRAMES)_Period : InpChartTf;
   g_htfTf     = (InpHtfTf   == PERIOD_CURRENT) ? (ENUM_TIMEFRAMES)_Period : InpHtfTf;
   g_maxLevels = MathMax(1, MathMin(50, max_levels));

   g_trade.SetExpertMagicNumber(InpMagic);
   g_trade.SetDeviationInPoints(InpSlippagePts);
   g_trade.SetTypeFillingBySymbol(_Symbol);
   g_trade.SetMarginMode();

   g_atrHandle = iATR(_Symbol, _Period, InpAtrPeriod);
   g_emaHandle = iMA(_Symbol, _Period, InpEmaPeriod, 0, MODE_EMA, InpEmaPrice);
   if(InpExitOnStoch)
      g_stochHandle = iStochastic(_Symbol, _Period, InpStochK, InpStochD, InpStochSlowing, InpStochMethod, InpStochPrice);

   if(g_atrHandle == INVALID_HANDLE || g_emaHandle == INVALID_HANDLE || (InpExitOnStoch && g_stochHandle == INVALID_HANDLE))
   {
      Print("Failed to create indicator handles (ATR/EMA/Stoch).");
      return INIT_FAILED;
   }

   // Warm-up history for higher timeframe so data is ready on the first bar
   MqlRates tmp[];
   CopyRates(_Symbol, g_htfTf, 0, 10, tmp);
   CopyRates(_Symbol, g_chartTf, 0, 10, tmp);

   InitSmc();                      // retried on ticks if history isn't loaded yet
   CreateVisualIndicator();

   g_lastBarTime = 0;
   UpdatePanel();
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization                                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   if(g_visWindow >= 0 && g_visName != "")
      ChartIndicatorDelete(0, g_visWindow, g_visName);
   if(g_visHandle != INVALID_HANDLE)   IndicatorRelease(g_visHandle);
   if(g_atrHandle != INVALID_HANDLE)   IndicatorRelease(g_atrHandle);
   if(g_emaHandle != INVALID_HANDLE)   IndicatorRelease(g_emaHandle);
   if(g_stochHandle != INVALID_HANDLE) IndicatorRelease(g_stochHandle);
   g_visHandle = g_atrHandle = g_emaHandle = g_stochHandle = INVALID_HANDLE;
   g_visWindow = -1;
   g_visName   = "";
   Comment("");
}

//+------------------------------------------------------------------+
//| Expert tick                                                      |
//+------------------------------------------------------------------+
void OnTick()
{
   ManageOpenPositions();

   datetime t0 = iTime(_Symbol, _Period, 0);
   if(t0 == 0 || t0 == g_lastBarTime) return;

   if(!g_smcReady && !InitSmc()) return;
   UpdateSmc();

   if(!EvaluateBar()) return;     // data not ready yet - retry on next tick
   g_lastBarTime = t0;
   UpdatePanel();
}
//+------------------------------------------------------------------+
