SMA Cross with a Price Filter
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Wormhole007


//@version=5
indicator("SMA Cross with a Filter", overlay=true)

// Input for the length of the SMA
smaLength = input(200, title="SMA Length")

// Input for the percentage threshold
threshold = input(3, title="Percentage Threshold")

// Calculate the 200-day SMA
sma200 = ta.sma(close, smaLength)


// Initialize variables
var bool lastBuySignal = na
var bool lastSellSignal = na

// Generate buy and sell signals
buySignal = ta.crossover(close, sma200 * (1 + threshold / 100)) and (na(lastSellSignal) or lastSellSignal)
sellSignal = ta.crossunder(close, sma200 * (1 - threshold / 100)) and (na(lastBuySignal) or lastBuySignal)

// Track the last buy and sell signals
lastBuySignal := buySignal ? true : (sellSignal ? false : lastBuySignal)
lastSellSignal := sellSignal ? true : (buySignal ? false : lastSellSignal)


// Plot arrows on the chart for entry and exit signals
plotshape(buySignal, title="ENTRY Signal", color=color.green, style=shape.triangleup, location = location.belowbar, size = size.small, text="ENTRY", textcolor = color.green)
plotshape(sellSignal, title="EXIT Signal", color=color.red, style=shape.triangledown, location = location.abovebar, size = size.small, text="EXIT", textcolor = color.red)


// Plot the specified SMA on the chart
plot(sma200, color=color.white, title="SMA")


