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.
Historical test results
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, save it in the MQL5/Experts folder, and compile with F7.
Generate a custom XAUUSD grid EA
Describe the ATR inputs, alert rules, visual style, or confirmation filter you want. Pineify generates editable MQL5 source code that you can inspect and compile in MetaEditor.
Pine Script vs MQL5: Same Strategy, Different Platforms
| Aspect | Pine Script (TradingView) | MQL5 (MetaTrader 5) |
|---|---|---|
| Execution | Series evaluated on chart updates | Event handlers with explicit buffers |
| Deployment | Runs in TradingView with alerts | Runs in the MT5 terminal or on a VPS |
| Broker access | Via TradingView broker integration | Direct broker connectivity |
| Backtesting | Strategy Tester for strategy scripts | Strategy Tester for Expert Advisors |
| Code complexity | Simpler, functional syntax | C++-like, more powerful |
The calculation can be implemented on either platform, but the runtime model and buffer APIs differ. Read the Pine Script Supertrend reference before porting logic between them.
Frequently Asked Questions
Related MQL5 pages
Risk and testing note
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.