Pine Script SMA (Simple Moving Average)
If you're new to technical analysis or TradingView's Pine Script, the Simple Moving Average (SMA) is the perfect starting point. This fundamental indicator helps traders identify trends by smoothing price data over a specified period.
What is SMA in Pine Script?
The Simple Moving Average calculates the average price over a defined number of bars. In Pine Script, you can create SMA indicators with just a few lines of code:
//@version=5
indicator("My SMA Indicator", overlay=true)
length = input(14, title="SMA Length")
sma = ta.sma(close, length)
plot(sma, color=color.blue, linewidth=2)
ta.sma()
function is built into Pine Script v5, making SMA implementation effortless.
How SMA Works
The SMA formula is straightforward:
SMA = (Sum of Closing Prices) / (Number of Periods)
For example, a 14-day SMA adds up the closing prices over 14 days and divides by 14. This value plots as a line on your chart.
Practical SMA Strategies
Here are three common SMA uses in Pine Script:
1. Basic Trend Identification
//@version=5
indicator("SMA Trend", overlay=true)
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
plot(sma50, color=color.blue)
plot(sma200, color=color.red)
2. Price Crossovers
//@version=5
strategy("SMA Crossover", overlay=true)
fastSMA = ta.sma(close, 9)
slowSMA = ta.sma(close, 21)
plot(fastSMA, color=color.green)
plot(slowSMA, color=color.orange)
Optimizing Your SMA
Consider these Pine Script best practices:
- Use
input()
for customizable lengths - Combine with other indicators like RSI
- Add alerts with
alertcondition()
Whether you're building your first Pine Script indicator or enhancing your trading strategy, mastering SMA is essential for any TradingView developer.
Enhance Your Trading
Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.
This strategy runs in live mode on TradingView, helping you identify potential opportunities.
Subscribe now @ $99/month