Here's the updated EA with the requested features:
//+------------------------------------------------------------------+
//| CustomPriceGridEA.mq5 |
//| Grid Trading EA with OCO Logic |
//| Enhanced with Grid Display and Reversal Trading |
//+------------------------------------------------------------------+
#property copyright "Grid Trading EA Enhanced"
#property version "2.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
//─ GLOBAL VARIABLES ──────────────────────────────────────────────────
CTrade trade;
CPositionInfo position;
COrderInfo order;
double g_point;
ulong g_buyTicket = 0;
ulong g_sellTicket = 0;
bool g_initialized = false;
// 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;
//+------------------------------------------------------------------+
//| 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();
// 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();
// Remove all grid lines
RemoveGridLines();
}
//+------------------------------------------------------------------+
//| Draw grid lines on chart |
//+------------------------------------------------------------------+
void DrawGridLines()
{
// Remove existing lines first
RemoveGridLines();
double startLevel = InpStartPrice - (InpNumLines * InpSpacing);
// Draw all grid levels
for(int i = 0; i <= (2 * InpNumLines); i++)
{
double level = startLevel + (i * InpSpacing);
string lineName = g_linePrefix + IntegerToString(i);
// Create horizontal line
if(!ObjectCreate(0, lineName, OBJ_HLINE, 0, 0, level))
{
// If object exists, just move it
ObjectMove(0, lineName, 0, 0, level);
}
// Set line properties
ObjectSetInteger(0, lineName, OBJPROP_COLOR, InpGridColor);
ObjectSetInteger(0, lineName, OBJPROP_WIDTH, InpLineWidth);
ObjectSetInteger(0, lineName, OBJPROP_STYLE, InpLineStyle);
ObjectSetInteger(0, lineName, OBJPROP_BACK, true);
ObjectSetInteger(0, lineName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, lineName, OBJPROP_SELECTED, false);
ObjectSetInteger(0, lineName, OBJPROP_HIDDEN, true);
// Add tooltip showing the price level
ObjectSetString(0, lineName, OBJPROP_TOOLTIP,
"Grid Level: " + DoubleToString(level, _Digits));
}
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Remove all grid lines from chart |
//+------------------------------------------------------------------+
void RemoveGridLines()
{
// Remove all objects with our prefix
int total = ObjectsTotal(0);
for(int i = total - 1; i >= 0; i--)
{
string name = ObjectName(0, i);
if(StringFind(name, g_linePrefix) == 0)
{
ObjectDelete(0, name);
}
}
ChartRedraw();
}
//+------------------------------------------------------------------+
//| 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());
}
}
}
//+------------------------------------------------------------------+
//| Place reversal trade after SL/TP hit |
//+------------------------------------------------------------------+
void PlaceReversalTrade()
{
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// If last position was a BUY that hit SL/TP, open SELL
if(g_lastClosed.type == POSITION_TYPE_BUY)
{
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 BUY ",
g_lastClosed.wasStopLoss ? "Stop Loss" : "Take Profit", " hit");
}
else
{
Print("Failed to open reversal SELL. Error: ", GetLastError());
}
}
// If last position was a SELL that hit SL/TP, open BUY
else if(g_lastClosed.type == POSITION_TYPE_SELL)
{
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 SELL ",
g_lastClosed.wasStopLoss ? "Stop Loss" : "Take Profit", " hit");
}
else
{
Print("Failed to open reversal BUY. 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 position closed by SL or TP |
//+------------------------------------------------------------------+
void CheckForClosedPosition()
{
// Track current positions
bool hasPosition = false;
ulong currentPositionTicket = 0;
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)
{
// Select the deal history for today
if(HistorySelect(TimeCurrent() - 86400, TimeCurrent()))
{
int dealsTotal = HistoryDealsTotal();
// Look for the closing deal of our position
for(int i = dealsTotal - 1; i >= 0; i--)
{
ulong dealTicket = HistoryDealGetTicket(i);
if(dealTicket > 0)
{
ulong positionId = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
// Check if this deal closed our position
if(positionId == g_lastPositionTicket)
{
ENUM_DEAL_ENTRY dealEntry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealTicket, DEAL_ENTRY);
// Only process OUT deals (position closing)
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 (opposite of closing deal)
ENUM_POSITION_TYPE posType = (dealType == DEAL_TYPE_BUY) ?
POSITION_TYPE_SELL : POSITION_TYPE_BUY;
// Get the original position's SL and TP from history
double posSL = 0, posTP = 0;
// Check if it was SL or TP
bool wasStopLoss = false;
bool wasTakeProfit = false;
// For a BUY position
if(posType == POSITION_TYPE_BUY)
{
// Rough check: if profit is negative, likely SL
if(dealProfit < 0)
wasStopLoss = true;
else
wasTakeProfit = true;
}
// For a SELL position
else
{
// Rough check: if profit is negative, likely SL
if(dealProfit < 0)
wasStopLoss = true;
else
wasTakeProfit = true;
}
// 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();
// 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