Watch how to download trading robots for free
Find us on Telegram!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Experts

Devil Trader AI Lite -Gold M30 and H1 Exclusive - expert for MetaTrader 5

Aakash Sour
Aakash Sour
Hello! I am Aakash Sour, an Independent Algorithmic Trader and MQL5 Developer based in Sagar (Bundelkhand), Madhya Pradesh, India.
Views:
79
Rating:
(1)
Published:
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

Devil Trader AI Lite — Institutional Gold Structure & Liquidity EA (M30 & H1 Exclusive)


IMPORTANT COMPATIBILITY NOTICE:
This Expert Advisor is engineered and calibrated strictly for GOLD (XAUUSD / GOLD) on the M30 (30-Minute) and H1 (1-Hour) timeframes ONLY. It is not intended for forex currency pairs, indices, cryptocurrencies, or lower timeframes (such as M1, M5, or M15). Please attach it exclusively to an XAUUSD / GOLD M30 or H1 chart for intended performance.

1. Strategy Overview & Philosophy
Gold (XAUUSD) exhibits unique intraday liquidity sweeps and strong institutional reactions at major higher-timeframe swing levels, while lower timeframes often suffer from spread spikes and false breakouts. Devil Trader AI Lite solves this by focusing strictly on M30 and H1 market structure—filtering out low-timeframe noise and waiting for confirmed institutional order block rejections before executing any trade.

2. Core Architecture & How It Works
- Exclusive GOLD (M30 & H1) Environment Lock: Built-in symbol and timeframe verification ensures the robot runs exclusively on Gold symbols across M30 and H1 charts, preventing accidental deployment on unsupported instruments or noisy timeframes.
- Deep Historical Order Block Mapping: Continuously scans historical swing highs and lows to identify fresh Major Demand (Buy) and Major Supply (Sell) zones, drawing them clearly on the chart for complete visual transparency.
- Confirmed Rejection Execution: Rather than placing blind limit orders, the EA monitors price interaction inside active Major Order Blocks and triggers entries only after a closed confirmation candle rejects the zone.
- Dynamic ATR Stop-Loss & Auto-Lot Sizing: Automatically computes lot size based on your defined risk percentage per trade, places a volatility-adjusted Stop Loss beyond the Order Block boundary, and targets structured Risk-to-Reward ratios.
- Capital Protection & Trailing Management: Operates strictly with one active trade at a time, fixed Stop Loss and Take Profit on every order, optional ATR-based Trailing Stop, and zero Martingale or grid averaging.

3. Recommended Setup & Inputs
- Symbol: XAUUSD / GOLD ONLY
- Timeframes: M30 or H1 ONLY
- Minimum Recommended Balance: $200+ (Standard, ECN, or Prop Firm Demo/Live accounts)
- Default Risk Per Trade: 1.0% (fully customizable in input parameters)
- Execution Mode: Run continuously on a stable terminal or VPS during active market sessions.

Disclaimer: Trading Gold involves substantial market risk. Always test the Expert Advisor on a demo account first to familiarize yourself with its M30 and H1 behavior before trading live capital.


⚠️ CRITICAL RISK & DEMO TESTING WARNING — READ BEFORE USE ⚠️


DO NOT deploy this Expert Advisor directly onto a Real / Live trading account without thorough testing first!


1. Mandatory Demo Testing First: You MUST test Devil Trader AI Lite on a Demo account (on GOLD / XAUUSD M30 and H1 timeframes only) for at least 2–4 weeks to fully understand its entry logic, trade frequency, drawdown behavior, and lot sizing under your specific broker's spread and execution conditions.

2. Broker & Market Conditions Vary: Historical backtest results do not guarantee future live profits. Slippage, spread widening during high-impact news, and different broker feed settings can significantly affect live execution.

3. Trade At Your Own Risk: Never risk money you cannot afford to lose. Always start with conservative risk settings (0.5% to 1.0% per trade) and verify proper behavior on a Demo terminal before considering any live capital.


4. Strategy Tester Backtest Report (GOLD — M30 / H1):

Below is the historical Strategy Tester backtest report demonstrating the EA's trade execution, risk-to-reward profile, and equity curve behavior on Gold. Please note that backtest performance reflects historical market conditions and should be used strictly for analytical reference before running your own demo tests:

BACKTEST

//+------------------------------------------------------------------+
//|                                        DEVIL_TRADER_AI_Lite.mq5 |
//|                             Copyright 2026, Devil Trader AI Lite |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Devil Trader AI Lite"
#property link      "https://www.mql5.com"
#property version   "6.70"
#property description "DEVIL TRADER AI Lite - Trend Momentum Breakout Engine, Order Blocks & Glass HUD"
#property strict

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>

CTrade         trade;
CPositionInfo  posInfo;
CSymbolInfo    symInfo;

//--- Inputs
input group "=== DEVIL TRADER AI LITE : TREND MOMENTUM ENGINE ==="
input double   InpGoldLotSize       = 0.05;          // Gold / Metals Lot Size (XAUUSD / GOLD)
input double   InpForexLotSize      = 0.25;          // Currency Pairs Lot Size (EURUSD, GBPJPY, GBPUSD etc.)
input int      InpAccumulationBars  = 12;            // Consolidation Range Lookback (Bars)
input int      InpFastTrendPeriod   = 50;            // Fast Trend EMA Period
input int      InpSlowTrendPeriod   = 200;           // Major Trend EMA Period
input int      InpCooldownBars      = 6;             // Cooldown Bars Between Trades
input double   InpSniperSL_ATR      = 1.8;           // Tight Safe Stop Loss (x ATR)
input double   InpRR_Multiplier     = 2.4;           // Target Ratio (2.4x of Actual SL Distance)
input ulong    InpMagicNumber       = 202699;        // Magic Number

input group "=== SMART PROFIT BOOKING & STEP-LOCK (NORMAL + BIG TP) ==="
input bool     InpUseEarlyBook      = true;          // Enable Early Profit Booking
input double   InpNormalBookPct     = 0.65;          // Normal TP Book % (0.65 = 65% of TP)
input double   InpBigTPBookPct      = 0.45;          // Big TP Fast Book % (0.45 = 45% of Big TP)
input bool     InpUseZeroLoss       = true;          // Enable Early Profit Lock (At 25% of TP)
input double   InpZeroLossPct       = 0.25;          // Lock SL Above Entry at 25% of TP
input bool     InpUseTrailing       = true;          // Enable Reliable Runner Trailing
input double   InpTrailStartPct     = 0.30;          // Start Trailing at 30% of TP
input double   InpTrailDistATR      = 1.2;           // Safe Trailing Cushion (x ATR)

input group "=== ORDER BLOCK ZONES & GLASS HUD TERMINAL ==="
input color    InpSellZoneColor     = C'235,65,115'; // Bearish Order Block Color
input color    InpBuyZoneColor      = C'0,175,185';   // Bullish Order Block Color
input bool     InpShowHUD           = true;          // Show Transparent Glass Terminal

//--- Global Variables
string   Pfx           = "DEV_AMD_";
string   GlassRes      = "::DevilAMDGlass_Lite_V67";
int      hudX          = 15;
int      hudY          = 25;
int      hudW          = 230;
int      hudH          = 252;
bool     isDragging    = false;
bool     prevMouseDown = false;
int      dragStartX    = 0;
int      dragStartY    = 0;
datetime lastBarTime   = 0;
datetime lastShotBar   = 0;
datetime lastZoneBar   = 0;
string   amdPhaseText  = "TREND RANGE SCAN";

//+------------------------------------------------------------------+
//| Hidden Pure Math Volatility (ATR) & Exponential Moving Average   |
//+------------------------------------------------------------------+
double GetHiddenATR(int period, int shift)
{
   if(Bars(_Symbol, _Period) <= shift + period + 2) return 0.0;
   double sum = 0.0;
   for(int i = shift; i < shift + period; i++)
   {
      double h  = iHigh(_Symbol, _Period, i);
      double l  = iLow(_Symbol, _Period, i);
      double pc = iClose(_Symbol, _Period, i + 1);
      sum += MathMax(h - l, MathMax(MathAbs(h - pc), MathAbs(l - pc)));
   }
   return (period > 0) ? (sum / period) : 0.0;
}

double GetHiddenEMA(int period, int shift)
{
   int totalBars = Bars(_Symbol, _Period);
   int startIdx  = shift + period * 2;
   if(totalBars <= startIdx + 2 || period <= 0) return 0.0;

   double alpha = 2.0 / (period + 1.0);
   double ema   = iClose(_Symbol, _Period, startIdx);
   for(int i = startIdx - 1; i >= shift; i--)
   {
      double c = iClose(_Symbol, _Period, i);
      ema = (c * alpha) + (ema * (1.0 - alpha));
   }
   return ema;
}

//+------------------------------------------------------------------+
//| Glass Transparent Background                                     |
//+------------------------------------------------------------------+
void CreateSniperGlass(int w, int h, uchar alpha)
{
   if(MQLInfoInteger(MQL_OPTIMIZATION)) return;

   uint pixels[];
   ArrayResize(pixels, w * h);
   uint bgCol     = ((uint)alpha << 24) | (8 << 16) | (16 << 8) | 32;
   uint headerCol = ((uint)MathMin(255, alpha + 45) << 24) | (16 << 16) | (34 << 8) | 64;
   uint borderCol = ((uint)220 << 24) | (0 << 16) | (155 << 8) | 225;

   for(int y = 0; y < h; y++)
   {
      for(int x = 0; x < w; x++)
      {
         int idx = y * w + x;
         if(x == 0 || x == w - 1 || y == 0 || y == h - 1 || y == 20)
            pixels[idx] = borderCol;
         else if(y < 20)
            pixels[idx] = headerCol;
         else
            pixels[idx] = bgCol;
      }
   }

   ResourceCreate(GlassRes, pixels, w, h, 0, 0, w, COLOR_FORMAT_ARGB_NORMALIZE);

   string objName = Pfx + "BG";
   if(ObjectFind(0, objName) < 0)
   {
      ObjectCreate(0, objName, OBJ_BITMAP_LABEL, 0, 0, 0);
      ObjectSetInteger(0, objName, OBJPROP_CORNER, CORNER_LEFT_UPPER);
      ObjectSetString(0, objName, OBJPROP_BMPFILE, GlassRes);
      ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, objName, OBJPROP_ZORDER, 0);
   }
   ObjectSetInteger(0, objName, OBJPROP_XDISTANCE, hudX);
   ObjectSetInteger(0, objName, OBJPROP_YDISTANCE, hudY);
}

//+------------------------------------------------------------------+
//| Initialization & Deinitialization                                |
//+------------------------------------------------------------------+
int OnInit()
{
   if(!symInfo.Name(_Symbol)) return(INIT_FAILED);
   TesterHideIndicators(true);

   trade.SetExpertMagicNumber(InpMagicNumber);
   trade.SetDeviationInPoints(30);
   trade.SetTypeFillingBySymbol(_Symbol);

   CreateSniperGlass(hudW, hudH, 130);
   ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0, Pfx);
   ResourceFree(GlassRes);
   ChartRedraw(0);
}

//+------------------------------------------------------------------+
//| Select Gold Lot vs Currency Pair Lot & Validate Broker Limits    |
//+------------------------------------------------------------------+
double GetPairLotSize()
{
   string sym = _Symbol;
   StringToUpper(sym);
   if(StringFind(sym, "XAU") >= 0 || StringFind(sym, "GOLD") >= 0 || StringFind(sym, "XAG") >= 0 || StringFind(sym, "SILVER") >= 0)
      return InpGoldLotSize;
   return InpForexLotSize;
}

double GetValidatedLot(ENUM_ORDER_TYPE orderType, double price, double reqLot)
{
   double minL  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxL  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double stepL = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   if(stepL <= 0.0) stepL = 0.01;

   double lots = MathFloor(reqLot / stepL) * stepL;
   lots = MathMax(minL, MathMin(maxL, lots));

   double maxLimit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT);
   if(maxLimit > 0.0 && lots > maxLimit)
      lots = MathFloor(maxLimit / stepL) * stepL;

   double marginReq = 0.0;
   double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
   if(OrderCalcMargin(orderType, _Symbol, lots, price, marginReq))
   {
      while(lots > minL && marginReq > freeMargin * 0.85)
      {
         lots = NormalizeDouble(lots - stepL, 2);
         if(!OrderCalcMargin(orderType, _Symbol, lots, price, marginReq)) break;
      }
      if(marginReq > freeMargin * 0.90) return 0.0;
   }

   return NormalizeDouble(lots, 2);
}

//+------------------------------------------------------------------+
//| Active Trades & Floating P/L                                     |
//+------------------------------------------------------------------+
int CountSniperTrades(double &pl)
{
   int cnt = 0;
   pl = 0.0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if(posInfo.SelectByIndex(i) && posInfo.Symbol() == _Symbol && posInfo.Magic() == InpMagicNumber)
      {
         cnt++;
         pl += posInfo.Profit() + posInfo.Swap();
      }
   }
   return cnt;
}

//+------------------------------------------------------------------+
//| Reliable Smart Profit Booking, Step-Lock & Trailing SL           |
//+------------------------------------------------------------------+
void ManageSniperPositions()
{
   if(!InpUseEarlyBook && !InpUseZeroLoss && !InpUseTrailing) return;

   double atr = GetHiddenATR(14, 1);
   if(atr <= 0.0) return;

   symInfo.RefreshRates();
   double ask = symInfo.Ask();
   double bid = symInfo.Bid();
   double pt  = symInfo.Point();
   int    dig = symInfo.Digits();
   if(ask <= 0.0 || bid <= 0.0 || pt <= 0.0) return;

   long stopLvl   = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   long freezeLvl = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);
   double minStop = (MathMax(stopLvl, freezeLvl) + 15) * pt;

   double standardTPDist = (atr * InpSniperSL_ATR) * InpRR_Multiplier;

   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if(!posInfo.SelectByIndex(i)) continue;
      if(posInfo.Symbol() != _Symbol || posInfo.Magic() != InpMagicNumber) continue;

      ulong  ticket = posInfo.Ticket();
      double openP  = posInfo.PriceOpen();
      double curSL  = posInfo.StopLoss();
      double curTP  = posInfo.TakeProfit();
      if(curTP == 0.0) continue;

      //--- BUY POSITION MANAGEMENT
      if(posInfo.PositionType() == POSITION_TYPE_BUY)
      {
         double totalTPDist = curTP - openP;
         double currentGain = bid - openP;
         if(totalTPDist <= 0.0) continue;

         bool isBigTP = (totalTPDist > standardTPDist * 1.15);
         double activeBookPct = isBigTP ? InpBigTPBookPct : InpNormalBookPct;

         // 0. Early Profit Booking
         if(InpUseEarlyBook && currentGain >= totalTPDist * activeBookPct)
         {
            if(trade.PositionClose(ticket))
            {
               lastShotBar = iTime(_Symbol, _Period, 0);
               continue;
            }
         }

         if((curTP - bid) <= minStop) continue;

         double targetSL = curSL;

         // 1. Step Profit Lock at 25% TP
         if(InpUseZeroLoss && currentGain >= totalTPDist * InpZeroLossPct)
         {
            double beSL = NormalizeDouble(openP + (atr * 0.25), dig);
            if((bid - beSL) >= minStop && (targetSL == 0.0 || beSL > targetSL))
               targetSL = beSL;
         }

         // 2. Continuous ATR Trailing Stop after 30% TP
         if(InpUseTrailing && currentGain >= totalTPDist * InpTrailStartPct)
         {
            double trailSL = NormalizeDouble(bid - (atr * InpTrailDistATR), dig);
            if((bid - trailSL) >= minStop && (targetSL == 0.0 || trailSL > targetSL))
               targetSL = trailSL;
         }

         double minStep = (curSL < openP || curSL == 0.0) ? (pt * 5.0) : (atr * 0.15);
         if(targetSL > 0.0 && (curSL == 0.0 || (targetSL - curSL) >= minStep) && (bid - targetSL) >= minStop)
         {
            trade.PositionModify(ticket, NormalizeDouble(targetSL, dig), curTP);
         }
      }
      //--- SELL POSITION MANAGEMENT
      else if(posInfo.PositionType() == POSITION_TYPE_SELL)
      {
         double totalTPDist = openP - curTP;
         double currentGain = openP - ask;
         if(totalTPDist <= 0.0) continue;

         bool isBigTP = (totalTPDist > standardTPDist * 1.15);
         double activeBookPct = isBigTP ? InpBigTPBookPct : InpNormalBookPct;

         // 0. Early Profit Booking
         if(InpUseEarlyBook && currentGain >= totalTPDist * activeBookPct)
         {
            if(trade.PositionClose(ticket))
            {
               lastShotBar = iTime(_Symbol, _Period, 0);
               continue;
            }
         }

         if((ask - curTP) <= minStop) continue;

         double targetSL = curSL;

         // 1. Step Profit Lock at 25% TP
         if(InpUseZeroLoss && currentGain >= totalTPDist * InpZeroLossPct)
         {
            double beSL = NormalizeDouble(openP - (atr * 0.25), dig);
            if((beSL - ask) >= minStop && (targetSL == 0.0 || beSL < targetSL))
               targetSL = beSL;
         }

         // 2. Continuous ATR Trailing Stop after 30% TP
         if(InpUseTrailing && currentGain >= totalTPDist * InpTrailStartPct)
         {
            double trailSL = NormalizeDouble(ask + (atr * InpTrailDistATR), dig);
            if((trailSL - ask) >= minStop && (targetSL == 0.0 || trailSL < targetSL))
               targetSL = trailSL;
         }

         double minStep = (curSL > openP || curSL == 0.0) ? (pt * 5.0) : (atr * 0.15);
         if(targetSL > 0.0 && (curSL == 0.0 || (curSL - targetSL) >= minStep) && (targetSL - ask) >= minStop)
         {
            trade.PositionModify(ticket, NormalizeDouble(targetSL, dig), curTP);
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Clean Small Order Block (No Text Labels) & Glass HUD             |
//+------------------------------------------------------------------+
void DrawOrderBlock(string name, datetime t1, double p1, datetime t2, double p2, color col)
{
   if(MQLInfoInteger(MQL_OPTIMIZATION)) return;
   if(ObjectFind(0, name) < 0)
   {
      ObjectCreate(0, name, OBJ_RECTANGLE, 0, t1, p1, t2, p2);
      ObjectSetInteger(0, name, OBJPROP_COLOR, col);
      ObjectSetInteger(0, name, OBJPROP_BGCOLOR, col);
      ObjectSetInteger(0, name, OBJPROP_FILL, true);
      ObjectSetInteger(0, name, OBJPROP_BACK, true);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   }
   else
   {
      ObjectMove(0, name, 0, t1, p1);
      ObjectMove(0, name, 1, t2, p2);
   }
}

void SetHUD(string key, int xOff, int yOff, string txt, color col, int sz=8, bool bold=false)
{
   string name = Pfx + "H_" + key;
   if(ObjectFind(0, name) < 0)
   {
      ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
      ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_ZORDER, 1);
   }
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, hudX + xOff);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, hudY + yOff);
   ObjectSetString(0, name, OBJPROP_TEXT, txt);
   ObjectSetInteger(0, name, OBJPROP_COLOR, col);
   ObjectSetString(0, name, OBJPROP_FONT, bold ? "Segoe UI Bold" : "Segoe UI");
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, sz);
}

void RenderSniperHUD(int openCnt, double pl)
{
   if(!InpShowHUD || MQLInfoInteger(MQL_OPTIMIZATION)) return;

   if(ObjectFind(0, Pfx + "BG") < 0) CreateSniperGlass(hudW, hudH, 130);
   else
   {
      ObjectSetInteger(0, Pfx + "BG", OBJPROP_XDISTANCE, hudX);
      ObjectSetInteger(0, Pfx + "BG", OBJPROP_YDISTANCE, hudY);
   }

   MqlDateTime dt;
   TimeToStruct(TimeCurrent(), dt);
   int h = dt.hour;

   SetHUD("TTL", 8, 3, "DEVIL TRADER AI LITE [DRAG]", clrGold, 8, true);
   SetHUD("TIM", 8, 24, StringFormat("Server Time: %02d:%02d:%02d", dt.hour, dt.min, dt.sec), clrWhite, 7);

   SetHUD("S1", 8, 42, "Sydney Session:", clrWhite, 7);
   SetHUD("S1V", 138, 42, (h >= 21 || h < 6) ? "● LIVE" : "● CLOSED", (h >= 21 || h < 6) ? clrLime : clrSilver, 7, true);
   SetHUD("S2", 8, 57, "Asian Session:", clrWhite, 7);
   SetHUD("S2V", 138, 57, (h >= 0 && h < 9) ? "● LIVE" : "● CLOSED", (h >= 0 && h < 9) ? clrLime : clrSilver, 7, true);
   SetHUD("S3", 8, 72, "London Session:", clrWhite, 7);
   SetHUD("S3V", 138, 72, (h >= 7 && h < 16) ? "● LIVE" : "● CLOSED", (h >= 7 && h < 16) ? clrLime : clrSilver, 7, true);
   SetHUD("S4", 8, 87, "New York Session:", clrWhite, 7);
   SetHUD("S4V", 138, 87, (h >= 12 && h < 21) ? "● LIVE" : "● CLOSED", (h >= 12 && h < 21) ? clrLime : clrSilver, 7, true);

   double bal = AccountInfoDouble(ACCOUNT_BALANCE);
   double eqt = AccountInfoDouble(ACCOUNT_EQUITY);
   string cur = AccountInfoString(ACCOUNT_CURRENCY);

   SetHUD("AH", 8, 110, "ACCOUNT & WHALE P/L", clrGold, 7, true);
   SetHUD("AB", 8, 126, StringFormat("Balance:  %.2f %s", bal, cur), clrWhite, 8);
   SetHUD("AE", 8, 142, StringFormat("Equity:   %.2f %s", eqt, cur), clrWhite, 8);
   SetHUD("AP", 8, 160, StringFormat("Live P/L: %+.2f %s", pl, cur), (pl > 0) ? clrSpringGreen : ((pl < 0) ? clrCrimson : clrWhite), 9, true);

   SetHUD("TR", 8, 186, StringFormat("Active Trades: %d / 1 (Trend Engine)", openCnt), clrDeepSkyBlue, 7);
   SetHUD("ST", 8, 202, "Phase: " + amdPhaseText, clrGold, 7, true);
   SetHUD("PR", 8, 218, "SMART TP & TRAIL: ACTIVE", clrSpringGreen, 7, true);
}

//+------------------------------------------------------------------+
//| Mouse Dragging                                                   |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   if(!InpShowHUD || MQLInfoInteger(MQL_OPTIMIZATION)) return;
   if(id == CHARTEVENT_MOUSE_MOVE)
   {
      int mx = (int)lparam, my = (int)dparam;
      bool down = (((uint)StringToInteger(sparam) & 1) == 1);

      if(down && !prevMouseDown && mx >= hudX && mx <= hudX + hudW && my >= hudY && my <= hudY + hudH)
      {
         isDragging = true;
         dragStartX = mx - hudX;
         dragStartY = my - hudY;
         ChartSetInteger(0, CHART_MOUSE_SCROLL, false);
      }
      else if(!down && prevMouseDown && isDragging)
      {
         isDragging = false;
         ChartSetInteger(0, CHART_MOUSE_SCROLL, true);
      }

      if(isDragging && down)
      {
         hudX = MathMax(5, mx - dragStartX);
         hudY = MathMax(5, my - dragStartY);
         double pl = 0.0;
         int cnt = CountSniperTrades(pl);
         RenderSniperHUD(cnt, pl);
         ChartRedraw(0);
      }
      prevMouseDown = down;
   }
}

//+------------------------------------------------------------------+
//| Main Trend-Aligned Breakout & Pullback Execution Loop            |
//+------------------------------------------------------------------+
void OnTick()
{
   ManageSniperPositions();

   double floatingPL = 0.0;
   int openShots = CountSniperTrades(floatingPL);

   if(Bars(_Symbol, _Period) > InpSlowTrendPeriod * 2 + InpAccumulationBars + 5)
   {
      datetime bar0 = iTime(_Symbol, _Period, 0);

      // Evaluate entry signals strictly on completed bar close (Bar 1)
      if(bar0 != lastBarTime)
      {
         lastBarTime = bar0;

         double o1 = iOpen(_Symbol, _Period, 1),  c1 = iClose(_Symbol, _Period, 1);
         double h1 = iHigh(_Symbol, _Period, 1),  l1 = iLow(_Symbol, _Period, 1);
         double c2 = iClose(_Symbol, _Period, 2);

         // 1. ACCUMULATION / CONSOLIDATION BOX (Bars 2 to 2 + InpAccumulationBars)
         double boxHigh = 0.0, boxLow = DBL_MAX;
         for(int k = 2; k < 2 + InpAccumulationBars; k++)
         {
            boxHigh = MathMax(boxHigh, iHigh(_Symbol, _Period, k));
            boxLow  = MathMin(boxLow,  iLow(_Symbol, _Period, k));
         }
         double boxHeight = boxHigh - boxLow;

         double atr     = GetHiddenATR(14, 1);
         double fastEMA = GetHiddenEMA(InpFastTrendPeriod, 1);
         double slowEMA = GetHiddenEMA(InpSlowTrendPeriod, 1);

         symInfo.RefreshRates();
         double ask     = symInfo.Ask();
         double bid     = symInfo.Bid();
         double pt      = symInfo.Point();
         int    dig     = symInfo.Digits();
         double minStop = ((int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) + 20) * pt;

         double obHeight = (atr > 0.0) ? (atr * 0.25) : (pt * 25.0);
         datetime obEndT = bar0 + PeriodSeconds(_Period) * 10;

         bool readyToShoot = ((bar0 - lastShotBar) >= PeriodSeconds(_Period) * InpCooldownBars);
         bool readyToDraw  = ((bar0 - lastZoneBar) >= PeriodSeconds(_Period) * 4);

         double body1  = MathAbs(c1 - o1);
         double range1 = h1 - l1;

         // 2. HIGH-PROBABILITY BULLISH BREAKOUT (Aligned with Fast & Slow Trend)
         bool bullTrend = (c1 > fastEMA && fastEMA > slowEMA);
         bool bullBreak = (c1 > boxHigh && c2 <= boxHigh && c1 > o1 && body1 >= range1 * 0.45 && boxHeight <= atr * 4.5);

         if(bullTrend && bullBreak && atr > 0.0)
         {
            amdPhaseText = "BULLISH BREAKOUT";
            if(readyToDraw)
            {
               lastZoneBar = bar0;
               DrawOrderBlock(Pfx + "OB_B_" + IntegerToString((long)bar0), bar0, l1 + obHeight, obEndT, l1, InpBuyZoneColor);
            }

            if(openShots == 0 && readyToShoot && TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
            {
               double sl = NormalizeDouble(MathMax(ask - (atr * InpSniperSL_ATR), boxLow - (atr * 0.3)), dig);
               if((ask - sl) < minStop) sl = NormalizeDouble(ask - minStop, dig);

               double slDist = ask - sl;
               double tp = NormalizeDouble(ask + (slDist * InpRR_Multiplier), dig);
               if((tp - ask) < minStop) tp = NormalizeDouble(ask + minStop, dig);

               double lots = GetValidatedLot(ORDER_TYPE_BUY, ask, GetPairLotSize());
               if(lots > 0.0 && trade.Buy(lots, _Symbol, ask, sl, tp, "DEVIL TRADER AI Lite Buy"))
                  lastShotBar = bar0;
            }
         }

         // 3. HIGH-PROBABILITY BEARISH BREAKOUT (Aligned with Fast & Slow Trend)
         bool bearTrend = (c1 < fastEMA && fastEMA < slowEMA);
         bool bearBreak = (c1 < boxLow && c2 >= boxLow && c1 < o1 && body1 >= range1 * 0.45 && boxHeight <= atr * 4.5);

         if(bearTrend && bearBreak && atr > 0.0)
         {
            amdPhaseText = "BEARISH BREAKOUT";
            if(readyToDraw)
            {
               lastZoneBar = bar0;
               DrawOrderBlock(Pfx + "OB_S_" + IntegerToString((long)bar0), bar0, h1, obEndT, h1 - obHeight, InpSellZoneColor);
            }

            if(openShots == 0 && readyToShoot && TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
            {
               double sl = NormalizeDouble(MathMin(bid + (atr * InpSniperSL_ATR), boxHigh + (atr * 0.3)), dig);
               if((sl - bid) < minStop) sl = NormalizeDouble(bid + minStop, dig);

               double slDist = sl - bid;
               double tp = NormalizeDouble(bid - (slDist * InpRR_Multiplier), dig);
               if((bid - tp) < minStop) tp = NormalizeDouble(bid - minStop, dig);

               double lots = GetValidatedLot(ORDER_TYPE_SELL, bid, GetPairLotSize());
               if(lots > 0.0 && trade.Sell(lots, _Symbol, bid, sl, tp, "DEVIL TRADER AI Lite Sell"))
                  lastShotBar = bar0;
            }
         }
      }
   }

   if(!isDragging)
   {
      RenderSniperHUD(openShots, floatingPL);
      ChartRedraw(0);
   }
}
//+------------------------------------------------------------------+
Break-even and Trailing Stop Manager in R Break-even and Trailing Stop Manager in R

Break-even and trailing stop for open positions, measured in R (distance to the first stop loss). Respects stops level and freeze level, only moves the stop in profit direction.

Seven-Bar Pressure Flip (SBPF) is a sell-only Expert Advisor for MetaTrader 5 Seven-Bar Pressure Flip (SBPF) is a sell-only Expert Advisor for MetaTrader 5

Seven-Bar Pressure Flip (SBPF) is a sell-only Expert Advisor for MetaTrader 5, provided as a research example for XAUUSD on the M15 timeframe. It looks for a bearish reversal candle following positive average candle-body pressure and manages positions using ATR-based stops, a fixed reward-to-risk setting, and a bar-count exit.

Market Watch Mini Scanner: RSI Overbought/Oversold Across Symbols Market Watch Mini Scanner: RSI Overbought/Oversold Across Symbols

A compact on-chart scanner that shows the RSI of the Market Watch symbols (or of a custom list) in a sorted, color-coded dashboard, marks overbought and oversold symbols, and can send alerts when a symbol enters one of these zones.

Trade History Export to CSV with Summary (win rate, profit factor, drawdown) Trade History Export to CSV with Summary (win rate, profit factor, drawdown)

Exports the closed positions of the account to a CSV file (one row per position) and shows a summary: trades, win rate, profit factor, net result, max drawdown and results per symbol. Read-only.