An EA often needs to know why a position closed. Did the stop loss hit, did the take profit hit, did the user close it by hand on their phone, or did the broker stop the account out? Each case deserves a different reaction. A manual close might mean "leave this symbol alone for today", while a stop loss is just normal business.
MT5 records this on every deal as DEAL_REASON. You can read it inside OnTradeTransaction as soon as the closing deal arrives.
Reading the reason
void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { if(trans.type != TRADE_TRANSACTION_DEAL_ADD) return; if(!HistoryDealSelect(trans.deal)) return; if(HistoryDealGetInteger(trans.deal, DEAL_MAGIC) != InpMagic) return; long entry = HistoryDealGetInteger(trans.deal, DEAL_ENTRY); if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_OUT_BY) return; long reason = HistoryDealGetInteger(trans.deal, DEAL_REASON); switch((int)reason) { case DEAL_REASON_SL: OnStopLossHit(); break; case DEAL_REASON_TP: OnTakeProfitHit(); break; case DEAL_REASON_SO: OnStopOut(); break; case DEAL_REASON_CLIENT: case DEAL_REASON_MOBILE: case DEAL_REASON_WEB: OnManualClose(); break; case DEAL_REASON_EXPERT: break; // our own close default: PrintFormat("Close deal %I64u reason %d", trans.deal, reason); } } Things that trip people up
- Check DEAL_ENTRY. Opening deals also arrive here, and their reason describes how the position was opened, not closed.
- A manual close of a position that still carries your magic number keeps the magic number, which is exactly why this works. A manual close from another EA's chart will not.
- A stop out is a big event. Do not reopen anything after DEAL_REASON_SO; log it and stop trading until a human looks.
- In the strategy tester you will only see SL, TP, SO and EXPERT. Test the manual branches on a demo account by closing a trade yourself.
A sensible default
When a manual close is detected, set a flag that pauses new entries on that symbol until the next session. Users close trades by hand because they know something the EA does not, and the EA reopening the same trade a minute later is the fastest way to lose their trust.


