Code Library / Grid Trading
MQL5 Dynamic Grid Spacing
Grid trading with ATR-based dynamic spacing adapting to volatility.
Language: MQL5 · Category: Grid Trading · Tags: grid, ATR, dynamic, MQL5, volatility
Source code
#include <Trade/Trade.mqh>
CTrade trade;
double DynGridStep(int atrP,double mult) {
double a[]; int h=iATR(_Symbol,PERIOD_H1,atrP);
CopyBuffer(h,0,0,1,a); IndicatorRelease(h); return a[0]*mult;
}
void PlaceDynGrid(int levels,double lots) {
double step=DynGridStep(14,1.0), bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);
for(int i=1;i<=levels;i++) {
trade.BuyLimit(lots,NormalizeDouble(bid-step*i,_Digits),_Symbol);
trade.SellLimit(lots,NormalizeDouble(bid+step*i,_Digits),_Symbol);
}
}How to use this snippet
This is a building block, not a finished trading system. Paste it into your own MQL5 project, compile it, and test it on a demo account with your broker's real spreads before relying on it. If MetaEditor reports errors, the compilation error fixer can help.