Search code examples
pine-scriptpine-script-v4back-testing

Pine script close trade after certain time


if we want to test a strategy that keeps a trade open for a particular time, how do we code that in pinescript?

Eg:

strategy(" test ")

long = .....
short = .....

strategy.entry("Long", strategy.long, 1, when = long)
strategy.entry("Short", strategy.short, 1, when = short)

strategy.close("Long", when = ?) // ** close long after 5 mins of entry ** //
strategy.close("Short", when = ?) // ** close long after 5 mins of entry ** //

Solution

  • You can do that with ta.barssince(), then convert it to minutes if you want.

    bars_since_long = ta.barssince(long)
    
    x = 5  // Close after 5 bars
    
    if (bars_since_long > x)
        strategy.close("Long")
    

    My code is for v5. Try using barssince() without the ta. namespace, if needed.