I’m developing an Expert Advisor (EA) in MT5 and I need to know why my previous trade was closed.
For example, if a Buy position gets closed, I want my EA to detect whether it was closed because the Stop Loss was hit, the Take Profit was hit, or it was closed manually.
Is there any way to identify the exact reason for a position being closed 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:
HistoryDealGetInteger(dealTicket, DEAL_REASON);
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.
Before reading the deal history, make sure you’ve selected the required history range using:
HistorySelect(fromTime, TimeCurrent());
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.