0

I am trying to add to a strategy, something very simple - to sell after X amount of bars when the trigger has been reached. I tried this code recommended online, but it doesn't seem to work:

if sellFb == true and buyFb == false
    strategy.entry("BreakDown", strategy.short, comment="Short")  

if buyFb == true and sellFb == false
    strategy.entry("BreakUp", strategy.long, comment="Buy")



if sellFb or buyFb
    alert(txt, alert.freq_once_per_bar_close)
    n = 4
    open_idx = strategy.opentrades.entry_bar_index(strategy.opentrades-1)
    diff_idx = bar_index - open_idx

    if (diff_idx >= n)
        strategy.close("BreakUp")
        strategy.close("BreakDown")

It doesn't close the strategy after the bars, only closes it when the next opposite direction trade comes (short/buy)

makat
  • 154
  • 1
  • 3
  • 14

1 Answers1

1

That's because you only execute that piece of code if sellFb or buyFb is true.

Instead, you should be checking for that in the global scope.

if sellFb == true and buyFb == false
    strategy.entry("BreakDown", strategy.short, comment="Short")  

if buyFb == true and sellFb == false
    strategy.entry("BreakUp", strategy.long, comment="Buy")  

if sellFb or buyFb
    alert(txt, alert.freq_once_per_bar_close)

n = 4
open_idx = strategy.opentrades.entry_bar_index(strategy.opentrades-1)
diff_idx = bar_index - open_idx

if (diff_idx >= n)
    strategy.close("BreakUp")
    strategy.close("BreakDown")
vitruvius
  • 15,740
  • 3
  • 16
  • 26