Try this. The problem doing it this way is you're assuming that if openpositionprofit > 0 the trade will close with profits, when that is not neccessarily the case. You could maybe change the 0 to 100 to give yourself some room.
vars: tt(0),size(1),tradesize(1);
tt=totaltrades...