The problem is that MT5 does not wait for it's local database to be updated when something important happens. For example, it can successfully close a position and the function to do that will return only success messages, but for all the other functions it will appear that the position is still present... for some time, sometimes 1 ms, sometimes seconds.
This was reported few times before, so I added some trick to wait while the local database is really updated. The trick is that the program will wait for 5 seconds (at most) for the local database to be updated after the position is closed. But maybe this happens slowly than 5 seconds for you. So I will just put an endless loop with the risk of someone complaining that his EA stuck while trying to close some position 



