Search code examples
pine-scripttradingalgorithmic-tradingpine-script-v5pine-script-v4

Stop Loss and revers positions in the strategy


I would like my Stop loss reverse my position. Is it possible to do? When SL Long go to Short and when SL Short go to Long. I was looking for a solution, but unfortunately I did not find it. Thank You!

strategy.entry('Long', strategy.long, when=long, comment='Long',alert_message = message_long_entry)
strategy.exit( "SL","Long", loss=8700, comment = "SL Long",alert_message = message_long_exit)
strategy.entry('Short', strategy.short, when=short, comment='Short',alert_message = message_short_entry)
strategy.exit( "SL","Short", loss=14700, comment = "SL Short",alert_message = message_short_exit)

Solution

  • Keep your stop-loss conditions (in case you have or do as follows) but use only strategy.entry().
    strategy.entry in the counter direction (short->long | long->short) automatically closes your positions (disregarding position size) and additionally opens the positions you want.

    isLong = strategy.opentrades.size > 0
    isShort = strategy.opentrades.size < 0
    if isLong and strategy.opentrades.entry_price * 0.95 >= close // 5% stop-loss
        strategy.entry('Reverse short', strategy.short, ...)
    
    if isShort and strategy.opentrades.entry_price * 1.05 <= close // 5% stop-loss
        strategy.entry('Reverse long', strategy.long, ...)