Relative Strength Rotation [Gabremoku]

Gabremoku · study · 216 行 · 点赞 149 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gabremoku
//@version=6
indicator("Relative Strength Rotation [Gabremoku]", shorttitle="RS Rotation [Gabremoku]", overlay=false)
 
// ═══════════════════════════════════════════════════════════════
//  Relative Strength Rotation [Gabremoku]
//  Quadrant-based relative strength rotation: RS-Ratio / RS-Momentum
//  against a benchmark, with volume-confirmed rotation
//  Bull = Blue | Bear = Yellow | Chop/Weak Rotation = Purple
// ═══════════════════════════════════════════════════════════════
 
// ── INPUTS ───────────────────────────────────────────────────────
grp0 = "⚙️ Core"
benchmarkInput = input.symbol("SPY", "Benchmark", group=grp0, tooltip="Symbol the chart is compared against. If it has no data on this chart, the dashboard shows 'No data'.")
rsRatioLen     = input.int(14, "RS-Ratio Length", minval=2, group=grp0)
rsMomLen       = input.int(14, "RS-Momentum Length", minval=1, group=grp0)
 
grp1 = "🎨 Colors"
bullColor    = input.color(color.rgb(33, 150, 243), "Bullish Color (Blue)", group=grp1)
bearColor    = input.color(color.rgb(241, 255, 48), "Bearish Color (Yellow)", group=grp1)
squeezeColor = input.color(color.rgb(156, 39, 176), "Chop / Weak Rotation Color (Purple)", group=grp1)
neutralColor = input.color(color.gray, "Neutral Color", group=grp1)
 
grp2 = "🌈 Gradient"
gradientScale      = input.float(20.0, "RS Distance Gradient Scale", minval=1.0, group=grp2)
scoreGradientScale = input.float(25.0, "Composite Score Gradient Scale", minval=1.0, group=grp2)
fillAggressive     = input.float(1.6, "Fill Aggressiveness", minval=0.5, maxval=4.0, step=0.1, group=grp2)
fillTranspNear     = input.int(85, "Fill Transparency Near Baseline", minval=0, maxval=100, group=grp2, tooltip="0 = solid, 100 = invisible. The fill is faint near the baseline and gets stronger as RS-Ratio moves away from it.")
fillTranspFar      = input.int(25, "Fill Transparency Far From Baseline", minval=0, maxval=100, group=grp2)
 
grp3 = "💧 Volume Confirmation"
cmfLen       = input.int(20, "CMF Length", minval=1, group=grp3)
cmfThreshold = input.float(0.05, "CMF Confirmation Threshold", step=0.01, group=grp3)
 
grp4 = "🗜️ Chop Zone"
chopLookback     = input.int(100, "Chop Lookback", minval=10, group=grp4)
chopThresholdPct = input.float(0.25, "Chop Threshold Percentile", minval=0.01, maxval=0.50, step=0.01, group=grp4)
highlightChopBg  = input.bool(false, "Highlight Chop Background", group=grp4)
 
grp5 = "📐 Style"
showBackground = input.bool(true, "Gradient Background by Score", group=grp5)
showFill       = input.bool(true, "Show Gradient Fill (RS-Ratio vs Baseline)", group=grp5)
showLabels     = input.bool(true, "Show Buy/Sell Labels on Chart", group=grp5)
 
grp6 = "🪧 Dashboard"
dashPosInput      = input.string("Bottom Right", "Dashboard Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grp6)
dashTextSizeInput = input.string("Small", "Dashboard Text Size", options=["Tiny", "Small", "Normal"], group=grp6)
showDashboard     = input.bool(true, "Show Dashboard", group=grp6)
 
dashTextSize = size.small
if dashTextSizeInput == "Tiny"
    dashTextSize := size.tiny
else if dashTextSizeInput == "Normal"
    dashTextSize := size.normal
 
dashPos = position.bottom_right
if dashPosInput == "Top Right"
    dashPos := position.top_right
else if dashPosInput == "Top Left"
    dashPos := position.top_left
else if dashPosInput == "Bottom Left"
    dashPos := position.bottom_left
 
// ── FUNCTIONS ──────────────────────────────────────────────────
clamp(_x, _min, _max) =>
    math.max(_min, math.min(_max, _x))
 
// ── RELATIVE STRENGTH CORE ──────────────────────────────────────
benchClose = request.security(benchmarkInput, timeframe.period, close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
 
ratio     = close / benchClose
ratioSma  = ta.sma(ratio, rsRatioLen)
ratioStd  = ta.stdev(ratio, rsRatioLen)
 
benchOk = not na(benchClose)
 
// z-score of the price ratio, rescaled around a 100 baseline (RS-Ratio)
rsRatio = ratioStd > 0 ? 100.0 + (ratio - ratioSma) / ratioStd * 10.0 : 100.0
 
// rate of change of RS-Ratio, offset to the same 100 baseline (RS-Momentum)
rsMomentum = 100.0 + nz(ta.roc(rsRatio, rsMomLen))
 
// ── VOLUME CONFIRMATION (Chaikin Money Flow) ────────────────────
mfm    = (high - low) != 0 ? ((close - low) - (high - close)) / (high - low) : 0.0
mfv    = mfm * volume
volSma = ta.sma(volume, cmfLen)
hasVolume = not na(volume) and volSma != 0
cmf    = hasVolume ? ta.sma(mfv, cmfLen) / volSma : 0.0
 
volConfirm = not hasVolume ? "No Volume" : cmf > cmfThreshold ? "Bullish" : cmf < -cmfThreshold ? "Bearish" : "Neutral"
 
// ── QUADRANT CLASSIFICATION ─────────────────────────────────────
isLeading   = rsRatio >= 100 and rsMomentum >= 100
isWeakening = rsRatio >= 100 and rsMomentum <  100
isLagging   = rsRatio <  100 and rsMomentum <  100
isImproving = rsRatio <  100 and rsMomentum >= 100
 
quadrant = isLeading ? "Leading" : isWeakening ? "Weakening" : isLagging ? "Lagging" : "Improving"
 
// composite score: rotation magnitude scaled by whether volume agrees with it
// (neutral multiplier when the symbol has no volume data, so the score is not penalized)
volAgrees      = ((isLeading or isImproving) and cmf > 0) or ((isWeakening or isLagging) and cmf < 0)
volMultiplier  = not hasVolume ? 1.0 : volAgrees ? 1.2 : 0.7
compositeScore = ((rsRatio - 100) + (rsMomentum - 100)) * volMultiplier
 
// ── CHOP / WEAK ROTATION DETECTION ───────────────────────────────
// Distance from the (100, 100) center in RS-Ratio / RS-Momentum space.
// Uses percentrank instead of min-max normalization: min-max collapses
// under a single historical outlier spike (e.g. an isolated blow-off),
// percentrank stays robust because it ranks the current value against
// its history rather than rescaling by the extremes.
ratioDist0 = rsRatio - 100.0
momDist0   = rsMomentum - 100.0
rotationStrength = math.sqrt(math.pow(ratioDist0, 2) + math.pow(momDist0, 2))
 
strengthPercentile = ta.percentrank(rotationStrength, chopLookback)
isChop = strengthPercentile <= (chopThresholdPct * 100.0)
 
// ── GRADIENT COLORS (blue = bullish rotation, yellow = bearish rotation) ──
scoreNorm = clamp(math.pow(clamp(math.abs(compositeScore) / scoreGradientScale, 0.0, 1.0), fillAggressive), 0.0, 1.0)
quadColorRaw = compositeScore >= 0
     ? color.from_gradient(scoreNorm, 0.0, 1.0, neutralColor, bullColor)
     : color.from_gradient(scoreNorm, 0.0, 1.0, neutralColor, bearColor)
quadColor = isChop ? squeezeColor : quadColorRaw
 
ratioDist     = rsRatio - 100.0
ratioDistNorm = clamp(math.pow(clamp(math.abs(ratioDist) / gradientScale, 0.0, 1.0), fillAggressive), 0.0, 1.0)
rsRatioColorRaw = ratioDist >= 0
     ? color.from_gradient(ratioDistNorm, 0.0, 1.0, neutralColor, bullColor)
     : color.from_gradient(ratioDistNorm, 0.0, 1.0, neutralColor, bearColor)
rsRatioColor = isChop ? squeezeColor : rsRatioColorRaw
 
momDist     = rsMomentum - 100.0
momDistNorm = clamp(math.pow(clamp(math.abs(momDist) / gradientScale, 0.0, 1.0), fillAggressive), 0.0, 1.0)
rsMomentumColorRaw = momDist >= 0
     ? color.from_gradient(momDistNorm, 0.0, 1.0, neutralColor, bullColor)
     : color.from_gradient(momDistNorm, 0.0, 1.0, neutralColor, bearColor)
rsMomentumColor = isChop ? color.new(squeezeColor, 30) : rsMomentumColorRaw
 
// gradient fill between RS-Ratio and the 100 baseline
bullNear = color.new(bullColor, fillTranspNear)
bullFar  = color.new(bullColor, fillTranspFar)
bearNear = color.new(bearColor, fillTranspNear)
bearFar  = color.new(bearColor, fillTranspFar)
chopFill = color.new(squeezeColor, fillTranspNear)
 
fillColor = isChop
     ? chopFill
     : ratioDist >= 0
         ? color.from_gradient(ratioDistNorm, 0.0, 1.0, bullNear, bullFar)
         : color.from_gradient(ratioDistNorm, 0.0, 1.0, bearNear, bearFar)
 
// ── PLOTTING ─────────────────────────────────────────────────────
baselinePlot = plot(100.0, "Baseline", color=color.new(neutralColor, 50), linewidth=1, style=plot.style_line)
rsRatioPlot  = plot(rsRatio, "RS-Ratio", color=rsRatioColor, linewidth=2)
plot(rsMomentum, "RS-Momentum", color=rsMomentumColor, linewidth=1)
 
fill(rsRatioPlot, baselinePlot, color=showFill ? fillColor : na, title="RS Gradient Fill")
 
bgColorFinal = highlightChopBg and isChop ? color.new(squeezeColor, 85) : (showBackground ? color.new(quadColor, 88) : na)
bgcolor(bgColorFinal)
 
// ── OVERLAY LABELS (BUY = blue, SELL = yellow, chop = purple) ────
var string lastSignal = "none"
 
buyCondition  = isLeading and not isLeading[1] and lastSignal != "buy"
sellCondition = isLagging and not isLagging[1] and lastSignal != "sell"
 
if showLabels and buyCondition
    buyLabelColor = isChop ? squeezeColor : bullColor
    label.new(bar_index, low, "BUY", xloc=xloc.bar_index, yloc=yloc.belowbar,
         style=label.style_label_up, color=buyLabelColor,
         textcolor=color.white, size=size.small, force_overlay=true)
    lastSignal := "buy"
 
if showLabels and sellCondition
    sellLabelColor = isChop ? squeezeColor : bearColor
    label.new(bar_index, high, "SELL", xloc=xloc.bar_index, yloc=yloc.abovebar,
         style=label.style_label_down, color=sellLabelColor,
         textcolor=isChop ? color.white : color.black, size=size.small, force_overlay=true)
    lastSignal := "sell"
 
// ── ALERTS ───────────────────────────────────────────────────────
alertcondition(isLeading and not isLeading[1], "Entered Leading", "Ticker entered Leading quadrant vs benchmark")
alertcondition(isWeakening and not isWeakening[1], "Entered Weakening", "Ticker entered Weakening quadrant vs benchmark")
alertcondition(isLagging and not isLagging[1], "Entered Lagging", "Ticker entered Lagging quadrant vs benchmark")
alertcondition(isImproving and not isImproving[1], "Entered Improving", "Ticker entered Improving quadrant vs benchmark")
 
// ── DASHBOARD ─────────────────────────────────────────────────
var table dash = table.new(dashPos, 2, 7, border_width=1)
 
if barstate.islast and showDashboard
    table.cell(dash, 0, 0, "Quadrant", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 0, quadrant, text_color=quadColor, text_halign=text.align_center, text_size=dashTextSize)
 
    table.cell(dash, 0, 1, "RS-Ratio", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 1, str.tostring(rsRatio, "0.00"), text_color=rsRatioColor, text_halign=text.align_center, text_size=dashTextSize)
    
    table.cell(dash, 0, 2, "RS-Momentum", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 2, str.tostring(rsMomentum, "0.00"), text_color=rsMomentumColor, text_halign=text.align_center, text_size=dashTextSize)
    
    table.cell(dash, 0, 3, "Volume Confirm", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 3, volConfirm, text_color=hasVolume and cmf > cmfThreshold ? bullColor : hasVolume and cmf < -cmfThreshold ? bearColor : neutralColor, text_halign=text.align_center, text_size=dashTextSize)
    
    table.cell(dash, 0, 4, "Composite Score", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 4, str.tostring(compositeScore, "0.00"), text_color=quadColor, text_halign=text.align_center, text_size=dashTextSize)
    
    table.cell(dash, 0, 5, "Chop Zone", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 5, isChop ? "ON" : "OFF", text_color=isChop ? squeezeColor : chart.fg_color, text_halign=text.align_center, text_size=dashTextSize)
    
    table.cell(dash, 0, 6, "Benchmark", text_color=chart.fg_color, text_halign=text.align_left, text_size=dashTextSize)
    table.cell(dash, 1, 6, benchOk ? benchmarkInput : "No data", text_color=benchOk ? chart.fg_color : bearColor, text_halign=text.align_center, text_size=dashTextSize)
 
if barstate.islast and not showDashboard
    table.clear(dash, 0, 0, 1, 6)

← 返回列表