How to get the last profit for a certain symbol

 

I am trying to get the ea to enter on candle open if previous trade on a symbol was a loss but my code doesn't if another symbol closes with tp. 

for example:

2 positions opened, 1 boom 1000 Index and the other Crash 1000.  

Crash 1000 hits Stop loss and then  Boom 1000 hits take profit before closing the current candle, at candle open crash should open a position but it doesn't.

But if Boom 1000 hits tp and then crash hits Sl before closing the current candle, at candle crash does open a position.

How to solve this?

           //+------------------------------------------------------------------+
            //|         Stop Insurance                                           |
            //+------------------------------------------------------------------+
            bool ord;
            double TotalLot=0;
            int i=HistoryDealsTotal()-1;
            ulong ticket=HistoryDealGetTicket(i);
            ord=HistoryDealSelect(ticket);
            double cake = HistoryDealGetDouble(ticket,DEAL_VOLUME);

              for(i; i>=0; i--)
              {
               if(ord && HistoryDealGetString(ticket,DEAL_SYMBOL) == _Symbol
                  && HistoryDealGetInteger(ticket,DEAL_MAGIC) == Magic_Number
                  && HistoryDealGetInteger(ticket,DEAL_ENTRY) == DEAL_ENTRY_OUT)
                 {
                  string dealtype = "";
                  long dtype;
                  dtype = HistoryDealGetInteger(ticket,DEAL_TYPE);
                  dtype = HistoryDealGetInteger(ticket,DEAL_TYPE);
                  if(dtype!=DEAL_TYPE_BUY && dtype!=DEAL_TYPE_SELL)
                     continue;

                  dealtype = "Buy";
                  if(dtype==DEAL_TYPE_BUY) //if a position closed by Buy, then the original is Sell
                     dealtype = "Sell";              

                  if(HistoryDealGetDouble(ticket,DEAL_PROFIT) < 0 && cake < Multiply)
                    {

                     //+------------------------------------------------------------------+
                     //|        SLI Open Buy Order                                        |
                     //+------------------------------------------------------------------+
                     if((_Symbol == "Crash 1000 Index" || _Symbol == "Crash 500 Index") && (dealtype == "Buy"))
                       {
                    
                        if(Allow_Buy == true)
                          {

                           if(co[0]&& Positions.Buy(Magic_Number) == 0)

                           
                             
                             {
                              if(glSellTicket > 0)
                                {
                                 Trade.Close(glSellTicket);
                                }