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 IDstruct TicketCloseSell
{
int ticket; // Trade ticketdouble 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 tradestruct TicketOpenBuy
{
int ticket; // Buy trade ticketdouble openBuy; // Buy open priceint packageID; // Package ID (to associate each trade)
};
// Arrays to store the values of closeSell and openBuy by package
TicketCloseSell closeSells[];
TicketOpenBuy openBuys[];
// Trade parametersinputdouble LotSize = 0.01; // Trade lot sizeinputdouble StopLoss = 0; // Stop Loss in pointsinputdouble TakeProfit = 60; // Take Profit in pointsinputdouble TakeProfitBuy = 0; // Specific Take Profit for Buy// Global variablesdatetime lastDrawTime = 0;
datetime lastCandleTime = 0;
string eaObjectPrefix = "EA_Object_";
// Package ID counterint packageCounter = 0;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
// Initialize last draw time
lastDrawTime = TimeCurrent();
// Print initialization messagePrint("EA started successfully.");
// Set a timer to check for new candle closures every 1 secondEventSetTimer(1);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
// Kill timerEventKillTimer();
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+voidOnTick()
{
// Call the function LlegoAlPrecio every time there's a new tick
LlegoAlPrecio();
}
//+------------------------------------------------------------------+//| Expert timer function |//+------------------------------------------------------------------+voidOnTimer()
{
// Check if the current candle has closedMqlRates 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 oneif (currentCandleTime != lastCandleTime)
{
// Update the last candle time
lastCandleTime = currentCandleTime;
// Check if it's the 26th minute to send ordersMqlDateTime dt;
TimeToStruct(currentCandleTime, dt);
// Check if the minute is 26if (dt.min == 3)
{
// Increment package counter
packageCounter++;
// Get current Ask and Bid pricesdouble Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
// Initialize Stop Loss and Take Profit levels with default valuesdouble stopLossBuy = 0;
double takeProfitBuy = 0;
double stopLossSell = 0;
double takeProfitSell = 0;
// Calculate Stop Loss and Take Profit if not zeroif (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 orderstring packageLabel = "Package_" + IntegerToString(packageCounter);
// Open a buy orderbool 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 10if (buyResult)
{
// Register the buy order
RegisterBuy(trade.ResultOrder(), packageCounter, Ask);
Print("Buy order executed, Package: ", packageLabel);
}
// Open a sell orderbool 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 ticketint ticket = trade.ResultOrder();
// Calculate and store the sell close pricedouble closeSell = Bid - 70 * _Point; // Close 180 pips below the sell open price// Store trade details in closeSells arrayArrayResize(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 ordersif (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 closeSellsfor (int i = 0; i < ArraySize(closeSells); i++)
{
Print("1");
// Get the current pricedouble currentPrice = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
// If the price has reached or exceeded the close priceif (currentPrice <= closeSells[i].closeSell)
{
// Check if the message has already been printed for this packageif (!closeSells[i].messagePrinted)
{
// Print the success messagePrint("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 positionif (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 tradevoid 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 packagefor (int i = 0; i < ArraySize(openBuys); i++)
{
if (openBuys[i].packageID == packageID)
{
// Get the buy trade ticketint buyTicket = openBuys[i].ticket;
double buyOpenPrice = openBuys[i].openBuy; // Get the buy open price// Print the buy open price for the packagePrint("Buy position for package ", packageID, " open price: ", buyOpenPrice);
break; // Stop the loop once the package is found
}
}
}
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
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: