Discrepancy in per symbol profit between backtest and optimization results

I use the following code to generate per-symbol profit:

function ProcessTrade( trade )
{
  global tradedSymbols;
  symbol = trade.Symbol;
  //
  if( ! StrFind( tradedSymbols, "," + symbol + "," ) )
  {
    tradedSymbols += symbol + ",";
  }
  //
  // HINT: you may replace it with GetPercentProfit if you wish
  profit = trade.GetProfit();
  //
  if( trade.IsLong() )
  {
      varname = "long_" + symbol;
      VarSet( varname, Nz( VarGet( varname ) ) + profit );
  }
  else
  {
      varname = "short_" + symbol;
      VarSet( varname, Nz( VarGet( varname ) ) + profit );
  }
}

SetCustomBacktestProc( "" );

if ( Status( "action" ) == actionPortfolio )
{
    bo = GetBacktesterObject();
    //
    bo.Backtest(); // run default backtest procedure
    // 
    
    tradedSymbols = ",";
    //
    //iterate through closed trades
    for ( trade = bo.GetFirstTrade( ); trade; trade = bo.GetNextTrade( ) )
    {
        ProcessTrade( trade );
    }
    //
    //iterate through open positions
    for ( trade = bo.GetFirstOpenPos( ); trade; trade = bo.GetNextOpenPos( ) )
    {
        ProcessTrade( trade );
    }
    //
    //iterate through the list of traded symbols and generate custom metrics
    for ( i = 1; ( sym = StrExtract( tradedSymbols, i ) ) != ""; i++ )
    {
        longprofit = VarGet( "long_" + sym );
        shortprofit = VarGet( "short_" + sym );
        allprofit = Nz( longprofit ) + Nz( shortprofit );
        // metric uses 2 decimal points and
         bo.AddCustomMetric( "Profit for " + sym, allprofit, longprofit, shortprofit, 2 );
    }
}type or paste code here

As you can see from attached pics, the results between backtests and optimization (the line with same parameters as backtest) do not match but are shuffled for the various symbols. For example, in backtest the gain for HYG is 17701.70 but this is the gain for IAU in optimization list.

Any suggestions of what could be wrong with the above code?