Parabolic1
Parabolic1

Reputation: 17

Stop function on Pine Strategy not working?

I'm using stop in lieu of loss on my strategy exit and for some reason it is not triggering when hit, whether Long or Short. On the other hand, the limit price I'm using in place of profit is triggering when hit sometimes and other times not. I would imagine the cause behind both issues is similar. Code is as follows:

entry = strategy.position_avg_price
shortTPPrice = entry - 0.004
shortSLPrice = entry + 0.003
shortCondition = short
if shortCondition
    strategy.entry  (id="Short", long=false, comment="Short")
    strategy.exit   (id="Short Exit", stop=shortSLPrice, limit=shortTPPrice)

Update1: Bjorgum's answer fixed most of the cases, but there are still some unsolved ones. I added a screenshot of one example that should have stopped out on the entry candle and didn't exit until awhile later when price crossed the TP line for the 3rd time. It seems the second signal in the screenshot added a TP/SL where they were missing on the first signal and that's why it exited where it did. But, I still don't understand why it didn't exit on the entry candle.screenshot

Update2: While I'm not sure what the cause of the above issue was, I managed to fix it along with other similar cases by adding:

if strategy.position_size < 0
    strategy.exit   (id="Short Exit", stop=shortSLPrice, limit=shortTPPrice)

Upvotes: 0

Views: 802

Answers (1)

Bjorgum
Bjorgum

Reputation: 2310

By placing the exit under the local scope of the if statement, we are hiding the exit to only trigger if our short condition is met, not when stops are hit etc. So we can move it back to the margin and introduce the "when" parameter here to set the stops when we are in a short trade.

entry = strategy.position_avg_price
shortTPPrice = entry - 0.004
shortSLPrice = entry + 0.003
shortCondition = short
if shortCondition
    strategy.entry  (id="Short", long=false, comment="Short")
    
strategy.exit   (id="Short Exit", stop=shortSLPrice, limit=shortTPPrice, when=strategy.position_size < 0)

Upvotes: 1

Related Questions