Simple Moving Average Pine Script — Complete TradingView Guide
The Simple Moving Average (SMA) is a trend-following indicator built into Pine Script v6 via ta.sma(source, length). The SMA calculates the arithmetic mean of price over a fixed number of bars, giving equal weight to every bar in the lookback window — making it the smoothest and most lag-consistent moving average available in TradingView. The SMA default period of 20 bars is the most common starting point, with 50 and 200 used as key institutional trend-filter levels. This guide covers the complete Pine Script v6 implementation using ta.sma(), all configurable parameters with recommended ranges, three concrete SMA trading strategies including the Golden Cross, plus a five-step guide to generating SMA scripts instantly with Pineify.
What Is the Simple Moving Average?
The Simple Moving Average is a trend-following overlay indicator that calculates the arithmetic mean of closing prices over a fixed lookback period, used to identify trend direction, dynamic support/resistance, and crossover trading signals. Unlike the Exponential Moving Average (EMA), which applies exponential weighting to recent bars, the SMA treats every bar in the lookback window equally — making it the most mathematically straightforward moving average and the least sensitive to short-term price spikes.
The SMA is one of the oldest indicators in technical analysis, with roots tracing back to the early 20th century. Richard Donchian, widely credited as the father of trend following, popularized moving average systems in the 1940s and 1950s. Later, Joseph Granville in 1963 formalized the use of the 200-day SMA as a bull/bear market dividing line in his book Granville's New Key to Stock Market Profits — a standard that institutional traders still follow today. The 50-day SMA became a companion indicator, forming the famous Golden Cross (SMA 50 crosses above SMA 200) and Death Cross (SMA 50 crosses below SMA 200) signals.
Core formula: SMA = (P₁ + P₂ + … + Pₙ) ÷ n, where n is the period length and P₁ through Pₙ are the most recent n closing prices. For a 20-period SMA, the indicator sums the last 20 closes and divides by 20. Each new bar adds the latest close and removes the oldest. In Pine Script v6, the entire calculation is handled by ta.sma(close, 20).
The SMA applies to all liquid asset classes: stocks, crypto, forex, and futures. It performs best in trending markets — the lagging nature of the SMA acts as a noise filter, confirming established trend direction rather than chasing short-term movements. Best timeframes are 1H charts and above — daily and weekly SMA 200 lines are the most widely cited levels across all market participants. On sub-hourly charts (5m, 15m), the SMA 20 can still serve as a dynamic support/resistance guide, but generates more false signals due to noise.
Best Markets
Stocks · Crypto · Forex · Futures
Best Timeframes
1H, 4H, Daily, Weekly
Overlay
Yes — plots directly on price chart
SMA Pine Script Code Example
The code below plots a 20-period SMA as a blue line overlaid on the price chart using Pine Script v6. To add it to TradingView, open the Pine Script editor with Alt+P, paste the code, and click Add to chart. Change the 20 in ta.sma(close, 20) to any period that suits your trading style — common choices are 10, 20, 50, and 200.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify
//@version=6
indicator(title="Simple Moving Average", overlay=true, max_labels_count=500)
// SMA — calculates the arithmetic mean of price over the given period
p_ind_1 = ta.sma(close, 20) // SMA with default period 20
// Plot the SMA line on the price chart
plot(p_ind_1, "SMA", color.rgb(41, 98, 255, 0), 1)Chart Preview

SMA Parameters
| Parameter | Default Value | Description | Recommended Range |
|---|---|---|---|
| source | close | The price series to average. Most commonly close, but can be open, high, hl2 (high+low)/2, or any numeric series. | Any numeric series |
| length | 20 | Number of bars included in the average. Controls how much historical data is averaged. Larger values produce a smoother, slower-reacting line with more lag; smaller values react faster with more noise. | 10–200 depending on style |
Tuning Guide by Trading Style
- Scalping (5m–15m charts): SMA 10–20 — fast average for short-term price mean; expect more noise
- Day trading (15m–1H charts): SMA 20 + SMA 50 — identify intraday trend and pullback levels
- Swing trading (4H–Daily charts): SMA 50 — mid-term trend gauge, widely watched by swing traders
- Position/Macro (Daily–Weekly charts): SMA 200 — the most-followed institutional trend filter across stocks, crypto, and forex
SMA Trading Strategies
The SMA is most effective as a trend direction filter and support/resistance level. Below are three concrete strategies with specific entry and exit conditions.
Strategy 1 — Golden Cross / Death Cross (SMA 50/200)
Market environment: macro trending markets · Best timeframe: Daily, Weekly
The Golden Cross (SMA 50 crossing above SMA 200) is the most widely followed long-term bullish signal in technical analysis, used across stocks, crypto, and forex. In Pine Script: ta.crossover(ta.sma(close, 50), ta.sma(close, 200)) detects the Golden Cross.
- Calculate slow SMA:
sma200 = ta.sma(close, 200) - Calculate fast SMA:
sma50 = ta.sma(close, 50) - Long entry (Golden Cross):
ta.crossover(sma50, sma200)— SMA 50 crosses above SMA 200 - Confirm price is above both SMAs (avoid false signals during sideways consolidation)
- Exit (Death Cross):
ta.crossunder(sma50, sma200)— SMA 50 crosses below SMA 200
Strategy 2 — SMA 200 Trend Filter + SMA 20 Pullback Entry
Market environment: trending bull markets · Best timeframe: Daily
The SMA 200 on the daily chart defines the macro trend. Price above SMA 200 signals a bull market; pullbacks to the SMA 20 offer lower-risk long entries within the primary uptrend without chasing extended moves.
- Calculate macro filter:
sma200 = ta.sma(close, 200) - Calculate pullback level:
sma20 = ta.sma(close, 20) - Condition 1 (regime): close > sma200 — only take long setups in bull territory
- Condition 2 (entry): price pulls back to touch sma20 then closes back above it on the next bar
- Stop loss: below sma50; hold until close below sma20 for 2 consecutive bars
Strategy 3 — SMA + MACD Confirmation (Trend + Momentum)
Market environment: trending and recovering markets · Best timeframe: 4H, Daily
Pairing the SMA 50 with MACD(12, 26, 9) filters out false entries. The SMA 50 identifies trend direction while the MACD histogram confirms that momentum supports the trade direction. Enter only when both conditions align.
- Calculate trend filter:
sma50 = ta.sma(close, 50) - Calculate momentum confirmation:
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9) - Long entry: close > sma50 AND macdLine crosses above signalLine (bullish MACD crossover)
- Avoid: entries where MACD histogram is declining even if price is above sma50 — momentum is weakening
- Exit: close falls below sma50 OR MACD line crosses below signal line
Disclaimer: The strategies above are for educational purposes only and do not constitute investment advice. Past performance does not guarantee future results. Always apply proper risk management and position sizing.
How to Generate the SMA Indicator in Pineify
- 1
Open Pineify
Go to pineify.app and sign in — a free account is sufficient to generate SMA indicators.
- 2
Click "New Indicator"
Select "Indicator" as the script type from the creation menu on the dashboard.
- 3
Describe the SMA you want
Type a prompt such as: "Plot a 20-period SMA as a blue line overlay on the price chart using ta.sma(close, 20)." Pineify's AI Coding Agent generates the complete Pine Script v6 code in seconds.
- 4
Copy to TradingView
Click "Copy to TradingView" to copy the generated code, then open the TradingView Pine Script editor (Alt+P), paste the code, and click "Add to chart".
- 5
Adjust the length parameter
In the TradingView indicator settings panel, change the SMA length (e.g., from 20 to 50 or 200) to match your trading style — no code editing required.
Frequently Asked Questions
Related Pine Script Indicators
Build Your SMA Indicator in Seconds
Skip the manual coding. Pineify's AI Coding Agent generates complete, ready-to-use Pine Script indicators — including SMA crossover strategies with MACD confirmation — instantly for free.
Try Pineify Free