Clear position before entering a new one. That means the "Close all Sell" or "Close all Buy" order will be sent before the Entry position. Not only is this an easy way to approach APIs or bots, but it also prevents duplicate or different order size.
Don't confuse the clearing position in the script with the position in your account. All transactions require your understanding and approval. If you implement the API yourself, please make sure you have handled this on your server side.