1
votes

i've this basic strategy on pinescript that enter a position based on the crossover of 2 moving averages. what i would do is this: when the cross occurs enter a long/short (weather on is a bull or bear cross) exit the position 3 candles later. i've tried with the function 'barssince' but i'm not very good at coding. this is my strategy:

strategy("MovingAvg2Line Cross", overlay=true, initial_capital=10000)
fastLength = input(50)
slowLength = input(200)
price = close

mafast = sma(price, fastLength)
maslow = sma(price, slowLength)

if (crossover(mafast, maslow))
    strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE")

if (crossunder(mafast, maslow))
    strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") ```
1

1 Answers

1
votes

Add this at the end. It detects changes in the number of open trades and counts bars from then:

strategy.close_all(when = barssince(change(strategy.opentrades)) == 2)