How can it be ok?
The loop only checks the first order, so there may be a buy order, but if it is not in the highest position, it will not be detected.
If last was not buy than he needs to delete pending. If it is buy than he do not want to delete pending.
What is the problem?