c++mql4

How to calculate the futurePrice to set Take Profit in MQL4?


I am creating an EA in MQL4. I am trading in XAUUSD. The scenario is - I open a buy trade of 0.01 lotsize on currentPrice which is 2000.00, now the price shifts in downward direction to 1995.00 which means my current P/L will be $5. I know the direction will go further down so make a hedge trade, which is a sell trade of 0.02 lot size on 1995.00 as the Market goes down the sell trade will be in profit and buy trade will be in loss. at 1990.00 buy trade will have $-10 and sell trade will have +$10 so the overal P/L will be zero. now it goes further down to 1980.00 buy trade will have $-20 and sell trade will have +$30 so the overal P/L will be $10. in my code i am unable to calculate this price of 1980.00 where my target of $10 is acheiving. how do i do that?


double CalculateFuturePrice()
{
    double lastOrderPrice = OrderOpenPrice();
    double increment = 0.01 \* Point;
    
    while(currentPl \< target)
    {
        lastOrderPrice += increment;
        double newBuyPL = (lastOrderPrice - OrderOpenPrice()) \* buyLots \* MarketInfo(Symbol(), MODE_TICKVALUE);
        double newSellPL = (OrderOpenPrice() - lastOrderPrice) \* sellLots \* MarketInfo(Symbol(), MODE_TICKVALUE);
        currentPl = buypl + sellpl + newBuyPL + newSellPL;
    }
    
    return lastOrderPrice;
    
}

i want to calculate the price where my current p/l will become positive and close all trade at my target.


Solution

  • MLQ4 is really close to C++ so I would suggest the below code.

    double CalculateFuturePrice(double buyPrice, double sellPrice, double buyLots, double sellLots, double targetPL)
    {
        double currentPrice = sellPrice;
        double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
    
        while(true)
        {
            // Calculate P/L for both trades at the current price
            double buyPL = (currentPrice - buyPrice) * buyLots * tickValue;
            double sellPL = (sellPrice - currentPrice) * sellLots * tickValue;
            double totalPL = buyPL + sellPL;
    
            // Check if the total P/L has reached or exceeded the target P/L
            if(totalPL >= targetPL)
            {
                return currentPrice;
            }
            
            // Decrement the price by one tick (since we are considering the price going down)
            currentPrice -= Point;
        }
    }