Yes sir, you can definitely detect this in MQL5.
The recommended way is to check the deals generated after a position is closed. MT5 stores the reason for every completed deal in the trading history, and you can read that information programmatically.
The most commonly used property is:
This returns the reason why the deal was executed.
Some commonly used values are:
-DEAL_REASON_SL
-> The position was closed because the Stop Loss was hit.
-DEAL_REASON_TP
-> The position was closed because the Take Profit was hit.
-DEAL_REASON_EXPERT
-> The position was closed by an Expert Advisor (EA).
-DEAL_REASON_CLIENT
-> The position was closed manually by the trader.
-DEAL_REASON_SO
-> The position was closed due to Stop Out.
A simple example is shown below:
Before reading the deal history, make sure you’ve selected the required history range using:
This ensures that the completed deals are available for reading.
This approach is very useful when you want to:
-Calculate separate statistics for Stop Loss and Take Profit trades.
-Trigger different logic after a winning or losing trade.
-Send different webhook messages depending on how the previous trade was closed.
-Generate detailed trading reports inside your EA.
So, instead of guessing why a position was closed, you can directly read the deal reason from the MT5 trading history and handle each case accordingly.