Search code examples
pine-scripttradingview-api

Pinescript Indicator not Displaying on Chart


Trying to make a moving average sensitive to volatility. You should be able to get the main idea from the code, it is very understandable. Problem is, the chart is not showing. When I switch ta.sma(close, adjusted_SMA_period) to ta.sma(close, 1) or any number, it works. And I've also checked with labels that adjusted_SMA_period is always a positive integer. And worse yet, there are no errors, it just does not show up whatsoever. This is very frustrating. Here is the code:

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © isaiahhoussou

//@version=5
indicator("Volatility Adjusted Simple Moving Average", overlay=true)

base_SMA_period = input(26, "Base Period")

current_ATR_period = input(10, "Current ATR Period")
average_ATR_period = input(50, "Average ATR Period")

volatility_ratio = ta.atr(current_ATR_period) / ta.atr(average_ATR_period)

adjusted_SMA_period = math.max(1, math.round(base_SMA_period / volatility_ratio))

VASMA = ta.sma(close, adjusted_SMA_period)

plot(VASMA)

I haven't been able to try much, as it is impossible to tell what is going on. Switching the period of the ta.sma function gives a result, though.


Solution

  • The built-in function for the SMA in Pine Script does not accept a changing value. Instead, use the equivalent function for SMA as mentioned in the reference manual:

    pine_sma(src, period) =>
        sum = 0.0
        for i = 0 to period - 1
            sum := sum + src[i] / period
    
    VASMA = pine_sma(close, adjusted_SMA_period)
    

    It should then plot without issues.

    By the way, if an indicator is not showing up despite there being no errors in the console, check next to the indicator on the chart. The error sometimes shows up there. I have attached an image for yours. Error on Chart