'Alert IF condition flow not right

I am struggling to find the right IF condition to trigger an alert. The idea is that the current active price (close) value go past the long or short points it must trigger the respective alert. Preferably, e.g. only one sell when it passes the sell_level. If it passes the buy_level, in the same realtime bar, then trigger the buy. If the current price go past the sell_level again, in the same bar, after a buy, then it should trigger a new sell alert.

I have played around with many options but just can't get it right. This is my code:

// goto SELL
if low < sell_price
    buy := false
    sell := true
// goto BUY
else if high > buy_price
    buy := true
    sell := false

if close > buy_level
    alert('buy: ' + 'price=' + str.tostring(sell_level), alert.freq_all)
else if close < sell_level
    alert('sell: ' + 'price=' + str.tostring(buy_level), alert.freq_all)

[Basic Flow example][1] [1]: https://i.stack.imgur.com/ycUZ3.jpg

Edit 1: amended code

// buy only if buy_sig triggered and not already long
buySig = actSell and not isLong

// sell only if sell_sig triggered and not already short
sellSig = actBuy and not isShort

if buySig
    isLong := true
    isShort := false
    alert('buy: ' + 'price=' + str.tostring(sell_level), alert.freq_all)

if sellSig
    isLong := false
    isShort := true
    alert('sell: ' + 'price=' + str.tostring(buy_level), alert.freq_all)

plotshape(series = buySig, text = "BuySig", style = shape.triangleup, location = location.belowbar, color = color.green, size = size.large)

plotshape(series = sellSig, text = "SellSig", style = shape.triangledown, location = location.abovebar, color = color.red, size = size.large)

Edit 2: varip

// see if long
varip bool isLong = false

// see if short
varip bool isShort = false

bool buySig = false
bool sellSig = false

// buy only if buy_sig triggered and not already long
buySig := not isLong and Buy

// sell only if sell_sig triggered and not already short
sellSig := not isShort and Sell

// alert conditions
if buySig
    if isLong == true
        isLong := false
    else
        isLong := true
    isShort := false
    alert('BUY price: ' + str.tostring(sell_level), alert.freq_all)
else if sellSig
    isLong := false
    if isShort == true
        isShort := false
    else
        isShort := true
    alert('SELL price: ' + str.tostring(buy_level), alert.freq_all)


Sources

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

Source: Stack Overflow

Solution Source