//+------------------------------------------------------------------+ // CustomPriceGridEA.mq5 // Grid Tradi…
- User
//+------------------------------------------------------------------+ //| CustomPriceGridEA.mq5 | //| Grid Trading EA with OCO Logic | //| Converted from Custom Price Red Line Indicator | //+------------------------------------------------------------------+ #property copyright "Grid Trading EA" #property version "1.00" #property strict
#include <Trade\Trade.mqh> #include <Trade\PositionInfo.mqh> #include <Trade\OrderInfo.mqh>
//─ INPUTS ──────────────────────────────────────────────────────────── input double InpStartPrice = 1000.0; // Starting Price input double InpSpacing = 25.0; // Price Spacing input int InpNumLines = 10; // Number of Lines (up & down) input double InpLotSize = 0.01; // Lot Size input int InpTakeProfit = 100; // Take Profit (points) input int InpStopLoss = 50; // Stop Loss (points) input int InpMagicNumber = 12345; // Magic Number input string InpComment = "GridEA"; // Order Comment
//─ GLOBAL VARIABLES ────────────────────────────────────────────────── CTrade trade; CPositionInfo position; COrderInfo order;
double g_point; ulong g_buyTicket = 0; ulong g_sellTicket = 0; bool g_initialized = false;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { // Setup trade parameters trade.SetExpertMagicNumber(InpMagicNumber); trade.SetDeviationInPoints(10); trade.SetTypeFilling(ORDER_FILLING_FOK);
// Get point value g_point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Place initial orders PlaceInitialOrders();
g_initialized = true;
return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Clean up any pending orders on removal DeleteAllPendingOrders(); }
//+------------------------------------------------------------------+ //| Find nearest grid levels above and below current price | //+------------------------------------------------------------------+ void GetNearestLevels(double &nearestAbove, double &nearestBelow) { double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double startLevel = InpStartPrice - (InpNumLines * InpSpacing);
nearestAbove = 0; nearestBelow = 0;
// Find all levels and identify nearest above/below for(int i = 0; i <= (2 * InpNumLines); i++) { double level = startLevel + (i * InpSpacing);
if(level > currentPrice) { if(nearestAbove == 0 || level < nearestAbove) nearestAbove = level; } else if(level < currentPrice) { if(nearestBelow == 0 || level > nearestBelow) nearestBelow = level; }} }
//+------------------------------------------------------------------+ //| Place initial buy and sell limit orders | //+------------------------------------------------------------------+ void PlaceInitialOrders() { double nearestAbove, nearestBelow; GetNearestLevels(nearestAbove, nearestBelow);
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Delete any existing pending orders first DeleteAllPendingOrders();
// Place SELL LIMIT at nearest level above (if valid) if(nearestAbove > 0 && nearestAbove > currentAsk) { double sl = nearestAbove + (InpStopLoss * g_point); double tp = nearestAbove - (InpTakeProfit * g_point);
if(trade.SellLimit(InpLotSize, nearestAbove, _Symbol, sl, tp, ORDER_TIME_GTC, 0, InpComment)) { g_sellTicket = trade.ResultOrder(); Print("SELL LIMIT placed at ", nearestAbove, " Ticket: ", g_sellTicket); } else { Print("Failed to place SELL LIMIT. Error: ", GetLastError()); }}
// Place BUY LIMIT at nearest level below (if valid) if(nearestBelow > 0 && nearestBelow < currentBid) { double sl = nearestBelow - (InpStopLoss * g_point); double tp = nearestBelow + (InpTakeProfit * g_point);
if(trade.BuyLimit(InpLotSize, nearestBelow, _Symbol, sl, tp, ORDER_TIME_GTC, 0, InpComment)) { g_buyTicket = trade.ResultOrder(); Print("BUY LIMIT placed at ", nearestBelow, " Ticket: ", g_buyTicket); } else { Print("Failed to place BUY LIMIT. Error: ", GetLastError()); }} }
//+------------------------------------------------------------------+ //| Delete all pending orders with our magic number | //+------------------------------------------------------------------+ void DeleteAllPendingOrders() { for(int i = OrdersTotal() - 1; i >= 0; i--) { if(order.SelectByIndex(i)) { if(order.Symbol() == _Symbol && order.Magic() == InpMagicNumber) { trade.OrderDelete(order.Ticket()); } } } }
//+------------------------------------------------------------------+ //| Check if a pending order was triggered | //+------------------------------------------------------------------+ void CheckOrderStatus() { bool buyExists = false; bool sellExists = false; bool hasPosition = false;
// Check if we have any open positions for(int i = PositionsTotal() - 1; i >= 0; i--) { if(position.SelectByIndex(i)) { if(position.Symbol() == _Symbol && position.Magic() == InpMagicNumber) { hasPosition = true; break; } } }
// Check pending orders for(int i = OrdersTotal() - 1; i >= 0; i--) { if(order.SelectByIndex(i)) { if(order.Symbol() == _Symbol && order.Magic() == InpMagicNumber) { if(order.Ticket() == g_buyTicket) buyExists = true; if(order.Ticket() == g_sellTicket) sellExists = true; } } }
// If one order triggered (we have position but one order missing) if(hasPosition && (!buyExists || !sellExists)) { // Delete the remaining pending order DeleteAllPendingOrders(); g_buyTicket = 0; g_sellTicket = 0; }
// If no position and no pending orders, place new ones if(!hasPosition && !buyExists && !sellExists && g_initialized) { PlaceInitialOrders(); } }
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Check order status on each tick CheckOrderStatus(); }
//+------------------------------------------------------------------+ //| Trade transaction event | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction& trans, const MqlTradeRequest& request, const MqlTradeResult& result) { // When a pending order becomes a position, delete the other if(trans.type == TRADE_TRANSACTION_DEAL_ADD) { if(trans.symbol == _Symbol) { // Give it a moment then check orders Sleep(100); CheckOrderStatus(); } } } //+------------------------------------------------------------------+
- Assistant
Your code is a solid start for a grid trading EA with OCO (One Cancels Other) logic in MQL5. Here are some important notes, improvements, and bug fixes to make it more robust and reliable:
1. Bug:
GetNearestLevelsLogic- The function does not always return the nearest levels above and below the current price, especially if the price is exactly on a grid line.
- Also, if the price is above the highest grid or below the lowest, both
nearestAboveandnearestBelowcan remain zero.
Improved version:
void GetNearestLevels(double &nearestAbove, double &nearestBelow) { double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double startLevel = InpStartPrice - (InpNumLines * InpSpacing); nearestAbove = DBL_MAX; nearestBelow = -DBL_MAX; for(int i = 0; i <= (2 * InpNumLines); i++) { double level = startLevel + (i * InpSpacing); if(level > currentPrice && level < nearestAbove) nearestAbove = level; if(level < currentPrice && level > nearestBelow) nearestBelow = level; } if(nearestAbove == DBL_MAX) nearestAbove = 0; if(nearestBelow == -DBL_MAX) nearestBelow = 0; }
2. Bug: Pending Order Placement
- You check
nearestAbove > currentAskandnearestBelow < currentBid. This can miss placing orders if the price is very close to the grid. - Suggestion: Use
>=and<=to ensure orders are always placed at the grid, even if price is exactly on the level.
3. Order Deletion
- You delete all pending orders in
DeleteAllPendingOrders()without checking order type. This is fine for this EA, but be aware if you add other order types in the future.
4. Order Ticket Handling
- You store only the last ticket for buy/sell. If multiple orders are placed (due to a bug or manual intervention), your logic may not handle it well.
- Suggestion: Always check all pending orders with your magic number and symbol.
5. OnTradeTransaction
- You use
Sleep(100);which is not recommended in MQL5 EAs. Instead, just callCheckOrderStatus()directly. The trade event is already after the transaction.
6. General Robustness
- Spread Check: Before placing limit orders, check that the grid level is not within the spread, or the order will be rejected.
- Lot Size Check: Ensure
InpLotSizeis not belowSymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN).
7. Magic Number and Symbol
- Always check both magic number and symbol when managing orders/positions.
8. Order Filling Type
ORDER_FILLING_FOKmay not be supported by all brokers. Consider making this an input or usingORDER_FILLING_IOCas fallback.
9. Code Clean-up
- Remove unused global variables if not needed.
10. Sample Improved
PlaceInitialOrdersvoid PlaceInitialOrders() { double nearestAbove, nearestBelow; GetNearestLevels(nearestAbove, nearestBelow); double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID); DeleteAllPendingOrders(); // SELL LIMIT if(nearestAbove > 0 && nearestAbove >= currentAsk + SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * g_point) { double sl = nearestAbove + (InpStopLoss * g_point); double tp = nearestAbove - (InpTakeProfit * g_point); if(trade.SellLimit(InpLotSize, nearestAbove, _Symbol, sl, tp, ORDER_TIME_GTC, 0, InpComment)) { g_sellTicket = trade.ResultOrder(); Print("SELL LIMIT placed at ", nearestAbove, " Ticket: ", g_sellTicket); } else { Print("Failed to place SELL LIMIT. Error: ", GetLastError()); } } // BUY LIMIT if(nearestBelow > 0 && nearestBelow <= currentBid - SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * g_point) { double sl = nearestBelow - (InpStopLoss * g_point); double tp = nearestBelow + (InpTakeProfit * g_point); if(trade.BuyLimit(InpLotSize, nearestBelow, _Symbol, sl, tp, ORDER_TIME_GTC, 0, InpComment)) { g_buyTicket = trade.ResultOrder(); Print("BUY LIMIT placed at ", nearestBelow, " Ticket: ", g_buyTicket); } else { Print("Failed to place BUY LIMIT. Error: ", GetLastError()); } } }
11. Final Note
- Test in Strategy Tester with visual mode and all error logs enabled.
- Add more logging for debugging, especially for order placement and deletion.
If you want a fully revised code with all these improvements, let me know!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.