'06.mq5' 0 'SELECTBYPOS' - undeclared identifier 06.mq5 113 26 'MODE_TRADES' -…
- User
'06.mq5' 0 'SELECT_BY_POS' - undeclared identifier 06.mq5 113 26 'MODE_TRADES' - undeclared identifier 06.mq5 113 41 'OrderSelect' - wrong parameters count 06.mq5 113 11 built-in: bool OrderSelect(ulong) 06.mq5 113 11 'OrderDelete' - undeclared identifier 06.mq5 136 10 'ticketBuy' - some operator expected 06.mq5 136 22 'OrderDelete' - undeclared identifier 06.mq5 145 10 'ticketSell' - some operator expected 06.mq5 145 22 7 errors, 0 warnings 7 0
Assistant
You're absolutely right! I mixed up MQL4 and MQL5 syntax. In MQL5, the order handling functions are completely different. Here's the corrected code:
//+------------------------------------------------------------------+ //| PriceGridTrader_EA.mq5 | //| © ChatGPT – OpenAI | //+------------------------------------------------------------------+ #property copyright "OpenAI – ChatGPT" #property version "1.10" #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; // Loop through all pending orders for(int i=0; i<OrdersTotal(); i++) { ulong ticket = OrderGetTicket(i); if(ticket <= 0) 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 = ticket; } if(type == ORDER_TYPE_SELL_LIMIT) { sellLimExist = true; ticketSell = 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) { if(OrderSelect(ticketBuy)) { double op = OrderGetDouble(ORDER_PRICE_OPEN); if(MathAbs(op-buyPrice) > (_Point*0.1)) // different grid level { DeleteOrder(ticketBuy); buyLimExist = false; } } } if(sellLimExist) { if(OrderSelect(ticketSell)) { double op = OrderGetDouble(ORDER_PRICE_OPEN); if(MathAbs(op-sellPrice) > (_Point*0.1)) { DeleteOrder(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 MANAGEMENT FUNCTIONS // //--------------------------------------------------------------------// bool DeleteOrder(ulong ticket) { MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_REMOVE; request.order = ticket; if(!OrderSend(request, result)) { PrintFormat("OrderSend delete failed: %d", GetLastError()); return false; } if(result.retcode != TRADE_RETCODE_DONE) { PrintFormat("Delete order failed, retcode: %d", result.retcode); return false; } return true; } //--------------------------------------------------------------------// 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!=TRADE_RETCODE_DONE && res.retcode!=TRADE_RETCODE_PLACED) { PrintFormat("OrderSend() retcode=%d", res.retcode); return false; } return true; } //+------------------------------------------------------------------+Key changes made:
- OrderSelect() - In MQL5, it only takes one parameter (the ticket number)
- OrdersTotal() and OrderGetTicket() - Proper MQL5 way to loop through pending orders
- DeleteOrder() - Created a proper MQL5 function using
TRADE_ACTION_REMOVE - Return codes - Updated to use proper MQL5 trade return codes (
TRADE_RETCODE_DONE,TRADE_RETCODE_PLACED)
This should compile without errors now!
- User
When the EA active one of these two initial trades , the other must automatically be removed. As soon as the initial order is active, the EA will plot one sell limit at the recent upper price spacing and one buy limit at the recent lower price spacing with the same stop loss and take profit as the settings and inputs of the EA. whenever price active the next trade it must place a sell order at the most recent price spacing and buy order at the most recent lower price spacing. this must happen for every trade the EA take.
Assistant
Perfect! You want a grid trading system where:
- Start with 2 pending orders (buy limit below, sell limit above)
- When one executes, delete the other pending order
- Immediately place 2 new pending orders around the current price
- Repeat this cycle for every trade
Here's the updated EA:
//+------------------------------------------------------------------+ //| PriceGridTrader_EA.mq5 | //| © ChatGPT – OpenAI | //+------------------------------------------------------------------+ #property copyright "OpenAI – ChatGPT" #property version "2.00" #property description "Grid Trading EA: Places buy/sell limits, when one executes" #property description "it removes the other and places new orders around current price" //--------------------------------------------------------------------// // ===== 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) int lastKnownPositions = 0; // Track position count changes int lastKnownOrders = 0; // Track pending order count changes //--------------------------------------------------------------------// // OnInit() // //--------------------------------------------------------------------// int OnInit() { if(InpSpacing<=0 || InpNumLines<1) return(INIT_FAILED); stops_level = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL); // Initialize counters lastKnownPositions = CountPositions(); lastKnownOrders = CountPendingOrders(); DrawGrid(); return(INIT_SUCCEEDED); } //--------------------------------------------------------------------// // OnDeinit() // //--------------------------------------------------------------------// void OnDeinit(const int reason) { DeleteGrid(); } //--------------------------------------------------------------------// // OnTick() - Main trading logic // //--------------------------------------------------------------------// void OnTick() { int currentPositions = CountPositions(); int currentOrders = CountPendingOrders(); // Check if a new position was opened (trade executed) if(currentPositions > lastKnownPositions) { Print("New position detected! Managing orders..."); // Remove all pending orders RemoveAllPendingOrders(); // Place new orders around current price PlaceNewGridOrders(); lastKnownPositions = currentPositions; lastKnownOrders = CountPendingOrders(); } // If no positions exist, maintain the initial 2 pending orders else if(currentPositions == 0) { MaintainInitialPendingOrders(); } // If we have positions but missing orders, place new ones else if(currentPositions > 0 && currentOrders < 2) { PlaceNewGridOrders(); } lastKnownPositions = currentPositions; lastKnownOrders = currentOrders; } //====================================================================// // POSITION AND ORDER COUNTING // //====================================================================// int CountPositions() { int count = 0; for(int i = 0; i < PositionsTotal(); i++) { if(PositionGetTicket(i) > 0) { if(PositionGetInteger(POSITION_MAGIC) == InpMagic) count++; } } return count; } //--------------------------------------------------------------------// int CountPendingOrders() { int count = 0; for(int i = 0; i < OrdersTotal(); i++) { ulong ticket = OrderGetTicket(i); if(ticket > 0) { if(OrderGetInteger(ORDER_MAGIC) == InpMagic) count++; } } return count; } //====================================================================// // ORDER MANAGEMENT FUNCTIONS // //====================================================================// void MaintainInitialPendingOrders() { bool buyLimExist = false; bool sellLimExist = false; // Check existing orders for(int i = 0; i < OrdersTotal(); i++) { ulong ticket = OrderGetTicket(i); if(ticket <= 0) 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; if(type == ORDER_TYPE_SELL_LIMIT) sellLimExist = true; } double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); // Place missing orders if(!buyLimExist) { double buyPrice = NearestGridBelow(bid); PlaceLimit(ORDER_TYPE_BUY_LIMIT, buyPrice, InpLots, InpSLpoints, InpTPpoints); } if(!sellLimExist) { double sellPrice = NearestGridAbove(ask); PlaceLimit(ORDER_TYPE_SELL_LIMIT, sellPrice, InpLots, InpSLpoints, InpTPpoints); } } //--------------------------------------------------------------------// void PlaceNewGridOrders() { double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double buyPrice = NearestGridBelow(bid); double sellPrice = NearestGridAbove(ask); PlaceLimit(ORDER_TYPE_BUY_LIMIT, buyPrice, InpLots, InpSLpoints, InpTPpoints); PlaceLimit(ORDER_TYPE_SELL_LIMIT, sellPrice, InpLots, InpSLpoints, InpTPpoints); Print("Placed new grid orders: Buy at ", buyPrice, ", Sell at ", sellPrice); } //--------------------------------------------------------------------// void RemoveAllPendingOrders() { for(int i = OrdersTotal() - 1; i >= 0; i--) { ulong ticket = OrderGetTicket(i); if(ticket <= 0) continue; if(OrderGetInteger(ORDER_MAGIC) == InpMagic) { DeleteOrder(ticket); Print("Removed pending order: ", ticket); } } } //--------------------------------------------------------------------// bool DeleteOrder(ulong ticket) { MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_REMOVE; request.order = ticket; if(!OrderSend(request, result)) { PrintFormat("OrderSend delete failed: %d", GetLastError()); return false; } if(result.retcode != TRADE_RETCODE_DONE) { PrintFormat("Delete order failed, retcode: %d", result.retcode); return false; } return true; } //--------------------------------------------------------------------// 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; } 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 != TRADE_RETCODE_DONE && res.retcode != TRADE_RETCODE_PLACED) { PrintFormat("OrderSend() retcode=%d", res.retcode); return false; } return true; } //====================================================================// // PRICE CALCULATION HELPERS // //====================================================================// double NearestGridBelow(double priceCurrent) { double k = MathFloor((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; } //--------------------------------------------------------------------// 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; } //====================================================================// // 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); } //+------------------------------------------------------------------+Key Features of this Updated EA:
-
Initial State: Places 2 pending orders (buy limit below, sell limit above current price)
-
Trade Execution Detection: Monitors position count changes to detect when an order executes
-
Automatic Order Management: When a trade executes:
- Removes ALL remaining pending orders
- Places 2 new pending orders around the current price
-
Continuous Grid Trading: This cycle repeats for every trade, creating a continuous grid trading system
-
Position Tracking: Uses
CountPositions()andCountPendingOrders()to monitor account state
How it works:
- Start: 1 buy limit + 1 sell limit
- Price hits buy limit → Position opens → Remove sell limit → Place new buy limit below + new sell limit above
- Price hits new sell limit → New position opens → Remove buy limit → Place new orders around current price
- This continues indefinitely, building positions in the direction of price movement
The EA will continuously trade the grid, placing new orders after each execution!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.