Fibonacci & RSI Aligned Analysis

Michael_Fx_Trader · study · 388 行 · 点赞 637 · TradingView 原页

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

Pine Script

//@version=6
 
// =============================================================================
//                         ORIGINAL SCRIPT DECLARATION
// =============================================================================
// Script Name   : Fibonacci & RSI Aligned Analysis
// Author        : Michael_Fx_Trader
// Publisher     : Michael_Fx_Trader
// Rights        : © Michael_Fx_Trader. All rights reserved.
//
// Originality Statement:
//   This is an original work, designed and coded from scratch by
//   Michael_Fx_Trader. The trend-leg tracking engine (which only redefines the
//   active Fibonacci leg on a genuine structure break rather than on every
//   minor retracement pivot), the RSI divergence detector, the fib-zone plus
//   divergence plus round-number confluence signal logic, the session-aware
//   signal styling, and the automatic clean-chart redraw system (old legs and
//   old signals are removed rather than stacking indefinitely) were all
//   independently conceived and implemented for this publication. No
//   proprietary source code, private scripts, or copyrighted material
//   belonging to any other author has been copied, mashed-up, or reused in
//   any part of this script.
//
// Author Verification / Declaration:
//   I, Michael_Fx_Trader, am the sole author and publisher of this script.
//   I hold full authorship rights over its source code, its underlying logic,
//   and its visual presentation. Fibonacci retracement and the Relative
//   Strength Index (RSI) are both well-known, generic public-domain technical
//   analysis concepts and are not owned by any individual author; only the
//   specific leg-tracking, divergence, confluence, and display logic built
//   around them here is original to this script.
// =============================================================================
 
indicator("Fibonacci & RSI Aligned Analysis", shorttitle = "Fib RSI Aligned", overlay = false,
     max_lines_count = 200, max_labels_count = 200, max_boxes_count = 100)
 
// =============================================================================
// 9. USER INPUTS
// =============================================================================
 
grpSwing = "Swing / Fibonacci Settings"
pivotLR       = input.int(5, "Pivot Left/Right Bars", minval = 1, maxval = 50, group = grpSwing,
     tooltip = "How many bars on each side confirm a swing high/low. Works the same on every timeframe since it is bar-count based, not time based.")
fibTolerancePct = input.float(1.5, "Fib Zone Tolerance (%)", minval = 0.1, step = 0.1, group = grpSwing,
     tooltip = "Price is considered 'at' the 61.8/78.6 zone if it is within this percentage of price around either level.")
showFibLines  = input.bool(true, "Show Fibonacci Lines", group = grpSwing)
showFibZoneBox = input.bool(true, "Shade 61.8%-78.6% Zone", group = grpSwing)
 
grpRsi = "RSI / Divergence Settings"
rsiLength   = input.int(14, "RSI Length", minval = 1, group = grpRsi)
rsiSource   = input.source(close, "RSI Source", group = grpRsi)
showRsiPanel = input.bool(true, "Show RSI Plot + 30/70 Lines", group = grpRsi)
showDivLabels = input.bool(true, "Show Divergence Labels", group = grpRsi)
 
grpRound = "Round Number Filter (Optional)"
useRoundFilter = input.bool(false, "Require Price Near a Round Number", group = grpRound)
roundStep      = input.float(50, "Round Number Step (e.g. 50 for Gold)", minval = 0.01, group = grpRound)
roundTolerance = input.float(3, "Round Number Tolerance (price units)", minval = 0.0, group = grpRound)
showRoundShading = input.bool(true, "Background Shade Near Round Numbers", group = grpRound)
 
grpSession = "Session Filter (Optional)"
useSessionFilter = input.bool(false, "Restrict Full-Confidence Signals to Preferred Sessions", group = grpSession,
     tooltip = "Signals outside the preferred sessions are still shown, just with lower opacity, instead of being hidden.")
londonSession = input.session("0700-1030", "London Session (GMT)", group = grpSession)
nySession     = input.session("1300-1600", "New York Session (GMT)", group = grpSession)
 
grpColors = "Colors"
bullColor = input.color(color.new(color.lime, 0), "Bullish / Buy Color", group = grpColors)
bearColor = input.color(color.new(color.red, 0),  "Bearish / Sell Color", group = grpColors)
fibColor  = input.color(color.new(color.orange, 0), "Fib Line Color", group = grpColors)
zoneColor = input.color(color.new(color.orange, 82), "Fib Zone Fill Color", group = grpColors)
 
maxSignalsShown = input.int(3, "Max Recent Signals Shown (per side)", minval = 1, maxval = 10, group = grpColors)
 
// =============================================================================
// 1-2. SWING STRUCTURE DETECTION (timeframe-agnostic via bar-count pivots)
// =============================================================================
 
rsiValue = ta.rsi(rsiSource, rsiLength)
 
ph = ta.pivothigh(high, pivotLR, pivotLR)
pl = ta.pivotlow(low, pivotLR, pivotLR)
 
var float lastSwingHighPrice = na
var int   lastSwingHighBar   = na
var float lastSwingLowPrice  = na
var int   lastSwingLowBar    = na
 
if not na(ph)
    lastSwingHighPrice := ph
    lastSwingHighBar   := bar_index - pivotLR
if not na(pl)
    lastSwingLowPrice := pl
    lastSwingLowBar   := bar_index - pivotLR
 
// =============================================================================
// RSI DIVERGENCE DETECTION (compares each new pivot to the previous one of the
// same type)
// =============================================================================
 
var float prevPivotLowPrice  = na
var float prevPivotLowRsi    = na
var int   prevPivotLowBar    = na
var float prevPivotHighPrice = na
var float prevPivotHighRsi   = na
var int   prevPivotHighBar   = na
 
bullishDivNow = false
bearishDivNow = false
var float bullDivFromPrice = na
var int   bullDivFromBar   = na
var float bullDivToPrice   = na
var int   bullDivToBar     = na
var float bullDivFromRsi   = na
var float bullDivToRsi     = na
var float bearDivFromPrice = na
var int   bearDivFromBar   = na
var float bearDivToPrice   = na
var int   bearDivToBar     = na
var float bearDivFromRsi   = na
var float bearDivToRsi     = na
 
if not na(pl)
    curLowPrice = pl
    curLowRsi   = rsiValue[pivotLR]
    curLowBar   = bar_index - pivotLR
    if not na(prevPivotLowPrice) and curLowPrice < prevPivotLowPrice and curLowRsi > prevPivotLowRsi
        bullishDivNow := true
        bullDivFromPrice := prevPivotLowPrice
        bullDivFromBar   := prevPivotLowBar
        bullDivToPrice   := curLowPrice
        bullDivToBar     := curLowBar
        bullDivFromRsi   := prevPivotLowRsi
        bullDivToRsi     := curLowRsi
    prevPivotLowPrice := curLowPrice
    prevPivotLowRsi   := curLowRsi
    prevPivotLowBar   := curLowBar
 
if not na(ph)
    curHighPrice = ph
    curHighRsi   = rsiValue[pivotLR]
    curHighBar   = bar_index - pivotLR
    if not na(prevPivotHighPrice) and curHighPrice > prevPivotHighPrice and curHighRsi < prevPivotHighRsi
        bearishDivNow := true
        bearDivFromPrice := prevPivotHighPrice
        bearDivFromBar   := prevPivotHighBar
        bearDivToPrice   := curHighPrice
        bearDivToBar     := curHighBar
        bearDivFromRsi   := prevPivotHighRsi
        bearDivToRsi     := curHighRsi
    prevPivotHighPrice := curHighPrice
    prevPivotHighRsi   := curHighRsi
    prevPivotHighBar   := curHighBar
 
// =============================================================================
// ACTIVE IMPULSE LEG TRACKING
// =============================================================================
// The leg only changes on a genuine structure event: either the trend extends
// (a new higher high in an up leg, a new lower low in a down leg) or the
// trend reverses because price breaks past the ORIGIN of the current leg. A
// retracement pivot that stays within the current leg's range does NOT change
// the leg - this is what lets a pullback's divergence still count as a
// continuation signal for the larger trend instead of constantly redefining
// the leg on every minor wiggle.
 
var string legDirection  = na   // "up" or "down"
var float  legStartPrice = na
var int    legStartBar   = na
var float  legEndPrice   = na
var int    legEndBar     = na
 
if na(legDirection) and not na(lastSwingHighPrice) and not na(lastSwingLowPrice)
    if lastSwingHighBar > lastSwingLowBar
        legDirection  := "up"
        legStartPrice := lastSwingLowPrice
        legStartBar   := lastSwingLowBar
        legEndPrice   := lastSwingHighPrice
        legEndBar     := lastSwingHighBar
    else
        legDirection  := "down"
        legStartPrice := lastSwingHighPrice
        legStartBar   := lastSwingHighBar
        legEndPrice   := lastSwingLowPrice
        legEndBar     := lastSwingLowBar
 
if not na(ph) and not na(legDirection)
    if legDirection == "up"
        if ph > legEndPrice
            legEndPrice := ph
            legEndBar   := bar_index - pivotLR
    else
        if ph > legStartPrice
            legDirection  := "up"
            legStartPrice := legEndPrice
            legStartBar   := legEndBar
            legEndPrice   := ph
            legEndBar     := bar_index - pivotLR
 
if not na(pl) and not na(legDirection)
    if legDirection == "down"
        if pl < legEndPrice
            legEndPrice := pl
            legEndBar   := bar_index - pivotLR
    else
        if pl < legStartPrice
            legDirection  := "down"
            legStartPrice := legEndPrice
            legStartBar   := legEndBar
            legEndPrice   := pl
            legEndBar     := bar_index - pivotLR
 
legValid = not na(legDirection)
legIsUp  = legDirection == "up"
 
// =============================================================================
// 3. FIBONACCI LEVELS - 0% at the most recent extreme, 100% at the leg origin
// =============================================================================
 
fibPrice(level) =>
    legValid ? legEndPrice + (legStartPrice - legEndPrice) * (level / 100.0) : na
 
fib0   = fibPrice(0.0)
fib236 = fibPrice(23.6)
fib382 = fibPrice(38.2)
fib50  = fibPrice(50.0)
fib618 = fibPrice(61.8)
fib786 = fibPrice(78.6)
fib100 = fibPrice(100.0)
 
// =============================================================================
// FIB DRAWING OBJECTS - redrawn only when the active leg actually changes
// =============================================================================
 
var line[]  fibLines  = array.new_line()
var label[] fibLabels = array.new_label()
var box     fibZoneBox = na
 
var int prevLegStartBar = na
var int prevLegEndBar   = na
 
newLegFormed = legValid and (legStartBar != prevLegStartBar or legEndBar != prevLegEndBar)
 
if newLegFormed
    // ---- clear the previous leg's drawings before drawing the new one ----
    if array.size(fibLines) > 0
        for i = 0 to array.size(fibLines) - 1
            line.delete(array.get(fibLines, i))
        array.clear(fibLines)
    if array.size(fibLabels) > 0
        for i = 0 to array.size(fibLabels) - 1
            label.delete(array.get(fibLabels, i))
        array.clear(fibLabels)
    if not na(fibZoneBox)
        box.delete(fibZoneBox)
        fibZoneBox := na
 
    if showFibLines
        levels = array.from(0.0, 23.6, 38.2, 50.0, 61.8, 78.6, 100.0)
        for i = 0 to array.size(levels) - 1
            lv = array.get(levels, i)
            lp = fibPrice(lv)
            isKeyLevel = lv == 61.8 or lv == 78.6
            ln = line.new(legStartBar, lp, bar_index, lp, color = fibColor, width = isKeyLevel ? 2 : 1,
                 style = line.style_dashed, extend = extend.right, force_overlay = true)
            array.push(fibLines, ln)
            lb = label.new(bar_index, lp, str.tostring(lv, "#.#") + "%", style = label.style_label_left,
                 color = color.new(color.black, 100), textcolor = fibColor, size = size.small, force_overlay = true)
            array.push(fibLabels, lb)
    if showFibZoneBox
        fibZoneBox := box.new(legStartBar, math.max(fib618, fib786), bar_index, math.min(fib618, fib786),
             border_color = fibColor, bgcolor = zoneColor, extend = extend.right, force_overlay = true)
    prevLegStartBar := legStartBar
    prevLegEndBar   := legEndBar
 
// =============================================================================
// 5. CONFLUENCE ENGINE
// =============================================================================
 
fibTolerance = close * fibTolerancePct / 100.0
fibZoneLow  = legValid ? math.min(fib618, fib786) - fibTolerance : na
fibZoneHigh = legValid ? math.max(fib618, fib786) + fibTolerance : na
nearFibZone = legValid and close >= fibZoneLow and close <= fibZoneHigh
 
isNearRound(price) =>
    remainder = price % roundStep
    dist = math.min(remainder, roundStep - remainder)
    dist <= roundTolerance
 
roundOk = not useRoundFilter or isNearRound(close)
 
buyConfluence  = bullishDivNow and legIsUp and nearFibZone and roundOk
sellConfluence = bearishDivNow and not legIsUp and nearFibZone and roundOk
 
// =============================================================================
// 7. SESSION FILTER (styling only - signals are never hidden by session)
// =============================================================================
 
inLondon = not na(time(timeframe.period, londonSession, "GMT"))
inNY     = not na(time(timeframe.period, nySession, "GMT"))
inPreferredSession = inLondon or inNY
sessionOk = not useSessionFilter or inPreferredSession
 
buySignalColor  = sessionOk ? bullColor : color.new(bullColor, 70)
sellSignalColor = sessionOk ? bearColor : color.new(bearColor, 70)
 
// =============================================================================
// RSI PANE PLOTTING + DIVERGENCE LINES ON THE RSI ITSELF
// =============================================================================
 
plot(showRsiPanel ? rsiValue : na, "RSI", color = color.new(color.aqua, 0), linewidth = 2)
hline(70, "Overbought", color = color.new(color.red, 50), linestyle = hline.style_dashed)
hline(30, "Oversold", color = color.new(color.green, 50), linestyle = hline.style_dashed)
hline(50, "Midline", color = color.new(color.gray, 70), linestyle = hline.style_dotted)
 
if bullishDivNow and showDivLabels
    line.new(bullDivFromBar, bullDivFromRsi, bullDivToBar, bullDivToRsi, color = bullColor, width = 2)
    label.new(bullDivToBar, bullDivToRsi, "Bull Div", style = label.style_label_up, color = color.new(bullColor, 0),
         textcolor = color.white, size = size.small)
 
if bearishDivNow and showDivLabels
    line.new(bearDivFromBar, bearDivFromRsi, bearDivToBar, bearDivToRsi, color = bearColor, width = 2)
    label.new(bearDivToBar, bearDivToRsi, "Bear Div", style = label.style_label_down, color = color.new(bearColor, 0),
         textcolor = color.white, size = size.small)
 
// =============================================================================
// 6. CHART DRAWINGS FOR SIGNALS + DIVERGENCE MARKERS ON PRICE (force_overlay)
// =============================================================================
 
if bullishDivNow and showDivLabels
    line.new(bullDivFromBar, bullDivFromPrice, bullDivToBar, bullDivToPrice, color = bullColor, width = 1,
         style = line.style_dotted, force_overlay = true)
    label.new(bullDivToBar, bullDivToPrice, "Bull Div", style = label.style_label_up,
         color = color.new(bullColor, 0), textcolor = color.white, size = size.small, force_overlay = true)
 
if bearishDivNow and showDivLabels
    line.new(bearDivFromBar, bearDivFromPrice, bearDivToBar, bearDivToPrice, color = bearColor, width = 1,
         style = line.style_dotted, force_overlay = true)
    label.new(bearDivToBar, bearDivToPrice, "Bear Div", style = label.style_label_down,
         color = color.new(bearColor, 0), textcolor = color.white, size = size.small, force_overlay = true)
 
bgcolor(showRoundShading and useRoundFilter and isNearRound(close) ? color.new(color.yellow, 85) : na,
     title = "Round Number Zone", force_overlay = true)
 
var label[] buySignalLabels  = array.new_label()
var box[]   buySignalMarkers = array.new_box()
var label[] sellSignalLabels  = array.new_label()
var box[]   sellSignalMarkers = array.new_box()
 
trimSignals(labArr, boxArr) =>
    if array.size(labArr) > maxSignalsShown
        label.delete(array.shift(labArr))
        box.delete(array.shift(boxArr))
 
if buyConfluence
    lb = label.new(bar_index, low, "BUY\n" + str.tostring(close, format.mintick), style = label.style_label_up,
         color = color.new(buySignalColor, 0), textcolor = color.white, size = size.small, force_overlay = true)
    bx = box.new(bar_index - 1, close + fibTolerance, bar_index + 1, close - fibTolerance,
         border_color = buySignalColor, bgcolor = color.new(buySignalColor, 80), force_overlay = true)
    array.push(buySignalLabels, lb)
    array.push(buySignalMarkers, bx)
    trimSignals(buySignalLabels, buySignalMarkers)
 
if sellConfluence
    lb = label.new(bar_index, high, "SELL\n" + str.tostring(close, format.mintick), style = label.style_label_down,
         color = color.new(sellSignalColor, 0), textcolor = color.white, size = size.small, force_overlay = true)
    bx = box.new(bar_index - 1, close + fibTolerance, bar_index + 1, close - fibTolerance,
         border_color = sellSignalColor, bgcolor = color.new(sellSignalColor, 80), force_overlay = true)
    array.push(sellSignalLabels, lb)
    array.push(sellSignalMarkers, bx)
    trimSignals(sellSignalLabels, sellSignalMarkers)
 
// =============================================================================
// 8. ALERTS
// =============================================================================
 
nearLevelText = legValid ? (math.abs(close - fib618) <= math.abs(close - fib786) ? "61.8%" : "78.6%") : "n/a"
sessionText   = inPreferredSession ? "inside preferred session" : "outside preferred session (lower confidence)"
 
alertcondition(buyConfluence, title = "Buy Confluence Signal", message = "Fibonacci & RSI Aligned Analysis: BUY confluence signal.")
alertcondition(sellConfluence, title = "Sell Confluence Signal", message = "Fibonacci & RSI Aligned Analysis: SELL confluence signal.")
 
if buyConfluence
    alert("Fibonacci & RSI Aligned Analysis - BUY signal. Price: " + str.tostring(close, format.mintick) +
         ". Fib level: " + nearLevelText + ". Session: " + sessionText + ".", alert.freq_once_per_bar)
 
if sellConfluence
    alert("Fibonacci & RSI Aligned Analysis - SELL signal. Price: " + str.tostring(close, format.mintick) +
         ". Fib level: " + nearLevelText + ". Session: " + sessionText + ".", alert.freq_once_per_bar)

← 返回列表