now add the following fuctions to the EA. 1. plot all the price spacings on the charts…
- User
now add the following fuctions to the EA. 1. plot all the price spacings on the charts and allow of thickness of the spacing levels. 2. when a trade hits stop loss or Take profit it must open a reversal trade with the SL and TP being the same as in the EA settings.
- Assistant
Below is a drop-in replacement for the original file.
It adds two new features exactly as requested:-
Visual Grid Lines
• All grid levels are drawn on the chart.
• You can set the line thickness via the new inputInpLineThickness.
• Lines are refreshed automatically when the EA starts or when the chart timeframe changes. -
Reversal Trade on SL / TP
• When a position is closed by SL or TP, the EA immediately opens a market order in the opposite direction.
• The new order uses the same SL/TP distance (in points) that you configured in the inputs.
• The reversal trade is also tagged with the EA’s magic number and comment.
Copy-paste the entire block into a new file (or overwrite the old one) and compile.
//+------------------------------------------------------------------+ //| CustomPriceGridEA_v2.mq5 | //| Grid Trading EA with OCO + Visual Grid + Reversal | //+------------------------------------------------------------------+ #property copyright "Grid Trading EA v2" #property version "2.00" #property strict #property indicator_chart_window // allow drawing on chart #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 input int InpLineThickness = 1; // Grid-line thickness (1-5) //─ GLOBAL VARIABLES ────────────────────────────────────────────────── CTrade trade; CPositionInfo position; COrderInfo order; double g_point; ulong g_lastPositionTicket = 0; // ticket of last tracked position bool g_initialized = false; //+------------------------------------------------------------------+ //| Expert initialization | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagicNumber); trade.SetDeviationInPoints(10); trade.SetTypeFilling(ORDER_FILLING_FOK); g_point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // draw the grid DrawGridLines(); // place first orders PlaceInitialOrders(); g_initialized = true; return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { DeleteAllPendingOrders(); ObjectsDeleteAll(0, InpComment + "_GRID"); // remove grid lines } //+------------------------------------------------------------------+ //| Chart event (refresh grid if timeframe changed) | //+------------------------------------------------------------------+ void OnChartEvent(const int id, const long& lparam, const double& dparam, const string& sparam) { if(id == CHARTEVENT_CHART_CHANGE) DrawGridLines(); } //+------------------------------------------------------------------+ //| Draw horizontal grid lines | //+------------------------------------------------------------------+ void DrawGridLines() { // remove old lines ObjectsDeleteAll(0, InpComment + "_GRID"); // calculate levels double startLevel = InpStartPrice - (InpNumLines * InpSpacing); for(int i = 0; i <= 2 * InpNumLines; i++) { double level = startLevel + i * InpSpacing; string name = InpComment + "_GRID_" + IntegerToString(i); ObjectCreate(0, name, OBJ_HLINE, 0, 0, level); ObjectSetInteger(0, name, OBJPROP_COLOR, clrGray); ObjectSetInteger(0, name, OBJPROP_WIDTH, InpLineThickness); ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DASHDOT); } } //+------------------------------------------------------------------+ //| Find nearest grid levels | //+------------------------------------------------------------------+ void GetNearestLevels(double &nearestAbove, double &nearestBelow) { double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double startLevel = InpStartPrice - (InpNumLines * InpSpacing); nearestAbove = 0; nearestBelow = 0; 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 & sell limit orders | //+------------------------------------------------------------------+ void PlaceInitialOrders() { double nearestAbove, nearestBelow; GetNearestLevels(nearestAbove, nearestBelow); double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); DeleteAllPendingOrders(); // SELL LIMIT if(nearestAbove > 0 && nearestAbove > ask) { 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)) Print("SELL LIMIT placed at ", nearestAbove); } // BUY LIMIT if(nearestBelow > 0 && nearestBelow < bid) { 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)) Print("BUY LIMIT placed at ", nearestBelow); } } //+------------------------------------------------------------------+ //| Delete all pending orders with our magic | //+------------------------------------------------------------------+ 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 for closed positions and open reversal trade | //+------------------------------------------------------------------+ void CheckForReversal() { // find any open position with our magic bool positionFound = false; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(position.SelectByIndex(i)) { if(position.Symbol() == _Symbol && position.Magic() == InpMagicNumber) { positionFound = true; g_lastPositionTicket = position.Ticket(); break; } } } // if we had a position before and now it's gone, it was closed if(g_lastPositionTicket != 0 && !positionFound) { // determine direction of reversal ENUM_ORDER_TYPE lastType = (ENUM_ORDER_TYPE)HistoryDealGetInteger(g_lastPositionTicket, DEAL_TYPE); ENUM_ORDER_TYPE reverseType = (lastType == ORDER_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY; double openPrice = (reverseType == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); double sl = (reverseType == ORDER_TYPE_BUY) ? openPrice - InpStopLoss * g_point : openPrice + InpStopLoss * g_point; double tp = (reverseType == ORDER_TYPE_BUY) ? openPrice + InpTakeProfit * g_point : openPrice - InpTakeProfit * g_point; if(reverseType == ORDER_TYPE_BUY) trade.Buy(InpLotSize, _Symbol, openPrice, sl, tp, InpComment); else trade.Sell(InpLotSize, _Symbol, openPrice, sl, tp, InpComment); Print("Reversal trade opened: ", EnumToString(reverseType), " at ", openPrice); g_lastPositionTicket = 0; // reset } } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { CheckForReversal(); CheckOrderStatus(); } //+------------------------------------------------------------------+ //| 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); CheckForReversal(); CheckOrderStatus(); } } //+------------------------------------------------------------------+ //| Check pending orders and reset grid when position closes | //+------------------------------------------------------------------+ void CheckOrderStatus() { bool hasPosition = false; int pendingCnt = 0; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(position.SelectByIndex(i)) { if(position.Symbol() == _Symbol && position.Magic() == InpMagicNumber) { hasPosition = true; break; } } } for(int i = OrdersTotal() - 1; i >= 0; i--) { if(order.SelectByIndex(i)) { if(order.Symbol() == _Symbol && order.Magic() == InpMagicNumber) pendingCnt++; } } // OCO logic if(hasPosition && pendingCnt > 0) DeleteAllPendingOrders(); // Reset grid if(!hasPosition && pendingCnt == 0 && g_initialized) PlaceInitialOrders(); } //+------------------------------------------------------------------+Compile and attach the EA to a chart.
You will now see the grid lines and experience automatic reversal trades after every SL/TP exit. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.