Conversion example · Strategy

RSI mean reversion: Pine Script to Python

An RSI mean-reversion strategy with an ATR exit bracket and a var counter that tracks bars since entry. It buys the oversold bounce (RSI crossing up through 30), exits on an ATR bracket or a 10-bar time stop. This is the second post in our tutorial series, and it is also the one that taught us the most — because the exit line, as written, does not mean what it looks like. The correction is part of this page, not hidden from it.

The Python below is the actual output of the Pine2Py converter, run on this exact Pine source with the local compiler (node bin/pine2pyne.mjs), with zero diagnostics.

The Pine original

rsi_mean_reversion.pinePine Script v6
//@version=6
strategy("RSI Mean Reversion", overlay=true, initial_capital=10000,
     default_qty_type=strategy.percent_of_equity, default_qty_value=100)

rsiLen     = input.int(14, "RSI length", minval=1)
overbought = input.int(70, "Overbought level", minval=51, maxval=100)
oversold   = input.int(30, "Oversold level", minval=0, maxval=49)
maxHold    = input.int(10, "Max hold (bars)", minval=1)

rsi = ta.rsi(close, rsiLen)
atrVal = ta.atr(14)

var int barsInTrade = 0
inTrade = strategy.position_size != 0
if inTrade
    barsInTrade += 1
else
    barsInTrade := 0

longSignal = ta.crossover(rsi, oversold)

if longSignal and not inTrade
    strategy.entry("Long", strategy.long)

if inTrade
    strategy.exit("Exit Long", "Long", profit=atrVal * 2, loss=atrVal)
    if barsInTrade >= maxHold
        strategy.close("Long", comment="Time exit")

plot(rsi, "RSI", color=color.new(color.purple, 0))
hline(overbought, "Overbought", color=color.new(color.red, 0))
hline(oversold, "Oversold", color=color.new(color.green, 0))

The Python output

rsi_mean_reversion.pyPython · PyneCore
"""
@pyne
"""

from pynecore import Persistent, Series
from pynecore.lib import close, color, hline, input, plot, script, strategy, ta

_pyne_in_rsiLen: int = input.int(14, "RSI length", minval=1)
_pyne_in_overbought: int = input.int(70, "Overbought level", minval=51, maxval=100)
_pyne_in_oversold: int = input.int(30, "Oversold level", minval=0, maxval=49)
_pyne_in_maxHold: int = input.int(10, "Max hold (bars)", minval=1)

@script.strategy(title="RSI Mean Reversion", overlay=True, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
def main():
    rsi: Series[float] = ta.rsi(close, _pyne_in_rsiLen)
    atrVal: Series[float] = ta.atr(14)
    barsInTrade: Persistent[int] = 0
    inTrade: Series[bool] = (strategy.position_size != 0)
    if inTrade:
        barsInTrade = (barsInTrade + 1)
    else:
        barsInTrade = 0
    longSignal: Series[float] = ta.crossover(rsi, _pyne_in_oversold)
    if (longSignal and (not inTrade)):
        strategy.entry("Long", strategy.long)
    if inTrade:
        strategy.exit("Exit Long", "Long", profit=(atrVal * 2), loss=atrVal)
        if (barsInTrade >= _pyne_in_maxHold):
            strategy.close("Long", comment="Time exit")
    plot(rsi, "RSI", color=color.new(color.purple, 0))
    hline(_pyne_in_overbought, "Overbought", color=color.new(color.red, 0))
    hline(_pyne_in_oversold, "Oversold", color=color.new(color.green, 0))

What translates 1:1

The var int barsInTrade = 0 counter becomes a Persistent[int] — a variable that keeps its value between bars, which is exactly what var means in Pine. The strategy.exit / strategy.close pair, the ta.crossover signal, and the plot / hline calls all carry over with their names and argument shapes intact. ta.rsi and ta.atr are the same functions in the PyneCore standard library.

The correction: the exit is in ticks, not points

Read the exit line again: strategy.exit("Exit Long", "Long", profit=atrVal * 2, loss=atrVal). In Pine, strategy.exit's profit and loss are distances in ticks from the entry price, not price points — TradingView's own strategy documentation says so. Price-level brackets use limit and stop instead. We verified the consequence by running this exact strategy in the PyneCore emulator on 4,089 bars of CSI 300 daily data (2010-01-04 to 2026-11-06): all 60 trades exited one bar after entry, and the 10-bar time exit fired zero times, because the tick bracket was about 0.00016 points wide at the default tick size.

The fix, if you want the bracket this script appears to describe, is price levels: limit = entryPrice + atrVal * 2, stop = entryPrice - atrVal, where entryPrice = strategy.position_avg_price. We re-ran the fixed version the same way: the time exit fired 6 times — the first on the very first trade — trades lasted 3.6 bars on average instead of 1.0, and the net result was -$2,572.67 (-25.73%) against the tick version's -$1,353.29 (-13.53%). Fixing the units changed what the strategy is, not whether it works. The full teardown, with the exact bar where the two runs diverge, is in our tutorial series: Same Pine Script, Two Backtests, Opposite Results.

Two things to take from this before you trust any converted exit: first, check the units of every strategy.exit argument — ticks, points, and percent are three different brackets wearing similar syntax. Second, quote the exit count, not just the net: "the time exit fired 6 times" is the check that the rule you think you tested is the rule that ran.

What else changes meaning

The fill is the next bar's open. The entry signaled on bar N fills at bar N+1's open in the emulator, and the bracket — once fixed to price levels — is evaluated against the following bar's high and low. A stop loss does not protect you from a gap: in the fixed run, one trade entered at 3014.91 with the stop at 2945.17 and the next bar opened at 2835.88, filling at the open for the run's largest loss.

The RSI warm-up matters. PyneCore's ta.rsi seeds Wilder's smoothing with the average of the first 14 bars; a hand-written pandas version starting its exponential average at bar 1 disagrees by up to 16.47 RSI points over the first hundred bars — enough to create a trade in one engine that never exists in the other. The first divergence between the two engines in our teardown was exactly that: bar 22, 2010-02-03.

Try it on your own script

Paste this Pine script — or your own — into the converter on the home page and compare the output. Every account gets 3 free conversions, no card required; Pro is $12/month via Paddle for unlimited conversions.

The output runs on the open-source PyneCore runtime. We ship a patched runtime build for the two constructs stock PyneCore doesn't handle yet — details are on the home page. Pine2Py translates code; it does not provide investment advice, and no backtest result on this page is a promise about any strategy's future performance.