Gold Grid EA MT5: MQL5 Code, Risk Management & Backtest Results
A MQL5 grid trading Expert Advisor for XAUUSD (Gold) on MetaTrader 5 with configurable grid step, lot multiplier, maximum order cap, and automatic profit harvesting.
Backtest Performance
Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.
Strategy Logic
Entry Conditions
Place the first buy order at market price. Subsequently place additional buy orders every GridStep pips below the previous order. Lot size multiplies by LotMultiplier for each subsequent order. Maximum concurrent orders capped by MaxOrders parameter.
Exit Conditions
Close all grid orders when total floating profit reaches ProfitTarget in account currency. Individual orders do not have TP/SL — only the collective profit target triggers closure.
MQL5 Expert Advisor Code
//+------------------------------------------------------------------+
//| Gold Grid EA - XAUUSD |
//| Pineify.app — WARNING: Grid EAs carry significant risk |
//+------------------------------------------------------------------+
#property copyright "Pineify.app"
#property version "1.00"
input int MagicNumber = 345678;
input double InitialLots = 0.01;
input double LotMultiplier= 1.5;
input int GridStep = 150; // Grid spacing in points
input int MaxOrders = 8;
input double ProfitTarget = 50.0; // USD profit to close grid
int OnInit() { return INIT_SUCCEEDED; }
void OnDeinit(const int reason) {}
void OnTick() {
int openOrders = CountPositions(MagicNumber);
double floatingProfit = GetFloatingProfit(MagicNumber);
// Close all if profit target reached
if (openOrders > 0 && floatingProfit >= ProfitTarget) {
CloseAllPositions(MagicNumber);
return;
}
// Open initial order
if (openOrders == 0) {
OpenTrade(ORDER_TYPE_BUY, InitialLots, MagicNumber);
return;
}
// Add grid orders if price drops GridStep from lowest order
if (openOrders < MaxOrders) {
double lowestPrice = GetLowestOrderPrice(MagicNumber);
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if (lowestPrice - currentBid >= GridStep * _Point) {
double nextLots = InitialLots * MathPow(LotMultiplier, openOrders);
nextLots = NormalizeDouble(nextLots, 2);
OpenTrade(ORDER_TYPE_BUY, nextLots, MagicNumber);
}
}
}
double GetLowestOrderPrice(int magic) {
double lowest = DBL_MAX;
for (int i = PositionsTotal() - 1; i >= 0; i--) {
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) &&
(int)PositionGetInteger(POSITION_MAGIC) == magic) {
double price = PositionGetDouble(POSITION_PRICE_OPEN);
if (price < lowest) lowest = price;
}
}
return lowest;
}
double GetFloatingProfit(int magic) {
double total = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--) {
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) &&
(int)PositionGetInteger(POSITION_MAGIC) == magic)
total += PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP);
}
return total;
}
void CloseAllPositions(int magic) {
for (int i = PositionsTotal() - 1; i >= 0; i--) {
ulong ticket = PositionGetTicket(i);
if (!PositionSelectByTicket(ticket)) continue;
if ((int)PositionGetInteger(POSITION_MAGIC) != magic) continue;
MqlTradeRequest req = {}; MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL;
req.position = ticket;
req.symbol = _Symbol;
req.volume = PositionGetDouble(POSITION_VOLUME);
req.type = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
req.price = (req.type == ORDER_TYPE_SELL)
? SymbolInfoDouble(_Symbol, SYMBOL_BID)
: SymbolInfoDouble(_Symbol, SYMBOL_ASK);
req.type_filling = ORDER_FILLING_IOC;
OrderSend(req, res);
}
}
int CountPositions(int magic) {
int count = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--) {
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) &&
(int)PositionGetInteger(POSITION_MAGIC) == magic) count++;
}
return count;
}
void OpenTrade(ENUM_ORDER_TYPE type, double lots, int magic) {
MqlTradeRequest req = {}; MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL; req.symbol = _Symbol; req.volume = lots;
req.type = type;
req.price = (type == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
: SymbolInfoDouble(_Symbol, SYMBOL_BID);
req.magic = magic; req.comment = "Pineify Grid";
req.type_filling = ORDER_FILLING_IOC;
OrderSend(req, res);
}Copy this code into MetaEditor (F4 in MT5), save in the Experts folder, and compile with F7.
Generate a Custom XAUUSD Grid EA →
Pineify AI generates syntactically validated MQL5 Expert Advisors from plain English descriptions. Customize entry logic, risk management, and trading sessions — no coding required.
Pine Script vs MQL5: Same Strategy, Different Platforms
| Aspect | Pine Script (TradingView) | MQL5 (MetaTrader 5) |
|---|---|---|
| Execution | Bar-based, backtesting only | Tick-based, live trading |
| Deployment | TradingView alerts | Runs 24/5 on VPS/MT5 |
| Broker access | Via TradingView broker integration | Direct broker connectivity |
| Backtesting | Built-in, no data download needed | Strategy Tester, tick data required |
| Code complexity | Simpler, functional syntax | C++-like, more powerful |
Pineify supports both platforms. Prototype your strategy visually in TradingView Pine Script, then generate the equivalent MQL5 EA for live MT5 trading.