Search code examples
positionpine-scriptlong-integerloss

Multiple long orders with separate take profit and stop loss


A bit new with coding. Hope to find some help.

I am trying to get each long position to have its own take profit and stop loss. What ends up happening is, whenever the next long position is triggered, the previous TP and SL get recalculated and I end up with all positions having only one TP and SL levels. Thanks Played around with exit code and lastEntryPriceLong but not a big coder, soo... any help would be appreciated.

//////// Long Position 0 (1) ////////

if longCondition and longConditionATR and longConditionEMA and barRangeCondition and strategy.opentrades == 0
    strategy.entry('Long', strategy.long)

lastEntryPriceLong = strategy.opentrades.entry_price(0)

var float LongTP = na
var float LongSL = na

if (strategy.position_size[1] != strategy.position_size)
    LongTP := lastEntryPriceLong*2 - low[1]
    LongSL := lastEntryPriceLong - (lastEntryPriceLong - low[1] + atr*2)

inTradeLong = strategy.position_size > 0

plot(inTradeLong ? LongTP : na, color=color.green, style=plot.style_circles)
plot(inTradeLong ? LongSL : na, color=color.red, style=plot.style_circles)

strategy.exit('Close Long', 'Long', stop=LongSL, limit=LongTP)


//////// Long Position 1 (2) ////////

if longCondition and longConditionATR and longConditionEMA and barRangeCondition and strategy.opentrades == 1
    strategy.entry('Long1', strategy.long)

lastEntryPriceLong1 = strategy.opentrades.entry_price(1)

var float LongTP1 = na
var float LongSL1 = na

if (strategy.position_size[1] != strategy.position_size)
    LongTP1 := lastEntryPriceLong1*2 - low[1]
    LongSL1 := lastEntryPriceLong1 - (lastEntryPriceLong1 - low[1] + atr*2)

inTradeLong1 = strategy.position_size > 0

plot(inTradeLong1 ? LongTP1 : na, color=color.green, style=plot.style_circles)
plot(inTradeLong1 ? LongSL1 : na, color=color.red, style=plot.style_circles)

strategy.exit('Close Long1', 'Long1', stop=LongSL1, limit=LongTP1)

You can see Example here

Thanks

.


Solution

  • strategy.exit is in the root scope. So, it gets executed on each bar overwriting earlier entry.

    You need to do few things here:

    1. Move strategy.exit and the related calculations inside if condition where you have strategy.entry. This way, exit and entry are set together.

    2. Use an auto incrementing Id instead of same id for all. You can do it using

    var id= 1
    if(longCondition)
      entryId = Long+str.tostring(id)
      exitId = ExitLong+str.tostring(id)
      id+=1
      strategy.entry(entryId, strategy.long, ...)
      strategy.exit(exitId, entryId, ...)
    
    1. In strategy definition, set close_entry_rule to ANY. This will let each trade track it's own exit based on id instead of closing order based on FIFO or FILO. https://www.tradingview.com/pine-script-reference/v5/#fun_strategy