egshih
Pine Script Rookie
Pine Script Rookie
Posts: 1
Joined: November 6th, 2020

Help with Script If User Input Moving Average

Hi Everyone,

Do you know where I am going wrong with my script? I keep getting an error around line 29 for undeclared identifier for the fullK. Big picture, I am trying to get the user to select a simple moving average or an exponential average, and I am trying to have the script do different calculations depending if this an EMA or SMA, but for some reason, when I go back and try to plot this to see where I am going wrong, its like the If statement is not picking up the fullK identifier.

Code: Select all

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

//@version=4
study(title="ElasticStochastic Lower",overlay=false)


over_bought = input(defval=80,title="OverBought")
over_sold = input(defval=20,title="OverSold")
KPeriod = input(title="KPeriod",defval=5)
DPeriod = input(title="DPeriod",defval=3)
slowing_period = input(title="Slowing Period",defval=2)
smoothingType =input(title="AverageType",defval="SMA",options=["SMA","EMA"])

priceH = high
priceL = low
priceC = close
lowest_k = lowest(priceL, KPeriod)
c1 = priceC - lowest_k
c2 = highest(priceH, KPeriod) - lowest_k
FastK = c2 != 0 ? c1 / c2 * 100 : 0

if smoothingType == "SMA" 
    fullk = sma(FastK, slowing_period)
else
    na
plot(fullk)

User avatar
Matthew
Site Admin
Site Admin
Posts: 92
Joined: July 1st, 2020
Location: Australia
Contact: Website Facebook Twitter TradingView Profile

Re: Help with Script If User Input Moving Average

Hi egshih!

The problem is that you can't declare a variable within the scope of an "if" statement. Any variables declared within an "if" block are only accessible within that block.

What you need to do is declare "fullk" before the if statement and then reassign it, like this:

Code: Select all

fullk = 0.0

if smoothingType == "SMA" 
    fullk := sma(FastK, slowing_period)
else
    fullk := na
plot(fullk)
Hope that helps :)

Return to “Pine Script Q&A”