Native MT5 problem to calculate total profit from history with magic number?

 
Hi, I am struggling with MT5 to calculate the profit of closed positions in the history, filtering them by magic number.

All the examples I have found on the net do not work because, I suppose, of a native MT5 problem. As you can see from the image (lines in yellow or orange), the positionID is matched to the magic number in the first line of commission (so it means that the position was actually opened with a magic number) but the magich numer is no longer present in the next line (profit) so obviously the SW routine does not work correctly. The green rows are the correct ones and on average, 10% of the history positions have this problem. I think the only possible way is to first look for the match between dealTicket and positionID, then between positionID and magic number, once found, look for all positionIDs and sum profit, commission and swap ignoring the magic number. Do you know why MT5 behaves this way?