Devil Trader AI Lite: Exclusive Gold Strategy for M30 & H1 Timeframes
Info The Devil Trader AI Lite: Exclusive Gold Strategy for M30 & H1 Timeframes is a Expert Advisor for MetaTrader 5 that devil trader ai lite
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).
Usage This tool is typically used for automated trading on major forex pairs and gold.
Platform This Expert Advisor works exclusively on MetaTrader 5 (both build 600+ and newer versions).
Setup Place the downloaded file in MQL5/Experts folder via File ? Open Data Folder in MetaTrader 5.
Download Source Code
</>
How to Install and Use Devil Trader AI Lite: Exclusive Gold Strategy for M30 & H1 Timeframes
1. Installation: Open the "File" menu, select "Open Data Folder," navigate to MQL/Experts, paste your file, and restart the terminal.
2. Activation: Drag the EA from the Navigator onto a chart, ensure "Allow live trading" is checked in the Common tab, and verify the AutoTrading button is green.
3. Optimization: Right-click your chart, choose "Expert List," click "Properties" to adjust inputs, and save your preferred setup as a set file for future use.
4. Maintenance: Regularly check the "Experts" tab in the terminal window to monitor trade logs and potential execution errors.
Frequently Asked Questions
Q: Why is my EA not opening trades? A: Check the "AutoTrading" button, ensure "Allow live trading" is enabled, and verify your broker allows automated trading on your account type.
Q: Can I run multiple EAs on one chart? A: No, each chart can only host one active EA; however, you can open multiple charts for different currency pairs to run several EAs.
Q: What does the "smiley face" icon mean? A: A smiley face in the top-right corner of the chart indicates the EA is successfully running; a frowny face means it is disabled.
What this tool does Devil Trader AI Lite
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.
Typical Use Case This Expert Advisor excels in automated trading and technical analysis on MetaTrader 5.
Compatible Platform & Setup This Expert Advisor works on MetaTrader 5 . Place the file in the MQL5/Experts folder and restart the terminal.
Description & Settings Related: Seven-Bar Pressure Flip (SBPF) Sell-Only Expert Advisor for MetaTrader 5 - another powerful expert for MetaTrader 5 traders.
Devil Trader AI Lite
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:
--------------------------------------------------
DEVIL_TRADER_AI_Lite.mq5
Copyright 2026, Devil Trader AI Lite
property
copyright
"Copyright 2026, Devil Trader AI Lite"
property
link
""
property
version
"6.70"
property
description
"DEVIL TRADER AI Lite - Trend Momentum Breakout Engine, Order Blocks & Glass HUD"
property
strict
include
include
include
CTrade trade;
CPositionInfo posInfo;
CSymbolInfo symInfo;
Inputs
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);
}
}
--------------------------------------------------Also recommended: Event Tracer: Understanding MetaTrader 5 Event Handling - similar expert with strong performance on MetaTrader 5.
You may also like: Risk Lot Calculator for MetaTrader 5 - excellent alternative for expert users on MetaTrader 5.
Source Code
#property copyright "RobotFX"
#property link "https://robotfx.org"
#property version "6.70"
#property description "This code is educational. Feel free to use, modify and upgrade as you wish. Visit ROBOTFX.ORG for professional trading tools"
#property strict
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
CTrade trade;
CPositionInfo posInfo;
.......
Discussion Board
⚠ Limitations & Risk Warning
This tool is provided for educational and testing purposes only .
Past performance does not guarantee future results.
Trading involves substantial risk of loss. Use on a demo account first .
Results may vary depending on market conditions, broker, and settings.
We recommend thorough backtesting and forward testing before using with real funds.