amibroker
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © doppelgunner

//@version=5

// @description This library consists of functions from amibroker that doesn't exist on tradingview pinescript. The example of these are the ExRem and Flip.
// In the example below, I used ExRem to remove the excessive buy and sell signals. Meanwhile, I used the Flip to highlight the bg color when there is an open position.
library("amibroker", overlay=true)

// @function Removes excessive signals. Pinescript version of ExRem in Amibroker (http://www.amibroker.com/guide/afl/exrem.html)
// @param series1 boolean
// @param series2 boolean
// @returns boolean
export exrem(bool series1, bool series2) =>
    result = false
    series1_index = ta.valuewhen(series1 == true, bar_index, 1)
    series2_index = ta.valuewhen(series2 == true, bar_index, 0)
    
    series1_current_index = ta.valuewhen(series1 == true, bar_index, 0)
    if (series1 and series2_index > series1_index) or (series1 and not na(series1_current_index) and na(series1_index))
        result := true
    result
    
// @function works as a flip/flop device or "latch". Pinescript version of Flip in Amibroker: (https://www.amibroker.com/guide/afl/flip.html)
// @param series1 boolan
// @param series2 boolean
// @returns boolean.
export flip(bool series1, bool series2) =>
	result = series1
    series1_index = ta.valuewhen(series1, bar_index, 0)
    series2_index = ta.valuewhen(series2, bar_index, 0)
    if (series1_index > series2_index)
        result := true
    result
    
buy = close >= ta.highest(close, 50)
sell = close <= ta.lowest(close, 50)

buy := exrem(buy, sell)
sell := exrem(sell, buy)

var hasPosition = false
hasPosition := flip(buy, sell)
bgcolor(hasPosition ? color.new(color.green, 90) : na)

plotshape(buy, "Buy", color=color.green, textcolor=color.white, text="Buy", location=location.belowbar, style=shape.labelup)
plotshape(sell, "Sell", color=color.red, textcolor=color.white, text="Sell", location=location.abovebar, style=shape.labeldown)