Detecting SL, TP and Stop Out closes with OnTradeTransaction

I needed a reliable way to tell whether a position left the account because of Stop Loss, Take Profit, Stop Out, or an EA/manual close, including partial closes. Polling `PositionsTotal()` only tells you that something disappeared. The deal in history has the reason.

The hook is `OnTradeTransaction`, looking at `TRADE_TRANSACTION_DEAL_ADD`, then `HistoryDealSelect`, then `DEAL_ENTRY` and `DEAL_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;

   const long entry = HistoryDealGetInteger(trans.deal, DEAL_ENTRY);
   if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_INOUT && entry != DEAL_ENTRY_OUT_BY)
      return;

   const string symbol = HistoryDealGetString(trans.deal, DEAL_SYMBOL);
   if(symbol != _Symbol)
      return;

   const long magic = HistoryDealGetInteger(trans.deal, DEAL_MAGIC);
   if(InpMagic != 0 && magic != InpMagic)
      return;

   const double money = HistoryDealGetDouble(trans.deal, DEAL_PROFIT)
                      + HistoryDealGetDouble(trans.deal, DEAL_SWAP)
                      + HistoryDealGetDouble(trans.deal, DEAL_COMMISSION)
                      + HistoryDealGetDouble(trans.deal, DEAL_FEE);

   PrintFormat("Close %s  deal=%I64u  pos=%I64d  magic=%I64d  entry=%s  reason=%s  vol=%.2f  money=%.2f",
               symbol,
               trans.deal,
               HistoryDealGetInteger(trans.deal, DEAL_POSITION_ID),
               magic,
               DealEntryText(entry),
               DealReasonText(HistoryDealGetInteger(trans.deal, DEAL_REASON)),
               HistoryDealGetDouble(trans.deal, DEAL_VOLUME),
               money);
  }

`DEAL_REASON_SL`, `DEAL_REASON_TP` and `DEAL_REASON_SO` are the three that matter for a guard. `DEAL_ENTRY_OUT` with a volume smaller than the position is a partial close. `DEAL_FEE` is a documented deal property and should be included with commission and swap if you are summing money.

Two traps:

  • If a position is closed manually, `DEAL_MAGIC` on the outgoing deal can be 0 even though the position was opened by the EA. Filtering only on magic will miss that close. I treat magic as a filter for EA exits, and I use `DEAL_POSITION_ID` (stored at open) when I also need to see manual exits of "my" positions.
  • `OnTradeTransaction` does not replay deals that happened while the EA was not running. On `OnInit` I still walk history from the last stored deal ticket and reconcile, otherwise a restart in the middle of a close is invisible.

I am interested in whether anyone has a clean pattern for the "closed while the EA was down" case, and whether you trust `DEAL_REASON_EXPERT` to mean "my EA" when several experts are running on the same account.