Mean Reversion

AI Pine Script Mean Reversion Strategy

How to prompt an AI for a Pine Script v6 mean reversion strategy, catch the fill and repainting assumptions it gets wrong, and paper trade it before going live.

Tom Hartman

Marketing

12 Min Read Reviewed by Tom Hartman Fact-checked by Tom Hartman
BluSky — The Future of Trading. Prop firm futures trading. Sign up at BluSky.pro.

An AI assistant can write a usable AI Pine Script mean reversion strategy in Pine Script v6, but only when the prompt defines the signal, exit, order type, bar confirmation and fill assumptions. Without those constraints, it can produce code that compiles while relying on repainting signals or optimistic fills.

The goal is not to ask AI to discover a profitable system. It is to turn a precise specification into code you can audit. The workflow below covers RSI, Bollinger Bands, z-scores, prompt design, a corrected strategy, execution mistakes, and paper testing before deployment. For choosing and prompting an assistant in general, see our best AI for Pine Script guide.

What Mean Reversion Strategies Cover

RSI And Bollinger Band Reversion

RSI-based reversion trades oscillator extremes against the prevailing short-term move. Bollinger Band reversion instead measures price relative to a moving average and a volatility envelope. A common long setup requires RSI below a threshold while price closes below the lower band.

Neither condition defines a complete strategy. RSI, price, and band values can fluctuate on an open realtime bar, so historical and realtime signals can differ unless the script waits for confirmation.1 Strong trends can also keep an oscillator or price-distance signal extended. Specify an independent exit, such as a close above the band basis, an RSI recovery, a stop, or a maximum holding period.

Z-Score And Statistical Entries

A rolling z-score expresses the distance between price and its mean in standard deviation units. A long rule might trigger below a fixed negative threshold, while a short rule triggers above a positive threshold. The prompt must fix the source, rolling window, threshold, and recalculation cadence. Changing any of them changes signal sensitivity and creates another parameter variant to test.

Limit Order Entries For Reversion

A reversion system may submit a limit order at a band, mean deviation, or predefined discount instead of chasing price with a market order. That adds precision, but also makes the result dependent on TradingView's limit-fill assumptions.

  • Market orders prioritize entry over exact price.
  • Limit orders control the maximum buy price or minimum sell price.
  • Untouched limits may remain unfilled.
  • Gap behavior can differ from the expected limit price.

Choose the order type before generating code. Otherwise, an AI assistant may select whichever syntax is easiest rather than the behavior your strategy requires.

What the Research Says About Mean Reversion

What Academic Evidence Shows

In a 1990 Quarterly Journal of Economics paper, Bruce Lehmann reported that weekly stock-market "winners" and "losers" experienced sizeable return reversals the following week, with apparent arbitrage profits that persisted after corrections for bid-ask spreads and plausible transaction costs.2

The same year, Andrew Lo and Craig MacKinlay presented evidence in the Review of Financial Studies against overreaction as the only source of contrarian profits: weekly portfolio returns reflected important cross-autocorrelations, and returns of large stocks led those of smaller stocks.3 In a 2006 Journal of Finance paper, Doron Avramov, Tarun Chordia and Amit Goyal found the largest reversals in high-turnover, low-liquidity stocks, and found the contrarian strategy profits smaller than the likely transaction costs.4

Why This Does Not Validate Backtests

These studies analyze weekly cross-sections of stocks. They do not validate a single-chart RSI or Bollinger rule on one symbol. A strategy selected after testing multiple RSI lengths, band multipliers, z-score thresholds, and exit rules also carries selection bias. Bailey, Borwein, Lopez de Prado and Zhu write that standard techniques for preventing overfitting, such as hold-out, "tend to be unreliable and inaccurate" for investment backtests.5

Crypto needs its own check. It trades around the clock, so session closes and overnight gaps matter less, while liquidity and transaction costs vary by venue. The signal and fill review still applies, but stock-market studies say nothing direct about high-volatility crypto mean reversion.

Writing A Precise AI Prompt

Pin The Pine Script Version

State Pine Script v6 at the beginning. Ask for one complete, compile-ready strategy rather than pseudocode, fragments, or an indicator that merely plots signals. If the assistant cannot provide a complete declaration and executable order logic, the output is not ready for review.

Name Exact Inputs And Conditions

Define every input name, default, and valid range. Specify whether entries require all conditions or any condition, and distinguish entering an oversold state from crossing back out of it. Name the exit separately.

  • Indicator source, length, and threshold
  • Long only, short only, or both
  • Market, limit, stop, or stop-limit entry
  • Exit condition and exit order type
  • Pyramiding and position-size rules
  • Alert message format

These constraints also apply when prompting AI for trend following strategies, momentum strategies, or scalping strategies. The indicators change, but execution ambiguity remains.

Require Confirmed-Bar Logic

Ask the assistant to gate entries with barstate.isconfirmed. TradingView's repainting page explains that on a realtime bar the high, low and close can change many times before the bar closes, while historical bars hold only fixed values. Waiting for the close gives later but repeatable signals.1

The prompt should also require comments stating the expected order delay, gap behavior, and limit-fill assumptions. Decide whether alerts use alert() when a condition occurs or alert_message attached to strategy orders. Adding alerts after the strategy is finished can create a mismatch between the tested order event and the live webhook event.

Worked Example: RSI and Bollinger Reversion

The Initial AI Prompt

Use a prompt with enough detail to remove discretionary coding choices:

“Write a complete, compile-ready Pine Script v6 strategy named RSI Bollinger Confirmed Reversion. Use inputs named RSI Length with default 14, RSI Oversold with default 30, Bollinger Length with default 20, Bollinger Multiplier with default 2.0, and Exit RSI with default 50. Trade long only. Enter with a market order when the confirmed bar closes below the lower Bollinger Band and RSI is below RSI Oversold. Exit with a market order when the confirmed close reaches the Bollinger basis or RSI reaches Exit RSI. Set pyramiding to zero, calc_on_every_tick to false, process_orders_on_close to false, and backtest_fill_limits_assumption to 1. Include dynamic JSON alert_message values for entry and exit. Plot the basis and bands. Comment the next-tick fill assumption.”

Reviewing The First Draft

First, locate the complete entry expression and confirm that barstate.isconfirmed gates it. Next, inspect strategy.entry(). Without a limit or stop argument, it creates a market order. By default, TradingView's broker emulator fills an order created at a bar's close at the next bar's open, not retroactively at the signal close.6

Finally, inspect strategy(). TradingView documents the default for process_orders_on_close as false.6 Write it explicitly anyway. Visible assumptions are easier to audit than defaults hidden in platform behavior.

The Corrected Code

//@version=6
strategy("RSI Bollinger Confirmed Reversion", overlay = true, pyramiding = 0, calc_on_every_tick = false, process_orders_on_close = false, backtest_fill_limits_assumption = 1)

int rsiLength = input.int(14, "RSI Length", minval = 2)
float rsiOversold = input.float(30.0, "RSI Oversold", minval = 0.0, maxval = 100.0)
int bbLength = input.int(20, "Bollinger Length", minval = 2)
float bbMultiplier = input.float(2.0, "Bollinger Multiplier", minval = 0.1, step = 0.1)
float exitRsi = input.float(50.0, "Exit RSI", minval = 0.0, maxval = 100.0)

float rsiValue = ta.rsi(close, rsiLength)
float basis = ta.sma(close, bbLength)
float deviation = bbMultiplier * ta.stdev(close, bbLength)
float upperBand = basis + deviation
float lowerBand = basis - deviation

bool longEntry = barstate.isconfirmed and strategy.position_size == 0 and close < lowerBand and rsiValue < rsiOversold
bool longExit = barstate.isconfirmed and strategy.position_size > 0 and (close >= basis or rsiValue >= exitRsi)

// Orders created on a confirmed bar fill at the next bar's open, because
// process_orders_on_close is false. No limit orders are used, so the
// backtest_fill_limits_assumption value only matters if limits are added later.
string entryMessage = "{\"ticker\":\"" + syminfo.ticker + "\",\"action\":\"buy\",\"orderType\":\"market\",\"quantity\":1,\"price\":" + str.tostring(close) + "}"
string exitMessage = "{\"ticker\":\"" + syminfo.ticker + "\",\"action\":\"exit\",\"orderType\":\"market\",\"price\":" + str.tostring(close) + "}"

if longEntry
    strategy.entry("Long", strategy.long, qty = 1, alert_message = entryMessage)

if longExit
    strategy.close("Long", alert_message = exitMessage)

plot(basis, "Basis", color = color.orange)
plot(upperBand, "Upper Band", color = color.blue)
plot(lowerBand, "Lower Band", color = color.blue)

The corrected version adds confirmation to both entry and exit conditions, prevents overlapping positions, fixes the direction to long only, and makes the market-order behavior explicit. It also disables intrabar recalculation and same-close processing. The limit-fill assumption is declared even though this version uses market orders, making a future conversion to limits easier to review.

Common AI Mistakes And Fixes

Limit Orders Priced Past Market

AI assistants often place a reversion limit on the wrong side of the market. TradingView's Strategies page says a limit order placed at a worse value than the current market price does not wait for that level: the broker emulator fills it on the next available tick. And when a gap between bars crosses the level of any price-based order (every type except market), the emulator fills it at the opening price of the bar after the gap.6

Fix: Require comments next to every price-based order explaining next-tick and gap-fill behavior. Then verify whether the order price is better or worse than the current market for its direction.

Same-Bar Close Fills Are Unrealistic

Setting process_orders_on_close = true allows an order created on the closing tick to fill on that same tick. TradingView calls this "typically unrealistic in real-world trading" and warns that order-fill alerts sent to a third-party service after the close might not work as intended, especially in non-continuous markets.6

A signal calculated from a closing price cannot travel through an alert and webhook and also receive that historical closing price. TradersPost receives the payload only after TradingView fires the alert, so an instant same-close backtest fill does not represent that live sequence.

Fix: Keep process_orders_on_close = false unless you understand and document the difference. In the July 2026 strategy update, TradingView replaced the fill-on-close checkbox in the Properties tab with an "Order execution delay" input.7

Limit Execution Assumption Defaults

The same update replaced the "Verify price for limit orders" input with a "Limit order execution" dropdown that sets assumptions about unfilled limit orders. Scripts can still declare their own default with a backtest_fill_limits_assumption argument.7

Fix: Ask which limit assumption the code relies on, then compare it with the behavior expected from the connected account. A touched price is not automatically equivalent to an executable live fill.

Review Checklist Before Deploying

Code-Level Checks Before Deployment

  • Confirm barstate.isconfirmed gates stable-bar entries.
  • Verify every entry and exit has an independent condition.
  • Confirm market, limit, or stop behavior matches the design.
  • Set process_orders_on_close deliberately.
  • Declare the limit execution assumption.
  • Check alert JSON against the tested order direction.

Backtest Interpretation Checks

Treat the strategy report as a simulation, not a guarantee. Re-run the logic on different symbols, periods, and market regimes. Record all tested variants rather than reporting only the best combination. Repeated parameter searches can produce overfit results even when an ordinary hold-out test appears acceptable.5

Use standard price charts when judging fills. Keep the academic context separate: weekly cross-sectional stock reversals do not establish the validity of a single-symbol intraday rule.

From Signal To Live Execution

Generating The Alert Message

Use alert() for dynamic condition messages or attach alert_message to an order-generating function. TradingView evaluates an order's dynamic alert_message when that order executes, and the Create Alert message can pass it through with {{strategy.order.alert_message}}.8

Routing Through A Webhook

A TradersPost strategy gives you a webhook URL for the JSON signals your TradingView alerts send. Payload fields such as ticker, action, orderType and quantity describe the order, and each strategy subscription then applies its own settings before routing it to your connected broker account.

Paper Trading Before Going Live

Compare paper-trade timestamps and prices with TradingView's alert log, which records what actually fired. Do not treat the list of trades in the strategy report as a substitute for the realtime alert record. Pay particular attention to gaps, unfilled limits, delayed entries, and differences between the signal price and paper fill.

Set up a TradersPost strategy, connect a paper account, and test the corrected code before enabling live execution. Confirm the payload, alert time, routed order type, and resulting fill for multiple signals rather than relying on one successful test.

Bottom Line

  • Prompt for Pine Script v6 and compile-ready code.
  • Define exact indicators, exits, direction, and order types.
  • Use confirmed-bar logic when signals must remain stable.
  • Audit next-tick, gap, same-close, and limit-fill assumptions.
  • Validate alerts and paper fills before live deployment.

AI is most useful as a code-generation assistant, not as evidence that a strategy works. Start with a precise specification, review every execution assumption, and use the same discipline described in the broader best AI for Pine Script guide.

Frequently Asked Questions

Does Reversion Survive Transaction Costs?

The evidence is mixed. One weekly-reversal study reported profits after plausible costs, while another found the largest reversals in illiquid stocks where likely transaction costs exceeded contrarian profits. Net results depend on actual liquidity, spreads, commissions, and slippage.

Repainting Versus Stable Signals

A repainting signal can use values such as close that fluctuate on an open realtime bar. A stable signal waits for confirmation, so it behaves consistently when that realtime bar later becomes historical. Confirmation produces later signals.

Why Did My Strategy Fail Live?

Common causes include parameter overfitting, optimistic same-close fills, permissive limit assumptions, gaps, and alert delays. Compare realtime alert records and paper fills rather than assuming the historical trade list describes live execution.

Limit Or Market Reversion Entry?

Use a market order when obtaining an entry matters more than controlling its price. Use a limit when price control matters and missed entries are acceptable. Remember that worse-than-market limits can fill on the next tick, gaps can fill at the following open, and the limit execution setting affects backtest results.

Does Crypto Mean Reversion Differ?

Crypto trades continuously, so stock-session closes and overnight gaps apply differently. Confirmed-bar logic, transaction costs, liquidity, webhook timing, and fill-assumption reviews still apply.

References

1 TradingView Pine Script Repainting
2 Fads, Martingales, and Market Efficiency
3 When Are Contrarian Profits Due to Stock Market Overreaction?
4 Liquidity and Autocorrelations in Individual Stock Returns
5 The Probability of Backtest Overfitting
6 TradingView Pine Script Strategies
7 TradingView Pine Script Release Notes
8 TradingView Pine Script Alerts

  • Mean Reversion Oct 16, 2025

    Mean Reversion Trading Systems

    Master automated mean reversion trading strategies with statistical indicators, entry signals, risk management, and platform recommendations.

Start trading at scale today. Sign up for free.

Free 7-day trial

Set-up in 3 minutes

Paper account for testing

By continuing, you agree to the TradersPost Terms of Service and Privacy Policy. This site is protected by reCAPTCHA.

TradersPost operates as a non-custodial automated trading platform, enabling users to connect alerts from their preferred trading platforms to their selected brokerage or exchange accounts. It abstains from the transmission, custody, or management of customer funds, covering both traditional and cryptocurrency assets. Typically, registration requirements set by regulatory entities such as the SEC, FINRA, or FinCEN apply to entities that hold or transmit customer funds. To ensure ongoing compliance, TradersPost regularly engages with regulatory authorities to confirm its adherence to all relevant local and federal laws.

TradersPost does not provide alerts, signals, research, analysis, or trading advice of any kind. It is designed to assist traders and investors in making their own trading decisions based on their alerts. The platform does not offer recommendations regarding securities to buy or sell, nor does it provide trading or investing advice. The platform and its features, capabilities, and tools are provided 'as-is' without any warranty.

Risk Disclosure: The use of automated trading systems involves inherent risks, including the potential for significant financial loss. These systems operate based on predetermined algorithms that may not fully adapt to changing market conditions, possibly making them unsuitable for some investors. Individuals are advised to thoroughly assess their financial situation and risk tolerance before using this platform.

Testimonials appearing on this website may not be representative of other clients or customers and is not a guarantee of future performance or success.

Broker, exchange, trading platform, company names, product names, service marks, trademarks, and logos appearing on this website are the property of their respective owners and are used solely to identify supported connections and technical compatibility. TradersPost is an independent third-party platform and is not affiliated with, endorsed by, sponsored by, or authorized by any of these organizations unless expressly stated. Technical compatibility does not imply a commercial partnership, sponsorship, endorsement, or authorization. See Important Disclosures for trademark information.

© 2026 TradersPost, Inc. All rights reserved.