Hi . I am trying to write a code to exist at breakeven point when I am in the market and the chance of market going my way is diminishing. I am using pending orders and place them based on how far the price goes in each direction. I backtested it and noticed that whenever the pending order is triggered it closes my existing position and simultaneasly opens opposite direction position. e.g. If I am Long on market it closes my long and opens a short at the same time. Just wondering what I am doing wrong here:
Once Flag1 = 0
Once Flag2 = 0
once Flag3=0
ONce Flag4=0
once flag5=0
once flag6=0
IF Not OnMarket OR (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket) THEN
Flag1 = 0
Flag2 = 0
Flag3=0
Flag4=0
flag5=0
flag6=0
ENDIF
if longonmarket and close >= positionprice +22 then
Flag2 = 1
endif
if longonmarket and close >= positionprice +15 then
Flag3 = 1
endif
if longonmarket and close <= positionprice -15 then
Flag4 = 1
endif
if longonmarket and flag3 and close <= positionprice -15 then
Flag5 = 1
endif
if longonmarket and flag4 and close >= positionprice +15 then
Flag6 = 1
endif
if shortonmarket and close <= positionprice -22 then
Flag2 = 1
endif
if shortonmarket and close <= positionprice -10 then
Flag3 = 1
endif
if shortonmarket and close >= positionprice +10 then
Flag4 = 1
endif
if shortonmarket and flag3 and close >= positionprice +10 then
Flag5 = 1
endif
if shortonmarket and flag4 and close <= positionprice -10 then
Flag6 = 1
endif
if LongOnMarket AND Flag2 then
sell countoflongshares contracts at positionprice stop
endif
if LongOnMarket AND Flag6 then
sell countoflongshares contracts at positionprice stop
endif
if LongOnMarket AND Flag5 then
sell countoflongshares contracts at positionprice limit
endif
if shortonmarket and Flag2 then
buy countofshortshares contracts at positionprice stop
endif
if shortonmarket and Flag5 then
buy countofshortshares contracts at positionprice limit
endif
if shortonmarket and Flag6 then
buy countofshortshares contracts at positionprice stop
endif
BUY is used to open a Long position (after closing any open Short position, in which case it does a Stop & Reverse).
SELL is used to exit a Long position.
SELLSHORT is used to open a Short position (after closing any open Long position, in which case it does a Stop & Reverse).
EXITSHORT is used to exit s Short position.