1 (edited by geektrader 2019-01-24 07:52:51)

Topic: RefreshRates() missing on failed trade retries in MQ4 code

Hi Popov,

I had a failing trade today because the broker did not accept it ("market closed" because of news spike, blah blah ;-)). Now I know that EA Studios code is retrying 4 times, but the IsTradeContextFree() function  (which is run before each retry, which of course is all right) does only do RefreshRates() if the trade context was busy and then becomes free. However, if a busy trade context is not the case for the failure (like in my case), the OpenPosition function loops X times and retries to place the trade. However, all subsequent tries failed too, because it tried to send the market order at an old price, because the price changed during the news spike (hence the first error) and EA Studios code did not RefreshRates() before trying to place the trade again. To make this work correctly you´ll always have to do RefreshRates() in the IsTradeContextFree() function, so that it looks like:

bool IsTradeContextFree()
{
    RefreshRates();
    if (IsTradeAllowed())
        return(true);

    uint startWait = GetTickCount();
    Print("Trade context is busy! Waiting...");

    while (true)
    {
        if (IsStopped())
            return(false);

        uint diff = GetTickCount() - startWait;
        if (diff > 30 * 1000)
        {
            Print("The waiting limit exceeded!");
            return(false);
        }

        if (IsTradeAllowed())
        {
            RefreshRates();
            return(true);
        }
        Sleep(TRADE_RETRY_WAIT);
    }
    return(true);
}

Only then it´s guaranteed that the retry attemps that EA Studio actually does will work at all, because otherwise it´s working with outdates prices if the failure was not because of a busy trade context, as rates on subsequent trade retries are never refreshed and tried to be placed at wrong prices.