Auto Structure Fibonacci

horacebury · study · 320 行 · 点赞 425 · TradingView 原页

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

Pine Script

//@version=6
// =============================================================================
// Automatic Fibonacci from Price Structure
//
// Detects structural swings with an ATR zigzag, classifies them as HH/HL/LH/LL
// (optionally shown as a zigzag with labels), and draws a
// Fibonacci (0, 0.5, 0.618, 1) over each bullish leg (LL → HH, HL → HH) and
// bearish leg (HH → LL, LH → LL) once price has retraced to its 0.5 level.
// Confirmed Fibonaccis are fixed and kept up to a configurable maximum.
// =============================================================================
indicator("Auto Structure Fibonacci", shorttitle = "Auto Fib", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
// =============================================================================
// CONSTANTS
// =============================================================================
// Swings kept in memory, and so also shown by "Show Swing Structure".
// 50 swings + 100 Fibonaccis stays within the 500 line/label limits.
int MAX_SWINGS = 50
 
int DIR_BULL = 1
int DIR_BEAR = -1
 
color COL_BULL  = #26a69a
color COL_BEAR  = #ef5350
color COL_MUTED = #787b86
 
// =============================================================================
// INPUTS
// =============================================================================
string GRP_SWING = "Structure Detection"
string GRP_STYLE = "Fibonacci Appearance"
string GRP_ZONE  = "Gold Zone (0.5 – 0.618)"
 
int    atrLengthInput    = input.int(14, "ATR Length", minval = 1, group = GRP_SWING)
float  atrMultInput      = input.float(3.0, "ATR Reversal Multiplier", minval = 0.1, step = 0.1, group = GRP_SWING, tooltip = "A swing is confirmed once price reverses from it by ATR × this multiplier. Higher = fewer, larger swings.")
bool   showSwingsInput   = input.bool(false, "Show Swing Structure", group = GRP_SWING, tooltip = "Zigzag joining the detected swings, HH/HL/LH/LL labels (hover for price and confirmation delay), and a dashed line for the leg still forming. Shows the most recent 50 swings.")
 
int    maxFibsInput      = input.int(10, "Maximum Historical Fibonacci Structures", minval = 1, maxval = 100, group = GRP_STYLE, tooltip = "Total confirmed Fibonaccis kept on the chart (bullish and bearish combined). When exceeded, the oldest is removed.")
bool   showBullInput     = input.bool(true, "Show Bullish Structures", group = GRP_STYLE)
bool   showBearInput     = input.bool(true, "Show Bearish Structures", group = GRP_STYLE)
bool   showLabelsInput   = input.bool(true, "Show Level Values", group = GRP_STYLE, tooltip = "Level (0, 0.5, 0.618, 1) at the right-hand end of each line, in the line's colour.")
bool   showPricesInput   = input.bool(false, "Show Prices in Level Values", group = GRP_STYLE, tooltip = "Adds the price after each level, e.g. 0.618 (1.27450).")
int    extensionInput    = input.int(30, "Fibonacci Extension Bars", minval = 0, maxval = 400, group = GRP_STYLE, tooltip = "How far the levels extend to the right of the bar where the Fibonacci was confirmed.")
int    lineWidthInput    = input.int(1, "Line Width", minval = 1, maxval = 4, group = GRP_STYLE)
string lineStyleInput    = input.string("Solid", "Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_STYLE)
string labelSizeInput    = input.string("Small", "Level Value Size", options = ["Tiny", "Small", "Normal"], group = GRP_STYLE)
color  colLevel0Input    = input.color(#787b86, "Level 0 Colour", group = GRP_STYLE)
color  colLevel05Input   = input.color(#f5b400, "Level 0.5 Colour", group = GRP_STYLE)
color  colLevel0618Input = input.color(#f5b400, "Level 0.618 Colour", group = GRP_STYLE)
color  colLevel1Input    = input.color(#787b86, "Level 1 Colour", group = GRP_STYLE)
 
bool   showGoldZoneInput = input.bool(true, "Show Gold Zone", group = GRP_ZONE)
color  colGoldZoneInput  = input.color(color.new(#f5b400, 85), "Gold Zone Fill", group = GRP_ZONE)
 
// =============================================================================
// TYPES
// =============================================================================
// A confirmed structural swing point.
type Swing
    bool   isHigh
    float  price
    int    bar         // bar where the high/low actually printed
    int    confirmBar  // bar on whose close the swing became known (no lookahead)
    string tag         // H / L / HH / HL / LH / LL / EQH / EQL
    label  tagLabel    // optional structure display
    line   legLine     // optional zigzag leg from the previous swing to this one
 
// A Fibonacci over one structural leg. Pending until price retraces to 0.5,
// then drawn once with all levels fixed.
type Fib
    int   dir
    float hiPrice
    int   hiBar
    float loPrice
    int   loBar
    float level05
    float level0618
    int   createdBar
    float retraceExtreme  // deepest retracement reached since the leg ended
    int   confirmBar
    line  line0
    line  line05
    line  line0618
    line  line1
    label label0
    label label05
    label label0618
    label label1
    linefill goldZone
 
// =============================================================================
// STRUCTURE STATE
// =============================================================================
// Confirmed swings, strictly alternating high / low / high / ...
var array<Swing> swings = array.new<Swing>()
 
// Confirmed (drawn) Fibonaccis, oldest first. Never modified once added.
var array<Fib> drawnFibs = array.new<Fib>()
 
float atrValue = ta.atr(atrLengthInput)
 
// =============================================================================
// CLASSIFICATION
// =============================================================================
// Compares a swing with the previous swing of the same type.
structureTag(bool isHigh, float price, float prevSameTypePrice) =>
    string tag = isHigh ? "H" : "L"
    if not na(prevSameTypePrice)
        if price > prevSameTypePrice
            tag := isHigh ? "HH" : "HL"
        else if price < prevSameTypePrice
            tag := isHigh ? "LH" : "LL"
        else
            tag := isHigh ? "EQH" : "EQL"
    tag
 
// Optional structure display: the swing's label and the zigzag leg into it.
method drawStructure(Swing this, Swing prev) =>
    if showSwingsInput
        color  tagCol = this.tag == "HH" or this.tag == "HL" ? COL_BULL : this.tag == "LH" or this.tag == "LL" ? COL_BEAR : COL_MUTED
        string tip    = this.tag + "  " + str.tostring(this.price, format.mintick) + "\nconfirmed " + str.tostring(this.confirmBar - this.bar) + " bars later"
        this.tagLabel := label.new(this.bar, this.price, this.tag, style = this.isHigh ? label.style_label_down : label.style_label_up, color = color.new(tagCol, 20), textcolor = color.white, size = size.small, tooltip = tip)
        if not na(prev)
            this.legLine := line.new(prev.bar, prev.price, this.bar, this.price, color = color.new(COL_MUTED, 20), width = 1)
    this
 
// Records a confirmed swing and classifies it against the previous swing of
// the same type (two entries back, since swings alternate).
recordSwing(bool isHigh, float price, int bar) =>
    int   n        = swings.size()
    float prevSame = na
    Swing prevLeg  = na
    if n >= 2
        prevSame := swings.get(n - 2).price
    if n >= 1
        prevLeg := swings.get(n - 1)
    Swing s = Swing.new(isHigh, price, bar, bar_index, structureTag(isHigh, price, prevSame))
    swings.push(s)
    s.drawStructure(prevLeg)
    if swings.size() > MAX_SWINGS
        Swing oldest = swings.shift()
        label.delete(oldest.tagLabel)
        line.delete(oldest.legLine)
    s
 
// =============================================================================
// FIBONACCI
// =============================================================================
// Bullish: 0 = high, 1 = low  -> level = high - range × ratio
// Bearish: 0 = low,  1 = high -> level = low  + range × ratio
fibLevel(int dir, float hiPrice, float loPrice, float ratio) =>
    float legRange = hiPrice - loPrice
    dir == DIR_BULL ? hiPrice - legRange * ratio : loPrice + legRange * ratio
 
// Bullish structural legs: LL → HH and HL → HH.
isBullishLeg(Swing start, Swing end) =>
    end.tag == "HH" and (start.tag == "LL" or start.tag == "HL")
 
// Bearish structural legs: HH → LL and LH → LL.
isBearishLeg(Swing start, Swing end) =>
    end.tag == "LL" and (start.tag == "HH" or start.tag == "LH")
 
createFib(int dir, Swing start, Swing end, float retraceSoFar) =>
    float hi    = dir == DIR_BULL ? end.price : start.price
    float lo    = dir == DIR_BULL ? start.price : end.price
    int   hiBar = dir == DIR_BULL ? end.bar : start.bar
    int   loBar = dir == DIR_BULL ? start.bar : end.bar
    Fib.new(dir = dir, hiPrice = hi, hiBar = hiBar, loPrice = lo, loBar = loBar, level05 = fibLevel(dir, hi, lo, 0.5), level0618 = fibLevel(dir, hi, lo, 0.618), createdBar = bar_index, retraceExtreme = retraceSoFar)
 
// Advances a pending Fibonacci by one closed bar.
// Returns  1 = confirmed (price has retraced to 0.5),
//         -1 = cancelled (price went beyond the leg's end before retracing to 0.5),
//          0 = still waiting.
method step(Fib this) =>
    bool bull   = this.dir == DIR_BULL
    int  status = 0
    // The creation bar's retracement is already included via retraceSoFar.
    if bar_index > this.createdBar
        if bull ? high > this.hiPrice : low < this.loPrice
            status := -1
        else
            this.retraceExtreme := bull ? math.min(this.retraceExtreme, low) : math.max(this.retraceExtreme, high)
    if status == 0 and (bull ? this.retraceExtreme <= this.level05 : this.retraceExtreme >= this.level05)
        status := 1
    status
 
// Level value at the right-hand end of a line: "0.618", or "0.618 (1.27450)"
// when prices are shown.
levelLabel(int x, float price, string levelText, color textCol) =>
    string labelSize = labelSizeInput == "Tiny" ? size.tiny : labelSizeInput == "Normal" ? size.normal : size.small
    string labelText = showPricesInput ? levelText + " (" + str.tostring(price, format.mintick) + ")" : levelText
    label.new(x, price, labelText, style = label.style_label_left, color = color(na), textcolor = textCol, size = labelSize)
 
levelLine(int x1, int x2, float price, color lineCol) =>
    string style = lineStyleInput == "Dashed" ? line.style_dashed : lineStyleInput == "Dotted" ? line.style_dotted : line.style_solid
    line.new(x1, price, x2, price, color = lineCol, style = style, width = lineWidthInput)
 
method drawFib(Fib this) =>
    bool  bull  = this.dir == DIR_BULL
    float level0 = bull ? this.hiPrice : this.loPrice
    float level1 = bull ? this.loPrice : this.hiPrice
    int   x1    = math.min(this.hiBar, this.loBar)
    int   x2    = this.confirmBar + extensionInput
    this.line0    := levelLine(x1, x2, level0, colLevel0Input)
    this.line05   := levelLine(x1, x2, this.level05, colLevel05Input)
    this.line0618 := levelLine(x1, x2, this.level0618, colLevel0618Input)
    this.line1    := levelLine(x1, x2, level1, colLevel1Input)
    if showGoldZoneInput
        this.goldZone := linefill.new(this.line05, this.line0618, colGoldZoneInput)
    if showLabelsInput
        this.label0    := levelLabel(x2, level0, "0", colLevel0Input)
        this.label05   := levelLabel(x2, this.level05, "0.5", colLevel05Input)
        this.label0618 := levelLabel(x2, this.level0618, "0.618", colLevel0618Input)
        this.label1    := levelLabel(x2, level1, "1", colLevel1Input)
    this
 
method deleteDrawing(Fib this) =>
    linefill.delete(this.goldZone)
    line.delete(this.line0)
    line.delete(this.line05)
    line.delete(this.line0618)
    line.delete(this.line1)
    label.delete(this.label0)
    label.delete(this.label05)
    label.delete(this.label0618)
    label.delete(this.label1)
    this
 
// Adds a newly confirmed Fibonacci to the history, removing the oldest ones
// beyond the configured maximum.
storeFib(Fib confirmed) =>
    drawnFibs.push(confirmed)
    while drawnFibs.size() > maxFibsInput
        drawnFibs.shift().deleteDrawing()
 
// Advances a pending Fibonacci one bar: draws it once confirmed and returns na
// once it is resolved (drawn or cancelled), otherwise returns it unchanged.
resolvePending(Fib pending) =>
    Fib result = pending
    if not na(pending)
        int status = pending.step()
        if status == 1
            pending.confirmBar := bar_index
            pending.drawFib()
            storeFib(pending)
            result := na
        else if status == -1
            result := na
    result
 
// =============================================================================
// SWING DETECTION — ATR ZIGZAG
// =============================================================================
// Tracks the extreme of the current leg. A swing is confirmed only when price
// has since moved against it by ATR × multiplier, measured on CLOSED bars.
// The swing is placed on the bar that made the extreme, but is only known from
// the confirming bar onward — nothing uses it before then.
var int   zzDir        = 0     // +1 rising leg (tracking a high), -1 falling leg (tracking a low)
var float zzExtreme    = na    // extreme of the current leg
var int   zzExtremeBar = na
var float zzCounter    = na    // furthest pull-back against the leg since that extreme
var int   zzCounterBar = na
 
var Fib pendingBull = na
var Fib pendingBear = na
 
if barstate.isconfirmed
    if zzDir == 0
        zzDir        := 1
        zzExtreme    := high
        zzExtremeBar := bar_index
    else
        bool  up      = zzDir == 1
        float pushSrc = up ? high : low   // extends the current leg
        float pullSrc = up ? low : high   // moves against it
        if up ? pushSrc > zzExtreme : pushSrc < zzExtreme
            // Leg extends: new extreme, pull-back measurement restarts.
            zzExtreme    := pushSrc
            zzExtremeBar := bar_index
            zzCounter    := na
            zzCounterBar := na
        else
            if na(zzCounter) or (up ? pullSrc < zzCounter : pullSrc > zzCounter)
                zzCounter    := pullSrc
                zzCounterBar := bar_index
            if math.abs(zzExtreme - zzCounter) >= atrValue * atrMultInput
                // Reversal large enough: the extreme is a confirmed swing and
                // the pull-back extreme becomes the start of the new leg.
                Swing newSwing     = recordSwing(up, zzExtreme, zzExtremeBar)
                float retraceSoFar = zzCounter
                zzDir        := -zzDir
                zzExtreme    := zzCounter
                zzExtremeBar := zzCounterBar
                zzCounter    := na
                zzCounterBar := na
 
                // A newly confirmed HH (LL) completes a bullish (bearish) leg
                // from the opposite swing just before it.
                int n = swings.size()
                if n >= 2
                    Swing legStart = swings.get(n - 2)
                    if showBullInput and newSwing.isHigh and isBullishLeg(legStart, newSwing)
                        pendingBull := createFib(DIR_BULL, legStart, newSwing, retraceSoFar)
                    else if showBearInput and not newSwing.isHigh and isBearishLeg(legStart, newSwing)
                        pendingBear := createFib(DIR_BEAR, legStart, newSwing, retraceSoFar)
 
    // Pending legs: drawn once price has retraced to 0.5, dropped if price goes
    // beyond the leg's end (new high / new low) first.
    pendingBull := resolvePending(pendingBull)
    pendingBear := resolvePending(pendingBear)
 
// Optional structure display: dashed line for the leg still forming (not yet a
// confirmed swing).
var line formingLegLine = na
if barstate.islast and showSwingsInput
    line.delete(formingLegLine)
    int n = swings.size()
    if n > 0 and not na(zzExtremeBar)
        Swing lastSwing = swings.get(n - 1)
        formingLegLine := line.new(lastSwing.bar, lastSwing.price, zzExtremeBar, zzExtreme, color = COL_MUTED, style = line.style_dashed, width = 1)

← 返回列表