Closing positions - profit is biger befor, then after closing positions

 

Hey, i have strange issue, when my tp is rising, acc equity also

Then when tp is reached im closing positions (both types, BUY and SELL)

And now when positions are closed, total profit is decreased as on attached pict:

so i know it is tester and generally logic should be ok, but i dont want to show users even in tester that some things like that has place.

So generaly tp reached -> positions are closed. It takes second and should be no so big difference in equity

Here is my logic for calculating tp:

double CalculateTotalProfitInPips()
{
    double totalProfitInPips = 0.0;

    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_MAGIC) == magicNumber)
        {
            double positionProfitInPips = PositionProfitInPips(i);
            totalProfitInPips += positionProfitInPips;
        }
    }

    return totalProfitInPips;
}

double PositionProfitInPips(int positionIndex)
{
   if(!PositionSelectByTicket(PositionGetTicket(positionIndex)) || PositionGetInteger(POSITION_MAGIC) != magicNumber)
      return 0;

   double positionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
   double currentPrice;

   if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
   {
      currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   }
   else
   {
      currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   }

   int positionType = PositionGetInteger(POSITION_TYPE);
   double profitInPips = (positionType == POSITION_TYPE_BUY) ?
                         (currentPrice - positionOpenPrice) / _Point :
                         (positionOpenPrice - currentPrice) / _Point;
   
   if(includeCommissionsAndSwap)
   {
       double volume = PositionGetDouble(POSITION_VOLUME);
       double swap = PositionGetDouble(POSITION_SWAP);
       double commission = PositionGetDouble(POSITION_COMMISSION);
       double pipValueForOneLot = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) / _Point;

       double swapInPips = (swap / (pipValueForOneLot * volume)) * 100; 
       double commissionInPips = (commission / (pipValueForOneLot * volume)) * 100;
       
       profitInPips -= (swapInPips + commissionInPips);
   }
   
   return profitInPips;
}

void CheckAndClosePositionsDynamically()
{
    double totalProfit = CalculateTotalProfitInPips();

    if(totalProfit >= profitThresholdToStartTrailing)
    {
        CloseAllPositionsForSymbol(_Symbol);
    }
}

void CloseAllPositionsForSymbol(string symbol)
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if(PositionGetSymbol(i) == symbol && PositionGetInteger(POSITION_MAGIC) == magicNumber)
      {
         ulong ticket = PositionGetTicket(i);
         trade.PositionClose(ticket);
         
      }
   }
}

Any ideas? :)