Monthly RSI 70 Breakout

Vishwajeeth_JK · strategy · 290 行 · 点赞 39 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// Monthly RSI(14) > 70 Breakout — trend-following, long-only
// Use on the MONTHLY timeframe.
// Bar magnifier (Premium+) makes intramonth fills follow the real daily path.
strategy("Monthly RSI 70 Breakout", shorttitle = "M-RSI70", overlay = false,
     initial_capital = 1000000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20,
     commission_type = strategy.commission.percent, commission_value = 0.1, slippage = 2,
     pyramiding = 0, process_orders_on_close = true, max_labels_count = 500,
     use_bar_magnifier = true)
 
// ───────── Inputs ─────────
grpE = "Entry"
rsiLen       = input.int(14, "RSI length", minval = 2, group = grpE)
entryLevel   = input.float(70.0, "RSI entry level", group = grpE)
requireBull  = input.bool(true, "Signal candle must be bullish (close > open)", group = grpE)
requireAth   = input.bool(false, "Signal candle must close above prior all-time high", group = grpE)
useBreakout  = input.bool(false, "Breakout filter: enter above signal high (next month only)", group = grpE,
     tooltip = "OFF = enter at the signal month's close.\nON = buy-stop above the signal candle's high, valid only during the very next month.")
invalidOnLow = input.bool(true, "   Invalid if signal low breaks before entry", group = grpE,
     tooltip = "Uses daily data inside the trigger month to see which broke first. If the low broke first, the setup is invalid. If the order still filled, it is closed at that month's close and excluded from the stats table.")
startDate    = input.time(timestamp("2005-01-01T00:00:00"), "Backtest start", group = grpE)
 
grpX = "Exit"
usePrevLow    = input.bool(true, "Initial stop: previous month's low", group = grpX)
prevLowMonths = input.int(2, "   Initial-stop period (months)", minval = 1, maxval = 12, group = grpX)
ratchetStop   = input.bool(true, "   Never lower the stop", group = grpX)
useRsiExit    = input.bool(true, "RSI exit (after initial period)", group = grpX)
rsiExitLevel  = input.float(69.3, "   RSI exit level", group = grpX)
 
grpP = "Profit taking (optional)"
usePartial = input.bool(false, "Partial profits at price multiples", group = grpP)
tp1Mult    = input.float(2.0, "   Target 1 (x entry price)", minval = 1.1, step = 0.5, group = grpP)
tp1Pct     = input.float(33, "   Target 1: sell % of position", minval = 1, maxval = 100, group = grpP)
tp2Mult    = input.float(3.0, "   Target 2 (x entry price)", minval = 1.1, step = 0.5, group = grpP)
tp2Pct     = input.float(50, "   Target 2: sell % of remaining", minval = 1, maxval = 100, group = grpP)
useRsiTp   = input.bool(false, "Partial profit at extreme RSI", group = grpP)
rsiTpLevel = input.float(85.0, "   RSI profit level", minval = 70, maxval = 100, group = grpP)
rsiTpPct   = input.float(50, "   Sell % of remaining", minval = 1, maxval = 100, group = grpP)
 
grpD = "Display"
showTradeLbl = input.bool(true, "Show % captured + duration on each trade", group = grpD)
showStats    = input.bool(true, "Show stats table", group = grpD)
 
// ───────── Calculations ─────────
rsiVal   = ta.rsi(close, rsiLen)
priorAth = ta.max(high)[1]
bullOk   = not requireBull or close > open
athOk    = not requireAth or na(priorAth) or close > priorAth
inWindow = time >= startDate
signal   = ta.crossover(rsiVal, entryLevel) and bullOk and athOk and inWindow
 
isFlat = strategy.position_size == 0
inPos  = strategy.position_size > 0
 
// Daily bars inside each chart bar (used to see whether high or low broke first)
ltfTf = timeframe.in_seconds() > 86400 ? "D" : timeframe.period
[dO, dH, dL] = request.security_lower_tf(syminfo.tickerid, ltfTf, [open, high, low])
 
// ───────── State ─────────
var int   pendingBar   = na
var float sigHigh      = na
var float sigLow       = na
var float stopLvl      = na
var bool  tp1Done      = false
var bool  tp2Done      = false
var bool  rsiTpDone    = false
var bool  invalidTrade = false
var int   invalidCount = 0
 
if isFlat
    tp1Done   := false
    tp2Done   := false
    rsiTpDone := false
 
// ───────── Breakout resolution (the month after the signal) ─────────
isTriggerBar = not na(pendingBar) and bar_index == pendingBar + 1
 
lowFirst = false
if isTriggerBar and useBreakout and invalidOnLow and not na(sigLow)
    trig = sigHigh + syminfo.mintick
    n    = array.size(dH)
    if n > 0
        int hiIdx = -1
        int loIdx = -1
        for i = 0 to n - 1
            if loIdx < 0 and array.get(dL, i) < sigLow
                loIdx := i
            if hiIdx < 0 and array.get(dH, i) >= trig
                hiIdx := i
        if loIdx >= 0 and hiIdx >= 0 and loIdx == hiIdx
            // Both broke on the same day → gap at open decides, else whichever is closer to the open
            o = array.get(dO, loIdx)
            lowFirst := o < sigLow ? true : o >= trig ? false : (o - array.get(dL, loIdx)) < (array.get(dH, loIdx) - o)
        else
            lowFirst := loIdx >= 0 and (hiIdx < 0 or loIdx < hiIdx)
    else
        // No daily data available → conservative: any low break in the trigger month invalidates
        lowFirst := low < sigLow
 
if isTriggerBar
    // Order was valid for this one month only
    if isFlat
        strategy.cancel("Long")
        strategy.cancel("Init SL")
 
    // Low broke before the breakout → setup invalid
    enteredNow = inPos and strategy.opentrades.entry_bar_index(0) == bar_index
    stoppedNow = isFlat and strategy.closedtrades > 0 and strategy.closedtrades.entry_bar_index(strategy.closedtrades - 1) == bar_index
    if lowFirst and (enteredNow or stoppedNow)
        invalidTrade := true
        if enteredNow
            strategy.close("Long", comment = "Invalid: low broke first")
    pendingBar := na
 
// ───────── Entry ─────────
if signal and isFlat
    sigHigh := high
    sigLow  := low
    stopLvl := low
    if not useBreakout
        strategy.entry("Long", strategy.long, comment = "RSI>70 close")
    else
        strategy.entry("Long", strategy.long, stop = high + syminfo.mintick, comment = "RSI>70 breakout")
        pendingBar := bar_index
    if usePrevLow
        strategy.exit("Init SL", "Long", stop = low, comment = "Prev-month low")
 
// ───────── Position management ─────────
monthsHeld   = inPos ? bar_index - strategy.opentrades.entry_bar_index(0) : na
initialPhase = inPos and usePrevLow and monthsHeld < prevLowMonths and not invalidTrade
 
if inPos and not invalidTrade
    // 1) Initial period: stop at previous month's low (optionally never lowered)
    if initialPhase
        stopLvl := ratchetStop ? math.max(nz(stopLvl, low), low) : low
        strategy.exit("Init SL", "Long", stop = stopLvl, comment = "Prev-month low")
    else
        strategy.cancel("Init SL")
        // 2) After that: exit on monthly close below RSI exit level
        if useRsiExit and rsiVal < rsiExitLevel
            strategy.close("Long", comment = "RSI exit")
 
    // 3) Optional partial profits (checked on monthly close)
    entryPx = strategy.position_avg_price
    if usePartial
        if not tp1Done and close >= entryPx * tp1Mult
            strategy.close("Long", qty_percent = tp1Pct, comment = "TP1 " + str.tostring(tp1Mult) + "x")
            tp1Done := true
        else if tp1Done and not tp2Done and close >= entryPx * tp2Mult
            strategy.close("Long", qty_percent = tp2Pct, comment = "TP2 " + str.tostring(tp2Mult) + "x")
            tp2Done := true
 
    if useRsiTp and not rsiTpDone and rsiVal >= rsiTpLevel
        strategy.close("Long", qty_percent = rsiTpPct, comment = "RSI " + str.tostring(rsiTpLevel))
        rsiTpDone := true
 
// ───────── Helpers ─────────
DAY_MS = 86400000.0
 
fmtPct(float p) =>
    (p >= 0 ? "+" : "") + str.tostring(p, "#.##") + "%"
 
fmtDur(int months, float days) =>
    str.tostring(months) + " months · " + str.tostring(math.round(days)) + " days"
 
// ───────── % captured + duration per trade ─────────
var int          lastClosed = 0
var float        accPnl     = 0.0
var float        accCost    = 0.0
var array<float> tradePcts  = array.new<float>()
var array<int>   tradeBars  = array.new<int>()
var array<float> tradeDays  = array.new<float>()
 
if strategy.closedtrades > lastClosed
    for i = lastClosed to strategy.closedtrades - 1
        ep = strategy.closedtrades.entry_price(i)
        xp = strategy.closedtrades.exit_price(i)
        sz = math.abs(strategy.closedtrades.size(i))
        accPnl  += (xp - ep) * sz
        accCost += ep * sz
    lastClosed := strategy.closedtrades
 
    // Position fully closed → record the whole trade
    if strategy.position_size == 0 and accCost > 0
        lastI = strategy.closedtrades - 1
        pct   = accPnl / accCost * 100
        xBar  = strategy.closedtrades.exit_bar_index(lastI)
        bars  = xBar - strategy.closedtrades.entry_bar_index(lastI)
        days  = (strategy.closedtrades.exit_time(lastI) - strategy.closedtrades.entry_time(lastI)) / DAY_MS
        if invalidTrade
            // Setup was invalid (low broke first) → excluded from stats
            invalidCount += 1
            if showTradeLbl
                label.new(xBar, 0, "INVALID\nlow broke first\n(" + fmtPct(pct) + ")",
                     yloc = yloc.abovebar, style = label.style_label_down, size = size.small,
                     color = color.new(color.gray, 10), textcolor = color.white, force_overlay = true)
            invalidTrade := false
        else
            array.push(tradePcts, pct)
            array.push(tradeBars, bars)
            array.push(tradeDays, days)
            if showTradeLbl
                label.new(xBar, 0, fmtPct(pct) + "\n" + fmtDur(bars, days),
                     yloc = yloc.abovebar, style = label.style_label_down, size = size.normal,
                     color = pct >= 0 ? color.new(color.green, 10) : color.new(color.red, 10),
                     textcolor = color.white, force_overlay = true)
        accPnl  := 0.0
        accCost := 0.0
 
// Open trade: running % and time in trade
var label openLbl = na
openPct  = inPos ? (close - strategy.position_avg_price) / strategy.position_avg_price * 100 : na
openFrom = inPos ? (not useBreakout ? time_close[monthsHeld] : strategy.opentrades.entry_time(0)) : na
openDays = inPos ? (timenow - openFrom) / DAY_MS : na
 
if barstate.islast
    label.delete(openLbl)
    if inPos and showTradeLbl
        openLbl := label.new(bar_index, 0, "OPEN " + fmtPct(openPct) + "\n" + fmtDur(monthsHeld, openDays),
             yloc = yloc.abovebar, style = label.style_label_down,
             color = color.new(color.blue, 10), textcolor = color.white, force_overlay = true)
 
// ───────── Stats table ─────────
var table stats = table.new(position.top_left, 2, 13, bgcolor = color.new(color.black, 20),
     border_color = color.gray, border_width = 1)
 
cell(int row, string k, string v, color vc) =>
    table.cell(stats, 0, row, k, text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(stats, 1, row, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
if barstate.islast and showStats
    n       = array.size(tradePcts)
    wins    = 0
    sumWin  = 0.0
    sumLoss = 0.0
    growth  = 1.0
    for p in tradePcts
        if p > 0
            wins   += 1
            sumWin += p
        else
            sumLoss += p
        growth *= (1 + p / 100)
    losses  = n - wins
    pos     = color.lime
    neg     = color.red
    avgP    = n > 0 ? array.avg(tradePcts) : na
    bestP   = n > 0 ? array.max(tradePcts) : na
    worstP  = n > 0 ? array.min(tradePcts) : na
    avgBars = n > 0 ? array.avg(tradeBars) : na
    avgDays = n > 0 ? array.avg(tradeDays) : na
    totalP  = (growth - 1) * 100
 
    cell(0,  "Trades (closed)", str.tostring(n), color.white)
    cell(1,  "Win rate", n > 0 ? str.tostring(wins / n * 100, "#.#") + "%  (" + str.tostring(wins) + "W / " + str.tostring(losses) + "L)" : "-", color.white)
    cell(2,  "Avg % per trade", n > 0 ? fmtPct(avgP) : "-", avgP >= 0 ? pos : neg)
    cell(3,  "Avg winner", wins > 0 ? fmtPct(sumWin / wins) : "-", pos)
    cell(4,  "Avg loser", losses > 0 ? fmtPct(sumLoss / losses) : "-", neg)
    cell(5,  "Best trade", n > 0 ? fmtPct(bestP) : "-", pos)
    cell(6,  "Worst trade", n > 0 ? fmtPct(worstP) : "-", neg)
    cell(7,  "Avg holding", n > 0 ? str.tostring(avgBars, "#.#") + " months · " + str.tostring(avgDays, "#") + " days" : "-", color.white)
    cell(8,  "Compounded (all trades)", n > 0 ? fmtPct(totalP) : "-", totalP >= 0 ? pos : neg)
    cell(9,  "Open trade", inPos ? fmtPct(openPct) + "  ·  " + fmtDur(monthsHeld, openDays) : "None", inPos ? (openPct >= 0 ? pos : neg) : color.gray)
    cell(10, "Entry mode", useBreakout ? "Breakout (next month)" : "Monthly close", color.white)
    if useBreakout and invalidOnLow
        cell(11, "Invalid fills (excluded)", str.tostring(invalidCount), color.gray)
    if not timeframe.ismonthly
        cell(12, "⚠ Timeframe", "Switch chart to 1M", color.orange)
 
// ───────── Visuals ─────────
plot(rsiVal, "RSI", color = rsiVal >= entryLevel ? color.green : color.gray, linewidth = 2)
hline(entryLevel, "Entry level", color = color.green, linestyle = hline.style_dashed)
hline(rsiExitLevel, "Exit level", color = color.red, linestyle = hline.style_dotted)
hline(rsiTpLevel, "Profit level", color = color.orange, linestyle = hline.style_dotted)
bgcolor(signal ? color.new(color.green, 85) : na)
 
plotshape(signal, "Signal", shape.triangleup, location.belowbar, color.green, size = size.small, force_overlay = true)
 
stopToShow = initialPhase ? stopLvl : (signal and isFlat and usePrevLow) ? low : na
plot(stopToShow, "Initial stop", color = color.red, style = plot.style_linebr, linewidth = 2, offset = 1, force_overlay = true)
 
brkToShow = signal and isFlat and useBreakout ? high + syminfo.mintick : na
plot(brkToShow, "Breakout level", color = color.lime, style = plot.style_linebr, linewidth = 2, offset = 1, force_overlay = true)
 
// Alert (create via Alerts > "alert() function calls only")
if signal
    msg = syminfo.ticker + ": monthly RSI crossed above " + str.tostring(entryLevel)
    if useBreakout
        msg += " | Buy above " + str.tostring(high + syminfo.mintick, format.mintick) + " next month, invalid below " + str.tostring(low, format.mintick)
    alert(msg, alert.freq_once_per_bar_close)

← 返回列表