mql4metatrader4mt4

OrderClosePrice returns a price different from the history pool


When closing a (selected) existing order with the api, and in that moment I try to get the closing price, sometimes (Perhaps one out of ten times) returns a price diferent from the one I can see in the history pool.

The code is something like this:

RefreshRates();

if(type == OP_BUY)
{
    currentPrice = NormalizeDouble(MarketInfo(symbol, MODE_ASK), vdigits);
}
else if(type == OP_SELL)
{
    currentPrice = NormalizeDouble(MarketInfo(symbol, MODE_BID), vdigits);
}

if (meetsRequirementsToClose(currentPrice))
{
    desiredPrice = currentPrice;


    // And then....

    bool retVal = OrderClose(OrderTicket(), numLots, desiredPrice, currSlippage);
    if (retVal)
    {
        this.reportClosePrice (myOrderId, OrderClosePrice(), desiredPrice, numLots, "closing");
        return true;
    }
}

The order was previously selected using SELECT_BY_POS in the pool MODE_TRADES.

anyone knows how to fix it?

Edited:

We have a broker that sometimes respects the requested price... sometimes not.

Disregarding the fact that we have to change broker for a more reliable one, we cannot rely on the requested price.

The deviation we see is greater than one hundred points, both for better and for worse prices than the real ones.


Solution

  • As sugested by @TheLastStark, the problem is solved selecting the order by its ticket just before closing.

    The final code is something like:

    RefreshRates();
    if(type == OP_BUY)
    {
        currentPrice = NormalizeDouble(MarketInfo(symbol, MODE_ASK), vdigits);
    }
    else if(type == OP_SELL)
    {
        currentPrice = NormalizeDouble(MarketInfo(symbol, MODE_BID), vdigits);
    }
    
    if (meetsRequirementsToClose(currentPrice))
    {
        desiredPrice = currentPrice;
    
    
        // And then....
        int tickNum = OrderTicket();
        bool retVal = OrderClose(OrderTicket(), numLots, desiredPrice, currSlippage);
        if (retVal)
        {
            if (OrderSelect(tickNum,SELECT_BY_TICKET,MODE_HISTORY)== false)
            {
                //this.logger.error ("Error selecting the order");
                 this.reportClosePrice (myOrderId, -1, desiredPrice, numLots, "closing");
            }
            else
            {
                this.reportClosePrice (myOrderId, OrderClosePrice(), desiredPrice, numLots, "closing");
            }
            return true;
        }
    }