looking at the state machine diagram that I quickly sketched, highlights another problem you need to think about how to handle:
What happens if when you try to close a bet, you get an error back due to that price disappearing before you can trade it?
This is a bit different from when you are entering the market because somehow you must get out of the bet. This makes it a bit more difficult to get the logic right because you also want to avoid closing the bet twice which effectively means going short if you were long or vice versa (back/lay to you)