The issue is pretty straightforward. The labels 'BUY' and 'SELL' are not always displayed, because of enterLong and enterShort and more specifically not inTrade in their conditions. It's because sometimes the exit becomes an entry.
The whole point is to simulate a strategy (the following), but in an indicator. LucF helped me about that back in the time in this question, so you can use the example there as a reference.
FLAT = strategy.position_size == 0
LONG = strategy.position_size > 0
SHORT = strategy.position_size < 0
entry = strategy.position_avg_price
Snippet
//@version=4
study("not in a trade - StackOverflow issue", overlay = true, precision = 6)
// —————————— Constants {
// ————— Input options
var string TD1 = "Both"
var string TD2 = "Longs Only"
var string TD3 = "Shorts Only"
// }
// —————————— Inputs {
// ————— Entries
var string GP1 = "Entries"
string i_tradeDirection = input(TD1, "Trade Direction", options = [TD1, TD2, TD3], group = GP1)
// ————— User-selected trade directions
var bool doLongs = (i_tradeDirection == TD2 or i_tradeDirection == TD1)
var bool doShorts = (i_tradeDirection == TD3 or i_tradeDirection == TD1)
// }
// —————————— Calculations {
ema = ema(close, 200)
// }
// —————————— Strategy Calculations {
// ————— States
var float entryPrice = na
var bool inLong = false
var bool inShort = false
bool inTrade = inLong or inShort
// ————— Conditions
a = close > ema
enterLongCondition = not a[1] and a
enterShortCondition = a[1] and not a
exitLongCondition = enterShortCondition
exitShortCondition = enterLongCondition
// ————— Filter
filterLong = true
filterShort = true
// ————— Entries
enterLong = doLongs and not inTrade and enterLongCondition
enterShort = doShorts and not inTrade and enterShortCondition
// ————— Stops
atr = atr(14)
stopLong = min(lowest(5), min(close, open) - atr * 1.5)
stopShort = max(highest(5), max(close, open) + atr * 1.5)
// ————— Exits
exitLong = inLong and (exitLongCondition or close < stopLong[1])
exitShort = inShort and (exitShortCondition or close > stopShort[1])
// ————— States continuation
// plotchar(enterShort, color = color.yellow)
// plotchar(exitShort, color = color.yellow)
// plotchar(enterLong, color = color.green)
// plotchar(exitLong, color = color.green)
if enterLong
inLong := true
entryPrice := close
else if enterShort
inShort := true
entryPrice := close
else if exitLong
inLong := false
entryPrice := na
else if exitShort
inShort := false
entryPrice := na
// }
// —————————— Plots {
color colorBar = close > ema ? color.green : color.red
plot(ema, "EMA", color = colorBar, linewidth = 2, style = plot.style_circles)
// ————— Shapes
plotshape(enterLong, style = shape.labelup, location = location.belowbar, color = color.new(color.green, 20), text = "BUY", textcolor = color.white, size = size.normal)
plotshape(enterShort, style = shape.labeldown, location = location.abovebar, color = color.new(color.red, 20), text = "SELL", textcolor = color.white, size = size.normal)
// }
