TradingView indicators

Simple moving average on TradingView

A simple moving average (SMA) adds a fixed number of source values and divides by that number. Each value has equal weight. As a new observation arrives, the oldest leaves the window. The resulting line describes recent prices; it cannot tell you whether the next price will rise or fall.

SMA = (P₀ + P₁ + ... + Pₙ₋₁) / N

P₀ is the newest value. With five observations, each receives one fifth of the weight. In Pine Script, ta.sma handles the window and skips missing source values.

Inspect the SMA trend filter example

Simple moving average formula, one value at a time

Take five hypothetical closing prices in chronological order: 100, 102, 101, 105 and 107. Their sum is 515, so the five-period SMA is 103. The table shows each price's contribution to that result. These are illustrative numbers, not market data.

Five-period SMA: 20 + 20.4 + 20.2 + 21 + 21.4 = 103
ObservationCloseWeightContribution
Oldest1001/520.0
Second1021/520.4
Third1011/520.2
Fourth1051/521.0
Newest1071/521.4

If the next close is 110, remove 100 and add 110. The new window is 102, 101, 105, 107, 110: its sum is 525 and its SMA is 105. The update is also 103 + (110 − 100) / 5 = 105. Do not append the sixth value while keeping all five old values: that would change the window length.

This follows TradingView's SMA calculation. To enter your own values, use the moving average calculator.

The same length can describe different data

Length counts observations in the calculation timeframe. A 20-period SMA on a daily chart uses daily values; on a 15-minute chart it uses 15-minute values. Exchange closures and session settings mean 20 bars need not cover a fixed amount of elapsed calendar time.

Source determines which value each bar contributes. Close uses the closing price; hl2 averages high and low; hlc3 averages high, low and close. For a hypothetical bar with high 110, low 100 and close 108, these sources are 108, 105 and 106 respectively. Changing Source changes the entire input sequence. TradingView documents these series under chart information.

When two SMA lines disagree, match the symbol and exchange, timeframe, session, price adjustments, chart type, Source, Length and plot offset. Keep offset at zero when comparing a value with its own bar. Moving a plot horizontally does not provide earlier information.

Missing values change the span of the window

Pine Script's ta.sma ignores na values in its source. It collects the requested number of valid observations, which can span more chart bars than Length. Until enough valid values exist, the average is na. This matters for sparse external or conditional sources, even when ordinary chart prices are complete.

For the hypothetical source sequence 100, na, 102, 104 and Length 3, the last bar averages 100, 102 and 104 to get 102. It uses three values across four bars. Replacing na with zero would instead average 0, 102 and 104 at the last bar, giving about 68.67. Zero is a real input, not an empty value. See TradingView's conditional averages explanation.

Why the SMA lags, and what its slope actually measures

A new value contributes only 1/N of an N-period SMA. In a hypothetical five-period window of all 100s, one new close at 110 moves the average to 102. If every following close stays at 110, the SMA progresses through 104, 106, 108 and 110 as the old values leave. A longer window takes more observations to replace its history.

With a fixed length and no missing values, subtracting two adjacent window sums gives SMA[t] − SMA[t−1] = (source[t] − source[t−N]) / N. The SMA rises when the incoming value exceeds the departing value. It can therefore rise even if today's close is below yesterday's close. For example, a window of 90, 100, 105, 110, 112 averages 103.4; replacing 90 with 111 raises it to 107.6 despite the latest price falling from 112 to 111.

Equal weights describe a different response from the EMA or WMA. There is no universal number of bars of entry delay, and a smoother line does not establish a trading advantage.

A confirmed-bar SMA trend filter in Pine Script

This illustrative filter passes when the bar is closed, the chosen source is above its SMA, and the SMA is above its value on the previous bar. With the default Source of close, it means the close is above a rising average. The green background marks every passing bar; it is not an entry order or a one-time crossover signal.

Pine Script v6
//@version=6
indicator("SMA trend filter example", overlay=true)

length = input.int(20, "Length", minval=1)
source = input.source(close, "Source")
smaValue = ta.sma(source, length)

isReady = not na(source) and not na(smaValue) and not na(smaValue[1])
longFilter = barstate.isconfirmed and isReady and source > smaValue and smaValue > smaValue[1]

plot(smaValue, "SMA", color=color.blue, linewidth=2)
bgcolor(longFilter ? color.new(color.green, 88) : na, title="Long filter passes")

The average is calculated on every bar. Its previous value is needed to compare slope, so a complete source needs N + 1 bars before the filter can pass. Missing source values or a missing previous average keep it false. The ta.sma reference covers the function's API.

On an open bar, close is the latest price and the SMA line can move. The background waits for barstate.isconfirmed. That adds a wait until the bar closes; it does not make a price source immune to revisions. This example uses the chart timeframe and makes no higher-timeframe data requests.

In a range, the filter may alternate repeatedly. After a sudden reversal, it may remain true until price and the average catch up. It specifies no exit, position size, fees or order timing. Any strategy built around it needs those rules and separate testing, including periods when the filter excludes profitable trades or permits losing ones.

Check the example on TradingView

  1. Open Pine Editor, paste the script into a new indicator, save it and add it to the chart.
  2. Set Length and Source explicitly. Start with standard candles and the chart timeframe you intend to study.
  3. Compare closed bars with a built-in SMA using the same inputs and zero offset. Turn off any additional smoothing line when making that comparison.
  4. Inspect a few passing and failing bars in the Data Window: compare the source, current SMA and previous SMA. Then observe an open bar to distinguish the moving line from the confirmed filter.

Build your SMA condition in Pineify

Pineify's Visual Editor includes SMA with Source and Length inputs. AI Coding Agent can draft or revise a script from a description. Specify the source, length, timeframe, comparison and bar-close rule so the generated condition is something you can inspect.

Create an indicator with a 20-period SMA of close on the chart timeframe. Highlight closed bars where close is above the SMA and the SMA is higher than on the previous bar. Make Length and Source adjustable. Do not place orders.

This is an example request. Review generated code and compare it with chart values before extending it into a strategy.

Frequently asked questions

What is a simple moving average?

A simple moving average (SMA) is the arithmetic mean of a chosen number of observations. Each has equal weight. A 20-period SMA of close on a daily chart averages 20 daily closing values when the source has no missing values.

What is the simple moving average formula?

Add the latest N source values and divide by N. For the hypothetical sequence 100, 102, 101, 105, 107, the five-period SMA is 515 / 5 = 103. Each observation contributes 20% of the result.

How does ta.sma handle missing values?

Pine Script ta.sma ignores na values in its source and uses the requested number of non-na observations. A length of 5 can therefore span more than five chart bars. Before enough valid observations exist, the result is na. Replacing missing prices with zero changes the average and is usually a different calculation.

Does SMA repaint?

An SMA using close can change during the open bar as that price changes. The example waits for barstate.isconfirmed before showing its filter, but the SMA line still updates during the bar. This does not protect against revisions to historical data or changes in an external source.

Is SMA always slower than EMA?

EMA gives the newest observation more weight at the same length greater than one, so its initial response to a price jump is larger. SMA drops observations completely once they leave its window; EMA retains a decaying influence. Their full response depends on the sequence, so there is no fixed number of bars by which EMA always leads SMA.

What are the best SMA settings on TradingView?

There is no universal best length. Choose the observation horizon you want to describe and test any trading rule separately. The example starts at 20, matching Pineify's SMA configuration. TradingView's built-in SMA help page lists a default of 9. Always inspect the actual Length, Source, timeframe and offset.

Can Pineify create an SMA condition?

Yes. Visual Editor includes SMA with adjustable Source and Length inputs. You can also ask AI Coding Agent to draft or revise an SMA script. Specify the comparison, timeframe and confirmation rule, then inspect the result on TradingView before using it in a strategy.

Sources and scope

Official documentation checked October 16, 2026. Arithmetic examples are hypothetical and calculated from the values shown. This material is educational, not investment advice; an SMA condition does not establish profitability.