'How to close a position when bar opens in PineScript

Anyone knows if one is able to close a position when a bar opens, if such bar meets a certain condition ?

I am trying to close trades at the opening bar of a new trading session if such bar is a gap

I wrote the following code to identify first bar

t = time("1440", session.regular) // 
is_first = na(t[1]) and not na(t) or t[1] < t 

Then to identify a Gap

longGap = open > close[1]
shortGap = open < close[1]

Exit Code

if strategy.position_size > 0 and is_first 
    strategy.close("LONG", when = longGap, comment = "close long open Gap")
if strategy.position_size < 0 and is_first 
    strategy.close("SHORT", when = shortGap, comment = "close short open Gap")

Ideally I would like for the trade to close right at the open if such condition is true but it waits for the candle to close and closes the trade on next open bar EVEN if I set calc_on_every_tick=true



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source