004 — Inputs and moving averages
Inputs let users change a script from its settings without editing the source code.
Complete script
Section titled “Complete script”//@version=6indicator("Configurable Moving Average", overlay = true)
int length = input.int(20, "Length", minval = 1)float source = input.source(close, "Source")color lineColor = input.color(color.blue, "Line color")
float average = ta.sma(source, length)
plot(average, "SMA", color = lineColor, linewidth = 2)Integer input
Section titled “Integer input”int length = input.int(20, "Length", minval = 1)20is the default value."Length"is the label in the Inputs tab.minval = 1prevents zero or negative lengths.
Source input
Section titled “Source input”float source = input.source(close, "Source")The default source is close. The user can change it to values such as open, high, low, hl2, hlc3, or another compatible plotted series.
Color input
Section titled “Color input”color lineColor = input.color(color.blue, "Line color")This adds a color picker to the script’s settings.
Calculate the average
Section titled “Calculate the average”float average = ta.sma(source, length)ta.sma() is in the ta namespace, which contains technical-analysis functions. It calculates the arithmetic mean of the selected source over the chosen number of bars.
For a three-bar SMA:
SMA = (current value + previous value + value two bars ago) / 3Why inputs matter
Section titled “Why inputs matter”Hard-coded values are useful while experimenting, but inputs make a script reusable. One script can support many symbols and timeframes without changing its code.