Concept 29 / 52·Trend·Moving averages
‹ Money Flow Index (MFI)Moving Average Crossover ›

Moving Average in Pine Script

SMA · EMA · simple moving average · exponential moving average · weighted moving average · MA

The average price over a fixed number of bars, redrawn every bar, so the line smooths the noise out of price and shows the direction and level of the trend.

Reads best on: Every liquid market. Daily charts for the 50 and 200, 5 minute to 1 hour charts for the 9 and 21; on thin or gappy instruments the line jumps and the crosses lose meaning.
On this page: the Pine v6 script, checked, drawn on real NVDA bars. Backtest it free, costs charged, every trade on the chart.
Backtest results: Moving average strategy, EMA pullback strategy: SPY, QQQ and more since 2016, costs charged, every trade listed.
01

Definition

A moving average is the average price of the last n bars, recalculated on every new bar so the window moves forward with the chart. It is the base of the moving averages family: crossovers, ribbons, envelopes, slope filters and the Hull average are all built on it. The simple moving average (SMA) weights every bar equally. The exponential (EMA) and weighted (WMA) versions give recent bars more weight, so they turn sooner. The Hull moving average (HMA) goes further and removes most of the lag at the cost of some overshoot.

The line works because it removes the part of price that does not persist. Single bars carry news, order flow and noise; the average of 20 or 50 of them carries mostly the drift. When the line rises, traders have paid more on average than they did a window ago, and that is the definition of an uptrend a trader can test. The line is also a shared reference: enough traders watch the 20, 50 and 200 that pullbacks into them attract orders, which gives the level a self-fulfilling quality.

Moving averages are among the oldest tools in technical analysis and need no attribution. The conventions are firm: 20 (about a month of daily bars), 50 (a quarter) and 200 (a year) on daily charts, 9 and 21 on intraday charts, and the EMA where speed matters. Most platforms default to a 20 period line on the close. The library's implementation draws one average of any of the 4 types, coloured green while price closes above it and red while it closes below.

On the chart the line lags price by roughly half its length, so a 20 period SMA reflects where price was about 10 bars ago. In a trend the average sits below price in an uptrend and above it in a downtrend, and pullbacks tend to stall near it. In a range price crosses it repeatedly, and every cross is a false signal. The longer the length, the smoother and later the line: a 200 period average turns rarely and is a regime marker, while a 9 period line follows every swing.

02

Reading the chart

Reading a moving average is a question of three things: its slope, which side of it price is on, and how price behaves when it returns to the line.

  1. Choose the length to match your holding period. Use 9 or 21 for intraday swings, 20 or 50 for multi-day positions, and 200 for the regime. One line you understand beats 4 lines you do not.
  2. Read the slope first. A rising line is an uptrend, a falling line a downtrend, and a flat line a range where crosses mean little. The slope is a better filter than the cross itself.
  3. Note which side price is on. Closes above a rising average confirm the uptrend; closes below a falling one confirm the downtrend. A close on the wrong side of a flat line is noise.
  4. Watch how price treats the line on a pullback. A wick into the average followed by a close back on the trend side is a defended test. Repeated closes through it mean the trend is losing the line.
  5. Measure the distance from the line. Price far above a rising average is stretched, and late entries there have poor risk. Price back at the line is where trend entries offer a defined stop.
  6. Confirm with a longer average. A 20 period line above a rising 50 puts both timeframes on the same side, and pullbacks into the 20 are higher quality than the same pullback under a falling 50.
03

The maths

Every moving average is a weighted sum of recent closes divided by the sum of the weights; the 4 types differ only in how the weights are spread across the window.

SMAt=1n∑i=0n−1Ct−i\mathrm{SMA}_t = \frac{1}{n} \sum_{i=0}^{n-1} C_{t-i}
EMAt=α Ct+(1−α) EMAt−1\mathrm{EMA}_t = \alpha \, C_t + (1 - \alpha) \, \mathrm{EMA}_{t-1}
α=2n+1\alpha = \frac{2}{n + 1}
WMAt=∑i=0n−1(n−i) Ct−in(n+1)2\mathrm{WMA}_t = \frac{\sum_{i=0}^{n-1} (n - i) \, C_{t-i}}{\frac{n (n + 1)}{2}}
HMAt=WMA(2 WMA(C,⌊n2⌋)−WMA(C,n),  ⌊n⌋)\mathrm{HMA}_t = \mathrm{WMA}\bigl(2 \, \mathrm{WMA}(C, \lfloor \tfrac{n}{2} \rfloor) - \mathrm{WMA}(C, n),\; \lfloor \sqrt{n} \rfloor\bigr)
CtC_tthe close of the current bar (or another chosen source)
Ct−iC_{t-i}the close i bars ago
nnthe length, the number of bars in the window
α\alphathe EMA smoothing factor, 2 divided by n plus 1
SMAt\mathrm{SMA}_tthe simple moving average at bar t
EMAt\mathrm{EMA}_tthe exponential moving average at bar t
WMAt\mathrm{WMA}_tthe linearly weighted moving average at bar t
HMAt\mathrm{HMA}_tthe Hull moving average at bar t

The EMA never drops a bar; it decays the weight of old bars instead, so its value depends on where the series started. Platforms seed it with the first close or a short SMA, and the difference fades after a few hundred bars.

The WMA's weights fall in a straight line from n down to 1, so it sits between the SMA and the EMA in responsiveness.

The Hull average takes the weighted average of half the length, doubles it, subtracts the full-length weighted average, and smooths the result over √n bars. The subtraction removes lag and creates the overshoot at turns.

The library's implementation computes all 4 types on every bar and shows the one selected, so switching the type never changes the entry logic: Long on a confirmed close crossing above the line, Short on a close crossing below.

04

Inputs that matter

InputTypicalWhat changing it does
Length20 (50 and 200 on daily charts, 9 and 21 intraday)Shorter lengths follow price closely and cross often; longer lengths smooth more, turn later and act as regime lines rather than entry triggers.
MA typeEMA (SMA for the 50 and 200)SMA is the slowest and most watched; EMA and WMA turn sooner with a little more noise; HMA turns soonest and overshoots at reversals.
SourcecloseTypical price (hlc3) or the median price gives a slightly steadier line on wide-range bars; the close is the standard for crosses.
05

In practice

  • As a trend filter: the rule trades only in the direction of a rising or falling average. Long setups above a rising 50 and short setups below a falling one remove most counter-trend trades from a system.
  • As dynamic support and resistance: the rule goes long on pullbacks into a rising 20 or 50 with a stop below the line, and short on rallies into a falling one. The stop is defined by the level the trend has to hold.
  • As a regime marker: the 200 period average on the daily chart splits the market into a bull regime above and a bear regime below, which decides which playbook you run rather than any single entry.
  • As a cross trigger: the library's script marks Long when the close crosses above the line and Short when it crosses below, on confirmed bars only. It is a starting point for a system, not a finished one.
  • As a stretch gauge: the distance from price to the average, measured in ATR or percent, shows how extended a move is. Far from the line is where exits trigger, not entries.
  • As a trailing exit: a close below a rising 9 or 21 period EMA ends a momentum trade, which lets the trend decide the exit rather than a fixed target.
06

Where it goes wrong

  • Trading every cross in a range. When the line is flat, crosses happen every few bars and each one loses; require a sloping line or a second filter before acting on a cross.
  • Optimising the length to the last trend. A length fitted to one move will fit the next one badly; use the conventional lengths so you share the level with other traders.
  • Reading the average as a precise price. It is a zone a few ticks wide that moves every bar; judge tests by the close and by what happens on the next bar, not by a wick touching the line.
  • Expecting the line to lead. A moving average reports what price already did, so use it to confirm and to place stops, and use price itself for timing.
07

Compared with

Anchored VWAP. A moving average weights price over a fixed lookback and forgets the oldest bar every day; an anchored VWAP weights by traded volume from a chosen event and never forgets, so it tracks a cohort's average cost rather than smoothed price.

Hull Moving Average. The Hull average is a moving average rebuilt to remove lag: it turns almost with price but overshoots at reversals. A plain SMA or EMA lags more and is calmer, which is why the 50 and 200 stay simple while fast triggers use the Hull.

SuperTrend. SuperTrend is a trailing stop line that steps in one direction until price crosses it, so it can only flip; a moving average moves both ways every bar and can be crossed repeatedly without a regime change.

Moving Average Envelopes. Envelopes are the same average with bands a fixed percentage above and below it. The average shows direction and level; the envelope adds a stretch gauge, which is the same job the distance to the line does by eye.

08

Build it in Quant

Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.

Open Moving Average on the workbench chart
Drawn on real data; then audit, backtest and refine in conversation.
Open in Quant →
09

Questions

  • Which moving average is best, SMA or EMA?

    Neither, they answer different needs. The SMA is slower and more widely watched, so the daily 50 and 200 work best as simple averages. The EMA reacts sooner and suits short lengths such as 9 and 21 on intraday charts. Pick the type by the job: SMA for shared levels and regimes, EMA for timing.

  • What length should I use?

    Match it to your holding period. Day traders use 9 and 21 EMAs, swing traders the 20 and 50, and position traders the 200. The conventional lengths matter because other traders watch them, so pullbacks into a 50 attract orders in a way a 47 period line does not.

  • Why does price bounce off a moving average?

    Two reasons. The average sits close to the trend's fair value, so pullbacks into it are where traders who missed the move step in. It is also a level enough traders watch that orders cluster around it. Neither reason holds when the line is flat, which is why bounces fail in ranges.

  • Does a moving average repaint?

    No. Each value uses closed bars, so the history never changes. The current bar's value moves while the bar is forming, because the close is not final, which is why the library's script waits for the bar to confirm before it marks a cross.

  • How much does a moving average lag price?

    About half its length for an SMA: a 20 period line reflects where price was roughly 10 bars ago. The EMA and WMA lag a little less, and the Hull average lags far less. Lag is the price of smoothing, so choose the amount of each you can trade with.

  • Can I use a moving average as a stop?

    Yes, and it is one of its better uses. A close below a rising 20 or 50 says the pullback has become a break, which is a reason to exit a long. Use the close rather than a wick so one spike does not stop you, and accept that the exit will be late by design.