This Pine Script is designed to visualize the crossover between two Simple Moving Averages (SMAs) on a chart: a fast SMA (9-period) and a slow SMA (20-period). The script will dynamically adjust the background color based on whether the fast SMA is above or below the slow SMA.
Key Components of the Script: Inputs for SMA Lengths:
The script allows you to adjust the lengths of the two SMAs by inputting values for smaFastLength (default = 9) and smaSlowLength (default = 20). These lengths define how many periods (candles) the SMAs consider when calculating the moving averages. SMA Calculations:
The script calculates two SMAs using the close price: smaFast is the 9-period SMA. smaSlow is the 20-period SMA. These are calculated using TradingView’s built-in ta.sma function, which computes the simple moving average for the given period.
Background Color Logic:
The background color is dynamically updated based on the crossover condition: Green background: When the fast SMA (smaFast) is above the slow SMA (smaSlow), indicating a bullish trend. Red background: When the fast SMA is below the slow SMA, indicating a bearish trend. The bgcolor function is used to change the background color on the chart. The transparency of the background color is set to 35% using color.new(color.green, 35) or color.new(color.red, 35). Plotting the SMAs:
The two SMAs are plotted on the chart for visual reference: The fast SMA is plotted in lime green (color.lime). The slow SMA is plotted in red (color.red).