Page 1 of 1

Help with Script If User Input Moving Average

Posted: Fri Nov 06, 2020 6:33 pm
by egshih
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)

Re: Help with Script If User Input Moving Average

Posted: Thu Nov 12, 2020 1:44 am
by Matthew
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 :)