Quantum RSI - Multi-Timeframe Confluence

TheScalpingAnt · study · 252 行 · 点赞 34 · TradingView 原页

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

Pine Script

//@version=6
indicator("Quantum RSI - Multi-Timeframe Confluence", shorttitle="Q-RSI", overlay=false, scale=scale.right, max_bars_back=5000)
 
// ENGINE - original Quantum RSI calculation, with numerical safeguards.
grpEngine = "Q-RSI Engine & Timeframes"
tfChart   = input.timeframe("", "Chart Timeframe - Zone 3", group=grpEngine, tooltip="Timeframe used for Zone 3 (the fast/local oscillator). Leave empty to automatically use the timeframe of the chart you are viewing.")
tfMacro1  = input.timeframe("2D", "Macro 1 - Zone 2", group=grpEngine, tooltip="Timeframe used for Zone 2 (the intermediate oscillator). Default is the 2-day chart. This should normally be higher than the Chart Timeframe to represent a broader market structure.")
tfMacro2  = input.timeframe("W", "Macro 2 - Zone 1", group=grpEngine, tooltip="Timeframe used for Zone 1 (the slow/macro oscillator). Default is the weekly chart. This should normally be the highest timeframe of the three, representing the dominant trend context.")
length3   = input.int(14, "RSI Length - Zone 3", minval=2, group=grpEngine, tooltip="Number of bars used in the Zone 3 (Chart Timeframe) oscillator calculation. Lower values react faster but produce more noise; higher values are smoother but slower to react.")
length2   = input.int(14, "RSI Length - Zone 2", minval=2, group=grpEngine, tooltip="Number of bars used in the Zone 2 (Macro 1) oscillator calculation. Lower values react faster but produce more noise; higher values are smoother but slower to react.")
length1   = input.int(14, "RSI Length - Zone 1", minval=2, group=grpEngine, tooltip="Number of bars used in the Zone 1 (Macro 2) oscillator calculation. Lower values react faster but produce more noise; higher values are smoother but slower to react.")
useVW     = input.bool(false, "Volume-weighted RSI", group=grpEngine, tooltip="When enabled, each bar's contribution to the oscillator is weighted by its traded volume, giving more influence to high-volume bars. Automatically falls back to an unweighted sample on symbols that report zero or missing volume, such as most forex and some CFD/index feeds.")
src       = input.source(close, "Source", group=grpEngine, tooltip="Price input used by all three oscillators. Close is the standard choice; HL2, HLC3 or OHLC4 can be used to smooth out single-print noise.")
confirmedHTF = input.bool(true, "Confirmed higher-timeframe values", group=grpEngine, tooltip="When enabled, Zone 1 and Zone 2 only use the value of the last fully closed higher-timeframe bar. This stabilizes those values at the cost of a one-higher-timeframe-bar delay. Zone 3 reflects its selected timeframe and develops until that bar closes. Disabling this allows higher-timeframe values to change while their current bar is forming.")
// --- HTF SMOOTHING PATCH (only addition - no engine change) ---
smooth2   = input.int(4, "Smoothing - Zone 2 (Macro 1)", minval=1, maxval=20, group=grpEngine, tooltip="Chart-bar smoothing applied after the Macro 1 request to round higher-timeframe steps into a continuous curve. 1 = off (original step line). 3-5 is typical.")
smooth1   = input.int(5, "Smoothing - Zone 1 (Macro 2)", minval=1, maxval=20, group=grpEngine, tooltip="Chart-bar smoothing applied after the Macro 2 request to round higher-timeframe steps into a continuous curve. 1 = off (original step line). 4-7 is typical for Weekly.")
 
// COLORS - the original white, #00ff00, #ff0000 and black are preserved.
groupLevels = "Levels Settings"
ob = input.int(70, "Overbought Level", minval=51, maxval=99, group=groupLevels, tooltip="Upper threshold on the 0-100 scale. Applies identically to all three zones.")
os = input.int(30, "Oversold Level", minval=1, maxval=49, group=groupLevels, tooltip="Lower threshold on the 0-100 scale. Applies identically to all three zones.")
colRsi3 = input.color(color.white, "RSI Color - Zone 3", group=groupLevels, tooltip="Base color for the Zone 3 oscillator when it is between the oversold and overbought levels. Also colors its value label in the neutral range.")
colRsi2 = input.color(color.white, "RSI Color - Zone 2", group=groupLevels, tooltip="Base color for the Zone 2 oscillator when it is between the oversold and overbought levels. Also colors its value label in the neutral range.")
colRsi1 = input.color(color.white, "RSI Color - Zone 1", group=groupLevels, tooltip="Base color for the Zone 1 oscillator when it is between the oversold and overbought levels. Also colors its value label in the neutral range.")
colOb = input.color(#00ff00, "70 Level Color", group=groupLevels, tooltip="Color of the overbought reference lines and of value labels above the overbought threshold.")
colOs = input.color(#ff0000, "30 Level Color", group=groupLevels, tooltip="Color of the oversold reference lines and of value labels below the oversold threshold.")
colMid = input.color(#000000, "50 Midline Color", group=groupLevels, tooltip="Color of the neutral 50 midline in every zone.")
colFillBull = input.color(#00ff00, "Bullish Gradient Color", group=groupLevels, tooltip="Shared base color for the gradient fill above the overbought level in all three zones.")
colFillBear = input.color(#ff0000, "Bearish Gradient Color", group=groupLevels, tooltip="Shared base color for the gradient fill below the oversold level in all three zones.")
obWidth = input.int(2, "70 Level Width", minval=1, maxval=4, group=groupLevels, tooltip="Line thickness of the overbought reference lines.")
osWidth = input.int(2, "30 Level Width", minval=1, maxval=4, group=groupLevels, tooltip="Line thickness of the oversold reference lines.")
midWidth = input.int(2, "50 Midline Width", minval=1, maxval=4, group=groupLevels, tooltip="Line thickness of the 50 midlines.")
 
grpLabels = "RSI Value Labels"
showValueLabels = input.bool(true, "Show RSI Value Labels", group=grpLabels, tooltip="Displays each zone's current 0-100 oscillator value as text to the right of its plotted line. This is a readout only and does not affect calculations or alerts.")
labelOffset = input.int(30, "Label Horizontal Offset (bars)", minval=0, maxval=40, group=grpLabels, tooltip="Number of chart bars to the right of the latest bar where the value labels are placed.")
labelSizeOpt = input.string("Normal", "Label Text Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpLabels, tooltip="Text size of the right-edge RSI value labels.")
 
grpLiquidity = "Liquidity Filter"
useVolFilter = input.bool(false, "Suppress alerts on low volume", group=grpLiquidity, tooltip="When enabled, alignment, recovery/rejection, and midline-cross alerts are suppressed when the current bar's volume is below the selected fraction of its recent average. Has no effect when volume is missing or zero.")
volAvgLen = input.int(20, "Volume average length", minval=5, group=grpLiquidity, tooltip="Number of chart bars used to calculate the rolling average volume baseline.")
volMinRatio = input.float(0.5, "Minimum volume ratio", minval=0.05, maxval=1.0, step=0.05, group=grpLiquidity, tooltip="Minimum ratio of current volume to its recent average required for alerts. For example, 0.5 requires volume to be at least half its average.")
 
grpPro = "Pro - Confluence & Alerts"
w3 = input.float(1.0, "Chart weight", minval=0.1, group=grpPro, tooltip="Relative weight of Zone 3 when calculating the bullish and bearish alignment percentages.")
w2 = input.float(1.5, "Macro 1 weight", minval=0.1, group=grpPro, tooltip="Relative weight of Zone 2 when calculating the bullish and bearish alignment percentages.")
w1 = input.float(2.0, "Macro 2 weight", minval=0.1, group=grpPro, tooltip="Relative weight of Zone 1 when calculating the bullish and bearish alignment percentages.")
threshold = input.float(75, "Alignment threshold (%)", minval=51, maxval=100, group=grpPro, tooltip="Minimum weighted alignment percentage required for a bullish or bearish MTF alignment alert.")
cooldown = input.int(5, "Alert cooldown (chart bars)", minval=0, group=grpPro, tooltip="Minimum number of chart bars between alignment, recovery, or rejection alerts. Does not apply to the discrete midline-cross alerts.")
waitForClose = input.bool(true, "Wait for bar close (anti-repaint)", group=grpPro, tooltip="When enabled, alerts are evaluated only after the chart bar closes. Disabling this allows alert conditions to change while the current bar is forming.")
showDashboard = input.bool(true, "Show dashboard", group=grpPro, tooltip="Displays the timeframe labels, zone values, HTF state, alignment percentages, and a warning if the configured timeframe order is inconsistent.")
 
clamp01(x) =>
    math.max(0.0, math.min(100.0, x))
 
calcQrsi(source, len, useVol) =>
    hi = ta.highest(source, len)
    lo = ta.lowest(source, len)
    rng = hi - lo
    d = source - source[1]
    diff = hi > hi[1] ? rng : lo < lo[1] ? -rng : d
    // Symbols with absent/zero volume fall back to unweighted samples.
    vm = useVol and not na(volume) and volume > 0 ? volume : 1.0
    num = ta.rma(diff * vm, len)
    den = ta.rma(math.abs(diff) * vm, len)
    na(den) ? na : den == 0 ? 50.0 : clamp01(num / den * 50.0 + 50.0)
 
chartTf = tfChart == "" ? timeframe.period : tfChart
 
// Offset + lookahead_on is used only for confirmed higher-timeframe requests.
getQrsi(tf, len) =>
    isHTF = timeframe.in_seconds(tf) > timeframe.in_seconds(chartTf)
    if confirmedHTF and isHTF
        request.security(syminfo.tickerid, tf, calcQrsi(src, len, useVW)[1], lookahead=barmerge.lookahead_on)
    else
        request.security(syminfo.tickerid, tf, calcQrsi(src, len, useVW), lookahead=barmerge.lookahead_off)
 
z3raw = getQrsi(chartTf, length3)
z2raw = getQrsi(tfMacro1, length2)
z1raw = getQrsi(tfMacro2, length1)
 
// --- HTF SMOOTHING PATCH: chart-bar EMA after the request (no engine change) ---
smoothLine(v, len) =>
    len <= 1 ? v : ta.ema(v, len)
 
z3 = z3raw
z2 = smoothLine(z2raw, smooth2)
z1 = smoothLine(z1raw, smooth1)
y3 = 200.0 + z3
y2 = 100.0 + z2
y1 = z1
 
plot(0.0, "Frame 0", color=color.new(#000000, 75), display=display.pane)
plot(100.0, "Separator 1", color=#000000, display=display.pane)
plot(200.0, "Separator 2", color=color.new(#000000, 40), display=display.pane)
plot(300.0, "Frame 300", color=color.new(#000000, 75), display=display.pane)
 
p_o1 = plot(ob, "Z1 70", color=colOb, linewidth=obWidth, display=display.pane)
p_s1 = plot(os, "Z1 30", color=colOs, linewidth=osWidth, display=display.pane)
plot(50, "Z1 50", color=colMid, linewidth=midWidth, display=display.pane)
p_o2 = plot(100 + ob, "Z2 70", color=colOb, linewidth=obWidth, display=display.pane)
p_s2 = plot(100 + os, "Z2 30", color=colOs, linewidth=osWidth, display=display.pane)
plot(150, "Z2 50", color=colMid, linewidth=midWidth, display=display.pane)
p_o3 = plot(200 + ob, "Z3 70", color=colOb, linewidth=obWidth, display=display.pane)
p_s3 = plot(200 + os, "Z3 30", color=colOs, linewidth=osWidth, display=display.pane)
plot(250, "Z3 50", color=colMid, linewidth=midWidth, display=display.pane)
 
lineColor(v, normal) =>
    v > ob ? colFillBull : v < os ? colFillBear : normal
 
// All oscillator plots use the standard line style and the original width.
r1 = plot(y1, "Z1 RSI", color=lineColor(z1, colRsi1), linewidth=1, style=plot.style_line, trackprice=true, display=display.pane)
r2 = plot(y2, "Z2 RSI", color=lineColor(z2, colRsi2), linewidth=1, style=plot.style_line, trackprice=true, display=display.pane)
r3 = plot(y3, "Z3 RSI", color=lineColor(z3, colRsi3), linewidth=1, style=plot.style_line, trackprice=true, display=display.pane)
 
bullFillCol(v, base) =>
    v > ob ? color.from_gradient(v, ob, 100, color.new(base, 50), color.new(base, 5)) : na
bearFillCol(v, base) =>
    v < os ? color.from_gradient(v, 0, os, color.new(base, 5), color.new(base, 50)) : na
 
fill(p_o1, r1, bullFillCol(z1, colFillBull), title="Z1 OB Fill")
fill(p_s1, r1, bearFillCol(z1, colFillBear), title="Z1 OS Fill")
fill(p_o2, r2, bullFillCol(z2, colFillBull), title="Z2 OB Fill")
fill(p_s2, r2, bearFillCol(z2, colFillBear), title="Z2 OS Fill")
fill(p_o3, r3, bullFillCol(z3, colFillBull), title="Z3 OB Fill")
fill(p_s3, r3, bearFillCol(z3, colFillBear), title="Z3 OS Fill")
 
// RSI value labels track each zone's current value at the right edge.
toLabelSize(s) =>
    s == "Tiny" ? size.tiny :
     s == "Small" ? size.small :
     s == "Large" ? size.large :
     s == "Huge" ? size.huge :
     size.normal
 
valueLabelColor(v, neutralCol) =>
    v > ob ? colOb : v < os ? colOs : neutralCol
 
var label lblZ1 = na
var label lblZ2 = na
var label lblZ3 = na
 
if showValueLabels and not na(z1)
    txt1 = str.tostring(z1, "#.##")
    col1 = valueLabelColor(z1, colRsi1)
    if na(lblZ1)
        lblZ1 := label.new(bar_index + labelOffset, y1, txt1, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=col1, size=toLabelSize(labelSizeOpt))
    else
        label.set_xy(lblZ1, bar_index + labelOffset, y1)
        label.set_text(lblZ1, txt1)
        label.set_textcolor(lblZ1, col1)
        label.set_size(lblZ1, toLabelSize(labelSizeOpt))
else if not na(lblZ1)
    label.delete(lblZ1)
    lblZ1 := na
 
if showValueLabels and not na(z2)
    txt2 = str.tostring(z2, "#.##")
    col2 = valueLabelColor(z2, colRsi2)
    if na(lblZ2)
        lblZ2 := label.new(bar_index + labelOffset, y2, txt2, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=col2, size=toLabelSize(labelSizeOpt))
    else
        label.set_xy(lblZ2, bar_index + labelOffset, y2)
        label.set_text(lblZ2, txt2)
        label.set_textcolor(lblZ2, col2)
        label.set_size(lblZ2, toLabelSize(labelSizeOpt))
else if not na(lblZ2)
    label.delete(lblZ2)
    lblZ2 := na
 
if showValueLabels and not na(z3)
    txt3 = str.tostring(z3, "#.##")
    col3 = valueLabelColor(z3, colRsi3)
    if na(lblZ3)
        lblZ3 := label.new(bar_index + labelOffset, y3, txt3, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=col3, size=toLabelSize(labelSizeOpt))
    else
        label.set_xy(lblZ3, bar_index + labelOffset, y3)
        label.set_text(lblZ3, txt3)
        label.set_textcolor(lblZ3, col3)
        label.set_size(lblZ3, toLabelSize(labelSizeOpt))
else if not na(lblZ3)
    label.delete(lblZ3)
    lblZ3 := na
 
// Liquidity filter for alert conditions.
volAvg = ta.sma(volume, volAvgLen)
hasVolume = not na(volume) and volume > 0
liquidityOK = not useVolFilter or not hasVolume or na(volAvg) or volAvg <= 0 or (volume / volAvg >= volMinRatio)
 
// Directional agreement, not a win probability or trading recommendation.
ready = not na(z1) and not na(z2) and not na(z3)
totalWeight = w1 + w2 + w3
bullScore = ready ? ((z1 > 50 ? w1 : 0) + (z2 > 50 ? w2 : 0) + (z3 > 50 ? w3 : 0)) / totalWeight * 100 : na
bearScore = ready ? ((z1 < 50 ? w1 : 0) + (z2 < 50 ? w2 : 0) + (z3 < 50 ? w3 : 0)) / totalWeight * 100 : na
plot(bullScore, "Bullish alignment %", display=display.data_window)
plot(bearScore, "Bearish alignment %", display=display.data_window)
 
bullCrossAlign = ta.crossover(bullScore, threshold)
bearCrossAlign = ta.crossover(bearScore, threshold)
chartRecovery = ta.crossover(z3, os)
chartRejection = ta.crossunder(z3, ob)
 
var int lastAlert = na
canAlert = na(lastAlert) or bar_index - lastAlert > cooldown
closeGate = not waitForClose or barstate.isconfirmed
baseGate = closeGate and liquidityOK
 
bullSignal = ready and baseGate and canAlert and bullCrossAlign
bearSignal = ready and baseGate and canAlert and bearCrossAlign
recoverySignal = ready and baseGate and canAlert and chartRecovery and bullScore >= threshold
rejectionSignal = ready and baseGate and canAlert and chartRejection and bearScore >= threshold
 
if bullSignal or bearSignal or recoverySignal or rejectionSignal
    lastAlert := bar_index
 
alertcondition(bullSignal, "Bullish MTF alignment", "Q-RSI: bullish alignment threshold crossed on {{ticker}} · {{interval}}. Bar closed.")
alertcondition(bearSignal, "Bearish MTF alignment", "Q-RSI: bearish alignment threshold crossed on {{ticker}} · {{interval}}. Bar closed.")
alertcondition(recoverySignal, "Aligned oversold recovery", "Q-RSI: oversold recovery with bullish alignment on {{ticker}} · {{interval}}.")
alertcondition(rejectionSignal, "Aligned overbought rejection", "Q-RSI: overbought rejection with bearish alignment on {{ticker}} · {{interval}}.")
 
// Midline crosses are calculated on every bar, then gated for alerts.
z1CrossUp = ta.crossover(z1, 50)
z1CrossDown = ta.crossunder(z1, 50)
z2CrossUp = ta.crossover(z2, 50)
z2CrossDown = ta.crossunder(z2, 50)
z3CrossUp = ta.crossover(z3, 50)
z3CrossDown = ta.crossunder(z3, 50)
z1Mid = ready and baseGate and (z1CrossUp or z1CrossDown)
z2Mid = ready and baseGate and (z2CrossUp or z2CrossDown)
z3Mid = ready and baseGate and (z3CrossUp or z3CrossDown)
alertcondition(z1Mid, "Zone 1 - 50 midline cross", "Q-RSI: Zone 1 crossed the 50 midline on {{ticker}} · {{interval}}.")
alertcondition(z2Mid, "Zone 2 - 50 midline cross", "Q-RSI: Zone 2 crossed the 50 midline on {{ticker}} · {{interval}}.")
alertcondition(z3Mid, "Zone 3 - 50 midline cross", "Q-RSI: Zone 3 crossed the 50 midline on {{ticker}} · {{interval}}.")
 
// Stable, right-aligned dashboard.
tfOrderOK = timeframe.in_seconds(tfMacro1) >= timeframe.in_seconds(chartTf) and timeframe.in_seconds(tfMacro2) >= timeframe.in_seconds(tfMacro1)
 
var table dash = table.new(position.middle_right, 2, 6, bgcolor=#000000, border_width=1, border_color=color.new(color.white, 80))
if barstate.islast and showDashboard
    table.cell(dash, 0, 0, "Q-RSI PRO", text_color=color.white)
    table.cell(dash, 1, 0, confirmedHTF ? "CONFIRMED HTF" : "DEVELOPING", text_color=color.white)
    table.cell(dash, 0, 1, "Chart - " + chartTf, text_color=color.white)
    table.cell(dash, 1, 1, str.tostring(z3, "#.##"), text_color=lineColor(z3, colRsi3))
    table.cell(dash, 0, 2, "Macro 1 - " + tfMacro1, text_color=color.white)
    table.cell(dash, 1, 2, str.tostring(z2, "#.##"), text_color=lineColor(z2, colRsi2))
    table.cell(dash, 0, 3, "Macro 2 - " + tfMacro2, text_color=color.white)
    table.cell(dash, 1, 3, str.tostring(z1, "#.##"), text_color=lineColor(z1, colRsi1))
    table.cell(dash, 0, 4, "Bull / Bear alignment", text_color=color.white)
    table.cell(dash, 1, 4, str.tostring(bullScore, "#") + "% / " + str.tostring(bearScore, "#") + "%", text_color=color.white)
    table.cell(dash, 0, 5, tfOrderOK ? "" : "! TF ORDER", text_color=color.yellow)
    table.cell(dash, 1, 5, tfOrderOK ? "" : "check settings", text_color=color.yellow)

← 返回列表