Conversion example · Strategy

RSI trailing stop: Pine Script to Python

An RSI mean-reversion strategy on the CSI 300, long only, with one change from the RSI example: the 10-bar clock exit is gone, replaced by a trailing stop. The trail is the highest close since entry minus 2×ATR, recomputed every bar and tracked with a var so it only ever rises; the trade closes when the close falls below it. The hard stop (2×ATR below entry) stays as the backstop. This page is about what a trailing stop actually does when you measure it instead of assuming it — because “let your winners run” is a slogan, and the run below prices 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_trail.pinePine Script v6
//@version=6
strategy("RSI Mean Reversion (trailing exit, stop 2xATR)", 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)

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

// Trailing exit, fixed before running (pre-announced in #17):
// trail = highest close since entry minus 2xATR, recomputed each bar,
// tracked with a var so it only ever rises. The trade closes when the
// close falls below it. No time exit. Hard stop (2xATR below entry)
// stays as the backstop.
var float trailLevel = na
inTrade = strategy.position_size != 0
if inTrade
    trailLevel := na(trailLevel) ? close - atrVal * 2 : math.max(trailLevel, close - atrVal * 2)
else
    trailLevel := na

longSignal = ta.crossover(rsi, oversold)

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

if inTrade
    strategy.exit("Exit Long", "Long", stop=strategy.position_avg_price - atrVal * 2)
    if close < trailLevel
        strategy.close("Long", comment="Trail 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_trail.pyPython · PyneCore
"""
@pyne
"""

from pynecore import Persistent, Series
from pynecore.lib import close, color, hline, input, math, na, plot, script
from pynecore.lib import 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)

@script.strategy(title="RSI Mean Reversion (trailing exit, stop 2xATR)", 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)
    trailLevel: Persistent[float] = na
    inTrade: Series[bool] = (strategy.position_size != 0)
    if inTrade:
        trailLevel = ((close - (atrVal * 2)) if na(trailLevel) else math.max(trailLevel, (close - (atrVal * 2))))
    else:
        trailLevel = na
    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", stop=(strategy.position_avg_price - (atrVal * 2)))
        if (close < trailLevel):
            strategy.close("Long", comment="Trail 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

var float trailLevel = na becomes a Persistent[float] in Python — the same bar-by-bar persistence the RSI example's var int barsInTrade counter uses, now holding a price level instead of a count. na(trailLevel) ? ... : math.max(trailLevel, ...) survives verbatim: the ternary, the na() test and math.max all keep their names and shapes. strategy.exit with a stop= and strategy.close with a comment= both pass through untouched, and the comment string (“Trail exit”) is what the backtest log later uses to classify the exit by reason.

What else changes meaning

The trail is judged on closes and paid at opens. strategy.close placed at bar b's close fills at bar b+1's open, so any overnight gap between the trigger close and the exit open is yours to keep. In this run, trade #16 is the receipt: trigger close 2,190.48 on 2013-07-19, exit at the next open 2,170.09 — 20.39 points below the trigger close — turning a +$83.12 clock exit into a −$229.04 trail exit. A trailing stop doesn't exit at the trail. It exits at the next open after the trail breaks.

Every trail exit pays give-back, and it is measured. Give-back = highest close since entry minus exit price: median 156.60 points across the 29 trail exits, mean 161.78, max 410.85 (trade #19, which ran to 4,250.81 and still lost $75.78). The 10-bar clock's give-back was zero by construction — it never waited for a high — so the trail's advantage below is after paying that toll 29 times. The trail's trigger logic was verified independently: all 29 trail exits match a recomputed trigger bar (first close below the running trail) plus a next-bar-open fill, 29/29, no mismatches.

The stop column is still winless. 19 of 48 exits hit the hard stop, 0 wins, −$6,428.11 — and four of those are trades the 10-bar clock used to exit by time, which the trail held until the stop took them (−$997.22 against the clock). A close-based exit is slow by construction: when price falls fast enough to hit the stop intrabar, the trail never gets to speak.

The run: the best exit of four, by $109.65

We ran the trailing-stop variant in the PyneCore patched runtime on 4,089 bars of CSI 300 daily data (2010-01-04 to 2026-11-06), $10,000, 100% of equity per trade, no commission, no slippage — in our testing. Same 49 entries as the three clock variants (10, 15 and 20 bars), identical bars and prices, so every dollar below is an exit effect:

Clock 10 barsTrailing stop
Closed trades4848
Stop exits / trail exits18 / 30 clock19 / 29 trail
Wins23 (47.9%)19 (39.6%)
Net profit+$2,420.59+$2,530.24
Profit Factor1.3781.302
Gross profit / gross loss+$8,830.95 / −$6,410.36+$10,908.26 / −$8,378.02
Avg win / avg loss$383.95 / −$256.41$574.12 / −$288.90
Avg hold7.77 bars17.04 bars
Max equity drawdown$1,927.79 (19.02%)$1,881.50 (18.82%)
Buy & hold, same span+$1,468.22+$1,468.22
Top-5 winners' share of gross profit55.7%63.7%
Net minus the biggest trade (#45)+$88.60+$168.70

The honest version of that headline: the trail is the best of the four exits, and the margin over the 10-bar clock is $109.65 on 49 trades — less than one average losing trade — while the Profit Factor moved the wrong way (1.302 vs 1.378) and the concentration got worse (63.7% vs 55.7%). The trail did keep the two long winners the clock cut short (trade #20: 59 bars, +$925.95; trade #14: 51 bars, +$1,883.80), and it saved three of the seven winners that flipped to losers between bars 10 and 15. But the whole advantage over the clock is +37.17 points across 49 trades, and without the single biggest trade (#45, +$2,361.54) the net is +$168.70 — below buy & hold on the same span. One symbol, one period, no costs — run it on your own symbol before believing any of it.

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.