'Avoiding reentry into positions of the same direction

Hello I am new to pine script and I am testing a strategy that has different entry conditions and exit conditions. The problem I am having is when an exit occurs, the entry conditions could still be met and is reentering into the same position as before. I never want to enter the same direction position, ie if I close a long I do not want to reenter a long again until I have encountered a short. Is there any way to ask the script to check if the last entered position was a long, to not enter into a long again unless a short has occurred first?



Solution 1:[1]

When your entry conditions are met and supplied to the strategy.entry() function, additionally set a persistent variable. For example:

var bool lastTradeLong = na
long = crossover(a,b)
long_entry = long and (na(lastTradeLong) or not lastTradeLong)
if long_entry
    lastTradeLong := true
strategy.entry('Long', strategy.long, when=long_entry)

And set the reverse for short, so enter when your short conditions are true, and lastTradeLong is either na or true, and then when that combination happens and the trade enters, set lastTradeLong to false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bajaco