How can I get an MQL5 AE, when submitting a Sell and Buy order at the same time, to close the Sell order immediately and set a TakeProfit for the Buy trade?

 

Each sell goes with a buy, if a sell is closed in its take profit, how could you put a take profit on that corresponding buy that was sent at the same time as the sell trade.

This is my code:

//+------------------------------------------------------------------+
//|                           Combined_VerticalLinesAndOrders.mq5    |
//|                        Copyright 2024, MetaQuotes Software Corp. |
//|                                       http://www.mql5.com        |
//+------------------------------------------------------------------+
#property strict

#include <Trade\Trade.mqh>
CTrade trade;

// Structure to store the ticket, close price, and package ID
struct TicketCloseSell
{
   int               ticket;         // Trade ticket
   double            closeSell;      // Calculated close price (open price - 180 pips)
   int               packageID;      // Package ID (to associate each trade)
   bool              messagePrinted; // Flag to ensure the message is printed only once
};

// Structure to store the ticket, open price, and package ID for the buy trade
struct TicketOpenBuy
{
   int          ticket;           // Buy trade ticket
   double       openBuy;          // Buy open price
   int          packageID;        // Package ID (to associate each trade)
};

// Arrays to store the values of closeSell and openBuy by package
TicketCloseSell closeSells[];
TicketOpenBuy openBuys[];

// Trade parameters
input double LotSize = 0.01;       // Trade lot size
input double StopLoss = 0;          // Stop Loss in points
input double TakeProfit = 60;       // Take Profit in points
input double TakeProfitBuy = 0;     // Specific Take Profit for Buy

// Global variables
datetime lastDrawTime = 0;
datetime lastCandleTime = 0;
string eaObjectPrefix = "EA_Object_";

// Package ID counter
int packageCounter = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Initialize last draw time
   lastDrawTime = TimeCurrent();

   // Print initialization message
   Print("EA started successfully.");

   // Set a timer to check for new candle closures every 1 second
   EventSetTimer(1);
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Kill timer
   EventKillTimer();
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Call the function LlegoAlPrecio every time there's a new tick
   LlegoAlPrecio();
}

//+------------------------------------------------------------------+
//| Expert timer function                                           |
//+------------------------------------------------------------------+
void OnTimer()
{
   // Check if the current candle has closed
   MqlRates priceInfo[];
   ArraySetAsSeries(priceInfo, true);
   int priceData = CopyRates(_Symbol, _Period, 0, 2, priceInfo);

   if (priceData > 1)
   {
      datetime currentCandleTime = priceInfo[1].time;

      // Execute orders only if the last closed candle time is different from the current one
      if (currentCandleTime != lastCandleTime)
      {
         // Update the last candle time
         lastCandleTime = currentCandleTime;

         // Check if it's the 26th minute to send orders
         MqlDateTime dt;
         TimeToStruct(currentCandleTime, dt);

         // Check if the minute is 26
         if (dt.min == 3)
         {
            // Increment package counter
            packageCounter++;

            // Get current Ask and Bid prices
            double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
            double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);

            // Initialize Stop Loss and Take Profit levels with default values
            double stopLossBuy = 0;
            double takeProfitBuy = 0;
            double stopLossSell = 0;
            double takeProfitSell = 0;

            // Calculate Stop Loss and Take Profit if not zero
            if (StopLoss > 0)
            {
               stopLossBuy = Ask - StopLoss * _Point;
               stopLossSell = Bid + StopLoss * _Point;
            }

            if (TakeProfit > 0)
            {
               takeProfitBuy = Ask + TakeProfitBuy * _Point;
               takeProfitSell = Bid - TakeProfit * _Point;
            }

            if (TakeProfitBuy > 0)
            {
               takeProfitBuy = Ask + TakeProfitBuy * _Point;
               takeProfitSell = Bid - TakeProfit * _Point;
            }

            // Assign package ID to each order
            string packageLabel = "Package_" + IntegerToString(packageCounter);

            // Open a buy order
            bool buyResult = trade.Buy(LotSize, NULL, Ask,
                                       (StopLoss > 0) ? stopLossBuy : 0,
                                       (TakeProfitBuy > 0) ? takeProfitBuy : 0,
                                       packageLabel);

            // Increment the buy order counter and reset if it reaches 10
            if (buyResult)
            {
               // Register the buy order
               RegisterBuy(trade.ResultOrder(), packageCounter, Ask);
               Print("Buy order executed, Package: ", packageLabel);
            }

            // Open a sell order
            bool sellResult = trade.Sell(LotSize, NULL, Bid,
                                         (StopLoss > 0) ? stopLossSell : 0,
                                         (TakeProfit > 0) ? takeProfitSell : 0,
                                         packageLabel);

            if (sellResult)
            {
               Print("Sell order executed, Package: ", packageLabel);

               // Get the sell trade ticket
               int ticket = trade.ResultOrder();

               // Calculate and store the sell close price
               double closeSell = Bid - 70 * _Point; // Close 180 pips below the sell open price

               // Store trade details in closeSells array
               ArrayResize(closeSells, ArraySize(closeSells) + 1);
               closeSells[ArraySize(closeSells) - 1].ticket = ticket;
               closeSells[ArraySize(closeSells) - 1].closeSell = closeSell;
               closeSells[ArraySize(closeSells) - 1].packageID = packageCounter;

               Print("Close price calculated and saved for ticket ", ticket, ": ", closeSell);
            }

            // Print the results of opening orders
            if (buyResult && sellResult)
            {
               Print("Buy and sell orders executed successfully. Package: ", packageLabel);
            }
            else
            {
               Print("Error executing orders. Buy: ", buyResult, ", Sell: ", sellResult, " error: ", GetLastError());
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Function LlegoAlPrecio                                            |
//+------------------------------------------------------------------+
void LlegoAlPrecio()
{
   Print("1");
   // Iterate through all packages in closeSells
   for (int i = 0; i < ArraySize(closeSells); i++)
   {
      Print("1");
      // Get the current price
      double currentPrice = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);

      // If the price has reached or exceeded the close price
      if (currentPrice <= closeSells[i].closeSell)
      {
         // Check if the message has already been printed for this package
         if (!closeSells[i].messagePrinted)
         {
            // Print the success message
            Print("Package ", closeSells[i].packageID, " has reached the close price: ", closeSells[i].closeSell);

            // Mark that the message has been printed
            closeSells[i].messagePrinted = true;

            // Try to close the sell position
            if (PositionSelectByTicket(closeSells[i].ticket))
            {
               if (trade.PositionClose(closeSells[i].ticket))
               {
                  Print("Trade closed successfully for package ", closeSells[i].packageID);

                  // Call the new function to get and show the buy open price
                  NewTakeProfitBuy(closeSells[i].packageID);
               }
               else
               {
                  Print("Error closing the trade for package ", closeSells[i].packageID, ", error: ", GetLastError());
               }
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Function RegisterBuy                                             |
//+------------------------------------------------------------------+
// Function to register the buy trade
void RegisterBuy(int buyTicket, int packageID, double buyPrice)
{
    ArrayResize(openBuys, ArraySize(openBuys) + 1);
    openBuys[ArraySize(openBuys) - 1].ticket = buyTicket;
    openBuys[ArraySize(openBuys) - 1].packageID = packageID;
    openBuys[ArraySize(openBuys) - 1].openBuy = buyPrice;
    Print("Buy registered, Package: ", packageID, ", Buy Ticket: ", buyTicket, ", Open Price: ", buyPrice);
}

//+------------------------------------------------------------------+
//| Function NewTakeProfit                                           |
//+------------------------------------------------------------------+
// Function called after printing "Trade closed successfully for package ..."
void NewTakeProfitBuy(int packageID)
{
    // Iterate through all buy trades to find the buy position of the package
    for (int i = 0; i < ArraySize(openBuys); i++)
    {
        if (openBuys[i].packageID == packageID)
        {
            // Get the buy trade ticket
            int buyTicket = openBuys[i].ticket;
            double buyOpenPrice = openBuys[i].openBuy;  // Get the buy open price

            // Print the buy open price for the package
            Print("Buy position for package ", packageID, " open price: ", buyOpenPrice);
            break; // Stop the loop once the package is found
        }
    }
}