Protrader, thanks for helping me, but i don't see how the code can handle situations when a position is closed and reversed at the same time. in these situations, the
if marketposition=0...
condition will be false, so TS will not generate an entry signal.