By looking at this, I think you need to look at this example: https://fxdreema.com/demo/mt4-wrong-closing-rule
How to detect if a trade is closed by TP? Depends. Under "on Tick" you can check if there are no trades, then to check if the latest closed trade was profitable. Or under "on Trade" you can detect the moment when a trade is closed. But better look at some examples in the Examples page 🙂