'PineScript / Trading View: How to check for openorders in strategy

pma = sma(maSource, periods)
entryLong = close * 1.10
longCondition = close >= pma

if longCondition
   strategy.entry(id = "Long Entry", long = true, stop = entryLong)

Several bars can meet this longCondition in a row, but I don't want subsequent bars to over-write the previous ones. Ideally I'd like to add a check to see if strategy.openentries == 0 , but of course such a variable doesn't exist in Tradingview.

Would like to do something like this:

pma = sma(maSource, periods)
entryLong = close * 1.10
longCondition = close >= pma

if longCondition and strategy.openorders == 0
   strategy.entry(id = "Long Entry", long = true, stop = entryLong)

if barssince(longCondition) = 3
   strategy.cancel(id = "Long Entry")


Solution 1:[1]

You can check if the condition was true on previous bar and ignore the current one. So the consecutive occurrences would be ignored.

pma = sma(close, 10)
entryLong = close * 1.10
longCondition = close >= pma
long = longCondition and not nz(longCondition[1])

// debug
bgcolor(longCondition ? color.green : na)
bgcolor(long ? color.blue : na)

You can also use the built-in strategy.position_size function.

strategy.position_size > 0  // long is opened.
strategy.position_size < 0  // short is opened.
strategy.position_size == 0  // no opened positions

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