Moving Average (MA) Pine Script — Complete TradingView Guide
The Moving Average (MA) indicator in Pine Script is the most foundational tool in technical analysis, averaging price data over a specified period to smooth volatility and highlight the dominant trend direction. Available as SMA, EMA, HMA, WMA, VWMA, and more, MAs are applied across every market — stocks, crypto, forex, and futures — on timeframes from 1-minute scalping to weekly position trading. This complete guide covers the Pine Script code, all configurable parameters, 11 supported MA types, and three proven trading strategies including the Golden Cross, dynamic support/resistance, and mean reversion. Whether you are a beginner adding your first EMA to a chart or an experienced trader comparing lag across MA algorithms, this page gives you everything needed to implement and optimise Moving Averages in TradingView Pine Script.
What Is the Moving Average (MA) Indicator?
The Moving Average (MA) is a trend-following indicator that calculates the arithmetic mean (or a weighted variant) of a price series over a fixed lookback period, used to identify trend direction, dynamic support/resistance levels, and momentum shifts in financial markets. The Simple Moving Average was formalised as a technical analysis tool in the early 20th century, with the Exponential Moving Average popularised by traders including Gerald Appel in the 1970s (who used dual EMAs to create the MACD). The Hull Moving Average was developed by Alan Hull in 2005 to reduce lag while preserving smoothness.
The Simple Moving Average (SMA) formula is: SMA = (P1 + P2 + … + Pn) / n, where P is the price at each bar and n is the lookback period. Every bar contributes equally to the average. The Exponential Moving Average (EMA) formula is: EMA = Price × k + EMA(prev) × (1 − k), where the smoothing factor k = 2 / (n + 1). For a 20-period EMA, k ≈ 0.0952, meaning the current bar contributes roughly 9.5% of the result while older bars decay exponentially. The Hull Moving Average (HMA) uses HMA = WMA(2×WMA(n/2) − WMA(n), √n) to dramatically reduce lag compared to a standard WMA.
In Pine Script v6, the core MA functions are:
ta.sma(source, length)— Simple Moving Averageta.ema(source, length)— Exponential Moving Averageta.wma(source, length)— Weighted Moving Averageta.hma(source, length)— Hull Moving Averageta.rma(source, length)— Wilder/Running MA (used in RSI, ATR)ta.vwma(source, length)— Volume-Weighted Moving Average
MAs are applicable across all major asset classes: equities (daily 50/200 EMA is standard for trend filters), crypto (20 EMA on 4-hour charts is widely used), forex (where the 200 EMA on H1 separates bull/bear bias), and futures (where VWMA is favoured for volume-weighted trend confirmation). The most effective timeframes are daily charts for position trading (50-period and 200-period EMA), 4-hour charts for swing trading (20-period and 50-period EMA), and 5–15 minute charts for day trading (9-period and 20-period EMA).
The primary limitation of all MAs is lag — because MAs are calculated from past prices, they always trail the current price. Faster MAs (shorter period) reduce lag but increase noise and false signals. Slower MAs (longer period) are smoother but react later to trend reversals. Traders resolve this trade-off by using two MAs simultaneously (a fast and a slow MA) and trading the crossover, or by choosing a lower-lag variant like HMA or ZLEMA when speed is critical.
Pine Script Code Example
The code below implements a 20-period Exponential Moving Average using Pine Script v6's built-in ta.ema() function, overlaid directly on the price chart. To use it: copy the entire script, open the TradingView Pine Editor (Alt+P), paste the code, and click Add to chart — the blue EMA line will appear immediately on your candlestick chart. You can change ta.ema to ta.sma, ta.wma, or ta.hma and adjust the length value to customise the indicator.
// 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="ma", overlay=true, max_labels_count=500)
// Moving Average — EMA 20 applied to close price
p_ind_1 = ta.ema(close, 20)
// Plot the MA line on the chart
plot(p_ind_1, "MA", color.rgb(41, 98, 255, 0), 1)
Parameters
The Pineify MA indicator exposes two core parameters. The table below lists each parameter, its default value, description, and recommended ranges for different trading styles.
| Parameter | Default Value | Description | Recommended Range |
|---|---|---|---|
length | 20 | Number of bars in the lookback window. Higher values produce smoother, slower-reacting MAs; lower values react faster but with more noise. | 5–9 (scalping), 20–50 (swing), 100–200 (position) |
ma_type | "EMA" | The smoothing algorithm. Supports: SMA, EMA, RMA, HMA, WMA, TMA, VAR, WWMA, ZLEMA, TSF, VWMA. Each type has different lag and responsiveness characteristics. | EMA (general), HMA (low-lag), VWMA (volume-weighted), SMA (long-term) |
Tuning Scenarios
- Scalping (1–5 min charts): Use EMA with length 9 or 20 for fast-responding trend signals with minimal lag.
- Swing trading (4H/Daily charts): Use EMA 50 or HMA 55 — EMA for standard trend tracking, HMA for reduced lag on momentum setups.
- Position trading (Daily/Weekly): Use SMA 200 or EMA 200 as a long-term trend filter; price above = bullish bias, price below = bearish bias.
Trading Strategies Using the MA Indicator
Strategy 1: Golden Cross / Death Cross (Dual EMA Crossover)
Market environment: Trending markets — best on daily charts for stocks, crypto, forex
The Golden Cross strategy uses a fast EMA (50-period) and a slow EMA (200-period). When the fast EMA crosses above the slow EMA, a bullish trend shift is confirmed; the reverse cross signals a bearish shift. Pair with RSI to avoid buying into overbought conditions.
Entry conditions (Long):
- EMA 50 crosses above EMA 200 (
ta.crossover(ta.ema(close,50), ta.ema(close,200))) - RSI(14) is between 50 and 70 (not yet overbought)
- Price closes above both EMAs on the signal bar
Exit conditions:
- EMA 50 crosses back below EMA 200 (Death Cross)
- Price closes below EMA 50 on two consecutive bars
- RSI(14) exceeds 80 (momentum exhaustion)
Strategy 2: Dynamic Support / Resistance Bounce
Market environment: Trending markets with pullbacks — 1H/4H charts on crypto and forex
In a strong uptrend, the 20-period EMA acts as dynamic support. Traders buy pullbacks to the EMA and sell when price extends too far above it. Confirm with a volume spike on the bounce bar and use ATR(14) for stop placement.
Entry conditions (Long):
- EMA 200 is rising (uptrend confirmed —
ta.ema(close,200) > ta.ema(close,200)[5]) - Price pulls back to within 0.5% of EMA 20 from above
- Current bar closes back above EMA 20 with volume above its 20-bar average
Exit conditions:
- Price reaches 2× ATR(14) above entry (profit target)
- Price closes below EMA 20 (stop — trend support broken)
Strategy 3: Mean Reversion with VWMA
Market environment: Ranging or low-volatility markets — intraday stocks and futures
The Volume-Weighted Moving Average (VWMA) gives more weight to bars with higher volume, making it a more accurate "fair value" benchmark than SMA. When price deviates significantly from the VWMA, a mean reversion trade targets a return to the average. Pair with Bollinger Bands to confirm overextension.
Entry conditions (Long):
- Price falls more than 1.5× ATR(14) below VWMA(20)
- Bollinger Band lower band (20,2) is touched or breached
- RSI(14) drops below 35 (oversold confirmation)
- Next bar opens back above the Bollinger lower band (entry trigger)
Exit conditions:
- Price reaches the VWMA(20) line (mean reversion target)
- Price closes below the entry low by more than 1× ATR(14) (stop loss)
Disclaimer: The strategies above are for educational purposes only. They do not constitute investment advice. Past performance of any indicator or strategy does not guarantee future results. Always backtest before risking real capital and use appropriate risk management.
How to Generate an MA Pine Script in Pineify
Pineify generates production-ready, customisable Moving Average Pine Script code in under 60 seconds — no coding required. Follow these 5 steps:
- 1
Open Pineify at pineify.app
Navigate to the Pineify indicator generator. No account required for the free tier.
- 2
Click "New Indicator" and select the Moving Average template
Choose "MA" from the indicator library, which pre-selects all 11 supported MA types.
- 3
Describe your MA configuration
Specify the MA type (e.g., "EMA"), period length (e.g., 20), source (close/open/hl2), and any additional requirements like alerts or dual-MA crossover logic.
- 4
Copy the generated Pine Script v6 code
Pineify outputs a complete, ready-to-paste script with your chosen MA type, configurable inputs, and plot statements. Click the copy button to copy the full code.
- 5
Adjust parameters in TradingView and add to your chart
Paste the code into TradingView's Pine Editor (Alt+P), click "Add to chart", then use the Settings panel to change the MA length, type, and colour without editing the code.
Frequently Asked Questions
Related Indicators
Explore other Pine Script indicator guides to expand your TradingView toolkit.
Generate Your MA Pine Script in Seconds
Pineify generates production-ready Moving Average Pine Script code with any MA type, length, and source. Free to start — no credit card required.
Start Generating for Free