Mean reversion trading strategy: entry, exit and regime filters
A mean reversion trading strategy takes a position after a measured price or momentum extreme and targets a return toward a defined reference. It needs an entry trigger, a target and a point at which the expectation is abandoned. A distant moving average does not require price to return, and buying more as price falls is a separate exposure decision.
Build the Pine Script strategyKey Takeaways
- Percentage distance, Z-score and RSI measure different things. Specify the reference and trigger before comparing them.
- A rolling mean can move toward a losing trade. Reaching the mean does not necessarily mean earning a profit.
- Set a price stop, a maximum holding period and a measurable regime rule before testing.
- Review the worst losses and losing sequences alongside the win rate. Repeated small wins can be outweighed by a few large losses.
Compare three mean reversion triggers
Moving-average distance measures price location. A rolling Z-score scales that distance by recent price dispersion. RSI measures the balance of smoothed gains and losses, so an RSI threshold is not a distance from fair value. The examples below are illustrative long-side specifications, not tested recommendations. Each waits for an extreme to ease before entry; entering at the first extreme would be a different strategy.
| Measure | Definition | Illustrative trigger | Main limitation |
|---|---|---|---|
| Moving-average deviation | 100 × (close − 20-bar SMA) / 20-bar SMA, expressed as a percentage. Require a positive reference price. | After a close at or below −3%, enter only when a later close crosses back above −3%. | The same percentage can be routine in one volatility regime and unusual in another. |
| Rolling Z-score | (close − mean) / standard deviation. Use the same 20 closes for the mean and population standard deviation; skip zero dispersion. | After Z is at or below −2, enter when a later confirmed value crosses above −2 and remains below zero. | A rolling price sample need not be stationary or normally distributed. Z = −2 is not a reversal probability. |
| RSI | A momentum oscillator from 0 to 100. State the length and price source, such as 14 bars and close. | After RSI is below 30, enter on a confirmed cross above 30; define a separate price target. | Momentum can recover while price remains far below a moving average, or weaken again after entry. |
- For an SMA basis and the same standard-deviation convention, a close below a lower two-deviation Bollinger Band is equivalent to Z below −2.
- Do not combine all three triggers by default. Compare each with the same exit and cost assumptions before adding another condition.
- A short-side test needs its own rules, including borrowing or funding costs where applicable.
A numeric example: a smaller Z-score is not always a rebound
Suppose a hypothetical instrument closes at 96, its 20-bar mean is 100 and its population standard deviation is 2. The percentage deviation is −4% and Z = (96 − 100) / 2 = −2. If a later window still has a mean of 100 but a standard deviation of 3, the same price of 96 has Z = −1.33. A threshold cross can therefore come from a changed denominator without a price recovery. These are assumed snapshots, not a historical trade or a performance result.
- Record price, mean and standard deviation at the signal; inspect which quantity caused the cross.
- If the rule requires an actual rebound, add an explicit price condition and test it separately.
- Skip the signal until the complete lookback exists and the denominator is nonzero.
Write one complete test before tuning inputs
The following long-only experiment uses a Z-score trigger. Its numbers are arbitrary starting assumptions, not preferred settings. Fix one symbol, standard candlestick timeframe, session, date range and cost model. Evaluate conditions at the close and model market orders at the next available tick. A change to any row creates a new experiment.
| Decision | Rule |
|---|---|
| Regime eligibility | Allow entry only when the absolute change in the 50-bar SMA over the last 10 bars is no greater than 0.5 × the current 14-bar ATR. Skip unavailable values. |
| Signal | The prior confirmed 20-bar Z-score is at or below −2; the current confirmed Z-score is above −2 but below zero. There is no open position. |
| Entry and size | Submit one long market order. Size from a fixed cash risk budget divided by (one signal-bar ATR × the instrument point value), using the same currency for risk and contract value; round down to the permitted quantity increment. |
| Price stop | Place a protective stop one signal-bar ATR below the actual entry fill. Freeze that ATR distance; do not widen it as volatility rises. |
| Reversion exit | Request a market exit after a confirmed close reaches or exceeds the current 20-bar SMA. This is a moving target, not a limit fill at the SMA. |
| Time and regime exit | Request a market exit at the close of the tenth held bar, counting the entry bar as bar one, or sooner if the regime filter fails. |
| Repeated signals | Ignore entry signals while holding a position. After an exit, require a fresh qualifying cross; never add solely because Z becomes more negative. |
- If the quantity rounds to zero, skip the order. Specify a maximum position value and leverage limit as additional constraints.
- Position sizing uses an intended stop distance. Gaps, slippage and fees can make the realized loss exceed the cash risk budget.
- A protective stop may fill before a close-based exit is evaluated. Cancel unused exit orders after the position closes.
Choose the reversion target and the deadline separately
A frozen target uses the reference value captured at the signal or fill. A rolling target recalculates that reference as new bars arrive. Neither choice is automatically better, but they produce different trades. In a hypothetical long entered at 96 with an initial mean of 100, price could later reach a falling mean at 95. The rolling target has been reached while the trade has lost 1 per unit before costs. A frozen target at 100 would keep waiting unless another exit fired.
- Full reversion: target the chosen mean and state whether a touch or a confirmed close counts.
- Partial reversion: specify a fixed fraction of the entry-to-reference distance; keep it distinct from a full-mean exit.
- Time stop: count bars from the actual fill, state whether the entry bar counts, and close when the deadline arrives.
- Price invalidation: keep a separate loss boundary even when the mean is still above the entry.
A regime filter limits eligibility; it does not prove a range
The slope filter in the example rejects entries after a sufficiently large moving-average change relative to ATR. It is a testable proxy for directional movement, not proof that a market is stationary. It can react late to a new trend, and a volatility shock can enlarge ATR enough to change the filter in unexpected ways. TradingView describes band walking in strong trends: repeated outer-band touches can reflect continued momentum rather than a reversal opportunity.
- Decide whether a failed filter blocks new entries only or also exits an open trade. The example does both.
- Compare the rule with and without the filter on the same untouched evaluation period; record trade count as well as drawdown.
- Inspect persistent trends, gaps and volatility shocks separately from quiet periods. Do not assign regime labels using future bars.
- For a higher-timeframe filter, state when its values become confirmed and available to the lower-timeframe strategy.
Mean reversion does not require averaging down
Mean reversion describes an expected price relationship; averaging down increases exposure after an adverse move. A strategy can test the first idea with one fixed position and no additions. If additions are allowed, each level, size, total exposure and final invalidation must be specified before entry. Lowering the average entry price does not reduce the cash loss already incurred and can increase the loss if the trend continues.
- Inspect the largest losing trades, consecutive losses and recovery time, not just win rate.
- Separate closed-trade losses from adverse movement while positions are open; a trade that eventually recovers can still require substantial capital.
- Include commission, spread, slippage and any financing cost. Check gaps through stops rather than assuming every stop fills at its level.
- Hold out a later period before selecting parameters. A favorable sample does not establish a durable return to the mean.
Match TradingView signal timing to fill timing
An RSI or Z-score condition evaluated during an open bar can disappear before that bar closes. Use confirmed inputs for a close-based test, and do not mix an unfinished higher-timeframe filter with confirmed historical values. TradingView strategies normally calculate after the bar closes and fill new market orders on the next available tick, usually the next bar open. A close that reaches a moving mean therefore does not imply an exit at that mean. TradingView documents these behaviors in the strategy and repainting sources below.
- Use standard candlesticks for the baseline and record any changes to order-processing settings.
- Review the trade list against signal bars and actual fill prices.
- If a bar contains both stop and target prices, inspect the emulator assumptions and available intrabar data instead of assuming the favorable sequence.
Build the rules, then inspect the losing tail
Pine Script AI Coding Agent can draft a strategy from the specification. Review the generated rules and test them in TradingView. Strategy Optimizer can compare bounded input ranges on that strategy. Backtest Deep Report accepts a TradingView trade-list CSV for drawdown and trade analysis. Use these steps to inspect the experiment; an optimized result or report cannot establish that future prices will revert.
- Give the coding agent the trigger, rolling or frozen target, time stop, regime exit, sizing and no-addition rule together.
- Compare a small, declared parameter range. Keep the holdout period out of parameter selection.
- Export and inspect the trades from difficult trend periods as well as the aggregate backtest.
- Check account and product access at the destination. This page explains a workflow; it does not run a live scanner or place orders.
Pineify next step
Turn the specification into a strategy you can inspect
Draft the entry and exit rules with Pine Script AI Coding Agent. After reviewing the script, compare a bounded parameter range and inspect the exported trades, especially losses during persistent trends.
This page is educational and does not provide investment advice. All numerical setups are illustrative and have no reported performance. Mean reversion trades can lose when price continues away from the reference. Historical and simulated results do not guarantee future performance.