Skip to main content

SMA Pine Script: Plot Moving Averages Easily

· 8 min read

Want to master Simple Moving Averages in Pine Script? You've come to the right place. SMAs are honestly one of the first things you should learn when diving into Pine Script - they're everywhere in trading, and once you get comfortable with them, you'll find yourself using them in pretty much every indicator you build.

SMA Pine Script

What's a Simple Moving Average, Really?

The Best Pine Script Generator

Think of a Simple Moving Average as the "reliable friend" of technical indicators. It's literally just the average price over a specific number of periods. Want a 20-day SMA? You take the closing prices from the last 20 days, add them all up, divide by 20, and there you have it - your moving average.

The math couldn't be simpler:

SMA Formula

The beauty of moving averages is how they smooth out all that market noise. Instead of getting caught up in every little price movement, you can see the actual direction the market is heading. It's like looking at the forest instead of getting lost in the trees.

Why Pine Script Makes SMA Implementation So Simple

Here's what I love about Pine Script - it was designed for traders who want to create custom indicators without becoming full-time programmers. The ta.sma function handles all the complex calculations for you. No need to manually loop through arrays or write complicated math formulas.

The syntax is beautifully simple:

ta.sma(source, length)

That's it! Just specify what data you want to average (usually closing prices) and how many periods to look back. Pine Script does the rest.

Building Your First SMA Indicator

Here's a basic SMA indicator that you can start using right away:

// 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("[Pineify - Best Pine Script Generator] Simple Moving Average", shorttitle="SMA", overlay=true)
length = input(20, title="Length")
smaValue = ta.sma(close, length)
plot(smaValue, title="SMA", color=color.blue)

What's happening in this code?

  • We're creating an indicator that overlays directly on the price chart
  • Users can adjust the length (defaulting to 20 periods)
  • We calculate the SMA using closing prices
  • Then we plot it as a blue line on the chart

Pretty straightforward, right? You can copy this code, paste it into TradingView's Pine Editor, and you'll have a working SMA indicator instantly.

The No-Code Approach to Adding SMAs

Pineify | Best Pine Script Editor

Website: Pineify

Not everyone wants to code, and that's perfectly fine. Pineify lets you add SMA indicators with just a few clicks. Unlike TradingView's built-in limitations on indicator count, Pineify doesn't restrict how many indicators you can add to your charts.

Pineify | Best Pine Script Editor | Add SMA Indicator

You can stack multiple indicators on your charts and customize SMA settings however you like. Plus, their condition editor makes it easy to build sophisticated trading rules based on SMA behavior without writing a single line of code.


Check out all of Pineify's features here.

Creating SMA Crossover Strategies

This is where things get really interesting. SMA crossover strategies are among the most popular trading approaches. The concept is straightforward: when a fast-moving average crosses above a slow one, that could signal a buy opportunity. When it crosses below, it might be time to sell.

Here's how you'd implement that strategy:

// 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
strategy("[Pineify - Best Pine Script Generator] SMA Crossover Strategy", overlay=true)

shortLength = input(9, title="Short SMA Length")
longLength = input(21, title="Long SMA Length")

shortSMA = ta.sma(close, shortLength)
longSMA = ta.sma(close, longLength)

plot(shortSMA, color=color.red)
plot(longSMA, color=color.green)

longCondition = ta.crossover(shortSMA, longSMA)
shortCondition = ta.crossunder(shortSMA, longSMA)

if (longCondition)
strategy.entry("Long", strategy.long)

if (shortCondition)
strategy.entry("Short", strategy.short)

What makes this strategy effective:

  • We use two SMAs - a 9-period (fast) and 21-period (slow)
  • The red line represents our fast SMA, green shows our slow SMA
  • When red crosses above green, we enter a long position
  • When red crosses below green, we enter a short position
[Pineify - Best Pine Script Generator] SMA Crossover Strategy

If you're interested in more advanced strategy examples, check out our comprehensive guide on Pine Script v6 Strategy Examples for real trading code that works.

Multi-Timeframe SMA Analysis

Want to take your analysis to the next level? You can pull SMA data from different timeframes. Maybe you're trading on the 1-hour chart but want to see what the daily SMA looks like. Pine Script makes this surprisingly easy:

// 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("[Pineify - Best Pine Script Generator] Multi-Timeframe SMA", overlay=true)

smaLength = input(50, title="SMA Length")
dailySMA = request.security(syminfo.tickerid, "D", ta.sma(close, smaLength))

plot(dailySMA, color=color.purple)

This code grabs the 50-day SMA from the daily timeframe and displays it on whatever chart you're viewing. It's like having x-ray vision into higher timeframes! For more detailed information about multi-timeframe analysis, our guide on Pine Script Different Time Frame covers everything you need to know.

Troubleshooting Common SMA Issues

Let me save you some frustration I've experienced over the years. Sometimes your SMA won't match TradingView's built-in indicators. Here's usually what's going wrong:

  • Timeframe mismatch: Make sure you're comparing the same timeframes. A daily SMA calculated on hourly data won't match a true daily SMA
  • Different price sources: Double-check you're using the same price data (close, open, high, low, etc.)
  • Session settings: Some indicators use different session times, which can affect calculations

If you're running into errors while coding, our guide on How to Fix 'no viable alternative at character pine script' Error covers the most common Pine Script troubleshooting techniques.

Advanced SMA Techniques

Once you're comfortable with basic SMAs, you might want to explore more sophisticated approaches. The Madrid Moving Average Ribbon uses 19 different moving averages to create a visual ribbon that makes trend identification incredibly easy.

You can also combine SMAs with other indicators for more robust signals. Many traders pair SMAs with RSI or MACD for confirmation signals, reducing false positives and improving overall strategy performance.

Final Thoughts

SMAs are the foundation of technical analysis. Once you understand how to implement them in Pine Script, you'll find yourself using them everywhere - not just as standalone indicators, but as building blocks for more sophisticated trading strategies.

The best part? You don't need to be a programming expert to get started. Begin with the basic examples I've shown you, experiment with different lengths and combinations, and see what works for your trading style.

Remember, no indicator is perfect, and SMAs are no exception. They work beautifully in trending markets but can give you false signals in choppy, sideways conditions. But that's part of trading - understanding when and how to use your tools effectively.

For beginners looking to dive deeper into Pine Script, I highly recommend checking out our Pine Script Tutorial: A Quick Start Guide for Beginners to build a solid foundation.

References