kaustubh natu
kaustubh natu

Reputation: 1

I am facing a problem with (strategy.exit) in pine script. it is working for the long call but not working for short calls

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


//Figure out take profit and stop loss price
longExitPrice  = strategy.position_avg_price * (1 + longProfitPerc ) // longProfitPerc=1.5 
longStopPrice = strategy.position_avg_price * (1 - longStopPerc ) // longStopPerc=1
shortExitPrice = strategy.position_avg_price * (1 + shortProfitPerc ) //shortProfitPerc=1.5
shortStopPrice = strategy.position_avg_price * (1 - shortStopPerc ) //shortStopPerc=1



if GL1 and GL2 == 1 and GL3 == 1 and GL4 == 1 and GL5 == 1 and notInTrade //GL1 TO GL5 ARE CONDITIONS
    strategy.entry("long_Entry", strategy.long)

if inTrade
    strategy.exit("Long_Exit", 'long_Entry', limit=longExitPrice, loss=longStopPrice)


if GS1 and GS2 == 0 and GS3 == 0 and GS4 == 0 and GS5 == 0 and notInTrade //GS1 TO GS5 ARE CONDITIONS
    strategy.entry("short_Entry", strategy.short)


if inTrade
    strategy.exit("Short_Exit", 'short_Entry', limit=shortExitPrice, loss=shortStopPrice)


in the case of long calls strategy.exit closes the call either when tp or sl percentages are achieved. but Short calls are only closed by Long calls, short calls continue till a new long is generated and only then close. they close with high profit or loss and not being triggered by the tp or enter image description heresl set in the code

Upvotes: 0

Views: 263

Answers (1)

vitruvius
vitruvius

Reputation: 21342

Your inTrade will only indicate if you are in a long position. That is because strategy.position_size will return > 0 when the market position is long and < 0 when the position is short.

Secondly, your short exit calculations are wrong. It looks like you copied the calculations for the long position but it should be the opposite.

Correct declarations should be as below:

inTrade = strategy.position_size != 0
inLongTrade = strategy.position_size > 0
inShortTrade = strategy.position_size < 0
notInTrade = strategy.position_size == 0

shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc ) //shortProfitPerc=1.5
shortStopPrice = strategy.position_avg_price * (1 + shortStopPerc ) //shortStopPerc=1

if inLongTrade
    strategy.exit("Long_Exit", 'long_Entry', limit=longExitPrice, loss=longStopPrice)

if inShortTrade
    strategy.exit("Short_Exit", 'short_Entry', limit=shortExitPrice, loss=shortStopPrice)

Upvotes: 0

Related Questions