I should use a BOT for MT4 from tradingview alerts, but to order a position inverse to the previous one I need a few seconds to close the previous position and open a new one. With my script it doesn't happen because it opens the next one directly (from long to short or from short to long) without closing the previous position. I tried to adapt other scripts read here, but they don't work. Please help me.
delay_seconds = input(defval = 20, title = "Delay seconds")
var float entrytime = na //is used to store the time when it should buy
if (strategy.position_size == 0)
strategy.entry("Long", strategy.long, qty=Lev, when=enterlong, comment="buy GBPUSD Q=0.3 TP=0.6% SL=0.3% TT=0.3% TD=0.1% TS=0.05%")
else if strategy.position_size < 0
strategy.exit("close GBPUSD Q=100% Short TP SL", "Short", stop=slPriceS , limit=tpPriceS)
strategy.close("Short", when=shortcondexit, comment="close GBPUSD Q=100%" )
if (enterlong==true and na(entrytime))
entrytime := time + delay_seconds * 1000
enterlong:=false
if (time >= entrytime)
entrytime := na
enterlong:=true
strategy.entry("Long", strategy.long, qty=Lev, when=enterlong, comment="buy GBPUSD Q=0.3 TP=0.6% SL=0.3% TT=0.3% TD=0.1% TS=0.05%")
//alert("buy GBPUSD Q=100% TP=0.6% SL=0.3%", alert.freq_once_per_bar_close )
if (strategy.position_size == 0)
strategy.entry("Short", strategy.short, qty=Lev, when=entershort, comment="sell GBPUSD Q=0.3 TP=0.6% SL=0.3% TT=0.3% TD=0.1% TS=0.05%")
else if strategy.position_size > 0
strategy.exit("close GBPUSD Q=100% Long TP SL" , "Long", stop=slPrice ,limit=tpPrice)
strategy.close("Long", when=longcondexit, comment="close GBPUSD Q=100%" )
if (entershort==true and na(entrytime))
entrytime := time + delay_seconds * 1000
entershort:=false
if (time >= entrytime)
entrytime := na
entershort:=true
strategy.entry("Short", strategy.short, qty=Lev, when=entershort, comment="sell GBPUSD Q=0.3 TP=0.6% SL=0.3% TT=0.3% TD=0.1% TS=0.05%")