'Pinescript - How to close a stop entry if price hits stoploss before entry

I created a code that has long and short entries. It enters long on a specific candle with specific criteria with an entry stop above the high plus a few pips and a stoploss a few pips below the low. The opposite for a short entry.

I would like the code to close the entry if the stoploss is hit before entry. I am having trouble with this. Currently using: strategy.close("Open Long", when=close<=longstoploss)

But it's not working.

Any suggestions?

Code for entries below:

//Entry
inTrade = strategy.position_size > 0
notInTrade = strategy.position_size <= 0

goShort = shortwicktrigger and htf_srsiShort and notInTrade
goLong = longwicktrigger and htf_srsiLong and notInTrade

float longstoploss = na
float longtakeprofit = na
float shortstoploss = na
float shorttakeprofit = na
float longentry = na
float shortentry = na

currentclose = request.security(syminfo.tickerid, timeframe.period, close)



if goLong
    longentry := high + syminfo.mintick * 20
    longstoploss := low - syminfo.mintick * 50
    longtakeprofit := longentry + (longentry - longstoploss) 
    strategy.entry("Open Long",strategy.long, stop=longentry)
    strategy.exit("Exit Long", "Open Long", stop=longstoploss, limit=longtakeprofit)
    strategy.close("Open Long", when=close<=longstoploss)
    
plot(longentry, color=color.blue, style=plot.style_linebr, linewidth=2)
plot(longstoploss, color=color.red, style=plot.style_linebr, linewidth=2)
plot(longtakeprofit, color=color.green, style=plot.style_linebr, linewidth=2)



if goShort
    shortentry := low - syminfo.mintick * 20
    shortstoploss := high + syminfo.mintick * 50
    shorttakeprofit := shortentry - (shortstoploss - shortentry)
    
    strategy.entry("Open Short", strategy.short, stop=shortentry)
    strategy.exit("Exit Short", "Open Short", stop=shortstoploss, limit=shorttakeprofit)
    strategy.close("Open Short", when=close>=shortstoploss)
    
plot(shortentry, color=color.blue, style=plot.style_linebr, linewidth=2)
plot(shortstoploss, color=color.red, style=plot.style_linebr, linewidth=2)
plot(shorttakeprofit, color=color.green, style=plot.style_linebr, linewidth=2)


Sources

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

Source: Stack Overflow

Solution Source