Video: THE COMPLETE GUIDE TO MOVING AVERAGES
Creator: Oliver Velez Trading
Original Video: Watch the original video
Difficulty: Intermediate
The Big Idea
A moving average becomes more useful when you ask what state it is in and how price behaves around it. Oliver Velez pairs a 20-period average with a 200-period average, treats both as areas rather than exact lines, and looks for price reactions that fit their slope and location.
His central distinction is that a relatively flat 200 can act as a reference area for support or resistance, while a rising or falling 20 can help organize trend-continuation decisions. A flat, repeatedly crossed 20 provides less directional guidance in his framework. These are trading hypotheses from the source, not measured probabilities established by the supplied transcript.
If You Remember One Thing
Read the moving average’s state before treating a price touch as a setup. A touch, a brief excursion and a confirmed return are different events. None guarantees follow-through.
A Map of the 20 and 200
| State in the source | Interpretation | Question before acting |
|---|---|---|
| Relatively flat 200; price above | Potential support area | Does price reject the area, or accept prices below it? |
| Relatively flat 200; price below | Potential resistance area | Is there an actual downward reaction rather than merely an overhead line? |
| Rising 20; price above | Potential support during a trend | Does the pullback resolve upward while the slope remains positive? |
| Declining 20; price below | Potential resistance during a trend | Does a rally fail and return downward? |
| Flat, wavy 20 | Repeated crossings and weak directional guidance | Are you forcing a trend trade into a range? |
The source says the 200 remains useful when angled, but considers its flat state most powerful for support and resistance. That is not the same as saying every flat 200 is a reliable barrier. A sustained break can change the context.
What a Moving Average Actually Measures
A simple moving average, or SMA, is the arithmetic mean of the last N prices, typically closes. A 20 SMA averages 20 bars, while a 200 SMA averages 200 bars. On a five-minute chart, those lengths represent 100 and 1,000 minutes of included bars; on a daily chart, they represent 20 and 200 trading sessions. The same period numbers therefore do not describe the same economic horizon across timeframes.
A useful identity is SMA change = (new close − close leaving the window) ÷ N. If the incoming and departing closes are similar, the average can look flat even when the bars inside the window are volatile. Flatness is not direct evidence of balanced orders, institutional buying or a hidden defense of that price.
The average also reacts after prices change. Smoothing makes direction easier to see but adds lag. The TradingView moving-average reference (paid link) explains their calculation and use. Our strategy uses SMAs, consistent with the supplied section headings; replacing them with EMAs would be a different experiment.
Why Treat the Line as a Zone?
The presenter compares moving averages to a flexible fence or boxing ropes. The practical lesson is to allow some tolerance around the plotted value rather than declaring every small penetration a decisive break. This can reduce reactions to minor noise, but a zone must have boundaries if you want reproducible research.
Imagine a 20 SMA at $100 and average true range, or ATR, of $2. A research zone with a half-width of 0.25 ATR spans $99.50 to $100.50. That width is our choice; the source does not specify it. A wick to $100.30 remains inside the zone. A close at $100.80 is outside its upper boundary. Neither observation alone tells you what the next bar will do.
Do not enlarge the zone afterward to make a losing example qualify. Choose its definition before reviewing outcomes. Percentage widths, ticks and ATR widths create different trade samples; ATR scales the area to recent volatility but changes over time.
Three Reactions Worth Separating
A Surge Away From the Area
Velez emphasizes sharp moves away from the 200 area, including large directional bars he calls elephant bars. He describes these as especially reliable. The transcript does not quantify bar size, the permitted distance from the average or the follow-through window, so the reliability claim cannot be calculated from this material.
A possible future definition is a body of at least one ATR, a close in the outer quarter of the bar and contact with a predefined zone. That is a proposed test, not a source rule or proof that large bars predict the next move.
A Color Change
The source describes the opposite candle color being neutralized by the desired direction near the area. For a downward setup, a bearish reaction after a bullish bar can be relevant. But “neutralized” is not fully specified: changing color, closing below the preceding close and engulfing a body are different rules.
Also distinguish candle color from movement inside the candle. A candle can fall substantially from its high yet close above its open and remain green. The transcript explicitly discusses this distinction. Final OHLC data cannot reconstruct every intrabar change of color or the exact moment a discretionary trader would have entered.
A Peekaboo Back Into Play
Price briefly moves beyond the moving-average area, then returns in the preferred direction. The useful sequence is context → excursion → return → entry decision. Waiting for a return avoids treating the first penetration as proof of either failure or continuation, but it can produce a later entry and still fail.
The source illustrates this around both averages. Our executable baseline below studies only a close-based version around the trending 20. It does not pretend to recreate every illustrated surge or discretionary intrabar entry.
Convergence and Separation
When the 20 and 200 zones approach each other, Velez looks for an important change in behavior. When the averages become widely separated, he says continuation reactions can lose consistency. These ideas are valuable research questions, but neither specifies an inevitable reversal or a universal distance threshold.
Both averages are calculated from the same price series. Their convergence is not two independent confirmations. A convergence event can lead to continuation, a reversal or a range. Likewise, wide separation can reflect a persistent trend instead of immediate exhaustion.
For comparison across prices, define separation as |20 SMA − 200 SMA| ÷ ATR. A value of four means the averages are four current ATR units apart. Our default spacing filter uses four as a research cutoff; it is not a number supplied by Velez.
Worked Example: A Long Return Into the 20 Zone
Suppose the preceding completed bar’s 20 SMA is $100 and ATR is $2. The fixed reference zone is $99.50–$100.50. The 20 SMA has risen $0.40 over five bars, giving a normalized slope of +0.20 ATR. Assume the 20/200 spacing also passes the selected filter.
The preceding close is $99.40, below the zone. The next candle opens at $99.70 and closes at $100.20, above the reference center and above its own open. This meets our long return rule. We require a return across the center, which is stricter than merely touching the outer edge.
If signal-bar ATR is $2.10, a 1.5 ATR experimental stop distance is $3.15. With a one-cent tick size, that is 315 ticks. Suppose the market entry actually fills next bar at $101. The bracket is then anchored to that fill: stop $97.85 and 2R target $107.30. Using the signal close of $100.20 instead would misstate the distance from the actual entry.
The short version mirrors the sequence: a previous close above the upper boundary, followed by a bearish close below the reference center while the 20’s slope is negative. These stops and targets are experimental additions. The transcript supplies no complete exit or position-sizing system.
From Visual Ideas to an Executable Baseline
View Pine Script Backtest Code
//@version=6
strategy("20 SMA zone reclaim: experimental baseline", overlay=true,
initial_capital=100000, default_qty_type=strategy.percent_of_equity,
default_qty_value=10, pyramiding=0, margin_long=100, margin_short=100,
commission_type=strategy.commission.percent, commission_value=0.05,
slippage=2, process_orders_on_close=false,
calc_on_every_tick=false, calc_on_order_fills=false)
// Source: 20/200 SMA zones, trend direction and back-into-play concept.
// All thresholds, close-based triggers and exits below are research choices.
int slopeBars = input.int(5, "20 SMA slope lookback", minval=1, maxval=50)
float minSlope = input.float(0.20, "Minimum slope in ATR units", minval=0.0, step=0.05)
float zoneATR = input.float(0.25, "Zone half-width in ATR", minval=0.01, step=0.05)
bool useSlope = input.bool(true, "Require directional 20 SMA slope")
bool useSpacing = input.bool(true, "Limit 20/200 separation")
float maxSpacing = input.float(4.0, "Maximum separation in ATR", minval=0.1, step=0.5)
float stopATR = input.float(1.5, "Experimental stop distance in ATR", minval=0.1, step=0.1)
float rewardR = input.float(2.0, "Experimental target multiple", minval=0.1, step=0.1)
string side = input.string("Both", "Direction", options=["Both", "Long only", "Short only"])
int startDate = input.time(timestamp("01 Jan 2020 00:00 +0000"), "First entry decision")
int endDate = input.time(timestamp("31 Dec 2030 23:59 +0000"), "Last entry decision")
float ma20 = ta.sma(close, 20)
float ma200 = ta.sma(close, 200)
float atr = ta.atr(14)
// Freeze the zone to values known on the preceding completed bar.
float center = ma20[1]
float upper = center + zoneATR * atr[1]
float lower = center - zoneATR * atr[1]
float slope = (ma20[1] - ma20[slopeBars + 1]) / atr[1]
float separation = math.abs(ma20[1] - ma200[1]) / atr[1]
bool ready = not na(ma200[1]) and not na(slope) and atr[1] > 0 and atr > 0
bool spacingOK = not useSpacing or separation <= maxSpacing
bool longTrend = not useSlope or slope >= minSlope
bool shortTrend = not useSlope or slope <= -minSlope
bool inWindow = time_close >= startDate and time_close <= endDate
// Consecutive closes across the frozen zone; wick-only excursions are excluded.
bool reclaimLong = close[1] < lower and close > center and close > open
bool reclaimShort = close[1] > upper and close < center and close < open
bool eligible = barstate.isconfirmed and ready and spacingOK and inWindow and strategy.position_size == 0
bool enterLong = eligible and reclaimLong and longTrend and side != "Short only"
bool enterShort = eligible and reclaimShort and shortTrend and side != "Long only"
if enterLong or enterShort
// Freeze tick distances at submission; relative exits anchor to actual fill.
int riskTicks = math.max(1, int(math.round(stopATR * atr / syminfo.mintick)))
int rewardTicks = math.max(1, int(math.round(rewardR * riskTicks)))
if enterLong
strategy.entry("Long", strategy.long)
strategy.exit("Long bracket", from_entry="Long", loss=riskTicks, profit=rewardTicks)
else
strategy.entry("Short", strategy.short)
strategy.exit("Short bracket", from_entry="Short", loss=riskTicks, profit=rewardTicks)
// Submitted brackets persist. New signals cannot alter an open trade's exits.
// No end-date liquidation: brackets continue to work after entry window ends.
plot(center, "Prior-bar 20 SMA zone center", color=color.blue)
u = plot(upper, "Zone upper", color=color.new(color.blue, 65))
l = plot(lower, "Zone lower", color=color.new(color.blue, 65))
fill(u, l, color=color.new(color.blue, 90))
plot(ma200, "200 SMA", color=color.orange)
plotshape(enterLong, "Long submission", shape.triangleup, location.belowbar, color=color.green, size=size.tiny)
plotshape(enterShort, "Short submission", shape.triangledown, location.abovebar, color=color.red, size=size.tiny)
| Element | Source concept | Our baseline definition |
|---|---|---|
| Direction | Rising 20 favors upward plays; falling 20 favors downward plays | Five-bar SMA change of at least +0.20 ATR for longs or at most −0.20 ATR for shorts. |
| Zone | A cushion around the average | Previous completed 20 SMA ± 0.25 of previous ATR(14). |
| Return | Peekaboo, then back into play | Consecutive closes from beyond the outer boundary to beyond the center, with matching signal-bar color. |
| Spacing | Wide separation can reduce consistency | Optional previous-bar 20/200 separation no greater than four ATR. |
| Entry | Discretionary entry on the return bar | Decision at confirmed close; market order on the next available tick. |
| Exit and size | No complete rules supplied | 10% equity exposure per entry, fixed 1.5 ATR stop distance and 2R target, all research choices. |
The preceding-bar zone stays fixed while the return is evaluated. This prevents the signal candle’s movement from redefining the area being crossed. The plot displays that same reference zone. Use ordinary candlesticks and sufficient earlier history for the 200 SMA.
What This Code Actually Tests
It tests whether a precisely defined two-bar return around the 20 SMA, combined with directional slope and optional spacing, produces useful outcomes under the selected fixed exits. It opens one position at a time and can separate long and short results. Disabling slope or spacing allows controlled comparisons while preserving the rest of the rules.
At submission, the script freezes signal-bar ATR into a stop distance measured in ticks. The target is a multiple of those ticks, subject to rounding. Relative bracket orders are submitted with the entry and anchor to the actual simulated fill; they are not recalculated from later ATR values. New signals cannot replace an open position’s exits.
What This Code Does Not Test
It does not establish that flat 200 zones are stronger than angled ones, detect elephant bars, reproduce an intrabar color change or test every source setup. Wick-only excursions and returns spanning more than two bars are deliberately excluded. It does not measure institutional activity, predict a convergence reversal or establish universal effectiveness across markets and timeframes.
The 10% equity setting controls entry exposure, not a fixed percentage of equity at risk. Stop distance varies with volatility and price, and gaps can exceed the planned loss. Short-selling availability, borrow fees and realistic share or contract constraints require separate attention. No news, volume, session or higher-timeframe filter is included.
Execution and Validation
The TradingView strategy documentation (paid link) explains the broker emulator, relative exit distances and cost settings. The baseline uses completed-bar signals, next-tick market fills, 0.05% commission per fill and two ticks of slippage. These defaults are research assumptions, not verified costs for every market.
There is no retrospective fill at the signal close, pyramiding or automatic reversal while a trade is open. Entry dates gate new submissions; existing brackets remain active after the entry window ends. There is no forced end-date liquidation. Include open-position market value when interpreting the evaluation endpoint.
If both stop and target are reached within a historical bar, the result depends on the emulator’s assumed path or available lower-timeframe information. Inspect these trades and compare Bar Magnifier behavior where available. A stop is not a guaranteed execution price during a gap. Synthetic charts can distort signals and fills; use standard candlesticks.
Validation status: The script and its order logic have been statically reviewed, and the complete code interface has been checked. It has not been compiled or backtested in TradingView. No win rate, return or drawdown is claimed.
Backtest Lab
- Does slope add information? Compare slope enabled versus disabled using the same symbol, timeframe, dates, exits and costs. Report expectancy, drawdown and trade count, with long and short results separately. Fewer trades alone do not establish an improvement.
- Does zone width matter? Compare half-widths of 0.10, 0.25 and 0.50 ATR. Record which setups change. Seek a reasonably stable neighborhood rather than the single best threshold.
- Is wide separation actually worse? Disable spacing, then compare cutoffs of two, four and six ATR. Review excluded winners as well as excluded losers, and preserve a later period for out-of-sample evaluation.
- Do results survive execution costs? Increase commission to 0.10% and slippage to five ticks. Inspect overnight gaps and bars touching both exits. Keep the signal rules fixed.
A separate flat-200 study would first define flatness, for example ten-bar 200 SMA change no greater than 0.20 ATR in absolute value. Then compare first zone reactions across flat and angled groups using identical reaction horizons, with overlapping events handled consistently. The current script does not perform that study.
Test multiple liquid symbols and distinct regimes. Changing timeframes changes the meaning of 20 and 200 bars; do not search every chart and report only the best one. A small or concentrated trade sample is weak evidence even when its return looks attractive.
Check Your Understanding
- Does a flat 200 prevent a breakout? No. It is a potential reference area in the source’s framework, not a price barrier.
- Why can a flat 20 be crossed repeatedly? Averaging can provide little directional guidance in a range; crossing the line is not automatically a new trend.
- Are the 20 and 200 two independent signals? No. They are related transformations of the same prices.
- Why fix the zone before the return bar? To avoid letting that bar move the reference used to judge its own return.
- Does a 2R target imply a profitable system? No. Win rate, realized losses, costs, gaps and the distribution of outcomes determine expectancy.
Practice Exercise
Mark 30 consecutive potential 20-zone reactions without skipping ugly examples. For each, record slope, ATR-scaled spacing, whether the excursion was a wick or a close, and whether price returned across the center. Label the setup before revealing subsequent bars.
Then calculate a zone for a $50 SMA and $0.80 ATR at 0.25 ATR half-width. The answer is $49.80–$50.20. If a previous close is $49.90, our long baseline does not qualify: it never closed below the lower edge, even if a later bounce looks excellent. This is how a precise definition protects a test from hindsight selection.
Final Takeaway
The value of this lesson is a better sequence of questions: What state is the average in? What area was defined before the reaction? Did price actually return in the preferred direction? Is the trade extended? What invalidates the position? Velez’s framework supplies the visual ideas. Transparent definitions, realistic execution and controlled tests determine which parts deserve confidence.
Risk Disclosure
This guide is educational and is not personalized financial advice. Trading involves substantial risk, and short positions can expose traders to losses beyond the initial proceeds. Stops may fill beyond their intended prices. Hypothetical examples and historical simulations do not guarantee future results; liquidity, borrowing, costs and market conditions affect outcomes.
CandleChasers is an independent educational publisher and is not affiliated with Oliver Velez Trading. The explanations, examples and experimental definitions in this guide are CandleChasers’ independent analysis of the supplied material.