Copy–paste into MetaEditor ➜ compile ➜ attach to a chart with Algo-Trading enabled.
mql5 Copy code
//+------------------------------------------------------------------+
//| PriceGridTrader_EA.mq5 |
//| © ChatGPT – OpenAI |
//+------------------------------------------------------------------+
#property copyright "OpenAI – ChatGPT"
#property version "1.10"
#property strict
#property description "Draws a static price grid AND keeps one BUY-LIMIT"
#property description "below the market and one SELL-LIMIT above the market"
#property description "at the nearest grid spacing. SL / TP definable."
//--------------------------------------------------------------------//
// ===== INPUTS ====================================================//
//--------------------------------------------------------------------//
input group "Grid Settings"
input double InpStartPrice = 1000; // Reference price for grid
input double InpSpacing = 25; // Distance between grid lines
input int InpNumLines = 10; // Lines above and below
input color InpLineColor = clrBlue; // Grid line colour
input int InpLineWidth = 2; // Grid line width
input group "Trading Settings"
input double InpLots = 0.10; // Order volume
input double InpSLpoints = 250; // Stop-Loss (points)
input double InpTPpoints = 500; // Take-Profit (points)
input ulong InpMagic = 20240619; // Magic number
//--------------------------------------------------------------------//
// CONSTANTS / GLOBALS //
//--------------------------------------------------------------------//
string PREFIX = "PGT_"; // Chart-object prefix
int stops_level; // Broker stop-level (points)
//--------------------------------------------------------------------//
// OnInit() //
//--------------------------------------------------------------------//
int OnInit()
{
// --- basic validation
if(InpSpacing<=0 || InpNumLines<1)
return(INIT_FAILED);
stops_level = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
DrawGrid(); // visual part
return(INIT_SUCCEEDED);
}
//--------------------------------------------------------------------//
// OnDeinit() //
//--------------------------------------------------------------------//
void OnDeinit(const int reason)
{
DeleteGrid();
}
//--------------------------------------------------------------------//
// OnTick() – keeps the two pending orders alive //
//--------------------------------------------------------------------//
void OnTick()
{
MaintainPendingOrders();
}
//====================================================================//
// VISUAL GRID FUNCTIONS //
//====================================================================//
void DrawGrid()
{
DeleteGrid();
double price = InpStartPrice - InpNumLines*InpSpacing;
int total = 2*InpNumLines+1;
for(int i=0;i<total;i++)
{
string ln = PREFIX+"L"+string(i);
string lbl = PREFIX+"LB"+string(i);
ObjectCreate(0,ln, OBJ_HLINE, 0, 0, price);
ObjectSetInteger(0,ln,OBJPROP_COLOR, InpLineColor);
ObjectSetInteger(0,ln,OBJPROP_WIDTH, InpLineWidth);
ObjectCreate(0,lbl,OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0,lbl,OBJPROP_CORNER , CORNER_RIGHT_UPPER);
ObjectSetInteger(0,lbl,OBJPROP_XDISTANCE , 10);
ObjectSetInteger(0,lbl,OBJPROP_YDISTANCE , 0);
ObjectSetInteger(0,lbl,OBJPROP_COLOR , InpLineColor);
ObjectSetString (0,lbl,OBJPROP_TEXT , DoubleToString(price,_Digits));
price += InpSpacing;
}
ChartRedraw();
}
//--------------------------------------------------------------------//
void DeleteGrid()
{
ObjectsDeleteAll(0, PREFIX);
}
//====================================================================//
// PENDING-ORDER MAINTENANCE //
//====================================================================//
void MaintainPendingOrders()
{
// Check if our Buy-Limit and Sell-Limit already exist
bool buyLimExist = false;
bool sellLimExist = false;
ulong ticketBuy = 0, ticketSell = 0;
for(int i=0;i<OrdersTotal();i++)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if(OrderGetInteger(ORDER_MAGIC)!=InpMagic) continue;
ENUM_ORDER_TYPE type = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE);
if(type==ORDER_TYPE_BUY_LIMIT)
{ buyLimExist = true; ticketBuy = OrderGetInteger(ORDER_TICKET); }
if(type==ORDER_TYPE_SELL_LIMIT)
{ sellLimExist = true; ticketSell = OrderGetInteger(ORDER_TICKET); }
}
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// --- Calculate grid prices
double buyPrice = NearestGridBelow(bid);
double sellPrice = NearestGridAbove(ask);
// --- Replace existing orders if price changed (after strong move)
if(buyLimExist)
{
double op= OrderGetDouble(ORDER_PRICE_OPEN);
if(MathAbs(op-buyPrice)>(_Point*0.1)) // different grid level
{
OrderDelete(ticketBuy);
buyLimExist=false;
}
}
if(sellLimExist)
{
double op= OrderGetDouble(ORDER_PRICE_OPEN);
if(MathAbs(op-sellPrice)>(_Point*0.1))
{
OrderDelete(ticketSell);
sellLimExist=false;
}
}
// --- Place orders if missing
if(!buyLimExist)
PlaceLimit(ORDER_TYPE_BUY_LIMIT , buyPrice , InpLots, InpSLpoints, InpTPpoints);
if(!sellLimExist)
PlaceLimit(ORDER_TYPE_SELL_LIMIT, sellPrice, InpLots, InpSLpoints, InpTPpoints);
}
//--------------------------------------------------------------------//
// PRICE-CALC HELPERS //
//--------------------------------------------------------------------//
double NearestGridBelow(double priceCurrent)
{
// k = floor((P - Start)/Spacing)
double k = MathFloor((priceCurrent - InpStartPrice)/InpSpacing);
double p = InpStartPrice + k*InpSpacing;
p = NormalizeDouble(p, _Digits);
// safety: ensure strictly below
if(p >= priceCurrent-(_Point*0.1))
p = NormalizeDouble(p-InpSpacing, _Digits);
return p;
}
//--------------------------------------------------------------------//
double NearestGridAbove(double priceCurrent)
{
double k = MathCeil((priceCurrent - InpStartPrice)/InpSpacing);
double p = InpStartPrice + k*InpSpacing;
p = NormalizeDouble(p, _Digits);
if(p <= priceCurrent+(_Point*0.1))
p = NormalizeDouble(p+InpSpacing, _Digits);
return p;
}
//--------------------------------------------------------------------//
// ORDER SENDER //
//--------------------------------------------------------------------//
bool PlaceLimit(ENUM_ORDER_TYPE orderType,
double price,
double lots,
double SLpoints,
double TPpoints)
{
double sl=0,tp=0;
double point = _Point;
if(orderType==ORDER_TYPE_BUY_LIMIT)
{
sl = (SLpoints>0)? price - SLpoints*point : 0;
tp = (TPpoints>0)? price + TPpoints*point : 0;
}
else if(orderType==ORDER_TYPE_SELL_LIMIT)
{
sl = (SLpoints>0)? price + SLpoints*point : 0;
tp = (TPpoints>0)? price - TPpoints*point : 0;
}
// Respect broker stop-level
if(SLpoints>0 && SLpoints<stops_level) Print("SL adjusted to broker stop-level.");
if(TPpoints>0 && TPpoints<stops_level) Print("TP adjusted to broker stop-level.");
MqlTradeRequest req;
MqlTradeResult res;
ZeroMemory(req); ZeroMemory(res);
req.action = TRADE_ACTION_PENDING;
req.symbol = _Symbol;
req.type = orderType;
req.volume = lots;
req.price = price;
req.sl = sl;
req.tp = tp;
req.deviation = 10;
req.magic = InpMagic;
req.comment = "GridEA";
if(!OrderSend(req,res))
{
PrintFormat("OrderSend() failed: %d", GetLastError());
return false;
}
if(res.retcode!=10009 && res.retcode!=10008) // accepted codes
{
PrintFormat("OrderSend() retcode=%d", res.retcode);
return false;
}
return true;
}
//+------------------------------------------------------------------+
Feel free to tweak lot-size, SL/TP, spacing, etc.
Happy trading! 🚀