It is not working properly because you are sending orders to buy or sell the next bar before you exit your position. TradeStation doesn't know if the trade you are in will close with profits or losses when you are sending your orders. A work around would be.....
vars: tt(0),size(1),lasttrade(1);
tt=totaltrades;
if tt>tt[1] then begin
if positionprofit(1)>=0 then size=1;
if positionprofit(1)<0 then size=size+1;
end;
if marketposition=0 then begin
buy size contracts next bar at highd(0) on stop;
sell size contracts next bar at lowd(0) on stop;
end;
setexitonclose;
vars: tt(0),size(1),lasttrade(1);
tt=totaltrades;
if tt>tt[1] then begin
if positionprofit(1)>=0 then size=1;
if positionprofit(1)<0 then size=size+1;
end;
if marketposition=0 then begin
buy size contracts next bar at highd(0) on stop;
sell size contracts next bar at lowd(0) on stop;
end;
setexitonclose;