theres a problem with the initial pendings orders, if the buy pending order hits SL it will contiune to open buy trades until a buy trade hits take profit, once the first take profit is hit the EA will now reverse all trades going forward. the same must happen for the first opening pending sell order
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I understand the issue now. The problem is that the EA should only start reversing trades after the first pending order hits either SL or TP, but currently, it might keep opening trades in the same direction until a TP is hit. Here's the corrected version with proper initial pending order handling and reversal logic:
mql5
//+------------------------------------------------------------------+
//| CustomPriceGridEA.mq5 - Grid Trading EA with Proper Reversal Logic |
//+------------------------------------------------------------------+
#property copyright "Grid Trading EA with Reversal Logic"
#property version "5.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
// Grid Display Settings
input color InpGridColor = clrRed; // Grid Line Color
input int InpLineWidth = 1; // Grid Line Width (1-5)
input ENUM_LINE_STYLE InpLineStyle = STYLE_SOLID; // Grid Line Style
// Account Alert Settings
input bool InpEnableAlerts = true; // Enable Account Alerts
input double InpAlertPercent = 5.0; // Alert at % of Balance
input color InpAlertColor = clrYellow; // Alert Text Color
//─ GLOBAL VARIABLES ──────────────────────────────────────────────────
CTrade trade;
CPositionInfo position;
COrderInfo order;
double g_point;
ulong g_buyTicket = 0;
ulong g_sellTicket = 0;
bool g_initialized = false;
bool g_reversalMode = false; // Flag for reversal trading
ENUM_POSITION_TYPE g_lastPositionType = POSITION_TYPE_BUY; // Track last position type
// Grid line names prefix
string g_linePrefix = "GridEA_Line_";
// Structure to track last closed position
struct LastClosedPosition
{
ENUM_POSITION_TYPE type;
double closePrice;
double profit;
bool wasStopLoss;
bool wasTakeProfit;
datetime closeTime;
};
LastClosedPosition g_lastClosed;
datetime g_lastPositionCloseTime = 0;
ulong g_lastPositionTicket = 0;
// Account monitoring
double g_initialBalance = 0;
double g_currentBalance = 0;
bool g_alertTriggered = 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);
// Validate line width
int lineWidth = InpLineWidth;
if(lineWidth < 1) lineWidth = 1;
if(lineWidth > 5) lineWidth = 5;
// Draw grid lines
DrawGridLines();
// Initialize account balance
g_initialBalance = AccountInfoDouble(ACCOUNT_BALANCE);
// Place initial pending orders
PlaceInitialOrders();
g_initialized = true;
g_reversalMode = false; // Start in initial pending order mode
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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());
}
}
}
//+------------------------------------------------------------------+
//| Place reversal trade after SL/TP hit |
//+------------------------------------------------------------------+
void PlaceReversalTrade()
{
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Determine reverse direction based on last closed position
ENUM_POSITION_TYPE reverseType = (g_lastPositionType == POSITION_TYPE_BUY) ?
POSITION_TYPE_SELL : POSITION_TYPE_BUY;
if(reverseType == POSITION_TYPE_SELL)
{
double sl = currentBid + (InpStopLoss * g_point);
double tp = currentBid - (InpTakeProfit * g_point);
if(trade.Sell(InpLotSize, _Symbol, currentBid, sl, tp, InpComment + "_Reversal"))
{
Print("Reversal SELL opened after ", EnumToString(g_lastPositionType),
" ", g_lastClosed.wasStopLoss ? "Stop Loss" : "Take Profit", " hit");
g_lastPositionType = POSITION_TYPE_SELL;
}
else
{
Print("Failed to open reversal SELL. Error: ", GetLastError());
}
}
else // POSITION_TYPE_BUY
{
double sl = currentAsk - (InpStopLoss * g_point);
double tp = currentAsk + (InpTakeProfit * g_point);
if(trade.Buy(InpLotSize, _Symbol, currentAsk, sl, tp, InpComment + "_Reversal"))
{
Print("Reversal BUY opened after ", EnumToString(g_lastPositionType),
" ", g_lastClosed.wasStopLoss ? "Stop Loss" : "Take Profit", " hit");
g_lastPositionType = POSITION_TYPE_BUY;
}
else
{
Print("Failed to open reversal BUY. Error: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Check if position closed by SL or TP |
//+------------------------------------------------------------------+
void CheckForClosedPosition()
{
bool hasPosition = false;
ulong currentPositionTicket = 0;
// Check current positions
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(position.SelectByIndex(i))
{
if(position.Symbol() == _Symbol && position.Magic() == InpMagicNumber)
{
hasPosition = true;
currentPositionTicket = position.Ticket();
break;
}
}
}
// If we had a position and now we don't, check history
if(g_lastPositionTicket > 0 && !hasPosition)
{
if(HistorySelect(TimeCurrent() - 86400, TimeCurrent()))
{
int dealsTotal = HistoryDealsTotal();
for(int i = dealsTotal - 1; i >= 0; i--)
{
ulong dealTicket = HistoryDealGetTicket(i);
if(dealTicket > 0)
{
ulong positionId = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
if(positionId == g_lastPositionTicket)
{
ENUM_DEAL_ENTRY dealEntry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealTicket, DEAL_ENTRY);
if(dealEntry == DEAL_ENTRY_OUT)
{
double dealPrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
double dealProfit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
ENUM_DEAL_TYPE dealType = (ENUM_DEAL_TYPE)HistoryDealGetInteger(dealTicket, DEAL_TYPE);
// Determine original position type
ENUM_POSITION_TYPE posType = (dealType == DEAL_TYPE_BUY) ?
POSITION_TYPE_SELL : POSITION_TYPE_BUY;
// Check if it was SL or TP
bool wasStopLoss = (dealProfit < 0);
bool wasTakeProfit = (dealProfit > 0);
// Store last closed position info
g_lastClosed.type = posType;
g_lastClosed.closePrice = dealPrice;
g_lastClosed.profit = dealProfit;
g_lastClosed.wasStopLoss = wasStopLoss;
g_lastClosed.wasTakeProfit = wasTakeProfit;
g_lastClosed.closeTime = TimeCurrent();
// If this was one of the initial pending orders
if(!g_reversalMode)
{
// Enable reversal mode after first pending order closes
g_reversalMode = true;
Print("Reversal mode activated after first pending order closed");
}
// Place reversal trade if it was SL or TP
if(wasStopLoss || wasTakeProfit)
{
PlaceReversalTrade();
}
break;
}
}
}
}
}
g_lastPositionTicket = 0;
}
// Update tracked position
if(hasPosition)
{
g_lastPositionTicket = currentPositionTicket;
}
}
//+------------------------------------------------------------------+
//| Check order status and manage positions |
//+------------------------------------------------------------------+
void CheckOrderStatus()
{
int pendingCount = 0;
bool hasPosition = false;
// Count open positions with magic
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(position.SelectByIndex(i))
{
if(position.Symbol() == _Symbol && position.Magic() == InpMagicNumber)
{
hasPosition = true;
break;
}
}
}
// Count pending orders with magic
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(order.SelectByIndex(i))
{
if(order.Symbol() == _Symbol && order.Magic() == InpMagicNumber)
pendingCount++;
}
}
// If we're not in reversal mode yet
if(!g_reversalMode)
{
// OCO: Delete remaining pending orders when a position opens
if(hasPosition && pendingCount > 0)
{
DeleteAllPendingOrders();
}
// If no position and no pending orders, place new initial orders
if(!hasPosition && pendingCount == 0 && g_initialized)
{
PlaceInitialOrders();
}
}
else // In reversal mode
{
// In reversal mode, we don't place new pending orders
// Just monitor for position closures to trigger reversals
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check order status
CheckOrderStatus();
// Check for closed positions
CheckForClosedPosition();
// Check account balance alerts
CheckAccountAlerts();
}
//+------------------------------------------------------------------+
//| Trade transaction event |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
const MqlTradeRequest& request,
const MqlTradeResult& result)
{
if(trans.type == TRADE_TRANSACTION_DEAL_ADD && trans.symbol == _Symbol)
{
Sleep(100);
CheckOrderStatus();
}
}
Key Improvements:
Added g_reversalMode Flag:
Starts as false (initial pending order mode)
Set to true after the first pending order closes (either buy or sell)
Ensures we only start reversing after the first trade closes
Proper Initial Pending Order Handling:
Places both buy limit and sell limit orders initially
Uses OCO logic (when one triggers, the other is deleted)
After the first pending order closes, switches to reversal mode
Reversal Trading Logic:
After first pending order closes (either SL or TP), enters reversal mode
Each subsequent trade that closes will open a reverse trade
Maintains the same lot size and SL/TP settings for all trades
Position Type Tracking:
Uses g_lastPositionType to track the last position type
Initial mode: Places pending orders and uses OCO logic
Reversal mode: Only opens market orders in reverse direction after closures
This version properly handles the initial pending orders and only starts reversing after the first trade closes, then continues reversing for all subsequent trades. The EA will:
Place initial pending orders (buy limit and sell limit)
When one triggers and closes, enter reversal mode
From then on, every trade that closes will open a reverse trade
Maintain consistent lot size and SL/TP settings throughout