Failed to update ticket when stop order is filled

 

Hi,

I have a stop order and want to save the new ticket after the stop order is filled. I tried to use OnTradeTransaction() class but failed to do so. Here's how I do it.

void OnTradeTransaction(
   const MqlTradeTransaction& trans,
   const MqlTradeRequest&     request,
   const MqlTradeResult&      result) {

      //... if there's an update from pending order
      if(trans.type == TRADE_TRANSACTION_HISTORY_ADD) {
         //... looked for the order type and the state of it
         if(trans.order_type == ORDER_TYPE_BUY_STOP && trans.order_state == ORDER_STATE_FILLED)
            //... set the new ticket
         if(HistoryOrderSelect(trans.order)) {
            BuyTicket[SymbolLoop] = result.order;
            Print("buy ticket: ", BuyTicket[SymbolLoop]);
         }

         //... looked for the order type and the state of it
         if(trans.order_type == ORDER_TYPE_SELL_STOP && trans.order_state == ORDER_STATE_FILLED)
            //... set the new ticket
            Print("result order: ", result.order);
         if(HistoryOrderSelect(trans.order)) {
            SellTicket[SymbolLoop] = result.order;
            Print("sell ticket: ", SellTicket[SymbolLoop]);
         }
      }
}

When I use the code above and stop order is filled it returns 0 and it also prints both buy and sell ticket even though only buy order is filled. Can anyone show me where I'm wrong?

 

Looks like there is a problem with program flow:

void OnTradeTransaction(
   const MqlTradeTransaction& trans,
   const MqlTradeRequest&     request,
   const MqlTradeResult&      result) 
{

      if(trans.type == TRADE_TRANSACTION_HISTORY_ADD) 
      {
         if(trans.order_type == ORDER_TYPE_BUY_STOP && trans.order_state == ORDER_STATE_FILLED)
	 {
	         if(HistoryOrderSelect(trans.order))
		 {
            	     BuyTicket[SymbolLoop] = result.order;
            	     Print("buy ticket: ", BuyTicket[SymbolLoop]);
         	 }
	 }
         if(trans.order_type == ORDER_TYPE_SELL_STOP && trans.order_state == ORDER_STATE_FILLED)
	 { 
                 if(HistoryOrderSelect(trans.order)) 
		 {
                     SellTicket[SymbolLoop] = result.order;
	             Print("sell ticket: ", SellTicket[SymbolLoop]);
	         }
	 }
      }
}